0doc.go 8.9 KB

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