helper.go 89 KB

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