doc.go 8.7 KB

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