helper.go 87 KB

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