Tizen_4.0 base
[platform/upstream/docker-engine.git] / vendor / github.com / tinylib / msgp / msgp / write.go
1 package msgp
2
3 import (
4         "errors"
5         "fmt"
6         "io"
7         "math"
8         "reflect"
9         "sync"
10         "time"
11 )
12
13 func abs(i int64) int64 {
14         if i < 0 {
15                 return -i
16         }
17         return i
18 }
19
20 // Sizer is an interface implemented
21 // by types that can estimate their
22 // size when MessagePack encoded.
23 // This interface is optional, but
24 // encoding/marshaling implementations
25 // may use this as a way to pre-allocate
26 // memory for serialization.
27 type Sizer interface {
28         Msgsize() int
29 }
30
31 var (
32         // Nowhere is an io.Writer to nowhere
33         Nowhere io.Writer = nwhere{}
34
35         btsType    = reflect.TypeOf(([]byte)(nil))
36         writerPool = sync.Pool{
37                 New: func() interface{} {
38                         return &Writer{buf: make([]byte, 2048)}
39                 },
40         }
41 )
42
43 func popWriter(w io.Writer) *Writer {
44         wr := writerPool.Get().(*Writer)
45         wr.Reset(w)
46         return wr
47 }
48
49 func pushWriter(wr *Writer) {
50         wr.w = nil
51         wr.wloc = 0
52         writerPool.Put(wr)
53 }
54
55 // freeW frees a writer for use
56 // by other processes. It is not necessary
57 // to call freeW on a writer. However, maintaining
58 // a reference to a *Writer after calling freeW on
59 // it will cause undefined behavior.
60 func freeW(w *Writer) { pushWriter(w) }
61
62 // Require ensures that cap(old)-len(old) >= extra
63 func Require(old []byte, extra int) []byte {
64         if cap(old)-len(old) >= extra {
65                 return old
66         }
67         if len(old) == 0 {
68                 return make([]byte, 0, extra)
69         }
70         n := make([]byte, len(old), cap(old)-len(old)+extra)
71         copy(n, old)
72         return n
73 }
74
75 // nowhere writer
76 type nwhere struct{}
77
78 func (n nwhere) Write(p []byte) (int, error) { return len(p), nil }
79
80 // Marshaler is the interface implemented
81 // by types that know how to marshal themselves
82 // as MessagePack. MarshalMsg appends the marshalled
83 // form of the object to the provided
84 // byte slice, returning the extended
85 // slice and any errors encountered.
86 type Marshaler interface {
87         MarshalMsg([]byte) ([]byte, error)
88 }
89
90 // Encodable is the interface implemented
91 // by types that know how to write themselves
92 // as MessagePack using a *msgp.Writer.
93 type Encodable interface {
94         EncodeMsg(*Writer) error
95 }
96
97 // Writer is a buffered writer
98 // that can be used to write
99 // MessagePack objects to an io.Writer.
100 // You must call *Writer.Flush() in order
101 // to flush all of the buffered data
102 // to the underlying writer.
103 type Writer struct {
104         w    io.Writer
105         buf  []byte
106         wloc int
107 }
108
109 // NewWriter returns a new *Writer.
110 func NewWriter(w io.Writer) *Writer {
111         if wr, ok := w.(*Writer); ok {
112                 return wr
113         }
114         return popWriter(w)
115 }
116
117 // NewWriterSize returns a writer with a custom buffer size.
118 func NewWriterSize(w io.Writer, sz int) *Writer {
119         // we must be able to require() 18
120         // contiguous bytes, so that is the
121         // practical minimum buffer size
122         if sz < 18 {
123                 sz = 18
124         }
125
126         return &Writer{
127                 w:   w,
128                 buf: make([]byte, sz),
129         }
130 }
131
132 // Encode encodes an Encodable to an io.Writer.
133 func Encode(w io.Writer, e Encodable) error {
134         wr := NewWriter(w)
135         err := e.EncodeMsg(wr)
136         if err == nil {
137                 err = wr.Flush()
138         }
139         freeW(wr)
140         return err
141 }
142
143 func (mw *Writer) flush() error {
144         if mw.wloc == 0 {
145                 return nil
146         }
147         n, err := mw.w.Write(mw.buf[:mw.wloc])
148         if err != nil {
149                 if n > 0 {
150                         mw.wloc = copy(mw.buf, mw.buf[n:mw.wloc])
151                 }
152                 return err
153         }
154         mw.wloc = 0
155         return nil
156 }
157
158 // Flush flushes all of the buffered
159 // data to the underlying writer.
160 func (mw *Writer) Flush() error { return mw.flush() }
161
162 // Buffered returns the number bytes in the write buffer
163 func (mw *Writer) Buffered() int { return len(mw.buf) - mw.wloc }
164
165 func (mw *Writer) avail() int { return len(mw.buf) - mw.wloc }
166
167 func (mw *Writer) bufsize() int { return len(mw.buf) }
168
169 // NOTE: this should only be called with
170 // a number that is guaranteed to be less than
171 // len(mw.buf). typically, it is called with a constant.
172 //
173 // NOTE: this is a hot code path
174 func (mw *Writer) require(n int) (int, error) {
175         c := len(mw.buf)
176         wl := mw.wloc
177         if c-wl < n {
178                 if err := mw.flush(); err != nil {
179                         return 0, err
180                 }
181                 wl = mw.wloc
182         }
183         mw.wloc += n
184         return wl, nil
185 }
186
187 // push one byte onto the buffer
188 //
189 // NOTE: this is a hot code path
190 func (mw *Writer) push(b byte) error {
191         if mw.wloc == len(mw.buf) {
192                 if err := mw.flush(); err != nil {
193                         return err
194                 }
195         }
196         mw.buf[mw.wloc] = b
197         mw.wloc++
198         return nil
199 }
200
201 func (mw *Writer) prefix8(b byte, u uint8) error {
202         const need = 2
203         if len(mw.buf)-mw.wloc < need {
204                 if err := mw.flush(); err != nil {
205                         return err
206                 }
207         }
208         prefixu8(mw.buf[mw.wloc:], b, u)
209         mw.wloc += need
210         return nil
211 }
212
213 func (mw *Writer) prefix16(b byte, u uint16) error {
214         const need = 3
215         if len(mw.buf)-mw.wloc < need {
216                 if err := mw.flush(); err != nil {
217                         return err
218                 }
219         }
220         prefixu16(mw.buf[mw.wloc:], b, u)
221         mw.wloc += need
222         return nil
223 }
224
225 func (mw *Writer) prefix32(b byte, u uint32) error {
226         const need = 5
227         if len(mw.buf)-mw.wloc < need {
228                 if err := mw.flush(); err != nil {
229                         return err
230                 }
231         }
232         prefixu32(mw.buf[mw.wloc:], b, u)
233         mw.wloc += need
234         return nil
235 }
236
237 func (mw *Writer) prefix64(b byte, u uint64) error {
238         const need = 9
239         if len(mw.buf)-mw.wloc < need {
240                 if err := mw.flush(); err != nil {
241                         return err
242                 }
243         }
244         prefixu64(mw.buf[mw.wloc:], b, u)
245         mw.wloc += need
246         return nil
247 }
248
249 // Write implements io.Writer, and writes
250 // data directly to the buffer.
251 func (mw *Writer) Write(p []byte) (int, error) {
252         l := len(p)
253         if mw.avail() < l {
254                 if err := mw.flush(); err != nil {
255                         return 0, err
256                 }
257                 if l > len(mw.buf) {
258                         return mw.w.Write(p)
259                 }
260         }
261         mw.wloc += copy(mw.buf[mw.wloc:], p)
262         return l, nil
263 }
264
265 // implements io.WriteString
266 func (mw *Writer) writeString(s string) error {
267         l := len(s)
268         if mw.avail() < l {
269                 if err := mw.flush(); err != nil {
270                         return err
271                 }
272                 if l > len(mw.buf) {
273                         _, err := io.WriteString(mw.w, s)
274                         return err
275                 }
276         }
277         mw.wloc += copy(mw.buf[mw.wloc:], s)
278         return nil
279 }
280
281 // Reset changes the underlying writer used by the Writer
282 func (mw *Writer) Reset(w io.Writer) {
283         mw.buf = mw.buf[:cap(mw.buf)]
284         mw.w = w
285         mw.wloc = 0
286 }
287
288 // WriteMapHeader writes a map header of the given
289 // size to the writer
290 func (mw *Writer) WriteMapHeader(sz uint32) error {
291         switch {
292         case sz < 16:
293                 return mw.push(wfixmap(uint8(sz)))
294         case sz < math.MaxUint16:
295                 return mw.prefix16(mmap16, uint16(sz))
296         default:
297                 return mw.prefix32(mmap32, sz)
298         }
299 }
300
301 // WriteArrayHeader writes an array header of the
302 // given size to the writer
303 func (mw *Writer) WriteArrayHeader(sz uint32) error {
304         switch {
305         case sz < 16:
306                 return mw.push(wfixarray(uint8(sz)))
307         case sz < math.MaxUint16:
308                 return mw.prefix16(marray16, uint16(sz))
309         default:
310                 return mw.prefix32(marray32, sz)
311         }
312 }
313
314 // WriteNil writes a nil byte to the buffer
315 func (mw *Writer) WriteNil() error {
316         return mw.push(mnil)
317 }
318
319 // WriteFloat64 writes a float64 to the writer
320 func (mw *Writer) WriteFloat64(f float64) error {
321         return mw.prefix64(mfloat64, math.Float64bits(f))
322 }
323
324 // WriteFloat32 writes a float32 to the writer
325 func (mw *Writer) WriteFloat32(f float32) error {
326         return mw.prefix32(mfloat32, math.Float32bits(f))
327 }
328
329 // WriteInt64 writes an int64 to the writer
330 func (mw *Writer) WriteInt64(i int64) error {
331         a := abs(i)
332         switch {
333         case i < 0 && i > -32:
334                 return mw.push(wnfixint(int8(i)))
335         case i >= 0 && i < 128:
336                 return mw.push(wfixint(uint8(i)))
337         case a < math.MaxInt8:
338                 return mw.prefix8(mint8, uint8(i))
339         case a < math.MaxInt16:
340                 return mw.prefix16(mint16, uint16(i))
341         case a < math.MaxInt32:
342                 return mw.prefix32(mint32, uint32(i))
343         default:
344                 return mw.prefix64(mint64, uint64(i))
345         }
346 }
347
348 // WriteInt8 writes an int8 to the writer
349 func (mw *Writer) WriteInt8(i int8) error { return mw.WriteInt64(int64(i)) }
350
351 // WriteInt16 writes an int16 to the writer
352 func (mw *Writer) WriteInt16(i int16) error { return mw.WriteInt64(int64(i)) }
353
354 // WriteInt32 writes an int32 to the writer
355 func (mw *Writer) WriteInt32(i int32) error { return mw.WriteInt64(int64(i)) }
356
357 // WriteInt writes an int to the writer
358 func (mw *Writer) WriteInt(i int) error { return mw.WriteInt64(int64(i)) }
359
360 // WriteUint64 writes a uint64 to the writer
361 func (mw *Writer) WriteUint64(u uint64) error {
362         switch {
363         case u < (1 << 7):
364                 return mw.push(wfixint(uint8(u)))
365         case u < math.MaxUint8:
366                 return mw.prefix8(muint8, uint8(u))
367         case u < math.MaxUint16:
368                 return mw.prefix16(muint16, uint16(u))
369         case u < math.MaxUint32:
370                 return mw.prefix32(muint32, uint32(u))
371         default:
372                 return mw.prefix64(muint64, u)
373         }
374 }
375
376 // WriteByte is analagous to WriteUint8
377 func (mw *Writer) WriteByte(u byte) error { return mw.WriteUint8(uint8(u)) }
378
379 // WriteUint8 writes a uint8 to the writer
380 func (mw *Writer) WriteUint8(u uint8) error { return mw.WriteUint64(uint64(u)) }
381
382 // WriteUint16 writes a uint16 to the writer
383 func (mw *Writer) WriteUint16(u uint16) error { return mw.WriteUint64(uint64(u)) }
384
385 // WriteUint32 writes a uint32 to the writer
386 func (mw *Writer) WriteUint32(u uint32) error { return mw.WriteUint64(uint64(u)) }
387
388 // WriteUint writes a uint to the writer
389 func (mw *Writer) WriteUint(u uint) error { return mw.WriteUint64(uint64(u)) }
390
391 // WriteBytes writes binary as 'bin' to the writer
392 func (mw *Writer) WriteBytes(b []byte) error {
393         sz := uint32(len(b))
394         var err error
395         switch {
396         case sz < math.MaxUint8:
397                 err = mw.prefix8(mbin8, uint8(sz))
398         case sz < math.MaxUint16:
399                 err = mw.prefix16(mbin16, uint16(sz))
400         default:
401                 err = mw.prefix32(mbin32, sz)
402         }
403         if err != nil {
404                 return err
405         }
406         _, err = mw.Write(b)
407         return err
408 }
409
410 // WriteBool writes a bool to the writer
411 func (mw *Writer) WriteBool(b bool) error {
412         if b {
413                 return mw.push(mtrue)
414         }
415         return mw.push(mfalse)
416 }
417
418 // WriteString writes a messagepack string to the writer.
419 // (This is NOT an implementation of io.StringWriter)
420 func (mw *Writer) WriteString(s string) error {
421         sz := uint32(len(s))
422         var err error
423         switch {
424         case sz < 32:
425                 err = mw.push(wfixstr(uint8(sz)))
426         case sz < math.MaxUint8:
427                 err = mw.prefix8(mstr8, uint8(sz))
428         case sz < math.MaxUint16:
429                 err = mw.prefix16(mstr16, uint16(sz))
430         default:
431                 err = mw.prefix32(mstr32, sz)
432         }
433         if err != nil {
434                 return err
435         }
436         return mw.writeString(s)
437 }
438
439 // WriteComplex64 writes a complex64 to the writer
440 func (mw *Writer) WriteComplex64(f complex64) error {
441         o, err := mw.require(10)
442         if err != nil {
443                 return err
444         }
445         mw.buf[o] = mfixext8
446         mw.buf[o+1] = Complex64Extension
447         big.PutUint32(mw.buf[o+2:], math.Float32bits(real(f)))
448         big.PutUint32(mw.buf[o+6:], math.Float32bits(imag(f)))
449         return nil
450 }
451
452 // WriteComplex128 writes a complex128 to the writer
453 func (mw *Writer) WriteComplex128(f complex128) error {
454         o, err := mw.require(18)
455         if err != nil {
456                 return err
457         }
458         mw.buf[o] = mfixext16
459         mw.buf[o+1] = Complex128Extension
460         big.PutUint64(mw.buf[o+2:], math.Float64bits(real(f)))
461         big.PutUint64(mw.buf[o+10:], math.Float64bits(imag(f)))
462         return nil
463 }
464
465 // WriteMapStrStr writes a map[string]string to the writer
466 func (mw *Writer) WriteMapStrStr(mp map[string]string) (err error) {
467         err = mw.WriteMapHeader(uint32(len(mp)))
468         if err != nil {
469                 return
470         }
471         for key, val := range mp {
472                 err = mw.WriteString(key)
473                 if err != nil {
474                         return
475                 }
476                 err = mw.WriteString(val)
477                 if err != nil {
478                         return
479                 }
480         }
481         return nil
482 }
483
484 // WriteMapStrIntf writes a map[string]interface to the writer
485 func (mw *Writer) WriteMapStrIntf(mp map[string]interface{}) (err error) {
486         err = mw.WriteMapHeader(uint32(len(mp)))
487         if err != nil {
488                 return
489         }
490         for key, val := range mp {
491                 err = mw.WriteString(key)
492                 if err != nil {
493                         return
494                 }
495                 err = mw.WriteIntf(val)
496                 if err != nil {
497                         return
498                 }
499         }
500         return
501 }
502
503 // WriteTime writes a time.Time object to the wire.
504 //
505 // Time is encoded as Unix time, which means that
506 // location (time zone) data is removed from the object.
507 // The encoded object itself is 12 bytes: 8 bytes for
508 // a big-endian 64-bit integer denoting seconds
509 // elapsed since "zero" Unix time, followed by 4 bytes
510 // for a big-endian 32-bit signed integer denoting
511 // the nanosecond offset of the time. This encoding
512 // is intended to ease portability accross languages.
513 // (Note that this is *not* the standard time.Time
514 // binary encoding, because its implementation relies
515 // heavily on the internal representation used by the
516 // time package.)
517 func (mw *Writer) WriteTime(t time.Time) error {
518         t = t.UTC()
519         o, err := mw.require(15)
520         if err != nil {
521                 return err
522         }
523         mw.buf[o] = mext8
524         mw.buf[o+1] = 12
525         mw.buf[o+2] = TimeExtension
526         putUnix(mw.buf[o+3:], t.Unix(), int32(t.Nanosecond()))
527         return nil
528 }
529
530 // WriteIntf writes the concrete type of 'v'.
531 // WriteIntf will error if 'v' is not one of the following:
532 //  - A bool, float, string, []byte, int, uint, or complex
533 //  - A map of supported types (with string keys)
534 //  - An array or slice of supported types
535 //  - A pointer to a supported type
536 //  - A type that satisfies the msgp.Encodable interface
537 //  - A type that satisfies the msgp.Extension interface
538 func (mw *Writer) WriteIntf(v interface{}) error {
539         if v == nil {
540                 return mw.WriteNil()
541         }
542         switch v := v.(type) {
543
544         // preferred interfaces
545
546         case Encodable:
547                 return v.EncodeMsg(mw)
548         case Extension:
549                 return mw.WriteExtension(v)
550
551         // concrete types
552
553         case bool:
554                 return mw.WriteBool(v)
555         case float32:
556                 return mw.WriteFloat32(v)
557         case float64:
558                 return mw.WriteFloat64(v)
559         case complex64:
560                 return mw.WriteComplex64(v)
561         case complex128:
562                 return mw.WriteComplex128(v)
563         case uint8:
564                 return mw.WriteUint8(v)
565         case uint16:
566                 return mw.WriteUint16(v)
567         case uint32:
568                 return mw.WriteUint32(v)
569         case uint64:
570                 return mw.WriteUint64(v)
571         case uint:
572                 return mw.WriteUint(v)
573         case int8:
574                 return mw.WriteInt8(v)
575         case int16:
576                 return mw.WriteInt16(v)
577         case int32:
578                 return mw.WriteInt32(v)
579         case int64:
580                 return mw.WriteInt64(v)
581         case int:
582                 return mw.WriteInt(v)
583         case string:
584                 return mw.WriteString(v)
585         case []byte:
586                 return mw.WriteBytes(v)
587         case map[string]string:
588                 return mw.WriteMapStrStr(v)
589         case map[string]interface{}:
590                 return mw.WriteMapStrIntf(v)
591         case time.Time:
592                 return mw.WriteTime(v)
593         }
594
595         val := reflect.ValueOf(v)
596         if !isSupported(val.Kind()) || !val.IsValid() {
597                 return fmt.Errorf("msgp: type %s not supported", val)
598         }
599
600         switch val.Kind() {
601         case reflect.Ptr:
602                 if val.IsNil() {
603                         return mw.WriteNil()
604                 }
605                 return mw.WriteIntf(val.Elem().Interface())
606         case reflect.Slice:
607                 return mw.writeSlice(val)
608         case reflect.Map:
609                 return mw.writeMap(val)
610         }
611         return &ErrUnsupportedType{val.Type()}
612 }
613
614 func (mw *Writer) writeMap(v reflect.Value) (err error) {
615         if v.Elem().Kind() != reflect.String {
616                 return errors.New("msgp: map keys must be strings")
617         }
618         ks := v.MapKeys()
619         err = mw.WriteMapHeader(uint32(len(ks)))
620         if err != nil {
621                 return
622         }
623         for _, key := range ks {
624                 val := v.MapIndex(key)
625                 err = mw.WriteString(key.String())
626                 if err != nil {
627                         return
628                 }
629                 err = mw.WriteIntf(val.Interface())
630                 if err != nil {
631                         return
632                 }
633         }
634         return
635 }
636
637 func (mw *Writer) writeSlice(v reflect.Value) (err error) {
638         // is []byte
639         if v.Type().ConvertibleTo(btsType) {
640                 return mw.WriteBytes(v.Bytes())
641         }
642
643         sz := uint32(v.Len())
644         err = mw.WriteArrayHeader(sz)
645         if err != nil {
646                 return
647         }
648         for i := uint32(0); i < sz; i++ {
649                 err = mw.WriteIntf(v.Index(int(i)).Interface())
650                 if err != nil {
651                         return
652                 }
653         }
654         return
655 }
656
657 func (mw *Writer) writeStruct(v reflect.Value) error {
658         if enc, ok := v.Interface().(Encodable); ok {
659                 return enc.EncodeMsg(mw)
660         }
661         return fmt.Errorf("msgp: unsupported type: %s", v.Type())
662 }
663
664 func (mw *Writer) writeVal(v reflect.Value) error {
665         if !isSupported(v.Kind()) {
666                 return fmt.Errorf("msgp: msgp/enc: type %q not supported", v.Type())
667         }
668
669         // shortcut for nil values
670         if v.IsNil() {
671                 return mw.WriteNil()
672         }
673         switch v.Kind() {
674         case reflect.Bool:
675                 return mw.WriteBool(v.Bool())
676
677         case reflect.Float32, reflect.Float64:
678                 return mw.WriteFloat64(v.Float())
679
680         case reflect.Complex64, reflect.Complex128:
681                 return mw.WriteComplex128(v.Complex())
682
683         case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8:
684                 return mw.WriteInt64(v.Int())
685
686         case reflect.Interface, reflect.Ptr:
687                 if v.IsNil() {
688                         mw.WriteNil()
689                 }
690                 return mw.writeVal(v.Elem())
691
692         case reflect.Map:
693                 return mw.writeMap(v)
694
695         case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8:
696                 return mw.WriteUint64(v.Uint())
697
698         case reflect.String:
699                 return mw.WriteString(v.String())
700
701         case reflect.Slice, reflect.Array:
702                 return mw.writeSlice(v)
703
704         case reflect.Struct:
705                 return mw.writeStruct(v)
706
707         }
708         return fmt.Errorf("msgp: msgp/enc: type %q not supported", v.Type())
709 }
710
711 // is the reflect.Kind encodable?
712 func isSupported(k reflect.Kind) bool {
713         switch k {
714         case reflect.Func, reflect.Chan, reflect.Invalid, reflect.UnsafePointer:
715                 return false
716         default:
717                 return true
718         }
719 }
720
721 // GuessSize guesses the size of the underlying
722 // value of 'i'. If the underlying value is not
723 // a simple builtin (or []byte), GuessSize defaults
724 // to 512.
725 func GuessSize(i interface{}) int {
726         if i == nil {
727                 return NilSize
728         }
729
730         switch i := i.(type) {
731         case Sizer:
732                 return i.Msgsize()
733         case Extension:
734                 return ExtensionPrefixSize + i.Len()
735         case float64:
736                 return Float64Size
737         case float32:
738                 return Float32Size
739         case uint8, uint16, uint32, uint64, uint:
740                 return UintSize
741         case int8, int16, int32, int64, int:
742                 return IntSize
743         case []byte:
744                 return BytesPrefixSize + len(i)
745         case string:
746                 return StringPrefixSize + len(i)
747         case complex64:
748                 return Complex64Size
749         case complex128:
750                 return Complex128Size
751         case bool:
752                 return BoolSize
753         case map[string]interface{}:
754                 s := MapHeaderSize
755                 for key, val := range i {
756                         s += StringPrefixSize + len(key) + GuessSize(val)
757                 }
758                 return s
759         case map[string]string:
760                 s := MapHeaderSize
761                 for key, val := range i {
762                         s += 2*StringPrefixSize + len(key) + len(val)
763                 }
764                 return s
765         default:
766                 return 512
767         }
768 }