helper.go 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691
  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. package codec
  4. // Contains code shared by both encode and decode.
  5. // Some shared ideas around encoding/decoding
  6. // ------------------------------------------
  7. //
  8. // If an interface{} is passed, we first do a type assertion to see if it is
  9. // a primitive type or a map/slice of primitive types, and use a fastpath to handle it.
  10. //
  11. // If we start with a reflect.Value, we are already in reflect.Value land and
  12. // will try to grab the function for the underlying Type and directly call that function.
  13. // This is more performant than calling reflect.Value.Interface().
  14. //
  15. // This still helps us bypass many layers of reflection, and give best performance.
  16. //
  17. // Containers
  18. // ------------
  19. // Containers in the stream are either associative arrays (key-value pairs) or
  20. // regular arrays (indexed by incrementing integers).
  21. //
  22. // Some streams support indefinite-length containers, and use a breaking
  23. // byte-sequence to denote that the container has come to an end.
  24. //
  25. // Some streams also are text-based, and use explicit separators to denote the
  26. // end/beginning of different values.
  27. //
  28. // During encode, we use a high-level condition to determine how to iterate through
  29. // the container. That decision is based on whether the container is text-based (with
  30. // separators) or binary (without separators). If binary, we do not even call the
  31. // encoding of separators.
  32. //
  33. // During decode, we use a different high-level condition to determine how to iterate
  34. // through the containers. That decision is based on whether the stream contained
  35. // a length prefix, or if it used explicit breaks. If length-prefixed, we assume that
  36. // it has to be binary, and we do not even try to read separators.
  37. //
  38. // Philosophy
  39. // ------------
  40. // On decode, this codec will update containers appropriately:
  41. // - If struct, update fields from stream into fields of struct.
  42. // If field in stream not found in struct, handle appropriately (based on option).
  43. // If a struct field has no corresponding value in the stream, leave it AS IS.
  44. // If nil in stream, set value to nil/zero value.
  45. // - If map, update map from stream.
  46. // If the stream value is NIL, set the map to nil.
  47. // - if slice, try to update up to length of array in stream.
  48. // if container len is less than stream array length,
  49. // and container cannot be expanded, handled (based on option).
  50. // This means you can decode 4-element stream array into 1-element array.
  51. //
  52. // ------------------------------------
  53. // On encode, user can specify omitEmpty. This means that the value will be omitted
  54. // if the zero value. The problem may occur during decode, where omitted values do not affect
  55. // the value being decoded into. This means that if decoding into a struct with an
  56. // int field with current value=5, and the field is omitted in the stream, then after
  57. // decoding, the value will still be 5 (not 0).
  58. // omitEmpty only works if you guarantee that you always decode into zero-values.
  59. //
  60. // ------------------------------------
  61. // We could have truncated a map to remove keys not available in the stream,
  62. // or set values in the struct which are not in the stream to their zero values.
  63. // We decided against it because there is no efficient way to do it.
  64. // We may introduce it as an option later.
  65. // However, that will require enabling it for both runtime and code generation modes.
  66. //
  67. // To support truncate, we need to do 2 passes over the container:
  68. // map
  69. // - first collect all keys (e.g. in k1)
  70. // - for each key in stream, mark k1 that the key should not be removed
  71. // - after updating map, do second pass and call delete for all keys in k1 which are not marked
  72. // struct:
  73. // - for each field, track the *typeInfo s1
  74. // - iterate through all s1, and for each one not marked, set value to zero
  75. // - this involves checking the possible anonymous fields which are nil ptrs.
  76. // too much work.
  77. //
  78. // ------------------------------------------
  79. // Error Handling is done within the library using panic.
  80. //
  81. // This way, the code doesn't have to keep checking if an error has happened,
  82. // and we don't have to keep sending the error value along with each call
  83. // or storing it in the En|Decoder and checking it constantly along the way.
  84. //
  85. // The disadvantage is that small functions which use panics cannot be inlined.
  86. // The code accounts for that by only using panics behind an interface;
  87. // since interface calls cannot be inlined, this is irrelevant.
  88. //
  89. // We considered storing the error is En|Decoder.
  90. // - once it has its err field set, it cannot be used again.
  91. // - panicing will be optional, controlled by const flag.
  92. // - code should always check error first and return early.
  93. // We eventually decided against it as it makes the code clumsier to always
  94. // check for these error conditions.
  95. import (
  96. "bytes"
  97. "encoding"
  98. "encoding/binary"
  99. "errors"
  100. "fmt"
  101. "io"
  102. "math"
  103. "reflect"
  104. "sort"
  105. "strconv"
  106. "strings"
  107. "sync"
  108. "sync/atomic"
  109. "time"
  110. )
  111. const (
  112. scratchByteArrayLen = 32
  113. // initCollectionCap = 16 // 32 is defensive. 16 is preferred.
  114. // Support encoding.(Binary|Text)(Unm|M)arshaler.
  115. // This constant flag will enable or disable it.
  116. supportMarshalInterfaces = true
  117. // for debugging, set this to false, to catch panic traces.
  118. // Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic.
  119. recoverPanicToErr = true
  120. // arrayCacheLen is the length of the cache used in encoder or decoder for
  121. // allowing zero-alloc initialization.
  122. // arrayCacheLen = 8
  123. // size of the cacheline: defaulting to value for archs: amd64, arm64, 386
  124. // should use "runtime/internal/sys".CacheLineSize, but that is not exposed.
  125. cacheLineSize = 64
  126. wordSizeBits = 32 << (^uint(0) >> 63) // strconv.IntSize
  127. wordSize = wordSizeBits / 8
  128. // so structFieldInfo fits into 8 bytes
  129. maxLevelsEmbedding = 14
  130. // useFinalizers=true configures finalizers to release pool'ed resources
  131. // acquired by Encoder/Decoder during their GC.
  132. //
  133. // Note that calling SetFinalizer is always expensive,
  134. // as code must be run on the systemstack even for SetFinalizer(t, nil).
  135. //
  136. // We document that folks SHOULD call Release() when done, or they can
  137. // explicitly call SetFinalizer themselves e.g.
  138. // runtime.SetFinalizer(e, (*Encoder).Release)
  139. // runtime.SetFinalizer(d, (*Decoder).Release)
  140. useFinalizers = false
  141. )
  142. var oneByteArr [1]byte
  143. var zeroByteSlice = oneByteArr[:0:0]
  144. var codecgen bool
  145. var refBitset bitset256
  146. var pool pooler
  147. var panicv panicHdl
  148. func init() {
  149. pool.init()
  150. refBitset.set(byte(reflect.Map))
  151. refBitset.set(byte(reflect.Ptr))
  152. refBitset.set(byte(reflect.Func))
  153. refBitset.set(byte(reflect.Chan))
  154. }
  155. type handleFlag uint8
  156. const (
  157. initedHandleFlag handleFlag = 1 << iota
  158. binaryHandleFlag
  159. jsonHandleFlag
  160. )
  161. type clsErr struct {
  162. closed bool // is it closed?
  163. errClosed error // error on closing
  164. }
  165. // type entryType uint8
  166. // const (
  167. // entryTypeBytes entryType = iota // make this 0, so a comparison is cheap
  168. // entryTypeIo
  169. // entryTypeBufio
  170. // entryTypeUnset = 255
  171. // )
  172. type charEncoding uint8
  173. const (
  174. _ charEncoding = iota // make 0 unset
  175. cUTF8
  176. cUTF16LE
  177. cUTF16BE
  178. cUTF32LE
  179. cUTF32BE
  180. // Deprecated: not a true char encoding value
  181. cRAW charEncoding = 255
  182. )
  183. // valueType is the stream type
  184. type valueType uint8
  185. const (
  186. valueTypeUnset valueType = iota
  187. valueTypeNil
  188. valueTypeInt
  189. valueTypeUint
  190. valueTypeFloat
  191. valueTypeBool
  192. valueTypeString
  193. valueTypeSymbol
  194. valueTypeBytes
  195. valueTypeMap
  196. valueTypeArray
  197. valueTypeTime
  198. valueTypeExt
  199. // valueTypeInvalid = 0xff
  200. )
  201. var valueTypeStrings = [...]string{
  202. "Unset",
  203. "Nil",
  204. "Int",
  205. "Uint",
  206. "Float",
  207. "Bool",
  208. "String",
  209. "Symbol",
  210. "Bytes",
  211. "Map",
  212. "Array",
  213. "Timestamp",
  214. "Ext",
  215. }
  216. func (x valueType) String() string {
  217. if int(x) < len(valueTypeStrings) {
  218. return valueTypeStrings[x]
  219. }
  220. return strconv.FormatInt(int64(x), 10)
  221. }
  222. type seqType uint8
  223. const (
  224. _ seqType = iota
  225. seqTypeArray
  226. seqTypeSlice
  227. seqTypeChan
  228. )
  229. // note that containerMapStart and containerArraySend are not sent.
  230. // This is because the ReadXXXStart and EncodeXXXStart already does these.
  231. type containerState uint8
  232. const (
  233. _ containerState = iota
  234. containerMapStart
  235. containerMapKey
  236. containerMapValue
  237. containerMapEnd
  238. containerArrayStart
  239. containerArrayElem
  240. containerArrayEnd
  241. )
  242. // // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo
  243. // type sfiIdx struct {
  244. // name string
  245. // index int
  246. // }
  247. // do not recurse if a containing type refers to an embedded type
  248. // which refers back to its containing type (via a pointer).
  249. // The second time this back-reference happens, break out,
  250. // so as not to cause an infinite loop.
  251. const rgetMaxRecursion = 2
  252. // Anecdotally, we believe most types have <= 12 fields.
  253. // - even Java's PMD rules set TooManyFields threshold to 15.
  254. // However, go has embedded fields, which should be regarded as
  255. // top level, allowing structs to possibly double or triple.
  256. // In addition, we don't want to keep creating transient arrays,
  257. // especially for the sfi index tracking, and the evtypes tracking.
  258. //
  259. // So - try to keep typeInfoLoadArray within 2K bytes
  260. const (
  261. typeInfoLoadArraySfisLen = 16
  262. typeInfoLoadArraySfiidxLen = 8 * 112
  263. typeInfoLoadArrayEtypesLen = 12
  264. typeInfoLoadArrayBLen = 8 * 4
  265. )
  266. // typeInfoLoad is a transient object used while loading up a typeInfo.
  267. type typeInfoLoad struct {
  268. // fNames []string
  269. // encNames []string
  270. etypes []uintptr
  271. sfis []structFieldInfo
  272. }
  273. // typeInfoLoadArray is a cache object used to efficiently load up a typeInfo without
  274. // much allocation.
  275. type typeInfoLoadArray struct {
  276. // fNames [typeInfoLoadArrayLen]string
  277. // encNames [typeInfoLoadArrayLen]string
  278. sfis [typeInfoLoadArraySfisLen]structFieldInfo
  279. sfiidx [typeInfoLoadArraySfiidxLen]byte
  280. etypes [typeInfoLoadArrayEtypesLen]uintptr
  281. b [typeInfoLoadArrayBLen]byte // scratch - used for struct field names
  282. }
  283. // // cacheLineSafer denotes that a type is safe for cache-line access.
  284. // // This could mean that
  285. // type cacheLineSafer interface {
  286. // cacheLineSafe()
  287. // }
  288. // mirror json.Marshaler and json.Unmarshaler here,
  289. // so we don't import the encoding/json package
  290. type jsonMarshaler interface {
  291. MarshalJSON() ([]byte, error)
  292. }
  293. type jsonUnmarshaler interface {
  294. UnmarshalJSON([]byte) error
  295. }
  296. type isZeroer interface {
  297. IsZero() bool
  298. }
  299. type codecError struct {
  300. name string
  301. err interface{}
  302. }
  303. func (e codecError) Cause() error {
  304. switch xerr := e.err.(type) {
  305. case nil:
  306. return nil
  307. case error:
  308. return xerr
  309. case string:
  310. return errors.New(xerr)
  311. case fmt.Stringer:
  312. return errors.New(xerr.String())
  313. default:
  314. return fmt.Errorf("%v", e.err)
  315. }
  316. }
  317. func (e codecError) Error() string {
  318. return fmt.Sprintf("%s error: %v", e.name, e.err)
  319. }
  320. // type byteAccepter func(byte) bool
  321. var (
  322. bigen = binary.BigEndian
  323. structInfoFieldName = "_struct"
  324. mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
  325. mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
  326. intfSliceTyp = reflect.TypeOf([]interface{}(nil))
  327. intfTyp = intfSliceTyp.Elem()
  328. reflectValTyp = reflect.TypeOf((*reflect.Value)(nil)).Elem()
  329. stringTyp = reflect.TypeOf("")
  330. timeTyp = reflect.TypeOf(time.Time{})
  331. rawExtTyp = reflect.TypeOf(RawExt{})
  332. rawTyp = reflect.TypeOf(Raw{})
  333. uintptrTyp = reflect.TypeOf(uintptr(0))
  334. uint8Typ = reflect.TypeOf(uint8(0))
  335. uint8SliceTyp = reflect.TypeOf([]uint8(nil))
  336. uintTyp = reflect.TypeOf(uint(0))
  337. intTyp = reflect.TypeOf(int(0))
  338. mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
  339. binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
  340. binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
  341. textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
  342. textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
  343. jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
  344. jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
  345. selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem()
  346. missingFielderTyp = reflect.TypeOf((*MissingFielder)(nil)).Elem()
  347. iszeroTyp = reflect.TypeOf((*isZeroer)(nil)).Elem()
  348. uint8TypId = rt2id(uint8Typ)
  349. uint8SliceTypId = rt2id(uint8SliceTyp)
  350. rawExtTypId = rt2id(rawExtTyp)
  351. rawTypId = rt2id(rawTyp)
  352. intfTypId = rt2id(intfTyp)
  353. timeTypId = rt2id(timeTyp)
  354. stringTypId = rt2id(stringTyp)
  355. mapStrIntfTypId = rt2id(mapStrIntfTyp)
  356. mapIntfIntfTypId = rt2id(mapIntfIntfTyp)
  357. intfSliceTypId = rt2id(intfSliceTyp)
  358. // mapBySliceTypId = rt2id(mapBySliceTyp)
  359. intBitsize = uint8(intTyp.Bits())
  360. uintBitsize = uint8(uintTyp.Bits())
  361. // bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
  362. bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  363. chkOvf checkOverflow
  364. errNoFieldNameToStructFieldInfo = errors.New("no field name passed to parseStructFieldInfo")
  365. )
  366. var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
  367. var immutableKindsSet = [32]bool{
  368. // reflect.Invalid: ,
  369. reflect.Bool: true,
  370. reflect.Int: true,
  371. reflect.Int8: true,
  372. reflect.Int16: true,
  373. reflect.Int32: true,
  374. reflect.Int64: true,
  375. reflect.Uint: true,
  376. reflect.Uint8: true,
  377. reflect.Uint16: true,
  378. reflect.Uint32: true,
  379. reflect.Uint64: true,
  380. reflect.Uintptr: true,
  381. reflect.Float32: true,
  382. reflect.Float64: true,
  383. reflect.Complex64: true,
  384. reflect.Complex128: true,
  385. // reflect.Array
  386. // reflect.Chan
  387. // reflect.Func: true,
  388. // reflect.Interface
  389. // reflect.Map
  390. // reflect.Ptr
  391. // reflect.Slice
  392. reflect.String: true,
  393. // reflect.Struct
  394. // reflect.UnsafePointer
  395. }
  396. // Selfer defines methods by which a value can encode or decode itself.
  397. //
  398. // Any type which implements Selfer will be able to encode or decode itself.
  399. // Consequently, during (en|de)code, this takes precedence over
  400. // (text|binary)(M|Unm)arshal or extension support.
  401. //
  402. // By definition, it is not allowed for a Selfer to directly call Encode or Decode on itself.
  403. // If that is done, Encode/Decode will rightfully fail with a Stack Overflow style error.
  404. // For example, the snippet below will cause such an error.
  405. // type testSelferRecur struct{}
  406. // func (s *testSelferRecur) CodecEncodeSelf(e *Encoder) { e.MustEncode(s) }
  407. // func (s *testSelferRecur) CodecDecodeSelf(d *Decoder) { d.MustDecode(s) }
  408. //
  409. // Note: *the first set of bytes of any value MUST NOT represent nil in the format*.
  410. // This is because, during each decode, we first check the the next set of bytes
  411. // represent nil, and if so, we just set the value to nil.
  412. type Selfer interface {
  413. CodecEncodeSelf(*Encoder)
  414. CodecDecodeSelf(*Decoder)
  415. }
  416. // MissingFielder defines the interface allowing structs to internally decode or encode
  417. // values which do not map to struct fields.
  418. //
  419. // We expect that this interface is bound to a pointer type (so the mutation function works).
  420. //
  421. // A use-case is if a version of a type unexports a field, but you want compatibility between
  422. // both versions during encoding and decoding.
  423. //
  424. // Note that the interface is completely ignored during codecgen.
  425. type MissingFielder interface {
  426. // CodecMissingField is called to set a missing field and value pair.
  427. //
  428. // It returns true if the missing field was set on the struct.
  429. CodecMissingField(field []byte, value interface{}) bool
  430. // CodecMissingFields returns the set of fields which are not struct fields
  431. CodecMissingFields() map[string]interface{}
  432. }
  433. // MapBySlice is a tag interface that denotes wrapped slice should encode as a map in the stream.
  434. // The slice contains a sequence of key-value pairs.
  435. // This affords storing a map in a specific sequence in the stream.
  436. //
  437. // Example usage:
  438. // type T1 []string // or []int or []Point or any other "slice" type
  439. // func (_ T1) MapBySlice{} // T1 now implements MapBySlice, and will be encoded as a map
  440. // type T2 struct { KeyValues T1 }
  441. //
  442. // var kvs = []string{"one", "1", "two", "2", "three", "3"}
  443. // var v2 = T2{ KeyValues: T1(kvs) }
  444. // // v2 will be encoded like the map: {"KeyValues": {"one": "1", "two": "2", "three": "3"} }
  445. //
  446. // The support of MapBySlice affords the following:
  447. // - A slice type which implements MapBySlice will be encoded as a map
  448. // - A slice can be decoded from a map in the stream
  449. // - It MUST be a slice type (not a pointer receiver) that implements MapBySlice
  450. type MapBySlice interface {
  451. MapBySlice()
  452. }
  453. // BasicHandle encapsulates the common options and extension functions.
  454. //
  455. // Deprecated: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
  456. type BasicHandle struct {
  457. // BasicHandle is always a part of a different type.
  458. // It doesn't have to fit into it own cache lines.
  459. // TypeInfos is used to get the type info for any type.
  460. //
  461. // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
  462. TypeInfos *TypeInfos
  463. // Note: BasicHandle is not comparable, due to these slices here (extHandle, intf2impls).
  464. // If *[]T is used instead, this becomes comparable, at the cost of extra indirection.
  465. // Thses slices are used all the time, so keep as slices (not pointers).
  466. extHandle
  467. intf2impls
  468. EncodeOptions
  469. DecodeOptions
  470. RPCOptions
  471. // TimeNotBuiltin configures whether time.Time should be treated as a builtin type.
  472. //
  473. // All Handlers should know how to encode/decode time.Time as part of the core
  474. // format specification, or as a standard extension defined by the format.
  475. //
  476. // However, users can elect to handle time.Time as a custom extension, or via the
  477. // standard library's encoding.Binary(M|Unm)arshaler or Text(M|Unm)arshaler interface.
  478. // To elect this behavior, users can set TimeNotBuiltin=true.
  479. // Note: Setting TimeNotBuiltin=true can be used to enable the legacy behavior
  480. // (for Cbor and Msgpack), where time.Time was not a builtin supported type.
  481. TimeNotBuiltin bool
  482. // ExplicitRelease configures whether Release() is implicitly called after an encode or
  483. // decode call.
  484. //
  485. // If you will hold onto an Encoder or Decoder for re-use, by calling Reset(...)
  486. // on it or calling (Must)Encode repeatedly into a given []byte or io.Writer,
  487. // then you do not want it to be implicitly closed after each Encode/Decode call.
  488. // Doing so will unnecessarily return resources to the shared pool, only for you to
  489. // grab them right after again to do another Encode/Decode call.
  490. //
  491. // Instead, you configure ExplicitRelease=true, and you explicitly call Release() when
  492. // you are truly done.
  493. //
  494. // As an alternative, you can explicitly set a finalizer - so its resources
  495. // are returned to the shared pool before it is garbage-collected. Do it as below:
  496. // runtime.SetFinalizer(e, (*Encoder).Release)
  497. // runtime.SetFinalizer(d, (*Decoder).Release)
  498. ExplicitRelease bool
  499. // flags handleFlag // holds flag for if binaryEncoding, jsonHandler, etc
  500. // be bool // is handle a binary encoding?
  501. // js bool // is handle javascript handler?
  502. // n byte // first letter of handle name
  503. // _ uint16 // padding
  504. // ---- cache line
  505. // noBuiltInTypeChecker
  506. inited uint32 // holds if inited, and also handle flags (binary encoding, json handler, etc)
  507. mu sync.Mutex
  508. // _ uint32 // padding
  509. rtidFns atomicRtidFnSlice
  510. // r []uintptr // rtids mapped to s above
  511. }
  512. // basicHandle returns an initialized BasicHandle from the Handle.
  513. func basicHandle(hh Handle) (x *BasicHandle) {
  514. x = hh.getBasicHandle()
  515. // ** We need to simulate once.Do, to ensure no data race within the block.
  516. // ** Consequently, below would not work.
  517. // if atomic.CompareAndSwapUint32(&x.inited, 0, 1) {
  518. // x.be = hh.isBinary()
  519. // _, x.js = hh.(*JsonHandle)
  520. // x.n = hh.Name()[0]
  521. // }
  522. // simulate once.Do using our own stored flag and mutex as a CompareAndSwap
  523. // is not sufficient, since a race condition can occur within init(Handle) function.
  524. // init is made noinline, so that this function can be inlined by its caller.
  525. if atomic.LoadUint32(&x.inited) == 0 {
  526. x.init(hh)
  527. }
  528. return
  529. }
  530. func (x *BasicHandle) isJs() bool {
  531. return handleFlag(x.inited)&jsonHandleFlag != 0
  532. }
  533. func (x *BasicHandle) isBe() bool {
  534. return handleFlag(x.inited)&binaryHandleFlag != 0
  535. }
  536. //go:noinline
  537. func (x *BasicHandle) init(hh Handle) {
  538. // make it uninlineable, as it is called at most once
  539. x.mu.Lock()
  540. if x.inited == 0 {
  541. var f = initedHandleFlag
  542. if hh.isBinary() {
  543. f |= binaryHandleFlag
  544. }
  545. if _, b := hh.(*JsonHandle); b {
  546. f |= jsonHandleFlag
  547. }
  548. // _, x.js = hh.(*JsonHandle)
  549. // x.n = hh.Name()[0]
  550. atomic.StoreUint32(&x.inited, uint32(f))
  551. }
  552. x.mu.Unlock()
  553. }
  554. func (x *BasicHandle) getBasicHandle() *BasicHandle {
  555. return x
  556. }
  557. func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  558. if x.TypeInfos == nil {
  559. return defTypeInfos.get(rtid, rt)
  560. }
  561. return x.TypeInfos.get(rtid, rt)
  562. }
  563. func findFn(s []codecRtidFn, rtid uintptr) (i uint, fn *codecFn) {
  564. // binary search. adapted from sort/search.go.
  565. // Note: we use goto (instead of for loop) so this can be inlined.
  566. // h, i, j := 0, 0, len(s)
  567. var h uint // var h, i uint
  568. var j = uint(len(s))
  569. LOOP:
  570. if i < j {
  571. h = i + (j-i)/2
  572. if s[h].rtid < rtid {
  573. i = h + 1
  574. } else {
  575. j = h
  576. }
  577. goto LOOP
  578. }
  579. if i < uint(len(s)) && s[i].rtid == rtid {
  580. fn = s[i].fn
  581. }
  582. return
  583. }
  584. func (x *BasicHandle) fn(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *codecFn) {
  585. rtid := rt2id(rt)
  586. sp := x.rtidFns.load()
  587. if sp != nil {
  588. if _, fn = findFn(sp, rtid); fn != nil {
  589. // xdebugf("<<<< %c: found fn for %v in rtidfns of size: %v", c.n, rt, len(sp))
  590. return
  591. }
  592. }
  593. c := x
  594. // xdebugf("#### for %c: load fn for %v in rtidfns of size: %v", c.n, rt, len(sp))
  595. fn = new(codecFn)
  596. fi := &(fn.i)
  597. ti := c.getTypeInfo(rtid, rt)
  598. fi.ti = ti
  599. rk := reflect.Kind(ti.kind)
  600. if checkCodecSelfer && (ti.cs || ti.csp) {
  601. fn.fe = (*Encoder).selferMarshal
  602. fn.fd = (*Decoder).selferUnmarshal
  603. fi.addrF = true
  604. fi.addrD = ti.csp
  605. fi.addrE = ti.csp
  606. } else if rtid == timeTypId && !c.TimeNotBuiltin {
  607. fn.fe = (*Encoder).kTime
  608. fn.fd = (*Decoder).kTime
  609. } else if rtid == rawTypId {
  610. fn.fe = (*Encoder).raw
  611. fn.fd = (*Decoder).raw
  612. } else if rtid == rawExtTypId {
  613. fn.fe = (*Encoder).rawExt
  614. fn.fd = (*Decoder).rawExt
  615. fi.addrF = true
  616. fi.addrD = true
  617. fi.addrE = true
  618. } else if xfFn := c.getExt(rtid); xfFn != nil {
  619. fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
  620. fn.fe = (*Encoder).ext
  621. fn.fd = (*Decoder).ext
  622. fi.addrF = true
  623. fi.addrD = true
  624. if rk == reflect.Struct || rk == reflect.Array {
  625. fi.addrE = true
  626. }
  627. } else if supportMarshalInterfaces && c.isBe() && (ti.bm || ti.bmp) && (ti.bu || ti.bup) {
  628. fn.fe = (*Encoder).binaryMarshal
  629. fn.fd = (*Decoder).binaryUnmarshal
  630. fi.addrF = true
  631. fi.addrD = ti.bup
  632. fi.addrE = ti.bmp
  633. } else if supportMarshalInterfaces && !c.isBe() && c.isJs() &&
  634. (ti.jm || ti.jmp) && (ti.ju || ti.jup) {
  635. //If JSON, we should check JSONMarshal before textMarshal
  636. fn.fe = (*Encoder).jsonMarshal
  637. fn.fd = (*Decoder).jsonUnmarshal
  638. fi.addrF = true
  639. fi.addrD = ti.jup
  640. fi.addrE = ti.jmp
  641. } else if supportMarshalInterfaces && !c.isBe() && (ti.tm || ti.tmp) && (ti.tu || ti.tup) {
  642. fn.fe = (*Encoder).textMarshal
  643. fn.fd = (*Decoder).textUnmarshal
  644. fi.addrF = true
  645. fi.addrD = ti.tup
  646. fi.addrE = ti.tmp
  647. } else {
  648. if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
  649. if ti.pkgpath == "" { // un-named slice or map
  650. if idx := fastpathAV.index(rtid); idx != -1 {
  651. fn.fe = fastpathAV[idx].encfn
  652. fn.fd = fastpathAV[idx].decfn
  653. fi.addrD = true
  654. fi.addrF = false
  655. }
  656. } else {
  657. // use mapping for underlying type if there
  658. var rtu reflect.Type
  659. if rk == reflect.Map {
  660. rtu = reflect.MapOf(ti.key, ti.elem)
  661. } else {
  662. rtu = reflect.SliceOf(ti.elem)
  663. }
  664. rtuid := rt2id(rtu)
  665. if idx := fastpathAV.index(rtuid); idx != -1 {
  666. xfnf := fastpathAV[idx].encfn
  667. xrt := fastpathAV[idx].rt
  668. fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) {
  669. xfnf(e, xf, xrv.Convert(xrt))
  670. }
  671. fi.addrD = true
  672. fi.addrF = false // meaning it can be an address(ptr) or a value
  673. xfnf2 := fastpathAV[idx].decfn
  674. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  675. if xrv.Kind() == reflect.Ptr {
  676. xfnf2(d, xf, xrv.Convert(reflect.PtrTo(xrt)))
  677. } else {
  678. xfnf2(d, xf, xrv.Convert(xrt))
  679. }
  680. }
  681. }
  682. }
  683. }
  684. if fn.fe == nil && fn.fd == nil {
  685. switch rk {
  686. case reflect.Bool:
  687. fn.fe = (*Encoder).kBool
  688. fn.fd = (*Decoder).kBool
  689. case reflect.String:
  690. fn.fe = (*Encoder).kString
  691. fn.fd = (*Decoder).kString
  692. case reflect.Int:
  693. fn.fd = (*Decoder).kInt
  694. fn.fe = (*Encoder).kInt
  695. case reflect.Int8:
  696. fn.fe = (*Encoder).kInt8
  697. fn.fd = (*Decoder).kInt8
  698. case reflect.Int16:
  699. fn.fe = (*Encoder).kInt16
  700. fn.fd = (*Decoder).kInt16
  701. case reflect.Int32:
  702. fn.fe = (*Encoder).kInt32
  703. fn.fd = (*Decoder).kInt32
  704. case reflect.Int64:
  705. fn.fe = (*Encoder).kInt64
  706. fn.fd = (*Decoder).kInt64
  707. case reflect.Uint:
  708. fn.fd = (*Decoder).kUint
  709. fn.fe = (*Encoder).kUint
  710. case reflect.Uint8:
  711. fn.fe = (*Encoder).kUint8
  712. fn.fd = (*Decoder).kUint8
  713. case reflect.Uint16:
  714. fn.fe = (*Encoder).kUint16
  715. fn.fd = (*Decoder).kUint16
  716. case reflect.Uint32:
  717. fn.fe = (*Encoder).kUint32
  718. fn.fd = (*Decoder).kUint32
  719. case reflect.Uint64:
  720. fn.fe = (*Encoder).kUint64
  721. fn.fd = (*Decoder).kUint64
  722. case reflect.Uintptr:
  723. fn.fe = (*Encoder).kUintptr
  724. fn.fd = (*Decoder).kUintptr
  725. case reflect.Float32:
  726. fn.fe = (*Encoder).kFloat32
  727. fn.fd = (*Decoder).kFloat32
  728. case reflect.Float64:
  729. fn.fe = (*Encoder).kFloat64
  730. fn.fd = (*Decoder).kFloat64
  731. case reflect.Invalid:
  732. fn.fe = (*Encoder).kInvalid
  733. fn.fd = (*Decoder).kErr
  734. case reflect.Chan:
  735. fi.seq = seqTypeChan
  736. fn.fe = (*Encoder).kSlice
  737. fn.fd = (*Decoder).kSlice
  738. case reflect.Slice:
  739. fi.seq = seqTypeSlice
  740. fn.fe = (*Encoder).kSlice
  741. fn.fd = (*Decoder).kSlice
  742. case reflect.Array:
  743. fi.seq = seqTypeArray
  744. fn.fe = (*Encoder).kSlice
  745. fi.addrF = false
  746. fi.addrD = false
  747. rt2 := reflect.SliceOf(ti.elem)
  748. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  749. d.h.fn(rt2, true, false).fd(d, xf, xrv.Slice(0, xrv.Len()))
  750. }
  751. // fn.fd = (*Decoder).kArray
  752. case reflect.Struct:
  753. if ti.anyOmitEmpty || ti.mf || ti.mfp {
  754. fn.fe = (*Encoder).kStruct
  755. } else {
  756. fn.fe = (*Encoder).kStructNoOmitempty
  757. }
  758. fn.fd = (*Decoder).kStruct
  759. case reflect.Map:
  760. fn.fe = (*Encoder).kMap
  761. fn.fd = (*Decoder).kMap
  762. case reflect.Interface:
  763. // encode: reflect.Interface are handled already by preEncodeValue
  764. fn.fd = (*Decoder).kInterface
  765. fn.fe = (*Encoder).kErr
  766. default:
  767. // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
  768. fn.fe = (*Encoder).kErr
  769. fn.fd = (*Decoder).kErr
  770. }
  771. }
  772. }
  773. c.mu.Lock()
  774. var sp2 []codecRtidFn
  775. sp = c.rtidFns.load()
  776. if sp == nil {
  777. sp2 = []codecRtidFn{{rtid, fn}}
  778. c.rtidFns.store(sp2)
  779. // xdebugf(">>>> adding rt: %v to rtidfns of size: %v", rt, len(sp2))
  780. // xdebugf(">>>> loading stored rtidfns of size: %v", len(c.rtidFns.load()))
  781. } else {
  782. idx, fn2 := findFn(sp, rtid)
  783. if fn2 == nil {
  784. sp2 = make([]codecRtidFn, len(sp)+1)
  785. copy(sp2, sp[:idx])
  786. copy(sp2[idx+1:], sp[idx:])
  787. sp2[idx] = codecRtidFn{rtid, fn}
  788. c.rtidFns.store(sp2)
  789. // xdebugf(">>>> adding rt: %v to rtidfns of size: %v", rt, len(sp2))
  790. }
  791. }
  792. c.mu.Unlock()
  793. return
  794. }
  795. // Handle defines a specific encoding format. It also stores any runtime state
  796. // used during an Encoding or Decoding session e.g. stored state about Types, etc.
  797. //
  798. // Once a handle is configured, it can be shared across multiple Encoders and Decoders.
  799. //
  800. // Note that a Handle is NOT safe for concurrent modification.
  801. // Consequently, do not modify it after it is configured if shared among
  802. // multiple Encoders and Decoders in different goroutines.
  803. //
  804. // Consequently, the typical usage model is that a Handle is pre-configured
  805. // before first time use, and not modified while in use.
  806. // Such a pre-configured Handle is safe for concurrent access.
  807. type Handle interface {
  808. Name() string
  809. // return the basic handle. It may not have been inited.
  810. // Prefer to use basicHandle() helper function that ensures it has been inited.
  811. getBasicHandle() *BasicHandle
  812. recreateEncDriver(encDriver) bool
  813. newEncDriver(w *Encoder) encDriver
  814. newDecDriver(r *Decoder) decDriver
  815. isBinary() bool
  816. hasElemSeparators() bool
  817. // IsBuiltinType(rtid uintptr) bool
  818. }
  819. // Raw represents raw formatted bytes.
  820. // We "blindly" store it during encode and retrieve the raw bytes during decode.
  821. // Note: it is dangerous during encode, so we may gate the behaviour
  822. // behind an Encode flag which must be explicitly set.
  823. type Raw []byte
  824. // RawExt represents raw unprocessed extension data.
  825. // Some codecs will decode extension data as a *RawExt
  826. // if there is no registered extension for the tag.
  827. //
  828. // Only one of Data or Value is nil.
  829. // If Data is nil, then the content of the RawExt is in the Value.
  830. type RawExt struct {
  831. Tag uint64
  832. // Data is the []byte which represents the raw ext. If nil, ext is exposed in Value.
  833. // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of types
  834. Data []byte
  835. // Value represents the extension, if Data is nil.
  836. // Value is used by codecs (e.g. cbor, json) which leverage the format to do
  837. // custom serialization of the types.
  838. Value interface{}
  839. }
  840. // BytesExt handles custom (de)serialization of types to/from []byte.
  841. // It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
  842. type BytesExt interface {
  843. // WriteExt converts a value to a []byte.
  844. //
  845. // Note: v is a pointer iff the registered extension type is a struct or array kind.
  846. WriteExt(v interface{}) []byte
  847. // ReadExt updates a value from a []byte.
  848. //
  849. // Note: dst is always a pointer kind to the registered extension type.
  850. ReadExt(dst interface{}, src []byte)
  851. }
  852. // InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
  853. // The Encoder or Decoder will then handle the further (de)serialization of that known type.
  854. //
  855. // It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of types.
  856. type InterfaceExt interface {
  857. // ConvertExt converts a value into a simpler interface for easy encoding
  858. // e.g. convert time.Time to int64.
  859. //
  860. // Note: v is a pointer iff the registered extension type is a struct or array kind.
  861. ConvertExt(v interface{}) interface{}
  862. // UpdateExt updates a value from a simpler interface for easy decoding
  863. // e.g. convert int64 to time.Time.
  864. //
  865. // Note: dst is always a pointer kind to the registered extension type.
  866. UpdateExt(dst interface{}, src interface{})
  867. }
  868. // Ext handles custom (de)serialization of custom types / extensions.
  869. type Ext interface {
  870. BytesExt
  871. InterfaceExt
  872. }
  873. // addExtWrapper is a wrapper implementation to support former AddExt exported method.
  874. type addExtWrapper struct {
  875. encFn func(reflect.Value) ([]byte, error)
  876. decFn func(reflect.Value, []byte) error
  877. }
  878. func (x addExtWrapper) WriteExt(v interface{}) []byte {
  879. bs, err := x.encFn(reflect.ValueOf(v))
  880. if err != nil {
  881. panic(err)
  882. }
  883. return bs
  884. }
  885. func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
  886. if err := x.decFn(reflect.ValueOf(v), bs); err != nil {
  887. panic(err)
  888. }
  889. }
  890. func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
  891. return x.WriteExt(v)
  892. }
  893. func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  894. x.ReadExt(dest, v.([]byte))
  895. }
  896. type bytesExtFailer struct{}
  897. func (bytesExtFailer) WriteExt(v interface{}) []byte {
  898. panicv.errorstr("BytesExt.WriteExt is not supported")
  899. return nil
  900. }
  901. func (bytesExtFailer) ReadExt(v interface{}, bs []byte) {
  902. panicv.errorstr("BytesExt.ReadExt is not supported")
  903. }
  904. type interfaceExtFailer struct{}
  905. func (interfaceExtFailer) ConvertExt(v interface{}) interface{} {
  906. panicv.errorstr("InterfaceExt.ConvertExt is not supported")
  907. return nil
  908. }
  909. func (interfaceExtFailer) UpdateExt(dest interface{}, v interface{}) {
  910. panicv.errorstr("InterfaceExt.UpdateExt is not supported")
  911. }
  912. // type extWrapper struct {
  913. // BytesExt
  914. // InterfaceExt
  915. // }
  916. type bytesExtWrapper struct {
  917. interfaceExtFailer
  918. BytesExt
  919. }
  920. type interfaceExtWrapper struct {
  921. bytesExtFailer
  922. InterfaceExt
  923. }
  924. type binaryEncodingType struct{}
  925. func (binaryEncodingType) isBinary() bool { return true }
  926. type textEncodingType struct{}
  927. func (textEncodingType) isBinary() bool { return false }
  928. // noBuiltInTypes is embedded into many types which do not support builtins
  929. // e.g. msgpack, simple, cbor.
  930. // type noBuiltInTypeChecker struct{}
  931. // func (noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false }
  932. // type noBuiltInTypes struct{ noBuiltInTypeChecker }
  933. type noBuiltInTypes struct{}
  934. func (noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
  935. func (noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
  936. // type noStreamingCodec struct{}
  937. // func (noStreamingCodec) CheckBreak() bool { return false }
  938. // func (noStreamingCodec) hasElemSeparators() bool { return false }
  939. type noElemSeparators struct{}
  940. func (noElemSeparators) hasElemSeparators() (v bool) { return }
  941. func (noElemSeparators) recreateEncDriver(e encDriver) (v bool) { return }
  942. // bigenHelper.
  943. // Users must already slice the x completely, because we will not reslice.
  944. type bigenHelper struct {
  945. x []byte // must be correctly sliced to appropriate len. slicing is a cost.
  946. w *encWriterSwitch
  947. }
  948. func (z bigenHelper) writeUint16(v uint16) {
  949. bigen.PutUint16(z.x, v)
  950. z.w.writeb(z.x)
  951. }
  952. func (z bigenHelper) writeUint32(v uint32) {
  953. bigen.PutUint32(z.x, v)
  954. z.w.writeb(z.x)
  955. }
  956. func (z bigenHelper) writeUint64(v uint64) {
  957. bigen.PutUint64(z.x, v)
  958. z.w.writeb(z.x)
  959. }
  960. type extTypeTagFn struct {
  961. rtid uintptr
  962. rtidptr uintptr
  963. rt reflect.Type
  964. tag uint64
  965. ext Ext
  966. // _ [1]uint64 // padding
  967. }
  968. type extHandle []extTypeTagFn
  969. // AddExt registes an encode and decode function for a reflect.Type.
  970. // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
  971. //
  972. // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  973. func (o *extHandle) AddExt(rt reflect.Type, tag byte,
  974. encfn func(reflect.Value) ([]byte, error),
  975. decfn func(reflect.Value, []byte) error) (err error) {
  976. if encfn == nil || decfn == nil {
  977. return o.SetExt(rt, uint64(tag), nil)
  978. }
  979. return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
  980. }
  981. // SetExt will set the extension for a tag and reflect.Type.
  982. // Note that the type must be a named type, and specifically not a pointer or Interface.
  983. // An error is returned if that is not honored.
  984. // To Deregister an ext, call SetExt with nil Ext.
  985. //
  986. // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  987. func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
  988. // o is a pointer, because we may need to initialize it
  989. rk := rt.Kind()
  990. for rk == reflect.Ptr {
  991. rt = rt.Elem()
  992. rk = rt.Kind()
  993. }
  994. if rt.PkgPath() == "" || rk == reflect.Interface { // || rk == reflect.Ptr {
  995. return fmt.Errorf("codec.Handle.SetExt: Takes named type, not a pointer or interface: %v", rt)
  996. }
  997. rtid := rt2id(rt)
  998. switch rtid {
  999. case timeTypId, rawTypId, rawExtTypId:
  1000. // all natively supported type, so cannot have an extension
  1001. return // TODO: should we silently ignore, or return an error???
  1002. }
  1003. // if o == nil {
  1004. // return errors.New("codec.Handle.SetExt: extHandle not initialized")
  1005. // }
  1006. o2 := *o
  1007. // if o2 == nil {
  1008. // return errors.New("codec.Handle.SetExt: extHandle not initialized")
  1009. // }
  1010. for i := range o2 {
  1011. v := &o2[i]
  1012. if v.rtid == rtid {
  1013. v.tag, v.ext = tag, ext
  1014. return
  1015. }
  1016. }
  1017. rtidptr := rt2id(reflect.PtrTo(rt))
  1018. *o = append(o2, extTypeTagFn{rtid, rtidptr, rt, tag, ext}) // , [1]uint64{}})
  1019. return
  1020. }
  1021. func (o extHandle) getExt(rtid uintptr) (v *extTypeTagFn) {
  1022. for i := range o {
  1023. v = &o[i]
  1024. if v.rtid == rtid || v.rtidptr == rtid {
  1025. return
  1026. }
  1027. }
  1028. return nil
  1029. }
  1030. func (o extHandle) getExtForTag(tag uint64) (v *extTypeTagFn) {
  1031. for i := range o {
  1032. v = &o[i]
  1033. if v.tag == tag {
  1034. return
  1035. }
  1036. }
  1037. return nil
  1038. }
  1039. type intf2impl struct {
  1040. rtid uintptr // for intf
  1041. impl reflect.Type
  1042. // _ [1]uint64 // padding // not-needed, as *intf2impl is never returned.
  1043. }
  1044. type intf2impls []intf2impl
  1045. // Intf2Impl maps an interface to an implementing type.
  1046. // This allows us support infering the concrete type
  1047. // and populating it when passed an interface.
  1048. // e.g. var v io.Reader can be decoded as a bytes.Buffer, etc.
  1049. //
  1050. // Passing a nil impl will clear the mapping.
  1051. func (o *intf2impls) Intf2Impl(intf, impl reflect.Type) (err error) {
  1052. if impl != nil && !impl.Implements(intf) {
  1053. return fmt.Errorf("Intf2Impl: %v does not implement %v", impl, intf)
  1054. }
  1055. rtid := rt2id(intf)
  1056. o2 := *o
  1057. for i := range o2 {
  1058. v := &o2[i]
  1059. if v.rtid == rtid {
  1060. v.impl = impl
  1061. return
  1062. }
  1063. }
  1064. *o = append(o2, intf2impl{rtid, impl})
  1065. return
  1066. }
  1067. func (o intf2impls) intf2impl(rtid uintptr) (rv reflect.Value) {
  1068. for i := range o {
  1069. v := &o[i]
  1070. if v.rtid == rtid {
  1071. if v.impl == nil {
  1072. return
  1073. }
  1074. if v.impl.Kind() == reflect.Ptr {
  1075. return reflect.New(v.impl.Elem())
  1076. }
  1077. return reflect.New(v.impl).Elem()
  1078. }
  1079. }
  1080. return
  1081. }
  1082. type structFieldInfoFlag uint8
  1083. const (
  1084. _ structFieldInfoFlag = 1 << iota
  1085. structFieldInfoFlagReady
  1086. structFieldInfoFlagOmitEmpty
  1087. )
  1088. func (x *structFieldInfoFlag) flagSet(f structFieldInfoFlag) {
  1089. *x = *x | f
  1090. }
  1091. func (x *structFieldInfoFlag) flagClr(f structFieldInfoFlag) {
  1092. *x = *x &^ f
  1093. }
  1094. func (x structFieldInfoFlag) flagGet(f structFieldInfoFlag) bool {
  1095. return x&f != 0
  1096. }
  1097. func (x structFieldInfoFlag) omitEmpty() bool {
  1098. return x.flagGet(structFieldInfoFlagOmitEmpty)
  1099. }
  1100. func (x structFieldInfoFlag) ready() bool {
  1101. return x.flagGet(structFieldInfoFlagReady)
  1102. }
  1103. type structFieldInfo struct {
  1104. encName string // encode name
  1105. fieldName string // field name
  1106. is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct
  1107. nis uint8 // num levels of embedding. if 1, then it's not embedded.
  1108. encNameAsciiAlphaNum bool // the encName only contains ascii alphabet and numbers
  1109. structFieldInfoFlag
  1110. // _ [1]byte // padding
  1111. }
  1112. func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
  1113. if v, valid := si.field(v, false); valid {
  1114. v.Set(reflect.Zero(v.Type()))
  1115. }
  1116. }
  1117. // rv returns the field of the struct.
  1118. // If anonymous, it returns an Invalid
  1119. func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
  1120. // replicate FieldByIndex
  1121. for i, x := range si.is {
  1122. if uint8(i) == si.nis {
  1123. break
  1124. }
  1125. if v, valid = baseStructRv(v, update); !valid {
  1126. return
  1127. }
  1128. v = v.Field(int(x))
  1129. }
  1130. return v, true
  1131. }
  1132. // func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value {
  1133. // v, _ = si.field(v, update)
  1134. // return v
  1135. // }
  1136. func parseStructInfo(stag string) (toArray, omitEmpty bool, keytype valueType) {
  1137. keytype = valueTypeString // default
  1138. if stag == "" {
  1139. return
  1140. }
  1141. for i, s := range strings.Split(stag, ",") {
  1142. if i == 0 {
  1143. } else {
  1144. switch s {
  1145. case "omitempty":
  1146. omitEmpty = true
  1147. case "toarray":
  1148. toArray = true
  1149. case "int":
  1150. keytype = valueTypeInt
  1151. case "uint":
  1152. keytype = valueTypeUint
  1153. case "float":
  1154. keytype = valueTypeFloat
  1155. // case "bool":
  1156. // keytype = valueTypeBool
  1157. case "string":
  1158. keytype = valueTypeString
  1159. }
  1160. }
  1161. }
  1162. return
  1163. }
  1164. func (si *structFieldInfo) parseTag(stag string) {
  1165. // if fname == "" {
  1166. // panic(errNoFieldNameToStructFieldInfo)
  1167. // }
  1168. if stag == "" {
  1169. return
  1170. }
  1171. for i, s := range strings.Split(stag, ",") {
  1172. if i == 0 {
  1173. if s != "" {
  1174. si.encName = s
  1175. }
  1176. } else {
  1177. switch s {
  1178. case "omitempty":
  1179. si.flagSet(structFieldInfoFlagOmitEmpty)
  1180. // si.omitEmpty = true
  1181. // case "toarray":
  1182. // si.toArray = true
  1183. }
  1184. }
  1185. }
  1186. }
  1187. type sfiSortedByEncName []*structFieldInfo
  1188. func (p sfiSortedByEncName) Len() int { return len(p) }
  1189. func (p sfiSortedByEncName) Less(i, j int) bool { return p[uint(i)].encName < p[uint(j)].encName }
  1190. func (p sfiSortedByEncName) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
  1191. const structFieldNodeNumToCache = 4
  1192. type structFieldNodeCache struct {
  1193. rv [structFieldNodeNumToCache]reflect.Value
  1194. idx [structFieldNodeNumToCache]uint32
  1195. num uint8
  1196. }
  1197. func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) {
  1198. for i, k := range &x.idx {
  1199. if uint8(i) == x.num {
  1200. return // break
  1201. }
  1202. if key == k {
  1203. return x.rv[i], true
  1204. }
  1205. }
  1206. return
  1207. }
  1208. func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) {
  1209. if x.num < structFieldNodeNumToCache {
  1210. x.rv[x.num] = fv
  1211. x.idx[x.num] = key
  1212. x.num++
  1213. return
  1214. }
  1215. }
  1216. type structFieldNode struct {
  1217. v reflect.Value
  1218. cache2 structFieldNodeCache
  1219. cache3 structFieldNodeCache
  1220. update bool
  1221. }
  1222. func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) {
  1223. // return si.fieldval(x.v, x.update)
  1224. // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding
  1225. // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc.
  1226. var valid bool
  1227. switch si.nis {
  1228. case 1:
  1229. fv = x.v.Field(int(si.is[0]))
  1230. case 2:
  1231. if fv, valid = x.cache2.get(uint32(si.is[0])); valid {
  1232. fv = fv.Field(int(si.is[1]))
  1233. return
  1234. }
  1235. fv = x.v.Field(int(si.is[0]))
  1236. if fv, valid = baseStructRv(fv, x.update); !valid {
  1237. return
  1238. }
  1239. x.cache2.tryAdd(fv, uint32(si.is[0]))
  1240. fv = fv.Field(int(si.is[1]))
  1241. case 3:
  1242. var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1])
  1243. if fv, valid = x.cache3.get(key); valid {
  1244. fv = fv.Field(int(si.is[2]))
  1245. return
  1246. }
  1247. fv = x.v.Field(int(si.is[0]))
  1248. if fv, valid = baseStructRv(fv, x.update); !valid {
  1249. return
  1250. }
  1251. fv = fv.Field(int(si.is[1]))
  1252. if fv, valid = baseStructRv(fv, x.update); !valid {
  1253. return
  1254. }
  1255. x.cache3.tryAdd(fv, key)
  1256. fv = fv.Field(int(si.is[2]))
  1257. default:
  1258. fv, _ = si.field(x.v, x.update)
  1259. }
  1260. return
  1261. }
  1262. func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) {
  1263. for v.Kind() == reflect.Ptr {
  1264. if v.IsNil() {
  1265. if !update {
  1266. return
  1267. }
  1268. v.Set(reflect.New(v.Type().Elem()))
  1269. }
  1270. v = v.Elem()
  1271. }
  1272. return v, true
  1273. }
  1274. type typeInfoFlag uint8
  1275. const (
  1276. typeInfoFlagComparable = 1 << iota
  1277. typeInfoFlagIsZeroer
  1278. typeInfoFlagIsZeroerPtr
  1279. )
  1280. // typeInfo keeps static (non-changing readonly)information
  1281. // about each (non-ptr) type referenced in the encode/decode sequence.
  1282. //
  1283. // During an encode/decode sequence, we work as below:
  1284. // - If base is a built in type, en/decode base value
  1285. // - If base is registered as an extension, en/decode base value
  1286. // - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
  1287. // - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
  1288. // - Else decode appropriately based on the reflect.Kind
  1289. type typeInfo struct {
  1290. rt reflect.Type
  1291. elem reflect.Type
  1292. pkgpath string
  1293. rtid uintptr
  1294. // rv0 reflect.Value // saved zero value, used if immutableKind
  1295. numMeth uint16 // number of methods
  1296. kind uint8
  1297. chandir uint8
  1298. anyOmitEmpty bool // true if a struct, and any of the fields are tagged "omitempty"
  1299. toArray bool // whether this (struct) type should be encoded as an array
  1300. keyType valueType // if struct, how is the field name stored in a stream? default is string
  1301. mbs bool // base type (T or *T) is a MapBySlice
  1302. // ---- cpu cache line boundary?
  1303. sfiSort []*structFieldInfo // sorted. Used when enc/dec struct to map.
  1304. sfiSrc []*structFieldInfo // unsorted. Used when enc/dec struct to array.
  1305. key reflect.Type
  1306. // ---- cpu cache line boundary?
  1307. // sfis []structFieldInfo // all sfi, in src order, as created.
  1308. sfiNamesSort []byte // all names, with indexes into the sfiSort
  1309. // format of marshal type fields below: [btj][mu]p? OR csp?
  1310. bm bool // T is a binaryMarshaler
  1311. bmp bool // *T is a binaryMarshaler
  1312. bu bool // T is a binaryUnmarshaler
  1313. bup bool // *T is a binaryUnmarshaler
  1314. tm bool // T is a textMarshaler
  1315. tmp bool // *T is a textMarshaler
  1316. tu bool // T is a textUnmarshaler
  1317. tup bool // *T is a textUnmarshaler
  1318. jm bool // T is a jsonMarshaler
  1319. jmp bool // *T is a jsonMarshaler
  1320. ju bool // T is a jsonUnmarshaler
  1321. jup bool // *T is a jsonUnmarshaler
  1322. cs bool // T is a Selfer
  1323. csp bool // *T is a Selfer
  1324. mf bool // T is a MissingFielder
  1325. mfp bool // *T is a MissingFielder
  1326. // other flags, with individual bits representing if set.
  1327. flags typeInfoFlag
  1328. infoFieldOmitempty bool
  1329. // _ [6]byte // padding
  1330. // _ [2]uint64 // padding
  1331. }
  1332. func (ti *typeInfo) isFlag(f typeInfoFlag) bool {
  1333. return ti.flags&f != 0
  1334. }
  1335. func (ti *typeInfo) indexForEncName(name []byte) (index int16) {
  1336. var sn []byte
  1337. if len(name)+2 <= 32 {
  1338. var buf [32]byte // should not escape to heap
  1339. sn = buf[:len(name)+2]
  1340. } else {
  1341. sn = make([]byte, len(name)+2)
  1342. }
  1343. copy(sn[1:], name)
  1344. sn[0], sn[len(sn)-1] = tiSep2(name), 0xff
  1345. j := bytes.Index(ti.sfiNamesSort, sn)
  1346. if j < 0 {
  1347. return -1
  1348. }
  1349. index = int16(uint16(ti.sfiNamesSort[j+len(sn)+1]) | uint16(ti.sfiNamesSort[j+len(sn)])<<8)
  1350. return
  1351. }
  1352. type rtid2ti struct {
  1353. rtid uintptr
  1354. ti *typeInfo
  1355. }
  1356. // TypeInfos caches typeInfo for each type on first inspection.
  1357. //
  1358. // It is configured with a set of tag keys, which are used to get
  1359. // configuration for the type.
  1360. type TypeInfos struct {
  1361. // infos: formerly map[uintptr]*typeInfo, now *[]rtid2ti, 2 words expected
  1362. infos atomicTypeInfoSlice
  1363. mu sync.Mutex
  1364. _ uint64 // padding (cache-aligned)
  1365. tags []string
  1366. _ uint64 // padding (cache-aligned)
  1367. }
  1368. // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
  1369. //
  1370. // This allows users customize the struct tag keys which contain configuration
  1371. // of their types.
  1372. func NewTypeInfos(tags []string) *TypeInfos {
  1373. return &TypeInfos{tags: tags}
  1374. }
  1375. func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
  1376. // check for tags: codec, json, in that order.
  1377. // this allows seamless support for many configured structs.
  1378. for _, x := range x.tags {
  1379. s = t.Get(x)
  1380. if s != "" {
  1381. return s
  1382. }
  1383. }
  1384. return
  1385. }
  1386. func findTypeInfo(s []rtid2ti, rtid uintptr) (i uint, ti *typeInfo) {
  1387. // binary search. adapted from sort/search.go.
  1388. // Note: we use goto (instead of for loop) so this can be inlined.
  1389. // if sp == nil {
  1390. // return -1, nil
  1391. // }
  1392. // s := *sp
  1393. // h, i, j := 0, 0, len(s)
  1394. var h uint // var h, i uint
  1395. var j = uint(len(s))
  1396. LOOP:
  1397. if i < j {
  1398. h = i + (j-i)/2
  1399. if s[h].rtid < rtid {
  1400. i = h + 1
  1401. } else {
  1402. j = h
  1403. }
  1404. goto LOOP
  1405. }
  1406. if i < uint(len(s)) && s[i].rtid == rtid {
  1407. ti = s[i].ti
  1408. }
  1409. return
  1410. }
  1411. func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  1412. sp := x.infos.load()
  1413. if sp != nil {
  1414. _, pti = findTypeInfo(sp, rtid)
  1415. if pti != nil {
  1416. return
  1417. }
  1418. }
  1419. rk := rt.Kind()
  1420. if rk == reflect.Ptr { // || (rk == reflect.Interface && rtid != intfTypId) {
  1421. panicv.errorf("invalid kind passed to TypeInfos.get: %v - %v", rk, rt)
  1422. }
  1423. // do not hold lock while computing this.
  1424. // it may lead to duplication, but that's ok.
  1425. ti := typeInfo{
  1426. rt: rt,
  1427. rtid: rtid,
  1428. kind: uint8(rk),
  1429. pkgpath: rt.PkgPath(),
  1430. keyType: valueTypeString, // default it - so it's never 0
  1431. }
  1432. // ti.rv0 = reflect.Zero(rt)
  1433. // ti.comparable = rt.Comparable()
  1434. ti.numMeth = uint16(rt.NumMethod())
  1435. ti.bm, ti.bmp = implIntf(rt, binaryMarshalerTyp)
  1436. ti.bu, ti.bup = implIntf(rt, binaryUnmarshalerTyp)
  1437. ti.tm, ti.tmp = implIntf(rt, textMarshalerTyp)
  1438. ti.tu, ti.tup = implIntf(rt, textUnmarshalerTyp)
  1439. ti.jm, ti.jmp = implIntf(rt, jsonMarshalerTyp)
  1440. ti.ju, ti.jup = implIntf(rt, jsonUnmarshalerTyp)
  1441. ti.cs, ti.csp = implIntf(rt, selferTyp)
  1442. ti.mf, ti.mfp = implIntf(rt, missingFielderTyp)
  1443. b1, b2 := implIntf(rt, iszeroTyp)
  1444. if b1 {
  1445. ti.flags |= typeInfoFlagIsZeroer
  1446. }
  1447. if b2 {
  1448. ti.flags |= typeInfoFlagIsZeroerPtr
  1449. }
  1450. if rt.Comparable() {
  1451. ti.flags |= typeInfoFlagComparable
  1452. }
  1453. switch rk {
  1454. case reflect.Struct:
  1455. var omitEmpty bool
  1456. if f, ok := rt.FieldByName(structInfoFieldName); ok {
  1457. ti.toArray, omitEmpty, ti.keyType = parseStructInfo(x.structTag(f.Tag))
  1458. ti.infoFieldOmitempty = omitEmpty
  1459. } else {
  1460. ti.keyType = valueTypeString
  1461. }
  1462. pp, pi := &pool.tiload, pool.tiload.Get() // pool.tiLoad()
  1463. pv := pi.(*typeInfoLoadArray)
  1464. pv.etypes[0] = ti.rtid
  1465. // vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]}
  1466. vv := typeInfoLoad{pv.etypes[:1], pv.sfis[:0]}
  1467. x.rget(rt, rtid, omitEmpty, nil, &vv)
  1468. // ti.sfis = vv.sfis
  1469. ti.sfiSrc, ti.sfiSort, ti.sfiNamesSort, ti.anyOmitEmpty = rgetResolveSFI(rt, vv.sfis, pv)
  1470. pp.Put(pi)
  1471. case reflect.Map:
  1472. ti.elem = rt.Elem()
  1473. ti.key = rt.Key()
  1474. case reflect.Slice:
  1475. ti.mbs, _ = implIntf(rt, mapBySliceTyp)
  1476. ti.elem = rt.Elem()
  1477. case reflect.Chan:
  1478. ti.elem = rt.Elem()
  1479. ti.chandir = uint8(rt.ChanDir())
  1480. case reflect.Array, reflect.Ptr:
  1481. ti.elem = rt.Elem()
  1482. }
  1483. // sfi = sfiSrc
  1484. x.mu.Lock()
  1485. sp = x.infos.load()
  1486. var sp2 []rtid2ti
  1487. if sp == nil {
  1488. pti = &ti
  1489. sp2 = []rtid2ti{{rtid, pti}}
  1490. x.infos.store(sp2)
  1491. } else {
  1492. var idx uint
  1493. idx, pti = findTypeInfo(sp, rtid)
  1494. if pti == nil {
  1495. pti = &ti
  1496. sp2 = make([]rtid2ti, len(sp)+1)
  1497. copy(sp2, sp[:idx])
  1498. copy(sp2[idx+1:], sp[idx:])
  1499. sp2[idx] = rtid2ti{rtid, pti}
  1500. x.infos.store(sp2)
  1501. }
  1502. }
  1503. x.mu.Unlock()
  1504. return
  1505. }
  1506. func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool,
  1507. indexstack []uint16, pv *typeInfoLoad) {
  1508. // Read up fields and store how to access the value.
  1509. //
  1510. // It uses go's rules for message selectors,
  1511. // which say that the field with the shallowest depth is selected.
  1512. //
  1513. // Note: we consciously use slices, not a map, to simulate a set.
  1514. // Typically, types have < 16 fields,
  1515. // and iteration using equals is faster than maps there
  1516. flen := rt.NumField()
  1517. if flen > (1<<maxLevelsEmbedding - 1) {
  1518. panicv.errorf("codec: types with > %v fields are not supported - has %v fields",
  1519. (1<<maxLevelsEmbedding - 1), flen)
  1520. }
  1521. // pv.sfis = make([]structFieldInfo, flen)
  1522. LOOP:
  1523. for j, jlen := uint16(0), uint16(flen); j < jlen; j++ {
  1524. f := rt.Field(int(j))
  1525. fkind := f.Type.Kind()
  1526. // skip if a func type, or is unexported, or structTag value == "-"
  1527. switch fkind {
  1528. case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
  1529. continue LOOP
  1530. }
  1531. isUnexported := f.PkgPath != ""
  1532. if isUnexported && !f.Anonymous {
  1533. continue
  1534. }
  1535. stag := x.structTag(f.Tag)
  1536. if stag == "-" {
  1537. continue
  1538. }
  1539. var si structFieldInfo
  1540. var parsed bool
  1541. // if anonymous and no struct tag (or it's blank),
  1542. // and a struct (or pointer to struct), inline it.
  1543. if f.Anonymous && fkind != reflect.Interface {
  1544. // ^^ redundant but ok: per go spec, an embedded pointer type cannot be to an interface
  1545. ft := f.Type
  1546. isPtr := ft.Kind() == reflect.Ptr
  1547. for ft.Kind() == reflect.Ptr {
  1548. ft = ft.Elem()
  1549. }
  1550. isStruct := ft.Kind() == reflect.Struct
  1551. // Ignore embedded fields of unexported non-struct types.
  1552. // Also, from go1.10, ignore pointers to unexported struct types
  1553. // because unmarshal cannot assign a new struct to an unexported field.
  1554. // See https://golang.org/issue/21357
  1555. if (isUnexported && !isStruct) || (!allowSetUnexportedEmbeddedPtr && isUnexported && isPtr) {
  1556. continue
  1557. }
  1558. doInline := stag == ""
  1559. if !doInline {
  1560. si.parseTag(stag)
  1561. parsed = true
  1562. doInline = si.encName == ""
  1563. // doInline = si.isZero()
  1564. }
  1565. if doInline && isStruct {
  1566. // if etypes contains this, don't call rget again (as fields are already seen here)
  1567. ftid := rt2id(ft)
  1568. // We cannot recurse forever, but we need to track other field depths.
  1569. // So - we break if we see a type twice (not the first time).
  1570. // This should be sufficient to handle an embedded type that refers to its
  1571. // owning type, which then refers to its embedded type.
  1572. processIt := true
  1573. numk := 0
  1574. for _, k := range pv.etypes {
  1575. if k == ftid {
  1576. numk++
  1577. if numk == rgetMaxRecursion {
  1578. processIt = false
  1579. break
  1580. }
  1581. }
  1582. }
  1583. if processIt {
  1584. pv.etypes = append(pv.etypes, ftid)
  1585. indexstack2 := make([]uint16, len(indexstack)+1)
  1586. copy(indexstack2, indexstack)
  1587. indexstack2[len(indexstack)] = j
  1588. // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
  1589. x.rget(ft, ftid, omitEmpty, indexstack2, pv)
  1590. }
  1591. continue
  1592. }
  1593. }
  1594. // after the anonymous dance: if an unexported field, skip
  1595. if isUnexported {
  1596. continue
  1597. }
  1598. if f.Name == "" {
  1599. panic(errNoFieldNameToStructFieldInfo)
  1600. }
  1601. // pv.fNames = append(pv.fNames, f.Name)
  1602. // if si.encName == "" {
  1603. if !parsed {
  1604. si.encName = f.Name
  1605. si.parseTag(stag)
  1606. parsed = true
  1607. } else if si.encName == "" {
  1608. si.encName = f.Name
  1609. }
  1610. si.encNameAsciiAlphaNum = true
  1611. for i := len(si.encName) - 1; i >= 0; i-- { // bounds-check elimination
  1612. b := si.encName[i]
  1613. if (b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') {
  1614. continue
  1615. }
  1616. si.encNameAsciiAlphaNum = false
  1617. break
  1618. }
  1619. si.fieldName = f.Name
  1620. si.flagSet(structFieldInfoFlagReady)
  1621. // pv.encNames = append(pv.encNames, si.encName)
  1622. // si.ikind = int(f.Type.Kind())
  1623. if len(indexstack) > maxLevelsEmbedding-1 {
  1624. panicv.errorf("codec: only supports up to %v depth of embedding - type has %v depth",
  1625. maxLevelsEmbedding-1, len(indexstack))
  1626. }
  1627. si.nis = uint8(len(indexstack)) + 1
  1628. copy(si.is[:], indexstack)
  1629. si.is[len(indexstack)] = j
  1630. if omitEmpty {
  1631. si.flagSet(structFieldInfoFlagOmitEmpty)
  1632. }
  1633. pv.sfis = append(pv.sfis, si)
  1634. }
  1635. }
  1636. func tiSep(name string) uint8 {
  1637. // (xn[0]%64) // (between 192-255 - outside ascii BMP)
  1638. // return 0xfe - (name[0] & 63)
  1639. // return 0xfe - (name[0] & 63) - uint8(len(name))
  1640. // return 0xfe - (name[0] & 63) - uint8(len(name)&63)
  1641. // return ((0xfe - (name[0] & 63)) & 0xf8) | (uint8(len(name) & 0x07))
  1642. return 0xfe - (name[0] & 63) - uint8(len(name)&63)
  1643. }
  1644. func tiSep2(name []byte) uint8 {
  1645. return 0xfe - (name[0] & 63) - uint8(len(name)&63)
  1646. }
  1647. // resolves the struct field info got from a call to rget.
  1648. // Returns a trimmed, unsorted and sorted []*structFieldInfo.
  1649. func rgetResolveSFI(rt reflect.Type, x []structFieldInfo, pv *typeInfoLoadArray) (
  1650. y, z []*structFieldInfo, ss []byte, anyOmitEmpty bool) {
  1651. sa := pv.sfiidx[:0]
  1652. sn := pv.b[:]
  1653. n := len(x)
  1654. var xn string
  1655. var ui uint16
  1656. var sep byte
  1657. for i := range x {
  1658. ui = uint16(i)
  1659. xn = x[i].encName // fieldName or encName? use encName for now.
  1660. if len(xn)+2 > cap(sn) {
  1661. sn = make([]byte, len(xn)+2)
  1662. } else {
  1663. sn = sn[:len(xn)+2]
  1664. }
  1665. // use a custom sep, so that misses are less frequent,
  1666. // since the sep (first char in search) is as unique as first char in field name.
  1667. sep = tiSep(xn)
  1668. sn[0], sn[len(sn)-1] = sep, 0xff
  1669. copy(sn[1:], xn)
  1670. j := bytes.Index(sa, sn)
  1671. if j == -1 {
  1672. sa = append(sa, sep)
  1673. sa = append(sa, xn...)
  1674. sa = append(sa, 0xff, byte(ui>>8), byte(ui))
  1675. } else {
  1676. index := uint16(sa[j+len(sn)+1]) | uint16(sa[j+len(sn)])<<8
  1677. // one of them must be cleared (reset to nil),
  1678. // and the index updated appropriately
  1679. i2clear := ui // index to be cleared
  1680. if x[i].nis < x[index].nis { // this one is shallower
  1681. // update the index to point to this later one.
  1682. sa[j+len(sn)], sa[j+len(sn)+1] = byte(ui>>8), byte(ui)
  1683. // clear the earlier one, as this later one is shallower.
  1684. i2clear = index
  1685. }
  1686. if x[i2clear].ready() {
  1687. x[i2clear].flagClr(structFieldInfoFlagReady)
  1688. n--
  1689. }
  1690. }
  1691. }
  1692. var w []structFieldInfo
  1693. sharingArray := len(x) <= typeInfoLoadArraySfisLen // sharing array with typeInfoLoadArray
  1694. if sharingArray {
  1695. w = make([]structFieldInfo, n)
  1696. }
  1697. // remove all the nils (non-ready)
  1698. y = make([]*structFieldInfo, n)
  1699. n = 0
  1700. var sslen int
  1701. for i := range x {
  1702. if !x[i].ready() {
  1703. continue
  1704. }
  1705. if !anyOmitEmpty && x[i].omitEmpty() {
  1706. anyOmitEmpty = true
  1707. }
  1708. if sharingArray {
  1709. w[n] = x[i]
  1710. y[n] = &w[n]
  1711. } else {
  1712. y[n] = &x[i]
  1713. }
  1714. sslen = sslen + len(x[i].encName) + 4
  1715. n++
  1716. }
  1717. if n != len(y) {
  1718. panicv.errorf("failure reading struct %v - expecting %d of %d valid fields, got %d",
  1719. rt, len(y), len(x), n)
  1720. }
  1721. z = make([]*structFieldInfo, len(y))
  1722. copy(z, y)
  1723. sort.Sort(sfiSortedByEncName(z))
  1724. sharingArray = len(sa) <= typeInfoLoadArraySfiidxLen
  1725. if sharingArray {
  1726. ss = make([]byte, 0, sslen)
  1727. } else {
  1728. ss = sa[:0] // reuse the newly made sa array if necessary
  1729. }
  1730. for i := range z {
  1731. xn = z[i].encName
  1732. sep = tiSep(xn)
  1733. ui = uint16(i)
  1734. ss = append(ss, sep)
  1735. ss = append(ss, xn...)
  1736. ss = append(ss, 0xff, byte(ui>>8), byte(ui))
  1737. }
  1738. return
  1739. }
  1740. func implIntf(rt, iTyp reflect.Type) (base bool, indir bool) {
  1741. return rt.Implements(iTyp), reflect.PtrTo(rt).Implements(iTyp)
  1742. }
  1743. // isEmptyStruct is only called from isEmptyValue, and checks if a struct is empty:
  1744. // - does it implement IsZero() bool
  1745. // - is it comparable, and can i compare directly using ==
  1746. // - if checkStruct, then walk through the encodable fields
  1747. // and check if they are empty or not.
  1748. func isEmptyStruct(v reflect.Value, tinfos *TypeInfos, deref, checkStruct bool) bool {
  1749. // v is a struct kind - no need to check again.
  1750. // We only check isZero on a struct kind, to reduce the amount of times
  1751. // that we lookup the rtid and typeInfo for each type as we walk the tree.
  1752. vt := v.Type()
  1753. rtid := rt2id(vt)
  1754. if tinfos == nil {
  1755. tinfos = defTypeInfos
  1756. }
  1757. ti := tinfos.get(rtid, vt)
  1758. if ti.rtid == timeTypId {
  1759. return rv2i(v).(time.Time).IsZero()
  1760. }
  1761. if ti.isFlag(typeInfoFlagIsZeroerPtr) && v.CanAddr() {
  1762. return rv2i(v.Addr()).(isZeroer).IsZero()
  1763. }
  1764. if ti.isFlag(typeInfoFlagIsZeroer) {
  1765. return rv2i(v).(isZeroer).IsZero()
  1766. }
  1767. if ti.isFlag(typeInfoFlagComparable) {
  1768. return rv2i(v) == rv2i(reflect.Zero(vt))
  1769. }
  1770. if !checkStruct {
  1771. return false
  1772. }
  1773. // We only care about what we can encode/decode,
  1774. // so that is what we use to check omitEmpty.
  1775. for _, si := range ti.sfiSrc {
  1776. sfv, valid := si.field(v, false)
  1777. if valid && !isEmptyValue(sfv, tinfos, deref, checkStruct) {
  1778. return false
  1779. }
  1780. }
  1781. return true
  1782. }
  1783. // func roundFloat(x float64) float64 {
  1784. // t := math.Trunc(x)
  1785. // if math.Abs(x-t) >= 0.5 {
  1786. // return t + math.Copysign(1, x)
  1787. // }
  1788. // return t
  1789. // }
  1790. func panicToErr(h errDecorator, err *error) {
  1791. // Note: This method MUST be called directly from defer i.e. defer panicToErr ...
  1792. // else it seems the recover is not fully handled
  1793. if recoverPanicToErr {
  1794. if x := recover(); x != nil {
  1795. // fmt.Printf("panic'ing with: %v\n", x)
  1796. // debug.PrintStack()
  1797. panicValToErr(h, x, err)
  1798. }
  1799. }
  1800. }
  1801. func panicValToErr(h errDecorator, v interface{}, err *error) {
  1802. switch xerr := v.(type) {
  1803. case nil:
  1804. case error:
  1805. switch xerr {
  1806. case nil:
  1807. case io.EOF, io.ErrUnexpectedEOF, errEncoderNotInitialized, errDecoderNotInitialized:
  1808. // treat as special (bubble up)
  1809. *err = xerr
  1810. default:
  1811. h.wrapErr(xerr, err)
  1812. }
  1813. case string:
  1814. if xerr != "" {
  1815. h.wrapErr(xerr, err)
  1816. }
  1817. case fmt.Stringer:
  1818. if xerr != nil {
  1819. h.wrapErr(xerr, err)
  1820. }
  1821. default:
  1822. h.wrapErr(v, err)
  1823. }
  1824. }
  1825. func isImmutableKind(k reflect.Kind) (v bool) {
  1826. // return immutableKindsSet[k]
  1827. // since we know reflect.Kind is in range 0..31, then use the k%32 == k constraint
  1828. return immutableKindsSet[k%reflect.Kind(len(immutableKindsSet))] // bounds-check-elimination
  1829. }
  1830. // ----
  1831. type codecFnInfo struct {
  1832. ti *typeInfo
  1833. xfFn Ext
  1834. xfTag uint64
  1835. seq seqType
  1836. addrD bool
  1837. addrF bool // if addrD, this says whether decode function can take a value or a ptr
  1838. addrE bool
  1839. }
  1840. // codecFn encapsulates the captured variables and the encode function.
  1841. // This way, we only do some calculations one times, and pass to the
  1842. // code block that should be called (encapsulated in a function)
  1843. // instead of executing the checks every time.
  1844. type codecFn struct {
  1845. i codecFnInfo
  1846. fe func(*Encoder, *codecFnInfo, reflect.Value)
  1847. fd func(*Decoder, *codecFnInfo, reflect.Value)
  1848. _ [1]uint64 // padding (cache-aligned)
  1849. }
  1850. type codecRtidFn struct {
  1851. rtid uintptr
  1852. fn *codecFn
  1853. }
  1854. // ----
  1855. // these "checkOverflow" functions must be inlinable, and not call anybody.
  1856. // Overflow means that the value cannot be represented without wrapping/overflow.
  1857. // Overflow=false does not mean that the value can be represented without losing precision
  1858. // (especially for floating point).
  1859. type checkOverflow struct{}
  1860. // func (checkOverflow) Float16(f float64) (overflow bool) {
  1861. // panicv.errorf("unimplemented")
  1862. // if f < 0 {
  1863. // f = -f
  1864. // }
  1865. // return math.MaxFloat32 < f && f <= math.MaxFloat64
  1866. // }
  1867. func (checkOverflow) Float32(v float64) (overflow bool) {
  1868. if v < 0 {
  1869. v = -v
  1870. }
  1871. return math.MaxFloat32 < v && v <= math.MaxFloat64
  1872. }
  1873. func (checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
  1874. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1875. return
  1876. }
  1877. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1878. overflow = true
  1879. }
  1880. return
  1881. }
  1882. func (checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
  1883. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1884. return
  1885. }
  1886. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1887. overflow = true
  1888. }
  1889. return
  1890. }
  1891. func (checkOverflow) SignedInt(v uint64) (overflow bool) {
  1892. //e.g. -127 to 128 for int8
  1893. pos := (v >> 63) == 0
  1894. ui2 := v & 0x7fffffffffffffff
  1895. if pos {
  1896. if ui2 > math.MaxInt64 {
  1897. overflow = true
  1898. }
  1899. } else {
  1900. if ui2 > math.MaxInt64-1 {
  1901. overflow = true
  1902. }
  1903. }
  1904. return
  1905. }
  1906. func (x checkOverflow) Float32V(v float64) float64 {
  1907. if x.Float32(v) {
  1908. panicv.errorf("float32 overflow: %v", v)
  1909. }
  1910. return v
  1911. }
  1912. func (x checkOverflow) UintV(v uint64, bitsize uint8) uint64 {
  1913. if x.Uint(v, bitsize) {
  1914. panicv.errorf("uint64 overflow: %v", v)
  1915. }
  1916. return v
  1917. }
  1918. func (x checkOverflow) IntV(v int64, bitsize uint8) int64 {
  1919. if x.Int(v, bitsize) {
  1920. panicv.errorf("int64 overflow: %v", v)
  1921. }
  1922. return v
  1923. }
  1924. func (x checkOverflow) SignedIntV(v uint64) int64 {
  1925. if x.SignedInt(v) {
  1926. panicv.errorf("uint64 to int64 overflow: %v", v)
  1927. }
  1928. return int64(v)
  1929. }
  1930. // ------------------ FLOATING POINT -----------------
  1931. func isNaN64(f float64) bool { return f != f }
  1932. func isNaN32(f float32) bool { return f != f }
  1933. func abs32(f float32) float32 {
  1934. return math.Float32frombits(math.Float32bits(f) &^ (1 << 31))
  1935. }
  1936. // Per go spec, floats are represented in memory as
  1937. // IEEE single or double precision floating point values.
  1938. //
  1939. // We also looked at the source for stdlib math/modf.go,
  1940. // reviewed https://github.com/chewxy/math32
  1941. // and read wikipedia documents describing the formats.
  1942. //
  1943. // It became clear that we could easily look at the bits to determine
  1944. // whether any fraction exists.
  1945. //
  1946. // This is all we need for now.
  1947. func noFrac64(f float64) (v bool) {
  1948. x := math.Float64bits(f)
  1949. e := uint64(x>>52)&0x7FF - 1023 // uint(x>>shift)&mask - bias
  1950. // clear top 12+e bits, the integer part; if the rest is 0, then no fraction.
  1951. if e < 52 {
  1952. // return x&((1<<64-1)>>(12+e)) == 0
  1953. return x<<(12+e) == 0
  1954. }
  1955. return
  1956. }
  1957. func noFrac32(f float32) (v bool) {
  1958. x := math.Float32bits(f)
  1959. e := uint32(x>>23)&0xFF - 127 // uint(x>>shift)&mask - bias
  1960. // clear top 9+e bits, the integer part; if the rest is 0, then no fraction.
  1961. if e < 23 {
  1962. // return x&((1<<32-1)>>(9+e)) == 0
  1963. return x<<(9+e) == 0
  1964. }
  1965. return
  1966. }
  1967. // func noFrac(f float64) bool {
  1968. // _, frac := math.Modf(float64(f))
  1969. // return frac == 0
  1970. // }
  1971. // -----------------------
  1972. type ioFlusher interface {
  1973. Flush() error
  1974. }
  1975. type ioPeeker interface {
  1976. Peek(int) ([]byte, error)
  1977. }
  1978. type ioBuffered interface {
  1979. Buffered() int
  1980. }
  1981. // -----------------------
  1982. type sfiRv struct {
  1983. v *structFieldInfo
  1984. r reflect.Value
  1985. }
  1986. // -----------------
  1987. type set []uintptr
  1988. func (s *set) add(v uintptr) (exists bool) {
  1989. // e.ci is always nil, or len >= 1
  1990. x := *s
  1991. // defer func() { xdebugf("set.add: len: %d", len(x)) }()
  1992. if x == nil {
  1993. x = make([]uintptr, 1, 8)
  1994. x[0] = v
  1995. *s = x
  1996. return
  1997. }
  1998. // typically, length will be 1. make this perform.
  1999. if len(x) == 1 {
  2000. if j := x[0]; j == 0 {
  2001. x[0] = v
  2002. } else if j == v {
  2003. exists = true
  2004. } else {
  2005. x = append(x, v)
  2006. *s = x
  2007. }
  2008. return
  2009. }
  2010. // check if it exists
  2011. for _, j := range x {
  2012. if j == v {
  2013. exists = true
  2014. return
  2015. }
  2016. }
  2017. // try to replace a "deleted" slot
  2018. for i, j := range x {
  2019. if j == 0 {
  2020. x[i] = v
  2021. return
  2022. }
  2023. }
  2024. // if unable to replace deleted slot, just append it.
  2025. x = append(x, v)
  2026. *s = x
  2027. return
  2028. }
  2029. func (s *set) remove(v uintptr) (exists bool) {
  2030. x := *s
  2031. if len(x) == 0 {
  2032. return
  2033. }
  2034. if len(x) == 1 {
  2035. if x[0] == v {
  2036. x[0] = 0
  2037. }
  2038. return
  2039. }
  2040. for i, j := range x {
  2041. if j == v {
  2042. exists = true
  2043. x[i] = 0 // set it to 0, as way to delete it.
  2044. // copy(x[i:], x[i+1:])
  2045. // x = x[:len(x)-1]
  2046. return
  2047. }
  2048. }
  2049. return
  2050. }
  2051. // ------
  2052. // bitset types are better than [256]bool, because they permit the whole
  2053. // bitset array being on a single cache line and use less memory.
  2054. //
  2055. // Also, since pos is a byte (0-255), there's no bounds checks on indexing (cheap).
  2056. //
  2057. // We previously had bitset128 [16]byte, and bitset32 [4]byte, but those introduces
  2058. // bounds checking, so we discarded them, and everyone uses bitset256.
  2059. //
  2060. // given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1).
  2061. // consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7
  2062. type bitset256 [32]byte
  2063. func (x *bitset256) isset(pos byte) bool {
  2064. return x[pos>>3]&(1<<(pos&7)) != 0
  2065. }
  2066. // func (x *bitset256) issetv(pos byte) byte {
  2067. // return x[pos>>3] & (1 << (pos & 7))
  2068. // }
  2069. func (x *bitset256) set(pos byte) {
  2070. x[pos>>3] |= (1 << (pos & 7))
  2071. }
  2072. // func (x *bitset256) unset(pos byte) {
  2073. // x[pos>>3] &^= (1 << (pos & 7))
  2074. // }
  2075. // type bit2set256 [64]byte
  2076. // func (x *bit2set256) set(pos byte, v1, v2 bool) {
  2077. // var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6
  2078. // if v1 {
  2079. // x[pos>>2] |= 1 << (pos2 + 1)
  2080. // }
  2081. // if v2 {
  2082. // x[pos>>2] |= 1 << pos2
  2083. // }
  2084. // }
  2085. // func (x *bit2set256) get(pos byte) uint8 {
  2086. // var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6
  2087. // return x[pos>>2] << (6 - pos2) >> 6 // 11000000 -> 00000011
  2088. // }
  2089. // ------------
  2090. type pooler struct {
  2091. // function-scoped pooled resources
  2092. tiload sync.Pool // for type info loading
  2093. sfiRv8, sfiRv16, sfiRv32, sfiRv64, sfiRv128 sync.Pool // for struct encoding
  2094. // lifetime-scoped pooled resources
  2095. // dn sync.Pool // for decNaked
  2096. buf1k, buf2k, buf4k, buf8k, buf16k, buf32k, buf64k sync.Pool // for [N]byte
  2097. }
  2098. func (p *pooler) init() {
  2099. p.tiload.New = func() interface{} { return new(typeInfoLoadArray) }
  2100. p.sfiRv8.New = func() interface{} { return new([8]sfiRv) }
  2101. p.sfiRv16.New = func() interface{} { return new([16]sfiRv) }
  2102. p.sfiRv32.New = func() interface{} { return new([32]sfiRv) }
  2103. p.sfiRv64.New = func() interface{} { return new([64]sfiRv) }
  2104. p.sfiRv128.New = func() interface{} { return new([128]sfiRv) }
  2105. // p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x }
  2106. p.buf1k.New = func() interface{} { return new([1 * 1024]byte) }
  2107. p.buf2k.New = func() interface{} { return new([2 * 1024]byte) }
  2108. p.buf4k.New = func() interface{} { return new([4 * 1024]byte) }
  2109. p.buf8k.New = func() interface{} { return new([8 * 1024]byte) }
  2110. p.buf16k.New = func() interface{} { return new([16 * 1024]byte) }
  2111. p.buf32k.New = func() interface{} { return new([32 * 1024]byte) }
  2112. p.buf64k.New = func() interface{} { return new([64 * 1024]byte) }
  2113. }
  2114. // func (p *pooler) sfiRv8() (sp *sync.Pool, v interface{}) {
  2115. // return &p.strRv8, p.strRv8.Get()
  2116. // }
  2117. // func (p *pooler) sfiRv16() (sp *sync.Pool, v interface{}) {
  2118. // return &p.strRv16, p.strRv16.Get()
  2119. // }
  2120. // func (p *pooler) sfiRv32() (sp *sync.Pool, v interface{}) {
  2121. // return &p.strRv32, p.strRv32.Get()
  2122. // }
  2123. // func (p *pooler) sfiRv64() (sp *sync.Pool, v interface{}) {
  2124. // return &p.strRv64, p.strRv64.Get()
  2125. // }
  2126. // func (p *pooler) sfiRv128() (sp *sync.Pool, v interface{}) {
  2127. // return &p.strRv128, p.strRv128.Get()
  2128. // }
  2129. // func (p *pooler) bytes1k() (sp *sync.Pool, v interface{}) {
  2130. // return &p.buf1k, p.buf1k.Get()
  2131. // }
  2132. // func (p *pooler) bytes2k() (sp *sync.Pool, v interface{}) {
  2133. // return &p.buf2k, p.buf2k.Get()
  2134. // }
  2135. // func (p *pooler) bytes4k() (sp *sync.Pool, v interface{}) {
  2136. // return &p.buf4k, p.buf4k.Get()
  2137. // }
  2138. // func (p *pooler) bytes8k() (sp *sync.Pool, v interface{}) {
  2139. // return &p.buf8k, p.buf8k.Get()
  2140. // }
  2141. // func (p *pooler) bytes16k() (sp *sync.Pool, v interface{}) {
  2142. // return &p.buf16k, p.buf16k.Get()
  2143. // }
  2144. // func (p *pooler) bytes32k() (sp *sync.Pool, v interface{}) {
  2145. // return &p.buf32k, p.buf32k.Get()
  2146. // }
  2147. // func (p *pooler) bytes64k() (sp *sync.Pool, v interface{}) {
  2148. // return &p.buf64k, p.buf64k.Get()
  2149. // }
  2150. // func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) {
  2151. // return &p.tiload, p.tiload.Get()
  2152. // }
  2153. // func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) {
  2154. // return &p.dn, p.dn.Get()
  2155. // }
  2156. // func (p *pooler) decNaked() (v *decNaked, f func(*decNaked) ) {
  2157. // sp := &(p.dn)
  2158. // vv := sp.Get()
  2159. // return vv.(*decNaked), func(x *decNaked) { sp.Put(vv) }
  2160. // }
  2161. // func (p *pooler) decNakedGet() (v interface{}) {
  2162. // return p.dn.Get()
  2163. // }
  2164. // func (p *pooler) tiLoadGet() (v interface{}) {
  2165. // return p.tiload.Get()
  2166. // }
  2167. // func (p *pooler) decNakedPut(v interface{}) {
  2168. // p.dn.Put(v)
  2169. // }
  2170. // func (p *pooler) tiLoadPut(v interface{}) {
  2171. // p.tiload.Put(v)
  2172. // }
  2173. // ----------------------------------------------------
  2174. type panicHdl struct{}
  2175. func (panicHdl) errorv(err error) {
  2176. if err != nil {
  2177. panic(err)
  2178. }
  2179. }
  2180. func (panicHdl) errorstr(message string) {
  2181. if message != "" {
  2182. panic(message)
  2183. }
  2184. }
  2185. func (panicHdl) errorf(format string, params ...interface{}) {
  2186. if format == "" {
  2187. } else if len(params) == 0 {
  2188. panic(format)
  2189. } else {
  2190. panic(fmt.Sprintf(format, params...))
  2191. }
  2192. }
  2193. // ----------------------------------------------------
  2194. type errDecorator interface {
  2195. wrapErr(in interface{}, out *error)
  2196. }
  2197. type errDecoratorDef struct{}
  2198. func (errDecoratorDef) wrapErr(v interface{}, e *error) { *e = fmt.Errorf("%v", v) }
  2199. // ----------------------------------------------------
  2200. type must struct{}
  2201. func (must) String(s string, err error) string {
  2202. if err != nil {
  2203. panicv.errorv(err)
  2204. }
  2205. return s
  2206. }
  2207. func (must) Int(s int64, err error) int64 {
  2208. if err != nil {
  2209. panicv.errorv(err)
  2210. }
  2211. return s
  2212. }
  2213. func (must) Uint(s uint64, err error) uint64 {
  2214. if err != nil {
  2215. panicv.errorv(err)
  2216. }
  2217. return s
  2218. }
  2219. func (must) Float(s float64, err error) float64 {
  2220. if err != nil {
  2221. panicv.errorv(err)
  2222. }
  2223. return s
  2224. }
  2225. // -------------------
  2226. type bytesBufPooler struct {
  2227. pool *sync.Pool
  2228. poolbuf interface{}
  2229. }
  2230. func (z *bytesBufPooler) end() {
  2231. if z.pool != nil {
  2232. z.pool.Put(z.poolbuf)
  2233. z.pool, z.poolbuf = nil, nil
  2234. }
  2235. }
  2236. func (z *bytesBufPooler) get(bufsize int) (buf []byte) {
  2237. // ensure an end is called first (if necessary)
  2238. if z.pool != nil {
  2239. z.pool.Put(z.poolbuf)
  2240. z.pool, z.poolbuf = nil, nil
  2241. }
  2242. // // Try to use binary search.
  2243. // // This is not optimal, as most folks select 1k or 2k buffers
  2244. // // so a linear search is better (sequence of if/else blocks)
  2245. // if bufsize < 1 {
  2246. // bufsize = 0
  2247. // } else {
  2248. // bufsize--
  2249. // bufsize /= 1024
  2250. // }
  2251. // switch bufsize {
  2252. // case 0:
  2253. // z.pool, z.poolbuf = pool.bytes1k()
  2254. // buf = z.poolbuf.(*[1 * 1024]byte)[:]
  2255. // case 1:
  2256. // z.pool, z.poolbuf = pool.bytes2k()
  2257. // buf = z.poolbuf.(*[2 * 1024]byte)[:]
  2258. // case 2, 3:
  2259. // z.pool, z.poolbuf = pool.bytes4k()
  2260. // buf = z.poolbuf.(*[4 * 1024]byte)[:]
  2261. // case 4, 5, 6, 7:
  2262. // z.pool, z.poolbuf = pool.bytes8k()
  2263. // buf = z.poolbuf.(*[8 * 1024]byte)[:]
  2264. // case 8, 9, 10, 11, 12, 13, 14, 15:
  2265. // z.pool, z.poolbuf = pool.bytes16k()
  2266. // buf = z.poolbuf.(*[16 * 1024]byte)[:]
  2267. // case 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31:
  2268. // z.pool, z.poolbuf = pool.bytes32k()
  2269. // buf = z.poolbuf.(*[32 * 1024]byte)[:]
  2270. // default:
  2271. // z.pool, z.poolbuf = pool.bytes64k()
  2272. // buf = z.poolbuf.(*[64 * 1024]byte)[:]
  2273. // }
  2274. // return
  2275. if bufsize <= 1*1024 {
  2276. z.pool, z.poolbuf = &pool.buf1k, pool.buf1k.Get() // pool.bytes1k()
  2277. buf = z.poolbuf.(*[1 * 1024]byte)[:]
  2278. } else if bufsize <= 2*1024 {
  2279. z.pool, z.poolbuf = &pool.buf2k, pool.buf2k.Get() // pool.bytes2k()
  2280. buf = z.poolbuf.(*[2 * 1024]byte)[:]
  2281. } else if bufsize <= 4*1024 {
  2282. z.pool, z.poolbuf = &pool.buf4k, pool.buf4k.Get() // pool.bytes4k()
  2283. buf = z.poolbuf.(*[4 * 1024]byte)[:]
  2284. } else if bufsize <= 8*1024 {
  2285. z.pool, z.poolbuf = &pool.buf8k, pool.buf8k.Get() // pool.bytes8k()
  2286. buf = z.poolbuf.(*[8 * 1024]byte)[:]
  2287. } else if bufsize <= 16*1024 {
  2288. z.pool, z.poolbuf = &pool.buf16k, pool.buf16k.Get() // pool.bytes16k()
  2289. buf = z.poolbuf.(*[16 * 1024]byte)[:]
  2290. } else if bufsize <= 32*1024 {
  2291. z.pool, z.poolbuf = &pool.buf32k, pool.buf32k.Get() // pool.bytes32k()
  2292. buf = z.poolbuf.(*[32 * 1024]byte)[:]
  2293. } else {
  2294. z.pool, z.poolbuf = &pool.buf64k, pool.buf64k.Get() // pool.bytes64k()
  2295. buf = z.poolbuf.(*[64 * 1024]byte)[:]
  2296. }
  2297. return
  2298. }
  2299. // ----------------
  2300. type sfiRvPooler struct {
  2301. pool *sync.Pool
  2302. poolv interface{}
  2303. }
  2304. func (z *sfiRvPooler) end() {
  2305. if z.pool != nil {
  2306. z.pool.Put(z.poolv)
  2307. z.pool, z.poolv = nil, nil
  2308. }
  2309. }
  2310. func (z *sfiRvPooler) get(newlen int) (fkvs []sfiRv) {
  2311. if newlen < 0 { // bounds-check-elimination
  2312. // cannot happen // here for bounds-check-elimination
  2313. } else if newlen <= 8 {
  2314. z.pool, z.poolv = &pool.sfiRv8, pool.sfiRv8.Get() // pool.sfiRv8()
  2315. fkvs = z.poolv.(*[8]sfiRv)[:newlen]
  2316. } else if newlen <= 16 {
  2317. z.pool, z.poolv = &pool.sfiRv16, pool.sfiRv16.Get() // pool.sfiRv16()
  2318. fkvs = z.poolv.(*[16]sfiRv)[:newlen]
  2319. } else if newlen <= 32 {
  2320. z.pool, z.poolv = &pool.sfiRv32, pool.sfiRv32.Get() // pool.sfiRv32()
  2321. fkvs = z.poolv.(*[32]sfiRv)[:newlen]
  2322. } else if newlen <= 64 {
  2323. z.pool, z.poolv = &pool.sfiRv64, pool.sfiRv64.Get() // pool.sfiRv64()
  2324. fkvs = z.poolv.(*[64]sfiRv)[:newlen]
  2325. } else if newlen <= 128 {
  2326. z.pool, z.poolv = &pool.sfiRv128, pool.sfiRv128.Get() // pool.sfiRv128()
  2327. fkvs = z.poolv.(*[128]sfiRv)[:newlen]
  2328. } else {
  2329. fkvs = make([]sfiRv, newlen)
  2330. }
  2331. return
  2332. }
  2333. // xdebugf printf. the message in red on the terminal.
  2334. // Use it in place of fmt.Printf (which it calls internally)
  2335. func xdebugf(pattern string, args ...interface{}) {
  2336. var delim string
  2337. if len(pattern) > 0 && pattern[len(pattern)-1] != '\n' {
  2338. delim = "\n"
  2339. }
  2340. fmt.Printf("\033[1;31m"+pattern+delim+"\033[0m", args...)
  2341. }
  2342. // xdebug2f printf. the message in blue on the terminal.
  2343. // Use it in place of fmt.Printf (which it calls internally)
  2344. func xdebug2f(pattern string, args ...interface{}) {
  2345. var delim string
  2346. if len(pattern) > 0 && pattern[len(pattern)-1] != '\n' {
  2347. delim = "\n"
  2348. }
  2349. fmt.Printf("\033[1;34m"+pattern+delim+"\033[0m", args...)
  2350. }
  2351. // func isImmutableKind(k reflect.Kind) (v bool) {
  2352. // return false ||
  2353. // k == reflect.Int ||
  2354. // k == reflect.Int8 ||
  2355. // k == reflect.Int16 ||
  2356. // k == reflect.Int32 ||
  2357. // k == reflect.Int64 ||
  2358. // k == reflect.Uint ||
  2359. // k == reflect.Uint8 ||
  2360. // k == reflect.Uint16 ||
  2361. // k == reflect.Uint32 ||
  2362. // k == reflect.Uint64 ||
  2363. // k == reflect.Uintptr ||
  2364. // k == reflect.Float32 ||
  2365. // k == reflect.Float64 ||
  2366. // k == reflect.Bool ||
  2367. // k == reflect.String
  2368. // }
  2369. // func timeLocUTCName(tzint int16) string {
  2370. // if tzint == 0 {
  2371. // return "UTC"
  2372. // }
  2373. // var tzname = []byte("UTC+00:00")
  2374. // //tzname := fmt.Sprintf("UTC%s%02d:%02d", tzsign, tz/60, tz%60) //perf issue using Sprintf.. inline below.
  2375. // //tzhr, tzmin := tz/60, tz%60 //faster if u convert to int first
  2376. // var tzhr, tzmin int16
  2377. // if tzint < 0 {
  2378. // tzname[3] = '-' // (TODO: verify. this works here)
  2379. // tzhr, tzmin = -tzint/60, (-tzint)%60
  2380. // } else {
  2381. // tzhr, tzmin = tzint/60, tzint%60
  2382. // }
  2383. // tzname[4] = timeDigits[tzhr/10]
  2384. // tzname[5] = timeDigits[tzhr%10]
  2385. // tzname[7] = timeDigits[tzmin/10]
  2386. // tzname[8] = timeDigits[tzmin%10]
  2387. // return string(tzname)
  2388. // //return time.FixedZone(string(tzname), int(tzint)*60)
  2389. // }