0doc.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. /*
  4. High Performance, Feature-Rich Idiomatic Go 1.4+ codec/encoding library for
  5. binc, msgpack, cbor, json
  6. Supported Serialization formats are:
  7. - msgpack: https://github.com/msgpack/msgpack
  8. - binc: http://github.com/ugorji/binc
  9. - cbor: http://cbor.io http://tools.ietf.org/html/rfc7049
  10. - json: http://json.org http://tools.ietf.org/html/rfc7159
  11. - simple:
  12. To install:
  13. go get github.com/ugorji/go/codec
  14. This package will carefully use 'unsafe' for performance reasons in specific places.
  15. You can build without unsafe use by passing the safe or appengine tag
  16. i.e. 'go install -tags=safe ...'. Note that unsafe is only supported for the last 3
  17. go sdk versions e.g. current go release is go 1.9, so we support unsafe use only from
  18. go 1.7+ . This is because supporting unsafe requires knowledge of implementation details.
  19. For detailed usage information, read the primer at http://ugorji.net/blog/go-codec-primer .
  20. The idiomatic Go support is as seen in other encoding packages in
  21. the standard library (ie json, xml, gob, etc).
  22. Rich Feature Set includes:
  23. - Simple but extremely powerful and feature-rich API
  24. - Support for go1.4 and above, while selectively using newer APIs for later releases
  25. - Good code coverage ( > 70% )
  26. - Very High Performance.
  27. Our extensive benchmarks show us outperforming Gob, Json, Bson, etc by 2-4X.
  28. - Careful selected use of 'unsafe' for targeted performance gains.
  29. 100% mode exists where 'unsafe' is not used at all.
  30. - Lock-free (sans mutex) concurrency for scaling to 100's of cores
  31. - Multiple conversions:
  32. Package coerces types where appropriate
  33. e.g. decode an int in the stream into a float, etc.
  34. - Corner Cases:
  35. Overflows, nil maps/slices, nil values in streams are handled correctly
  36. - Standard field renaming via tags
  37. - Support for omitting empty fields during an encoding
  38. - Encoding from any value and decoding into pointer to any value
  39. (struct, slice, map, primitives, pointers, interface{}, etc)
  40. - Extensions to support efficient encoding/decoding of any named types
  41. - Support encoding.(Binary|Text)(M|Unm)arshaler interfaces
  42. - Decoding without a schema (into a interface{}).
  43. Includes Options to configure what specific map or slice type to use
  44. when decoding an encoded list or map into a nil interface{}
  45. - Encode a struct as an array, and decode struct from an array in the data stream
  46. - Comprehensive support for anonymous fields
  47. - Fast (no-reflection) encoding/decoding of common maps and slices
  48. - Code-generation for faster performance.
  49. - Support binary (e.g. messagepack, cbor) and text (e.g. json) formats
  50. - Support indefinite-length formats to enable true streaming
  51. (for formats which support it e.g. json, cbor)
  52. - Support canonical encoding, where a value is ALWAYS encoded as same sequence of bytes.
  53. This mostly applies to maps, where iteration order is non-deterministic.
  54. - NIL in data stream decoded as zero value
  55. - Never silently skip data when decoding.
  56. User decides whether to return an error or silently skip data when keys or indexes
  57. in the data stream do not map to fields in the struct.
  58. - Detect and error when encoding a cyclic reference (instead of stack overflow shutdown)
  59. - Encode/Decode from/to chan types (for iterative streaming support)
  60. - Drop-in replacement for encoding/json. `json:` key in struct tag supported.
  61. - Provides a RPC Server and Client Codec for net/rpc communication protocol.
  62. - Handle unique idiosyncrasies of codecs e.g.
  63. - For messagepack, configure how ambiguities in handling raw bytes are resolved
  64. - For messagepack, provide rpc server/client codec to support
  65. msgpack-rpc protocol defined at:
  66. https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
  67. Extension Support
  68. Users can register a function to handle the encoding or decoding of
  69. their custom types.
  70. There are no restrictions on what the custom type can be. Some examples:
  71. type BisSet []int
  72. type BitSet64 uint64
  73. type UUID string
  74. type MyStructWithUnexportedFields struct { a int; b bool; c []int; }
  75. type GifImage struct { ... }
  76. As an illustration, MyStructWithUnexportedFields would normally be
  77. encoded as an empty map because it has no exported fields, while UUID
  78. would be encoded as a string. However, with extension support, you can
  79. encode any of these however you like.
  80. Custom Encoding and Decoding
  81. This package maintains symmetry in the encoding and decoding halfs.
  82. We determine how to encode or decode by walking this decision tree
  83. - is type a codec.Selfer?
  84. - is there an extension registered for the type?
  85. - is format binary, and is type a encoding.BinaryMarshaler and BinaryUnmarshaler?
  86. - is format specifically json, and is type a encoding/json.Marshaler and Unmarshaler?
  87. - is format text-based, and type an encoding.TextMarshaler?
  88. - else we use a pair of functions based on the "kind" of the type e.g. map, slice, int64, etc
  89. This symmetry is important to reduce chances of issues happening because the
  90. encoding and decoding sides are out of sync e.g. decoded via very specific
  91. encoding.TextUnmarshaler but encoded via kind-specific generalized mode.
  92. Consequently, if a type only defines one-half of the symetry
  93. (e.g. it implements UnmarshalJSON() but not MarshalJSON() ),
  94. then that type doesn't satisfy the check and we will continue walking down the
  95. decision tree.
  96. RPC
  97. RPC Client and Server Codecs are implemented, so the codecs can be used
  98. with the standard net/rpc package.
  99. Usage
  100. The Handle is SAFE for concurrent READ, but NOT SAFE for concurrent modification.
  101. The Encoder and Decoder are NOT safe for concurrent use.
  102. Consequently, the usage model is basically:
  103. - Create and initialize the Handle before any use.
  104. Once created, DO NOT modify it.
  105. - Multiple Encoders or Decoders can now use the Handle concurrently.
  106. They only read information off the Handle (never write).
  107. - However, each Encoder or Decoder MUST not be used concurrently
  108. - To re-use an Encoder/Decoder, call Reset(...) on it first.
  109. This allows you use state maintained on the Encoder/Decoder.
  110. Sample usage model:
  111. // create and configure Handle
  112. var (
  113. bh codec.BincHandle
  114. mh codec.MsgpackHandle
  115. ch codec.CborHandle
  116. )
  117. mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
  118. // configure extensions
  119. // e.g. for msgpack, define functions and enable Time support for tag 1
  120. // mh.SetExt(reflect.TypeOf(time.Time{}), 1, myExt)
  121. // create and use decoder/encoder
  122. var (
  123. r io.Reader
  124. w io.Writer
  125. b []byte
  126. h = &bh // or mh to use msgpack
  127. )
  128. dec = codec.NewDecoder(r, h)
  129. dec = codec.NewDecoderBytes(b, h)
  130. err = dec.Decode(&v)
  131. enc = codec.NewEncoder(w, h)
  132. enc = codec.NewEncoderBytes(&b, h)
  133. err = enc.Encode(v)
  134. //RPC Server
  135. go func() {
  136. for {
  137. conn, err := listener.Accept()
  138. rpcCodec := codec.GoRpc.ServerCodec(conn, h)
  139. //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h)
  140. rpc.ServeCodec(rpcCodec)
  141. }
  142. }()
  143. //RPC Communication (client side)
  144. conn, err = net.Dial("tcp", "localhost:5555")
  145. rpcCodec := codec.GoRpc.ClientCodec(conn, h)
  146. //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h)
  147. client := rpc.NewClientWithCodec(rpcCodec)
  148. Running Tests
  149. To run tests, use the following:
  150. go test
  151. To run the full suite of tests, use the following:
  152. go test -tags alltests -run Suite
  153. You can run the tag 'safe' to run tests or build in safe mode. e.g.
  154. go test -tags safe -run Json
  155. go test -tags "alltests safe" -run Suite
  156. Running Benchmarks
  157. Please see http://github.com/ugorji/go-codec-bench .
  158. */
  159. package codec