github.com/anacrolix/torrent@v1.61.0/peer_protocol/int.go (about)

     1  package peer_protocol
     2  
     3  import (
     4  	"encoding/binary"
     5  	"io"
     6  	"math"
     7  
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  type (
    12  	// An alias for the underlying type of Integer. This is needed for fuzzing.
    13  	IntegerKind = uint32
    14  	Integer     IntegerKind
    15  )
    16  
    17  const IntegerMax = math.MaxUint32
    18  
    19  func (i *Integer) UnmarshalBinary(b []byte) error {
    20  	if len(b) != 4 {
    21  		return errors.New("expected 4 bytes")
    22  	}
    23  	*i = Integer(binary.BigEndian.Uint32(b))
    24  	return nil
    25  }
    26  
    27  func (i *Integer) Read(r io.Reader) error {
    28  	var b [4]byte
    29  	n, err := io.ReadFull(r, b[:])
    30  	if err == nil {
    31  		if n != 4 {
    32  			panic(n)
    33  		}
    34  		return i.UnmarshalBinary(b[:])
    35  	}
    36  	return err
    37  }
    38  
    39  // It's perfectly fine to cast these to an int. TODO: Or is it?
    40  func (i Integer) Int() int {
    41  	return int(i)
    42  }
    43  
    44  func (i Integer) Uint64() uint64 {
    45  	return uint64(i)
    46  }
    47  
    48  func (i Integer) Uint32() uint32 {
    49  	return uint32(i)
    50  }