master
go 37 lines 936 Bytes
Raw
1 // INCREMENT codec (method 1) -- 8-byte payload: { u64 value }
2
3 package protocol
4
5 const IncrementPayloadSize = 8
6
7 // IncrementEncode writes a u64 value into buf. Returns 8 on success, 0 if
8 // buf is too small.
9 func IncrementEncode(value uint64, buf []byte) int {
10 if len(buf) < IncrementPayloadSize {
11 return 0
12 }
13 ne.PutUint64(buf[:8], value)
14 return IncrementPayloadSize
15 }
16
17 // IncrementDecode reads a u64 value from buf.
18 func IncrementDecode(buf []byte) (uint64, error) {
19 if len(buf) < IncrementPayloadSize {
20 return 0, ErrTruncated
21 }
22 return ne.Uint64(buf[:8]), nil
23 }
24
25 // DispatchIncrement decodes request, calls handler, encodes response.
26 func DispatchIncrement(req []byte, resp []byte, handler func(uint64) (uint64, bool)) (int, bool) {
27 value, err := IncrementDecode(req)
28 if err != nil {
29 return 0, false
30 }
31 result, ok := handler(value)
32 if !ok {
33 return 0, false
34 }
35 n := IncrementEncode(result, resp)
36 return n, n > 0
37 }