syncthing/internal/protocol/header.go

46 lines
1003 B
Go
Raw Normal View History

2014-07-12 22:45:33 +00:00
// Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
// All rights reserved. Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
2014-06-01 20:50:14 +00:00
2014-02-20 16:40:15 +00:00
package protocol
2014-08-01 11:12:54 +00:00
import "github.com/calmh/xdr"
2014-02-20 16:40:15 +00:00
type header struct {
version int
msgID int
msgType int
compression bool
2014-02-20 16:40:15 +00:00
}
func (h header) encodeXDR(xw *xdr.Writer) (int, error) {
u := encodeHeader(h)
return xw.WriteUint32(u)
}
func (h *header) decodeXDR(xr *xdr.Reader) error {
u := xr.ReadUint32()
*h = decodeHeader(u)
return xr.Error()
}
func encodeHeader(h header) uint32 {
var isComp uint32
if h.compression {
isComp = 1 << 0 // the zeroth bit is the compression bit
}
2014-02-20 16:40:15 +00:00
return uint32(h.version&0xf)<<28 +
uint32(h.msgID&0xfff)<<16 +
uint32(h.msgType&0xff)<<8 +
isComp
2014-02-20 16:40:15 +00:00
}
func decodeHeader(u uint32) header {
return header{
version: int(u>>28) & 0xf,
msgID: int(u>>16) & 0xfff,
msgType: int(u>>8) & 0xff,
compression: u&1 == 1,
2014-02-20 16:40:15 +00:00
}
}