header.go 1003 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package protocol
  5. import "github.com/calmh/xdr"
  6. type header struct {
  7. version int
  8. msgID int
  9. msgType int
  10. compression bool
  11. }
  12. func (h header) encodeXDR(xw *xdr.Writer) (int, error) {
  13. u := encodeHeader(h)
  14. return xw.WriteUint32(u)
  15. }
  16. func (h *header) decodeXDR(xr *xdr.Reader) error {
  17. u := xr.ReadUint32()
  18. *h = decodeHeader(u)
  19. return xr.Error()
  20. }
  21. func encodeHeader(h header) uint32 {
  22. var isComp uint32
  23. if h.compression {
  24. isComp = 1 << 0 // the zeroth bit is the compression bit
  25. }
  26. return uint32(h.version&0xf)<<28 +
  27. uint32(h.msgID&0xfff)<<16 +
  28. uint32(h.msgType&0xff)<<8 +
  29. isComp
  30. }
  31. func decodeHeader(u uint32) header {
  32. return header{
  33. version: int(u>>28) & 0xf,
  34. msgID: int(u>>16) & 0xfff,
  35. msgType: int(u>>8) & 0xff,
  36. compression: u&1 == 1,
  37. }
  38. }