doc.go 8.8 KB

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