int.go 844 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package peer_protocol
  2. import (
  3. "encoding/binary"
  4. "io"
  5. "math"
  6. "github.com/pkg/errors"
  7. )
  8. type (
  9. // An alias for the underlying type of Integer. This is needed for fuzzing.
  10. IntegerKind = uint32
  11. Integer IntegerKind
  12. )
  13. const IntegerMax = math.MaxUint32
  14. func (i *Integer) UnmarshalBinary(b []byte) error {
  15. if len(b) != 4 {
  16. return errors.New("expected 4 bytes")
  17. }
  18. *i = Integer(binary.BigEndian.Uint32(b))
  19. return nil
  20. }
  21. func (i *Integer) Read(r io.Reader) error {
  22. var b [4]byte
  23. n, err := io.ReadFull(r, b[:])
  24. if err == nil {
  25. if n != 4 {
  26. panic(n)
  27. }
  28. return i.UnmarshalBinary(b[:])
  29. }
  30. return err
  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. func (i Integer) Uint64() uint64 {
  37. return uint64(i)
  38. }
  39. func (i Integer) Uint32() uint32 {
  40. return uint32(i)
  41. }