Don Newton | 98fd881 | 2019-09-23 15:15:02 -0400 | [diff] [blame] | 1 | package goloxi |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/binary" |
| 6 | ) |
| 7 | |
| 8 | type Encoder struct { |
| 9 | buffer *bytes.Buffer |
| 10 | } |
| 11 | |
| 12 | func NewEncoder() *Encoder { |
| 13 | return &Encoder{ |
| 14 | buffer: new(bytes.Buffer), |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | func (e *Encoder) PutChar(c byte) { |
| 19 | e.buffer.WriteByte(c) |
| 20 | } |
| 21 | |
| 22 | func (e *Encoder) PutUint8(i uint8) { |
| 23 | e.buffer.WriteByte(i) |
| 24 | } |
| 25 | |
| 26 | func (e *Encoder) PutUint16(i uint16) { |
| 27 | var tmp [2]byte |
| 28 | binary.BigEndian.PutUint16(tmp[0:2], i) |
| 29 | e.buffer.Write(tmp[:]) |
| 30 | } |
| 31 | |
| 32 | func (e *Encoder) PutUint32(i uint32) { |
| 33 | var tmp [4]byte |
| 34 | binary.BigEndian.PutUint32(tmp[0:4], i) |
| 35 | e.buffer.Write(tmp[:]) |
| 36 | } |
| 37 | |
| 38 | func (e *Encoder) PutUint64(i uint64) { |
| 39 | var tmp [8]byte |
| 40 | binary.BigEndian.PutUint64(tmp[0:8], i) |
| 41 | e.buffer.Write(tmp[:]) |
| 42 | } |
| 43 | |
| 44 | func (e *Encoder) PutUint128(i Uint128) { |
| 45 | var tmp [16]byte |
| 46 | binary.BigEndian.PutUint64(tmp[0:8], i.Hi) |
| 47 | binary.BigEndian.PutUint64(tmp[8:16], i.Lo) |
| 48 | e.buffer.Write(tmp[:]) |
| 49 | } |
| 50 | |
| 51 | func (e *Encoder) Write(b []byte) { |
| 52 | e.buffer.Write(b) |
| 53 | } |
| 54 | |
| 55 | func (e *Encoder) Bytes() []byte { |
| 56 | return e.buffer.Bytes() |
| 57 | } |
| 58 | |
| 59 | func (e *Encoder) SkipAlign() { |
| 60 | length := len(e.buffer.Bytes()) |
| 61 | e.Write(bytes.Repeat([]byte{0}, (length+7)/8*8-length)) |
| 62 | } |