header.go 842 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright (C) 2014 The Protocol Authors.
  2. package protocol
  3. import "github.com/calmh/xdr"
  4. type header struct {
  5. version int
  6. msgID int
  7. msgType int
  8. compression bool
  9. }
  10. func (h header) encodeXDR(xw *xdr.Writer) (int, error) {
  11. u := encodeHeader(h)
  12. return xw.WriteUint32(u)
  13. }
  14. func (h *header) decodeXDR(xr *xdr.Reader) error {
  15. u := xr.ReadUint32()
  16. *h = decodeHeader(u)
  17. return xr.Error()
  18. }
  19. func encodeHeader(h header) uint32 {
  20. var isComp uint32
  21. if h.compression {
  22. isComp = 1 << 0 // the zeroth bit is the compression bit
  23. }
  24. return uint32(h.version&0xf)<<28 +
  25. uint32(h.msgID&0xfff)<<16 +
  26. uint32(h.msgType&0xff)<<8 +
  27. isComp
  28. }
  29. func decodeHeader(u uint32) header {
  30. return header{
  31. version: int(u>>28) & 0xf,
  32. msgID: int(u>>16) & 0xfff,
  33. msgType: int(u>>8) & 0xff,
  34. compression: u&1 == 1,
  35. }
  36. }