byteio - littleendianwriter_varint.go
1 package byteio
2
3 // WriteUintX writes the unsigned integer using a variable number of bytes
4 // This variable encoding uses the first seven bits of each byte to encode
5 // successive bits of the number, and the last bit to indicate that another
6 // byte is to be read. The exception to this is the ninth byte, which uses its
7 // highest bit to store the 64th bit of the number.
8 // To allow for unique encodings of all numbers, as well as having a smaller
9 // encoding for some numbers, the carry bit is also part of the number.
10 // If there is another byte of the encoding then, by definition, the number
11 // must be higher than what has currently been decoded. Thus, the next byte
12 // starts at the next number.
13 // For example, without this modification, the number 5 could be encoded as any
14 // of the following: -
15 // 0x05
16 // 0x85, 0x00
17 // 0x85, 0x80, 0x00
18 // 0x85, 0x80, 0x80, 0x00
19 // etc.
20 //
21 // By having the carry bit do double duty, adding 1 to the value of all bytes
22 // where the carry bit is set, the only valid encoding of 5 becomes 0x05.
23 func (e *LittleEndianWriter) WriteUintX(d uint64) (int, error) {
24 var pos int
25 for ; d > 127 && pos < 8; pos++ {
26 e.buffer[pos] = byte(d&0x7f) | 0x80
27 d >>= 7
28 d--
29 }
30 e.buffer[pos] = byte(d)
31 return e.Write(e.buffer[:pos+1])
32 }
33
34 // WriteIntX writes the integer using a variable number of bytes
35 func (e *LittleEndianWriter) WriteIntX(d int64) (int, error) {
36 return e.WriteUintX(zigzag(d))
37 }
38