]> Sergey Matveev's repositories - btrtrc.git/blob - peer_protocol/int.go
peer_protocol: Use faster form for Integer.{UnmarshalBinary,Read}
[btrtrc.git] / peer_protocol / int.go
1 package peer_protocol
2
3 import (
4         "encoding/binary"
5         "io"
6
7         "github.com/pkg/errors"
8 )
9
10 type Integer uint32
11
12 func (i *Integer) UnmarshalBinary(b []byte) error {
13         if len(b) != 4 {
14                 return errors.New("expected 4 bytes")
15         }
16         *i = Integer(binary.BigEndian.Uint32(b))
17         return nil
18 }
19
20 func (i *Integer) Read(r io.Reader) error {
21         var b [4]byte
22         n, err := r.Read(b[:])
23         if n == 4 {
24                 return i.UnmarshalBinary(b[:])
25         }
26         if err == nil {
27                 return io.ErrUnexpectedEOF
28         }
29         return err
30 }
31
32 // It's perfectly fine to cast these to an int. TODO: Or is it?
33 func (i Integer) Int() int {
34         return int(i)
35 }
36
37 func (i Integer) Uint64() uint64 {
38         return uint64(i)
39 }
40
41 func (i Integer) Uint32() uint32 {
42         return uint32(i)
43 }