msgpack-go

Message Pack Encoder/Decoder for Golang
git clone git://git.lair.cx/msgpack-go
Log | Files | Refs | LICENSE

encode.go (1618B)


      1 package msgpack
      2 
      3 import "github.com/google/uuid"
      4 
      5 func Marshal(v interface{}) []byte {
      6 	// TODO: Make encoder pool
      7 	return NewEncoder().Encode(v)
      8 }
      9 
     10 type Encoder struct {
     11 	buf []byte
     12 }
     13 
     14 func NewEncoder() *Encoder {
     15 	return &Encoder{
     16 		buf: make([]byte, 0, 512),
     17 	}
     18 }
     19 
     20 func (e *Encoder) Reset() {
     21 	e.buf = e.buf[:0]
     22 }
     23 
     24 func (e *Encoder) Encode(v interface{}) []byte {
     25 	e.Reset()
     26 	e.encode(v)
     27 	return e.buf
     28 }
     29 
     30 func (e *Encoder) encode(v interface{}) {
     31 	if v == nil {
     32 		e.Nil()
     33 		return
     34 	}
     35 	switch v := v.(type) {
     36 	case bool:
     37 		e.Bool(v)
     38 	case int:
     39 		e.Int(v)
     40 	case int8:
     41 		e.Int8(v)
     42 	case int16:
     43 		e.Int16(v)
     44 	case int32:
     45 		e.Int32(v)
     46 	case int64:
     47 		e.Int64(v)
     48 	case uint:
     49 		e.Uint(v)
     50 	case uint8:
     51 		e.Uint8(v)
     52 	case uint16:
     53 		e.Uint16(v)
     54 	case uint32:
     55 		e.Uint32(v)
     56 	case uint64:
     57 		e.Uint64(v)
     58 	case float32:
     59 		e.Float32(v)
     60 	case float64:
     61 		e.Float64(v)
     62 	case string:
     63 		e.String(v)
     64 	case []byte:
     65 		e.Binary(v)
     66 	case Array:
     67 		e.Array(v)
     68 	case Map:
     69 		e.Map(v)
     70 	case uuid.UUID:
     71 		e.Ext(&UUID{v})
     72 	case Extension:
     73 		e.Ext(v)
     74 	default:
     75 		// oh...
     76 		panic("unsupported value")
     77 	}
     78 }
     79 
     80 func (e *Encoder) grow(n int) {
     81 	if cap(e.buf)-len(e.buf) > n {
     82 		return
     83 	}
     84 	newbuf := make([]byte, len(e.buf), cap(e.buf)*2+n)
     85 	copy(newbuf, e.buf)
     86 	e.buf = newbuf
     87 }
     88 
     89 func (e *Encoder) serialize16(v uint16) {
     90 	e.buf = append(e.buf, byte(v>>8), byte(v))
     91 }
     92 
     93 func (e *Encoder) serialize32(v uint32) {
     94 	e.buf = append(e.buf, byte(v>>24), byte(v>>16), byte(v>>8),
     95 		byte(v))
     96 }
     97 
     98 func (e *Encoder) serialize64(v uint64) {
     99 	e.buf = append(e.buf, byte(v>>56), byte(v>>48), byte(v>>40),
    100 		byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
    101 }