helper.go 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987
  1. // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. // Contains code shared by both encode and decode.
  5. // Some shared ideas around encoding/decoding
  6. // ------------------------------------------
  7. //
  8. // If an interface{} is passed, we first do a type assertion to see if it is
  9. // a primitive type or a map/slice of primitive types, and use a fastpath to handle it.
  10. //
  11. // If we start with a reflect.Value, we are already in reflect.Value land and
  12. // will try to grab the function for the underlying Type and directly call that function.
  13. // This is more performant than calling reflect.Value.Interface().
  14. //
  15. // This still helps us bypass many layers of reflection, and give best performance.
  16. //
  17. // Containers
  18. // ------------
  19. // Containers in the stream are either associative arrays (key-value pairs) or
  20. // regular arrays (indexed by incrementing integers).
  21. //
  22. // Some streams support indefinite-length containers, and use a breaking
  23. // byte-sequence to denote that the container has come to an end.
  24. //
  25. // Some streams also are text-based, and use explicit separators to denote the
  26. // end/beginning of different values.
  27. //
  28. // Philosophy
  29. // ------------
  30. // On decode, this codec will update containers appropriately:
  31. // - If struct, update fields from stream into fields of struct.
  32. // If field in stream not found in struct, handle appropriately (based on option).
  33. // If a struct field has no corresponding value in the stream, leave it AS IS.
  34. // If nil in stream, set value to nil/zero value.
  35. // - If map, update map from stream.
  36. // If the stream value is NIL, set the map to nil.
  37. // - if slice, try to update up to length of array in stream.
  38. // if container len is less than stream array length,
  39. // and container cannot be expanded, handled (based on option).
  40. // This means you can decode 4-element stream array into 1-element array.
  41. //
  42. // ------------------------------------
  43. // On encode, user can specify omitEmpty. This means that the value will be omitted
  44. // if the zero value. The problem may occur during decode, where omitted values do not affect
  45. // the value being decoded into. This means that if decoding into a struct with an
  46. // int field with current value=5, and the field is omitted in the stream, then after
  47. // decoding, the value will still be 5 (not 0).
  48. // omitEmpty only works if you guarantee that you always decode into zero-values.
  49. //
  50. // ------------------------------------
  51. // We could have truncated a map to remove keys not available in the stream,
  52. // or set values in the struct which are not in the stream to their zero values.
  53. // We decided against it because there is no efficient way to do it.
  54. // We may introduce it as an option later.
  55. // However, that will require enabling it for both runtime and code generation modes.
  56. //
  57. // To support truncate, we need to do 2 passes over the container:
  58. // map
  59. // - first collect all keys (e.g. in k1)
  60. // - for each key in stream, mark k1 that the key should not be removed
  61. // - after updating map, do second pass and call delete for all keys in k1 which are not marked
  62. // struct:
  63. // - for each field, track the *typeInfo s1
  64. // - iterate through all s1, and for each one not marked, set value to zero
  65. // - this involves checking the possible anonymous fields which are nil ptrs.
  66. // too much work.
  67. //
  68. // ------------------------------------------
  69. // Error Handling is done within the library using panic.
  70. //
  71. // This way, the code doesn't have to keep checking if an error has happened,
  72. // and we don't have to keep sending the error value along with each call
  73. // or storing it in the En|Decoder and checking it constantly along the way.
  74. //
  75. // We considered storing the error is En|Decoder.
  76. // - once it has its err field set, it cannot be used again.
  77. // - panicing will be optional, controlled by const flag.
  78. // - code should always check error first and return early.
  79. //
  80. // We eventually decided against it as it makes the code clumsier to always
  81. // check for these error conditions.
  82. //
  83. // ------------------------------------------
  84. // We use sync.Pool only for the aid of long-lived objects shared across multiple goroutines.
  85. // Encoder, Decoder, enc|decDriver, reader|writer, etc do not fall into this bucket.
  86. //
  87. // Also, GC is much better now, eliminating some of the reasons to use a shared pool structure.
  88. // Instead, the short-lived objects use free-lists that live as long as the object exists.
  89. //
  90. // ------------------------------------------
  91. // Performance is affected by the following:
  92. // - Bounds Checking
  93. // - Inlining
  94. // - Pointer chasing
  95. // This package tries hard to manage the performance impact of these.
  96. //
  97. // ------------------------------------------
  98. // To alleviate performance due to pointer-chasing:
  99. // - Prefer non-pointer values in a struct field
  100. // - Refer to these directly within helper classes
  101. // e.g. json.go refers directly to d.d.decRd
  102. //
  103. // We made the changes to embed En/Decoder in en/decDriver,
  104. // but we had to explicitly reference the fields as opposed to using a function
  105. // to get the better performance that we were looking for.
  106. // For example, we explicitly call d.d.decRd.fn() instead of d.d.r().fn().
  107. //
  108. // ------------------------------------------
  109. // Bounds Checking
  110. // - Allow bytesDecReader to incur "bounds check error", and
  111. // recover that as an io.EOF.
  112. // This allows the bounds check branch to always be taken by the branch predictor,
  113. // giving better performance (in theory), while ensuring that the code is shorter.
  114. //
  115. // ------------------------------------------
  116. // Escape Analysis
  117. // - Prefer to return non-pointers if the value is used right away.
  118. // Newly allocated values returned as pointers will be heap-allocated as they escape.
  119. //
  120. // Prefer functions and methods that
  121. // - take no parameters and
  122. // - return no results and
  123. // - do not allocate.
  124. // These are optimized by the runtime.
  125. // For example, in json, we have dedicated functions for ReadMapElemKey, etc
  126. // which do not delegate to readDelim, as readDelim takes a parameter.
  127. // The difference in runtime was as much as 5%.
  128. //
  129. // ------------------------------------------
  130. // Handling Nil
  131. // - In dynamic (reflection) mode, decodeValue and encodeValue handle nil at the top
  132. // - Consequently, methods used with them as a parent in the chain e.g. kXXX
  133. // methods do not handle nil.
  134. // - Fastpath methods also do not handle nil.
  135. // The switch called in (en|de)code(...) handles it so the dependent calls don't have to.
  136. // - codecgen will handle nil before calling into the library for further work also.
  137. //
  138. // ------------------------------------------
  139. // Passing reflect.Kind to functions that take a reflect.Value
  140. // - Note that reflect.Value.Kind() is very cheap, as its fundamentally a binary AND of 2 numbers
  141. //
  142. // ------------------------------------------
  143. // Transient values during decoding
  144. //
  145. // With reflection, the stack is not used. Consequently, values which may be stack-allocated in
  146. // normal use will cause a heap allocation when using reflection.
  147. //
  148. // There are cases where we know that a value is transient, and we just need to decode into it
  149. // temporarily so we can right away use its value for something else.
  150. //
  151. // In these situations, we can elide the heap allocation by being deliberate with use of a pre-cached
  152. // scratch memory or scratch value.
  153. //
  154. // We use this for situations:
  155. // - decode into a temp value x, and then set x into an interface
  156. // - decode into a temp value, for use as a map key, to lookup up a map value
  157. // - decode into a temp value, for use as a map value, to set into a map
  158. // - decode into a temp value, for sending into a channel
  159. //
  160. // By definition, Transient values are NEVER pointer-shaped values,
  161. // like pointer, func, map, chan. Using transient for pointer-shaped values
  162. // can lead to data corruption when GC tries to follow what it saw as a pointer at one point.
  163. //
  164. // In general, transient values are values which can be decoded as an atomic value
  165. // using a single call to the decDriver. This naturally includes bool or numeric types.
  166. //
  167. // Note that some values which "contain" pointers, specifically string and slice,
  168. // can also be transient. In the case of string, it is decoded as an atomic value.
  169. // In the case of a slice, decoding into its elements always uses an addressable
  170. // value in memory ie we grow the slice, and then decode directly into the memory
  171. // address corresponding to that index in the slice.
  172. //
  173. // To handle these string and slice values, we have to use a scratch value
  174. // which has the same shape of a string or slice.
  175. //
  176. // Consequently, the full range of types which can be transient is:
  177. // - numbers
  178. // - bool
  179. // - string
  180. // - slice
  181. //
  182. // and whbut we MUST use a scratch space with that element
  183. // being defined as an unsafe.Pointer to start with.
  184. //
  185. // We have to be careful with maps. Because we iterate map keys and values during a range,
  186. // we must have 2 variants of the scratch space/value for maps and keys separately.
  187. //
  188. // These are the TransientAddrK and TransientAddr2K methods of decPerType.
  189. import (
  190. "encoding"
  191. "encoding/binary"
  192. "errors"
  193. "fmt"
  194. "io"
  195. "math"
  196. "reflect"
  197. "runtime"
  198. "sort"
  199. "strconv"
  200. "strings"
  201. "sync"
  202. "sync/atomic"
  203. "time"
  204. "unicode/utf8"
  205. )
  206. // if debugging is true, then
  207. // - within Encode/Decode, do not recover from panic's
  208. // - etc
  209. //
  210. // Note: Negative tests that check for errors will fail, so only use this
  211. // when debugging, and run only one test at a time preferably.
  212. //
  213. // Note: RPC tests espeially fail, as they depend on getting the error from an Encode/Decode call.
  214. const debugging = false
  215. const (
  216. // containerLenUnknown is length returned from Read(Map|Array)Len
  217. // when a format doesn't know apiori.
  218. // For example, json doesn't pre-determine the length of a container (sequence/map).
  219. containerLenUnknown = -1
  220. // containerLenNil is length returned from Read(Map|Array)Len
  221. // when a 'nil' was encountered in the stream.
  222. containerLenNil = math.MinInt32
  223. // [N]byte is handled by converting to []byte first,
  224. // and sending to the dedicated fast-path function for []byte.
  225. //
  226. // Code exists in case our understanding is wrong.
  227. // keep the defensive code behind this flag, so we can remove/hide it if needed.
  228. // For now, we enable the defensive code (ie set it to true).
  229. handleBytesWithinKArray = true
  230. // Support encoding.(Binary|Text)(Unm|M)arshaler.
  231. // This constant flag will enable or disable it.
  232. supportMarshalInterfaces = true
  233. // bytesFreeListNoCache is used for debugging, when we want to skip using a cache of []byte.
  234. bytesFreeListNoCache = false
  235. // size of the cacheline: defaulting to value for archs: amd64, arm64, 386
  236. // should use "runtime/internal/sys".CacheLineSize, but that is not exposed.
  237. cacheLineSize = 64
  238. wordSizeBits = 32 << (^uint(0) >> 63) // strconv.IntSize
  239. wordSize = wordSizeBits / 8
  240. // MARKER: determines whether to skip calling fastpath(En|De)codeTypeSwitch.
  241. // Calling the fastpath switch in encode() or decode() could be redundant,
  242. // as we still have to introspect it again within fnLoad
  243. // to determine the function to use for values of that type.
  244. skipFastpathTypeSwitchInDirectCall = false
  245. )
  246. const cpu32Bit = ^uint(0)>>32 == 0
  247. type rkind byte
  248. const (
  249. rkindPtr = rkind(reflect.Ptr)
  250. rkindString = rkind(reflect.String)
  251. rkindChan = rkind(reflect.Chan)
  252. )
  253. type mapKeyFastKind uint8
  254. const (
  255. mapKeyFastKind32 = iota + 1
  256. mapKeyFastKind32ptr
  257. mapKeyFastKind64
  258. mapKeyFastKind64ptr
  259. mapKeyFastKindStr
  260. )
  261. var (
  262. // use a global mutex to ensure each Handle is initialized.
  263. // We do this, so we don't have to store the basicHandle mutex
  264. // directly in BasicHandle, so it can be shallow-copied.
  265. handleInitMu sync.Mutex
  266. must mustHdl
  267. halt panicHdl
  268. digitCharBitset bitset256
  269. numCharBitset bitset256
  270. whitespaceCharBitset bitset256
  271. asciiAlphaNumBitset bitset256
  272. // numCharWithExpBitset64 bitset64
  273. // numCharNoExpBitset64 bitset64
  274. // whitespaceCharBitset64 bitset64
  275. //
  276. // // hasptrBitset sets bit for all kinds which always have internal pointers
  277. // hasptrBitset bitset32
  278. // refBitset sets bit for all kinds which are direct internal references
  279. refBitset bitset32
  280. // isnilBitset sets bit for all kinds which can be compared to nil
  281. isnilBitset bitset32
  282. // numBoolBitset sets bit for all number and bool kinds
  283. numBoolBitset bitset32
  284. // numBoolStrSliceBitset sets bits for all kinds which are numbers, bool, strings and slices
  285. numBoolStrSliceBitset bitset32
  286. // scalarBitset sets bit for all kinds which are scalars/primitives and thus immutable
  287. scalarBitset bitset32
  288. mapKeyFastKindVals [32]mapKeyFastKind
  289. // codecgen is set to true by codecgen, so that tests, etc can use this information as needed.
  290. codecgen bool
  291. oneByteArr [1]byte
  292. zeroByteSlice = oneByteArr[:0:0]
  293. eofReader devNullReader
  294. )
  295. var (
  296. errMapTypeNotMapKind = errors.New("MapType MUST be of Map Kind")
  297. errSliceTypeNotSliceKind = errors.New("SliceType MUST be of Slice Kind")
  298. errExtFnWriteExtUnsupported = errors.New("BytesExt.WriteExt is not supported")
  299. errExtFnReadExtUnsupported = errors.New("BytesExt.ReadExt is not supported")
  300. errExtFnConvertExtUnsupported = errors.New("InterfaceExt.ConvertExt is not supported")
  301. errExtFnUpdateExtUnsupported = errors.New("InterfaceExt.UpdateExt is not supported")
  302. errPanicUndefined = errors.New("panic: undefined error")
  303. errHandleInited = errors.New("cannot modify initialized Handle")
  304. errNoFormatHandle = errors.New("no handle (cannot identify format)")
  305. )
  306. var pool4tiload = sync.Pool{
  307. New: func() interface{} {
  308. return &typeInfoLoad{
  309. etypes: make([]uintptr, 0, 4),
  310. sfis: make([]structFieldInfo, 0, 4),
  311. sfiNames: make(map[string]uint16, 4),
  312. }
  313. },
  314. }
  315. func init() {
  316. xx := func(f mapKeyFastKind, k ...reflect.Kind) {
  317. for _, v := range k {
  318. mapKeyFastKindVals[byte(v)&31] = f // 'v % 32' equal to 'v & 31'
  319. }
  320. }
  321. var f mapKeyFastKind
  322. f = mapKeyFastKind64
  323. if wordSizeBits == 32 {
  324. f = mapKeyFastKind32
  325. }
  326. xx(f, reflect.Int, reflect.Uint, reflect.Uintptr)
  327. f = mapKeyFastKind64ptr
  328. if wordSizeBits == 32 {
  329. f = mapKeyFastKind32ptr
  330. }
  331. xx(f, reflect.Ptr)
  332. xx(mapKeyFastKindStr, reflect.String)
  333. xx(mapKeyFastKind32, reflect.Uint32, reflect.Int32, reflect.Float32)
  334. xx(mapKeyFastKind64, reflect.Uint64, reflect.Int64, reflect.Float64)
  335. numBoolBitset.
  336. set(byte(reflect.Bool)).
  337. set(byte(reflect.Int)).
  338. set(byte(reflect.Int8)).
  339. set(byte(reflect.Int16)).
  340. set(byte(reflect.Int32)).
  341. set(byte(reflect.Int64)).
  342. set(byte(reflect.Uint)).
  343. set(byte(reflect.Uint8)).
  344. set(byte(reflect.Uint16)).
  345. set(byte(reflect.Uint32)).
  346. set(byte(reflect.Uint64)).
  347. set(byte(reflect.Uintptr)).
  348. set(byte(reflect.Float32)).
  349. set(byte(reflect.Float64)).
  350. set(byte(reflect.Complex64)).
  351. set(byte(reflect.Complex128))
  352. numBoolStrSliceBitset = numBoolBitset
  353. numBoolStrSliceBitset.
  354. set(byte(reflect.String)).
  355. set(byte(reflect.Slice))
  356. scalarBitset = numBoolBitset
  357. scalarBitset.
  358. set(byte(reflect.String))
  359. // MARKER: reflect.Array is not a scalar, as its contents can be modified.
  360. refBitset.
  361. set(byte(reflect.Map)).
  362. set(byte(reflect.Ptr)).
  363. set(byte(reflect.Func)).
  364. set(byte(reflect.Chan)).
  365. set(byte(reflect.UnsafePointer))
  366. isnilBitset = refBitset
  367. isnilBitset.
  368. set(byte(reflect.Interface)).
  369. set(byte(reflect.Slice))
  370. // hasptrBitset = isnilBitset
  371. //
  372. // hasptrBitset.
  373. // set(byte(reflect.String))
  374. for i := byte(0); i <= utf8.RuneSelf; i++ {
  375. if (i >= '0' && i <= '9') || (i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z') {
  376. asciiAlphaNumBitset.set(i)
  377. }
  378. switch i {
  379. case ' ', '\t', '\r', '\n':
  380. whitespaceCharBitset.set(i)
  381. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  382. digitCharBitset.set(i)
  383. numCharBitset.set(i)
  384. case '.', '+', '-':
  385. numCharBitset.set(i)
  386. case 'e', 'E':
  387. numCharBitset.set(i)
  388. }
  389. }
  390. }
  391. // driverStateManager supports the runtime state of an (enc|dec)Driver.
  392. //
  393. // During a side(En|De)code call, we can capture the state, reset it,
  394. // and then restore it later to continue the primary encoding/decoding.
  395. type driverStateManager interface {
  396. resetState()
  397. captureState() interface{}
  398. restoreState(state interface{})
  399. }
  400. type bdAndBdread struct {
  401. bdRead bool
  402. bd byte
  403. }
  404. func (x bdAndBdread) captureState() interface{} { return x }
  405. func (x *bdAndBdread) resetState() { x.bd, x.bdRead = 0, false }
  406. func (x *bdAndBdread) reset() { x.resetState() }
  407. func (x *bdAndBdread) restoreState(v interface{}) { *x = v.(bdAndBdread) }
  408. type clsErr struct {
  409. err error // error on closing
  410. closed bool // is it closed?
  411. }
  412. type charEncoding uint8
  413. const (
  414. _ charEncoding = iota // make 0 unset
  415. cUTF8
  416. cUTF16LE
  417. cUTF16BE
  418. cUTF32LE
  419. cUTF32BE
  420. // Deprecated: not a true char encoding value
  421. cRAW charEncoding = 255
  422. )
  423. // valueType is the stream type
  424. type valueType uint8
  425. const (
  426. valueTypeUnset valueType = iota
  427. valueTypeNil
  428. valueTypeInt
  429. valueTypeUint
  430. valueTypeFloat
  431. valueTypeBool
  432. valueTypeString
  433. valueTypeSymbol
  434. valueTypeBytes
  435. valueTypeMap
  436. valueTypeArray
  437. valueTypeTime
  438. valueTypeExt
  439. // valueTypeInvalid = 0xff
  440. )
  441. var valueTypeStrings = [...]string{
  442. "Unset",
  443. "Nil",
  444. "Int",
  445. "Uint",
  446. "Float",
  447. "Bool",
  448. "String",
  449. "Symbol",
  450. "Bytes",
  451. "Map",
  452. "Array",
  453. "Timestamp",
  454. "Ext",
  455. }
  456. func (x valueType) String() string {
  457. if int(x) < len(valueTypeStrings) {
  458. return valueTypeStrings[x]
  459. }
  460. return strconv.FormatInt(int64(x), 10)
  461. }
  462. // note that containerMapStart and containerArraySend are not sent.
  463. // This is because the ReadXXXStart and EncodeXXXStart already does these.
  464. type containerState uint8
  465. const (
  466. _ containerState = iota
  467. containerMapStart
  468. containerMapKey
  469. containerMapValue
  470. containerMapEnd
  471. containerArrayStart
  472. containerArrayElem
  473. containerArrayEnd
  474. )
  475. // do not recurse if a containing type refers to an embedded type
  476. // which refers back to its containing type (via a pointer).
  477. // The second time this back-reference happens, break out,
  478. // so as not to cause an infinite loop.
  479. const rgetMaxRecursion = 2
  480. // fauxUnion is used to keep track of the primitives decoded.
  481. //
  482. // Without it, we would have to decode each primitive and wrap it
  483. // in an interface{}, causing an allocation.
  484. // In this model, the primitives are decoded in a "pseudo-atomic" fashion,
  485. // so we can rest assured that no other decoding happens while these
  486. // primitives are being decoded.
  487. //
  488. // maps and arrays are not handled by this mechanism.
  489. type fauxUnion struct {
  490. // r RawExt // used for RawExt, uint, []byte.
  491. // primitives below
  492. u uint64
  493. i int64
  494. f float64
  495. l []byte
  496. s string
  497. // ---- cpu cache line boundary?
  498. t time.Time
  499. b bool
  500. // state
  501. v valueType
  502. }
  503. // typeInfoLoad is a transient object used while loading up a typeInfo.
  504. type typeInfoLoad struct {
  505. etypes []uintptr
  506. sfis []structFieldInfo
  507. sfiNames map[string]uint16
  508. }
  509. func (x *typeInfoLoad) reset() {
  510. x.etypes = x.etypes[:0]
  511. x.sfis = x.sfis[:0]
  512. for k := range x.sfiNames { // optimized to zero the map
  513. delete(x.sfiNames, k)
  514. }
  515. }
  516. // mirror json.Marshaler and json.Unmarshaler here,
  517. // so we don't import the encoding/json package
  518. type jsonMarshaler interface {
  519. MarshalJSON() ([]byte, error)
  520. }
  521. type jsonUnmarshaler interface {
  522. UnmarshalJSON([]byte) error
  523. }
  524. type isZeroer interface {
  525. IsZero() bool
  526. }
  527. type isCodecEmptyer interface {
  528. IsCodecEmpty() bool
  529. }
  530. type codecError struct {
  531. err error
  532. name string
  533. pos int
  534. encode bool
  535. }
  536. func (e *codecError) Cause() error {
  537. return e.err
  538. }
  539. func (e *codecError) Error() string {
  540. if e.encode {
  541. return fmt.Sprintf("%s encode error: %v", e.name, e.err)
  542. }
  543. return fmt.Sprintf("%s decode error [pos %d]: %v", e.name, e.pos, e.err)
  544. }
  545. func wrapCodecErr(in error, name string, numbytesread int, encode bool) (out error) {
  546. x, ok := in.(*codecError)
  547. if ok && x.pos == numbytesread && x.name == name && x.encode == encode {
  548. return in
  549. }
  550. return &codecError{in, name, numbytesread, encode}
  551. }
  552. var (
  553. bigen bigenHelper
  554. bigenstd = binary.BigEndian
  555. structInfoFieldName = "_struct"
  556. mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
  557. mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
  558. intfSliceTyp = reflect.TypeOf([]interface{}(nil))
  559. intfTyp = intfSliceTyp.Elem()
  560. reflectValTyp = reflect.TypeOf((*reflect.Value)(nil)).Elem()
  561. stringTyp = reflect.TypeOf("")
  562. timeTyp = reflect.TypeOf(time.Time{})
  563. rawExtTyp = reflect.TypeOf(RawExt{})
  564. rawTyp = reflect.TypeOf(Raw{})
  565. uintptrTyp = reflect.TypeOf(uintptr(0))
  566. uint8Typ = reflect.TypeOf(uint8(0))
  567. uint8SliceTyp = reflect.TypeOf([]uint8(nil))
  568. uintTyp = reflect.TypeOf(uint(0))
  569. intTyp = reflect.TypeOf(int(0))
  570. mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
  571. binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
  572. binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
  573. textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
  574. textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
  575. jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
  576. jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
  577. selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem()
  578. missingFielderTyp = reflect.TypeOf((*MissingFielder)(nil)).Elem()
  579. iszeroTyp = reflect.TypeOf((*isZeroer)(nil)).Elem()
  580. isCodecEmptyerTyp = reflect.TypeOf((*isCodecEmptyer)(nil)).Elem()
  581. isSelferViaCodecgenerTyp = reflect.TypeOf((*isSelferViaCodecgener)(nil)).Elem()
  582. uint8TypId = rt2id(uint8Typ)
  583. uint8SliceTypId = rt2id(uint8SliceTyp)
  584. rawExtTypId = rt2id(rawExtTyp)
  585. rawTypId = rt2id(rawTyp)
  586. intfTypId = rt2id(intfTyp)
  587. timeTypId = rt2id(timeTyp)
  588. stringTypId = rt2id(stringTyp)
  589. mapStrIntfTypId = rt2id(mapStrIntfTyp)
  590. mapIntfIntfTypId = rt2id(mapIntfIntfTyp)
  591. intfSliceTypId = rt2id(intfSliceTyp)
  592. // mapBySliceTypId = rt2id(mapBySliceTyp)
  593. intBitsize = uint8(intTyp.Bits())
  594. uintBitsize = uint8(uintTyp.Bits())
  595. // bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
  596. bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  597. chkOvf checkOverflow
  598. )
  599. var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
  600. // SelfExt is a sentinel extension signifying that types
  601. // registered with it SHOULD be encoded and decoded
  602. // based on the native mode of the format.
  603. //
  604. // This allows users to define a tag for an extension,
  605. // but signify that the types should be encoded/decoded as the native encoding.
  606. // This way, users need not also define how to encode or decode the extension.
  607. var SelfExt = &extFailWrapper{}
  608. // Selfer defines methods by which a value can encode or decode itself.
  609. //
  610. // Any type which implements Selfer will be able to encode or decode itself.
  611. // Consequently, during (en|de)code, this takes precedence over
  612. // (text|binary)(M|Unm)arshal or extension support.
  613. //
  614. // By definition, it is not allowed for a Selfer to directly call Encode or Decode on itself.
  615. // If that is done, Encode/Decode will rightfully fail with a Stack Overflow style error.
  616. // For example, the snippet below will cause such an error.
  617. // type testSelferRecur struct{}
  618. // func (s *testSelferRecur) CodecEncodeSelf(e *Encoder) { e.MustEncode(s) }
  619. // func (s *testSelferRecur) CodecDecodeSelf(d *Decoder) { d.MustDecode(s) }
  620. //
  621. // Note: *the first set of bytes of any value MUST NOT represent nil in the format*.
  622. // This is because, during each decode, we first check the the next set of bytes
  623. // represent nil, and if so, we just set the value to nil.
  624. type Selfer interface {
  625. CodecEncodeSelf(*Encoder)
  626. CodecDecodeSelf(*Decoder)
  627. }
  628. type isSelferViaCodecgener interface {
  629. codecSelferViaCodecgen()
  630. }
  631. // MissingFielder defines the interface allowing structs to internally decode or encode
  632. // values which do not map to struct fields.
  633. //
  634. // We expect that this interface is bound to a pointer type (so the mutation function works).
  635. //
  636. // A use-case is if a version of a type unexports a field, but you want compatibility between
  637. // both versions during encoding and decoding.
  638. //
  639. // Note that the interface is completely ignored during codecgen.
  640. type MissingFielder interface {
  641. // CodecMissingField is called to set a missing field and value pair.
  642. //
  643. // It returns true if the missing field was set on the struct.
  644. CodecMissingField(field []byte, value interface{}) bool
  645. // CodecMissingFields returns the set of fields which are not struct fields.
  646. //
  647. // Note that the returned map may be mutated by the caller.
  648. CodecMissingFields() map[string]interface{}
  649. }
  650. // MapBySlice is a tag interface that denotes the slice or array value should encode as a map
  651. // in the stream, and can be decoded from a map in the stream.
  652. //
  653. // The slice or array must contain a sequence of key-value pairs.
  654. // The length of the slice or array must be even (fully divisible by 2).
  655. //
  656. // This affords storing a map in a specific sequence in the stream.
  657. //
  658. // Example usage:
  659. // type T1 []string // or []int or []Point or any other "slice" type
  660. // func (_ T1) MapBySlice{} // T1 now implements MapBySlice, and will be encoded as a map
  661. // type T2 struct { KeyValues T1 }
  662. //
  663. // var kvs = []string{"one", "1", "two", "2", "three", "3"}
  664. // var v2 = T2{ KeyValues: T1(kvs) }
  665. // // v2 will be encoded like the map: {"KeyValues": {"one": "1", "two": "2", "three": "3"} }
  666. //
  667. // The support of MapBySlice affords the following:
  668. // - A slice or array type which implements MapBySlice will be encoded as a map
  669. // - A slice can be decoded from a map in the stream
  670. type MapBySlice interface {
  671. MapBySlice()
  672. }
  673. // basicHandleRuntimeState holds onto all BasicHandle runtime and cached config information.
  674. //
  675. // Storing this outside BasicHandle allows us create shallow copies of a Handle,
  676. // which can be used e.g. when we need to modify config fields temporarily.
  677. // Shallow copies are used within tests, so we can modify some config fields for a test
  678. // temporarily when running tests in parallel, without running the risk that a test executing
  679. // in parallel with other tests does not see a transient modified values not meant for it.
  680. type basicHandleRuntimeState struct {
  681. // these are used during runtime.
  682. // At init time, they should have nothing in them.
  683. rtidFns atomicRtidFnSlice
  684. rtidFnsNoExt atomicRtidFnSlice
  685. // Note: basicHandleRuntimeState is not comparable, due to these slices here (extHandle, intf2impls).
  686. // If *[]T is used instead, this becomes comparable, at the cost of extra indirection.
  687. // Thses slices are used all the time, so keep as slices (not pointers).
  688. extHandle
  689. intf2impls
  690. mu sync.Mutex
  691. jsonHandle bool
  692. binaryHandle bool
  693. // timeBuiltin is initialized from TimeNotBuiltin, and used internally.
  694. // once initialized, it cannot be changed, as the function for encoding/decoding time.Time
  695. // will have been cached and the TimeNotBuiltin value will not be consulted thereafter.
  696. timeBuiltin bool
  697. _ bool // padding
  698. }
  699. // BasicHandle encapsulates the common options and extension functions.
  700. //
  701. // Deprecated: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
  702. type BasicHandle struct {
  703. // BasicHandle is always a part of a different type.
  704. // It doesn't have to fit into it own cache lines.
  705. // TypeInfos is used to get the type info for any type.
  706. //
  707. // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
  708. TypeInfos *TypeInfos
  709. *basicHandleRuntimeState
  710. // ---- cache line
  711. DecodeOptions
  712. // ---- cache line
  713. EncodeOptions
  714. RPCOptions
  715. // TimeNotBuiltin configures whether time.Time should be treated as a builtin type.
  716. //
  717. // All Handlers should know how to encode/decode time.Time as part of the core
  718. // format specification, or as a standard extension defined by the format.
  719. //
  720. // However, users can elect to handle time.Time as a custom extension, or via the
  721. // standard library's encoding.Binary(M|Unm)arshaler or Text(M|Unm)arshaler interface.
  722. // To elect this behavior, users can set TimeNotBuiltin=true.
  723. //
  724. // Note: Setting TimeNotBuiltin=true can be used to enable the legacy behavior
  725. // (for Cbor and Msgpack), where time.Time was not a builtin supported type.
  726. //
  727. // Note: DO NOT CHANGE AFTER FIRST USE.
  728. //
  729. // Once a Handle has been initialized (used), do not modify this option. It will be ignored.
  730. TimeNotBuiltin bool
  731. // ExplicitRelease configures whether Release() is implicitly called after an encode or
  732. // decode call.
  733. //
  734. // If you will hold onto an Encoder or Decoder for re-use, by calling Reset(...)
  735. // on it or calling (Must)Encode repeatedly into a given []byte or io.Writer,
  736. // then you do not want it to be implicitly closed after each Encode/Decode call.
  737. // Doing so will unnecessarily return resources to the shared pool, only for you to
  738. // grab them right after again to do another Encode/Decode call.
  739. //
  740. // Instead, you configure ExplicitRelease=true, and you explicitly call Release() when
  741. // you are truly done.
  742. //
  743. // As an alternative, you can explicitly set a finalizer - so its resources
  744. // are returned to the shared pool before it is garbage-collected. Do it as below:
  745. // runtime.SetFinalizer(e, (*Encoder).Release)
  746. // runtime.SetFinalizer(d, (*Decoder).Release)
  747. //
  748. // Deprecated: This is not longer used as pools are only used for long-lived objects
  749. // which are shared across goroutines.
  750. // Setting this value has no effect. It is maintained for backward compatibility.
  751. ExplicitRelease bool
  752. // ---- cache line
  753. inited uint32 // holds if inited, and also handle flags (binary encoding, json handler, etc)
  754. }
  755. // initHandle does a one-time initialization of the handle.
  756. // After this is run, do not modify the Handle, as some modifications are ignored
  757. // e.g. extensions, registered interfaces, TimeNotBuiltIn, etc
  758. func initHandle(hh Handle) {
  759. x := hh.getBasicHandle()
  760. // MARKER: We need to simulate once.Do, to ensure no data race within the block.
  761. // Consequently, below would not work.
  762. //
  763. // if atomic.CompareAndSwapUint32(&x.inited, 0, 1) {
  764. // x.be = hh.isBinary()
  765. // x.js = hh.isJson
  766. // x.n = hh.Name()[0]
  767. // }
  768. // simulate once.Do using our own stored flag and mutex as a CompareAndSwap
  769. // is not sufficient, since a race condition can occur within init(Handle) function.
  770. // init is made noinline, so that this function can be inlined by its caller.
  771. if atomic.LoadUint32(&x.inited) == 0 {
  772. x.initHandle(hh)
  773. }
  774. }
  775. func (x *BasicHandle) basicInit() {
  776. x.rtidFns.store(nil)
  777. x.rtidFnsNoExt.store(nil)
  778. x.timeBuiltin = !x.TimeNotBuiltin
  779. }
  780. func (x *BasicHandle) init() {}
  781. func (x *BasicHandle) isInited() bool {
  782. return atomic.LoadUint32(&x.inited) != 0
  783. }
  784. // clearInited: DANGEROUS - only use in testing, etc
  785. func (x *BasicHandle) clearInited() {
  786. atomic.StoreUint32(&x.inited, 0)
  787. }
  788. // TimeBuiltin returns whether time.Time OOTB support is used,
  789. // based on the initial configuration of TimeNotBuiltin
  790. func (x *basicHandleRuntimeState) TimeBuiltin() bool {
  791. return x.timeBuiltin
  792. }
  793. func (x *basicHandleRuntimeState) isJs() bool {
  794. return x.jsonHandle
  795. }
  796. func (x *basicHandleRuntimeState) isBe() bool {
  797. return x.binaryHandle
  798. }
  799. func (x *basicHandleRuntimeState) setExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
  800. rk := rt.Kind()
  801. for rk == reflect.Ptr {
  802. rt = rt.Elem()
  803. rk = rt.Kind()
  804. }
  805. if rt.PkgPath() == "" || rk == reflect.Interface { // || rk == reflect.Ptr {
  806. return fmt.Errorf("codec.Handle.SetExt: Takes named type, not a pointer or interface: %v", rt)
  807. }
  808. rtid := rt2id(rt)
  809. // handle all natively supported type appropriately, so they cannot have an extension.
  810. // However, we do not return an error for these, as we do not document that.
  811. // Instead, we silently treat as a no-op, and return.
  812. switch rtid {
  813. case rawTypId, rawExtTypId:
  814. return
  815. case timeTypId:
  816. if x.timeBuiltin {
  817. return
  818. }
  819. }
  820. for i := range x.extHandle {
  821. v := &x.extHandle[i]
  822. if v.rtid == rtid {
  823. v.tag, v.ext = tag, ext
  824. return
  825. }
  826. }
  827. rtidptr := rt2id(reflect.PtrTo(rt))
  828. x.extHandle = append(x.extHandle, extTypeTagFn{rtid, rtidptr, rt, tag, ext})
  829. return
  830. }
  831. // initHandle should be called only from codec.initHandle global function.
  832. // make it uninlineable, as it is called at most once for each handle.
  833. //go:noinline
  834. func (x *BasicHandle) initHandle(hh Handle) {
  835. handleInitMu.Lock()
  836. defer handleInitMu.Unlock() // use defer, as halt may panic below
  837. if x.inited == 0 {
  838. if x.basicHandleRuntimeState == nil {
  839. x.basicHandleRuntimeState = new(basicHandleRuntimeState)
  840. }
  841. x.jsonHandle = hh.isJson()
  842. x.binaryHandle = hh.isBinary()
  843. // ensure MapType and SliceType are of correct type
  844. if x.MapType != nil && x.MapType.Kind() != reflect.Map {
  845. halt.onerror(errMapTypeNotMapKind)
  846. }
  847. if x.SliceType != nil && x.SliceType.Kind() != reflect.Slice {
  848. halt.onerror(errSliceTypeNotSliceKind)
  849. }
  850. x.basicInit()
  851. hh.init()
  852. atomic.StoreUint32(&x.inited, 1)
  853. }
  854. }
  855. func (x *BasicHandle) getBasicHandle() *BasicHandle {
  856. return x
  857. }
  858. func (x *BasicHandle) typeInfos() *TypeInfos {
  859. if x.TypeInfos != nil {
  860. return x.TypeInfos
  861. }
  862. return defTypeInfos
  863. }
  864. func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  865. return x.typeInfos().get(rtid, rt)
  866. }
  867. func findRtidFn(s []codecRtidFn, rtid uintptr) (i uint, fn *codecFn) {
  868. // binary search. adapted from sort/search.go.
  869. // Note: we use goto (instead of for loop) so this can be inlined.
  870. // h, i, j := 0, 0, len(s)
  871. var h uint // var h, i uint
  872. var j = uint(len(s))
  873. LOOP:
  874. if i < j {
  875. h = (i + j) >> 1 // avoid overflow when computing h // h = i + (j-i)/2
  876. if s[h].rtid < rtid {
  877. i = h + 1
  878. } else {
  879. j = h
  880. }
  881. goto LOOP
  882. }
  883. if i < uint(len(s)) && s[i].rtid == rtid {
  884. fn = s[i].fn
  885. }
  886. return
  887. }
  888. func (x *BasicHandle) fn(rt reflect.Type) (fn *codecFn) {
  889. return x.fnVia(rt, x.typeInfos(), &x.rtidFns, x.CheckCircularRef, true)
  890. }
  891. func (x *BasicHandle) fnNoExt(rt reflect.Type) (fn *codecFn) {
  892. return x.fnVia(rt, x.typeInfos(), &x.rtidFnsNoExt, x.CheckCircularRef, false)
  893. }
  894. func (x *basicHandleRuntimeState) fnVia(rt reflect.Type, tinfos *TypeInfos, fs *atomicRtidFnSlice, checkCircularRef, checkExt bool) (fn *codecFn) {
  895. rtid := rt2id(rt)
  896. sp := fs.load()
  897. if sp != nil {
  898. if _, fn = findRtidFn(sp, rtid); fn != nil {
  899. return
  900. }
  901. }
  902. fn = x.fnLoad(rt, rtid, tinfos, checkCircularRef, checkExt)
  903. x.mu.Lock()
  904. sp = fs.load()
  905. // since this is an atomic load/store, we MUST use a different array each time,
  906. // else we have a data race when a store is happening simultaneously with a findRtidFn call.
  907. if sp == nil {
  908. sp = []codecRtidFn{{rtid, fn}}
  909. fs.store(sp)
  910. } else {
  911. idx, fn2 := findRtidFn(sp, rtid)
  912. if fn2 == nil {
  913. sp2 := make([]codecRtidFn, len(sp)+1)
  914. copy(sp2[idx+1:], sp[idx:])
  915. copy(sp2, sp[:idx])
  916. sp2[idx] = codecRtidFn{rtid, fn}
  917. fs.store(sp2)
  918. }
  919. }
  920. x.mu.Unlock()
  921. return
  922. }
  923. func fnloadFastpathUnderlying(ti *typeInfo) (f *fastpathE, u reflect.Type) {
  924. var rtid uintptr
  925. var idx int
  926. rtid = rt2id(ti.fastpathUnderlying)
  927. idx = fastpathAvIndex(rtid)
  928. if idx == -1 {
  929. return
  930. }
  931. f = &fastpathAv[idx]
  932. if uint8(reflect.Array) == ti.kind {
  933. u = reflectArrayOf(ti.rt.Len(), ti.elem)
  934. } else {
  935. u = f.rt
  936. }
  937. return
  938. }
  939. func (x *basicHandleRuntimeState) fnLoad(rt reflect.Type, rtid uintptr, tinfos *TypeInfos, checkCircularRef, checkExt bool) (fn *codecFn) {
  940. fn = new(codecFn)
  941. fi := &(fn.i)
  942. ti := tinfos.get(rtid, rt)
  943. fi.ti = ti
  944. rk := reflect.Kind(ti.kind)
  945. // anything can be an extension except the built-in ones: time, raw and rawext.
  946. // ensure we check for these types, then if extension, before checking if
  947. // it implementes one of the pre-declared interfaces.
  948. fi.addrDf = true
  949. // fi.addrEf = true
  950. if rtid == timeTypId && x.timeBuiltin {
  951. fn.fe = (*Encoder).kTime
  952. fn.fd = (*Decoder).kTime
  953. } else if rtid == rawTypId {
  954. fn.fe = (*Encoder).raw
  955. fn.fd = (*Decoder).raw
  956. } else if rtid == rawExtTypId {
  957. fn.fe = (*Encoder).rawExt
  958. fn.fd = (*Decoder).rawExt
  959. fi.addrD = true
  960. fi.addrE = true
  961. } else if xfFn := x.getExt(rtid, checkExt); xfFn != nil {
  962. fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
  963. fn.fe = (*Encoder).ext
  964. fn.fd = (*Decoder).ext
  965. fi.addrD = true
  966. if rk == reflect.Struct || rk == reflect.Array {
  967. fi.addrE = true
  968. }
  969. } else if (ti.flagSelfer || ti.flagSelferPtr) &&
  970. !(checkCircularRef && ti.flagSelferViaCodecgen && ti.kind == byte(reflect.Struct)) {
  971. // do not use Selfer generated by codecgen if it is a struct and CheckCircularRef=true
  972. fn.fe = (*Encoder).selferMarshal
  973. fn.fd = (*Decoder).selferUnmarshal
  974. fi.addrD = ti.flagSelferPtr
  975. fi.addrE = ti.flagSelferPtr
  976. } else if supportMarshalInterfaces && x.isBe() &&
  977. (ti.flagBinaryMarshaler || ti.flagBinaryMarshalerPtr) &&
  978. (ti.flagBinaryUnmarshaler || ti.flagBinaryUnmarshalerPtr) {
  979. fn.fe = (*Encoder).binaryMarshal
  980. fn.fd = (*Decoder).binaryUnmarshal
  981. fi.addrD = ti.flagBinaryUnmarshalerPtr
  982. fi.addrE = ti.flagBinaryMarshalerPtr
  983. } else if supportMarshalInterfaces && !x.isBe() && x.isJs() &&
  984. (ti.flagJsonMarshaler || ti.flagJsonMarshalerPtr) &&
  985. (ti.flagJsonUnmarshaler || ti.flagJsonUnmarshalerPtr) {
  986. //If JSON, we should check JSONMarshal before textMarshal
  987. fn.fe = (*Encoder).jsonMarshal
  988. fn.fd = (*Decoder).jsonUnmarshal
  989. fi.addrD = ti.flagJsonUnmarshalerPtr
  990. fi.addrE = ti.flagJsonMarshalerPtr
  991. } else if supportMarshalInterfaces && !x.isBe() &&
  992. (ti.flagTextMarshaler || ti.flagTextMarshalerPtr) &&
  993. (ti.flagTextUnmarshaler || ti.flagTextUnmarshalerPtr) {
  994. fn.fe = (*Encoder).textMarshal
  995. fn.fd = (*Decoder).textUnmarshal
  996. fi.addrD = ti.flagTextUnmarshalerPtr
  997. fi.addrE = ti.flagTextMarshalerPtr
  998. } else {
  999. if fastpathEnabled && (rk == reflect.Map || rk == reflect.Slice || rk == reflect.Array) {
  1000. // by default (without using unsafe),
  1001. // if an array is not addressable, converting from an array to a slice
  1002. // requires an allocation (see helper_not_unsafe.go: func rvGetSlice4Array).
  1003. //
  1004. // (Non-addressable arrays mostly occur as keys/values from a map).
  1005. //
  1006. // However, fastpath functions are mostly for slices of numbers or strings,
  1007. // which are small by definition and thus allocation should be fast/cheap in time.
  1008. //
  1009. // Consequently, the value of doing this quick allocation to elide the overhead cost of
  1010. // non-optimized (not-unsafe) reflection is a fair price.
  1011. var rtid2 uintptr
  1012. if !ti.flagHasPkgPath { // un-named type (slice or mpa or array)
  1013. rtid2 = rtid
  1014. if rk == reflect.Array {
  1015. rtid2 = rt2id(ti.key) // ti.key for arrays = reflect.SliceOf(ti.elem)
  1016. }
  1017. if idx := fastpathAvIndex(rtid2); idx != -1 {
  1018. fn.fe = fastpathAv[idx].encfn
  1019. fn.fd = fastpathAv[idx].decfn
  1020. fi.addrD = true
  1021. fi.addrDf = false
  1022. if rk == reflect.Array {
  1023. fi.addrD = false // decode directly into array value (slice made from it)
  1024. }
  1025. }
  1026. } else { // named type (with underlying type of map or slice or array)
  1027. // try to use mapping for underlying type
  1028. xfe, xrt := fnloadFastpathUnderlying(ti)
  1029. if xfe != nil {
  1030. xfnf := xfe.encfn
  1031. xfnf2 := xfe.decfn
  1032. if rk == reflect.Array {
  1033. fi.addrD = false // decode directly into array value (slice made from it)
  1034. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1035. xfnf2(d, xf, rvConvert(xrv, xrt))
  1036. }
  1037. } else {
  1038. fi.addrD = true
  1039. fi.addrDf = false // meaning it can be an address(ptr) or a value
  1040. xptr2rt := reflect.PtrTo(xrt)
  1041. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1042. if xrv.Kind() == reflect.Ptr {
  1043. xfnf2(d, xf, rvConvert(xrv, xptr2rt))
  1044. } else {
  1045. xfnf2(d, xf, rvConvert(xrv, xrt))
  1046. }
  1047. }
  1048. }
  1049. fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) {
  1050. xfnf(e, xf, rvConvert(xrv, xrt))
  1051. }
  1052. }
  1053. }
  1054. }
  1055. if fn.fe == nil && fn.fd == nil {
  1056. switch rk {
  1057. case reflect.Bool:
  1058. fn.fe = (*Encoder).kBool
  1059. fn.fd = (*Decoder).kBool
  1060. case reflect.String:
  1061. // Do not use different functions based on StringToRaw option, as that will statically
  1062. // set the function for a string type, and if the Handle is modified thereafter,
  1063. // behaviour is non-deterministic
  1064. // i.e. DO NOT DO:
  1065. // if x.StringToRaw {
  1066. // fn.fe = (*Encoder).kStringToRaw
  1067. // } else {
  1068. // fn.fe = (*Encoder).kStringEnc
  1069. // }
  1070. fn.fe = (*Encoder).kString
  1071. fn.fd = (*Decoder).kString
  1072. case reflect.Int:
  1073. fn.fd = (*Decoder).kInt
  1074. fn.fe = (*Encoder).kInt
  1075. case reflect.Int8:
  1076. fn.fe = (*Encoder).kInt8
  1077. fn.fd = (*Decoder).kInt8
  1078. case reflect.Int16:
  1079. fn.fe = (*Encoder).kInt16
  1080. fn.fd = (*Decoder).kInt16
  1081. case reflect.Int32:
  1082. fn.fe = (*Encoder).kInt32
  1083. fn.fd = (*Decoder).kInt32
  1084. case reflect.Int64:
  1085. fn.fe = (*Encoder).kInt64
  1086. fn.fd = (*Decoder).kInt64
  1087. case reflect.Uint:
  1088. fn.fd = (*Decoder).kUint
  1089. fn.fe = (*Encoder).kUint
  1090. case reflect.Uint8:
  1091. fn.fe = (*Encoder).kUint8
  1092. fn.fd = (*Decoder).kUint8
  1093. case reflect.Uint16:
  1094. fn.fe = (*Encoder).kUint16
  1095. fn.fd = (*Decoder).kUint16
  1096. case reflect.Uint32:
  1097. fn.fe = (*Encoder).kUint32
  1098. fn.fd = (*Decoder).kUint32
  1099. case reflect.Uint64:
  1100. fn.fe = (*Encoder).kUint64
  1101. fn.fd = (*Decoder).kUint64
  1102. case reflect.Uintptr:
  1103. fn.fe = (*Encoder).kUintptr
  1104. fn.fd = (*Decoder).kUintptr
  1105. case reflect.Float32:
  1106. fn.fe = (*Encoder).kFloat32
  1107. fn.fd = (*Decoder).kFloat32
  1108. case reflect.Float64:
  1109. fn.fe = (*Encoder).kFloat64
  1110. fn.fd = (*Decoder).kFloat64
  1111. case reflect.Complex64:
  1112. fn.fe = (*Encoder).kComplex64
  1113. fn.fd = (*Decoder).kComplex64
  1114. case reflect.Complex128:
  1115. fn.fe = (*Encoder).kComplex128
  1116. fn.fd = (*Decoder).kComplex128
  1117. case reflect.Chan:
  1118. fn.fe = (*Encoder).kChan
  1119. fn.fd = (*Decoder).kChan
  1120. case reflect.Slice:
  1121. fn.fe = (*Encoder).kSlice
  1122. fn.fd = (*Decoder).kSlice
  1123. case reflect.Array:
  1124. fi.addrD = false // decode directly into array value (slice made from it)
  1125. fn.fe = (*Encoder).kArray
  1126. fn.fd = (*Decoder).kArray
  1127. case reflect.Struct:
  1128. if ti.anyOmitEmpty ||
  1129. ti.flagMissingFielder ||
  1130. ti.flagMissingFielderPtr {
  1131. fn.fe = (*Encoder).kStruct
  1132. } else {
  1133. fn.fe = (*Encoder).kStructNoOmitempty
  1134. }
  1135. fn.fd = (*Decoder).kStruct
  1136. case reflect.Map:
  1137. fn.fe = (*Encoder).kMap
  1138. fn.fd = (*Decoder).kMap
  1139. case reflect.Interface:
  1140. // encode: reflect.Interface are handled already by preEncodeValue
  1141. fn.fd = (*Decoder).kInterface
  1142. fn.fe = (*Encoder).kErr
  1143. default:
  1144. // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
  1145. fn.fe = (*Encoder).kErr
  1146. fn.fd = (*Decoder).kErr
  1147. }
  1148. }
  1149. }
  1150. return
  1151. }
  1152. // Handle defines a specific encoding format. It also stores any runtime state
  1153. // used during an Encoding or Decoding session e.g. stored state about Types, etc.
  1154. //
  1155. // Once a handle is configured, it can be shared across multiple Encoders and Decoders.
  1156. //
  1157. // Note that a Handle is NOT safe for concurrent modification.
  1158. //
  1159. // A Handle also should not be modified after it is configured and has
  1160. // been used at least once. This is because stored state may be out of sync with the
  1161. // new configuration, and a data race can occur when multiple goroutines access it.
  1162. // i.e. multiple Encoders or Decoders in different goroutines.
  1163. //
  1164. // Consequently, the typical usage model is that a Handle is pre-configured
  1165. // before first time use, and not modified while in use.
  1166. // Such a pre-configured Handle is safe for concurrent access.
  1167. type Handle interface {
  1168. Name() string
  1169. getBasicHandle() *BasicHandle
  1170. newEncDriver() encDriver
  1171. newDecDriver() decDriver
  1172. isBinary() bool
  1173. isJson() bool // json is special for now, so track it
  1174. // desc describes the current byte descriptor, or returns "unknown[XXX]" if not understood.
  1175. desc(bd byte) string
  1176. // init initializes the handle based on handle-specific info (beyond what is in BasicHandle)
  1177. init()
  1178. }
  1179. // Raw represents raw formatted bytes.
  1180. // We "blindly" store it during encode and retrieve the raw bytes during decode.
  1181. // Note: it is dangerous during encode, so we may gate the behaviour
  1182. // behind an Encode flag which must be explicitly set.
  1183. type Raw []byte
  1184. // RawExt represents raw unprocessed extension data.
  1185. // Some codecs will decode extension data as a *RawExt
  1186. // if there is no registered extension for the tag.
  1187. //
  1188. // Only one of Data or Value is nil.
  1189. // If Data is nil, then the content of the RawExt is in the Value.
  1190. type RawExt struct {
  1191. Tag uint64
  1192. // Data is the []byte which represents the raw ext. If nil, ext is exposed in Value.
  1193. // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of types
  1194. Data []byte
  1195. // Value represents the extension, if Data is nil.
  1196. // Value is used by codecs (e.g. cbor, json) which leverage the format to do
  1197. // custom serialization of the types.
  1198. Value interface{}
  1199. }
  1200. func (re *RawExt) setData(xbs []byte, zerocopy bool) {
  1201. if zerocopy {
  1202. re.Data = xbs
  1203. } else {
  1204. re.Data = append(re.Data[:0], xbs...)
  1205. }
  1206. }
  1207. // BytesExt handles custom (de)serialization of types to/from []byte.
  1208. // It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
  1209. type BytesExt interface {
  1210. // WriteExt converts a value to a []byte.
  1211. //
  1212. // Note: v is a pointer iff the registered extension type is a struct or array kind.
  1213. WriteExt(v interface{}) []byte
  1214. // ReadExt updates a value from a []byte.
  1215. //
  1216. // Note: dst is always a pointer kind to the registered extension type.
  1217. ReadExt(dst interface{}, src []byte)
  1218. }
  1219. // InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
  1220. // The Encoder or Decoder will then handle the further (de)serialization of that known type.
  1221. //
  1222. // It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of types.
  1223. type InterfaceExt interface {
  1224. // ConvertExt converts a value into a simpler interface for easy encoding
  1225. // e.g. convert time.Time to int64.
  1226. //
  1227. // Note: v is a pointer iff the registered extension type is a struct or array kind.
  1228. ConvertExt(v interface{}) interface{}
  1229. // UpdateExt updates a value from a simpler interface for easy decoding
  1230. // e.g. convert int64 to time.Time.
  1231. //
  1232. // Note: dst is always a pointer kind to the registered extension type.
  1233. UpdateExt(dst interface{}, src interface{})
  1234. }
  1235. // Ext handles custom (de)serialization of custom types / extensions.
  1236. type Ext interface {
  1237. BytesExt
  1238. InterfaceExt
  1239. }
  1240. // addExtWrapper is a wrapper implementation to support former AddExt exported method.
  1241. type addExtWrapper struct {
  1242. encFn func(reflect.Value) ([]byte, error)
  1243. decFn func(reflect.Value, []byte) error
  1244. }
  1245. func (x addExtWrapper) WriteExt(v interface{}) []byte {
  1246. bs, err := x.encFn(reflect.ValueOf(v))
  1247. halt.onerror(err)
  1248. return bs
  1249. }
  1250. func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
  1251. halt.onerror(x.decFn(reflect.ValueOf(v), bs))
  1252. }
  1253. func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
  1254. return x.WriteExt(v)
  1255. }
  1256. func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  1257. x.ReadExt(dest, v.([]byte))
  1258. }
  1259. type bytesExtFailer struct{}
  1260. func (bytesExtFailer) WriteExt(v interface{}) []byte {
  1261. halt.onerror(errExtFnWriteExtUnsupported)
  1262. return nil
  1263. }
  1264. func (bytesExtFailer) ReadExt(v interface{}, bs []byte) {
  1265. halt.onerror(errExtFnReadExtUnsupported)
  1266. }
  1267. type interfaceExtFailer struct{}
  1268. func (interfaceExtFailer) ConvertExt(v interface{}) interface{} {
  1269. halt.onerror(errExtFnConvertExtUnsupported)
  1270. return nil
  1271. }
  1272. func (interfaceExtFailer) UpdateExt(dest interface{}, v interface{}) {
  1273. halt.onerror(errExtFnUpdateExtUnsupported)
  1274. }
  1275. type bytesExtWrapper struct {
  1276. interfaceExtFailer
  1277. BytesExt
  1278. }
  1279. type interfaceExtWrapper struct {
  1280. bytesExtFailer
  1281. InterfaceExt
  1282. }
  1283. type extFailWrapper struct {
  1284. bytesExtFailer
  1285. interfaceExtFailer
  1286. }
  1287. type binaryEncodingType struct{}
  1288. func (binaryEncodingType) isBinary() bool { return true }
  1289. func (binaryEncodingType) isJson() bool { return false }
  1290. type textEncodingType struct{}
  1291. func (textEncodingType) isBinary() bool { return false }
  1292. func (textEncodingType) isJson() bool { return false }
  1293. type notJsonType struct{}
  1294. func (notJsonType) isJson() bool { return false }
  1295. // noBuiltInTypes is embedded into many types which do not support builtins
  1296. // e.g. msgpack, simple, cbor.
  1297. type noBuiltInTypes struct{}
  1298. func (noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
  1299. func (noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
  1300. // bigenHelper handles ByteOrder operations directly using
  1301. // arrays of bytes (not slice of bytes).
  1302. //
  1303. // Since byteorder operations are very common for encoding and decoding
  1304. // numbers, lengths, etc - it is imperative that this operation is as
  1305. // fast as possible. Removing indirection (pointer chasing) to look
  1306. // at up to 8 bytes helps a lot here.
  1307. //
  1308. // For times where it is expedient to use a slice, delegate to the
  1309. // bigenstd (equal to the binary.BigEndian value).
  1310. //
  1311. // retrofitted from stdlib: encoding/binary/BigEndian (ByteOrder)
  1312. type bigenHelper struct{}
  1313. func (z bigenHelper) PutUint16(v uint16) (b [2]byte) {
  1314. return [...]byte{
  1315. byte(v >> 8),
  1316. byte(v),
  1317. }
  1318. }
  1319. func (z bigenHelper) PutUint32(v uint32) (b [4]byte) {
  1320. return [...]byte{
  1321. byte(v >> 24),
  1322. byte(v >> 16),
  1323. byte(v >> 8),
  1324. byte(v),
  1325. }
  1326. }
  1327. func (z bigenHelper) PutUint64(v uint64) (b [8]byte) {
  1328. return [...]byte{
  1329. byte(v >> 56),
  1330. byte(v >> 48),
  1331. byte(v >> 40),
  1332. byte(v >> 32),
  1333. byte(v >> 24),
  1334. byte(v >> 16),
  1335. byte(v >> 8),
  1336. byte(v),
  1337. }
  1338. }
  1339. func (z bigenHelper) Uint16(b [2]byte) (v uint16) {
  1340. return uint16(b[1]) |
  1341. uint16(b[0])<<8
  1342. }
  1343. func (z bigenHelper) Uint32(b [4]byte) (v uint32) {
  1344. return uint32(b[3]) |
  1345. uint32(b[2])<<8 |
  1346. uint32(b[1])<<16 |
  1347. uint32(b[0])<<24
  1348. }
  1349. func (z bigenHelper) Uint64(b [8]byte) (v uint64) {
  1350. return uint64(b[7]) |
  1351. uint64(b[6])<<8 |
  1352. uint64(b[5])<<16 |
  1353. uint64(b[4])<<24 |
  1354. uint64(b[3])<<32 |
  1355. uint64(b[2])<<40 |
  1356. uint64(b[1])<<48 |
  1357. uint64(b[0])<<56
  1358. }
  1359. func (z bigenHelper) writeUint16(w *encWr, v uint16) {
  1360. x := z.PutUint16(v)
  1361. w.writen2(x[0], x[1])
  1362. }
  1363. func (z bigenHelper) writeUint32(w *encWr, v uint32) {
  1364. w.writen4(z.PutUint32(v))
  1365. }
  1366. func (z bigenHelper) writeUint64(w *encWr, v uint64) {
  1367. w.writen8(z.PutUint64(v))
  1368. }
  1369. type extTypeTagFn struct {
  1370. rtid uintptr
  1371. rtidptr uintptr
  1372. rt reflect.Type
  1373. tag uint64
  1374. ext Ext
  1375. }
  1376. type extHandle []extTypeTagFn
  1377. // AddExt registes an encode and decode function for a reflect.Type.
  1378. // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
  1379. //
  1380. // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  1381. func (x *BasicHandle) AddExt(rt reflect.Type, tag byte,
  1382. encfn func(reflect.Value) ([]byte, error),
  1383. decfn func(reflect.Value, []byte) error) (err error) {
  1384. if encfn == nil || decfn == nil {
  1385. return x.SetExt(rt, uint64(tag), nil)
  1386. }
  1387. return x.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
  1388. }
  1389. // SetExt will set the extension for a tag and reflect.Type.
  1390. // Note that the type must be a named type, and specifically not a pointer or Interface.
  1391. // An error is returned if that is not honored.
  1392. // To Deregister an ext, call SetExt with nil Ext.
  1393. //
  1394. // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  1395. func (x *BasicHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
  1396. if x.isInited() {
  1397. return errHandleInited
  1398. }
  1399. if x.basicHandleRuntimeState == nil {
  1400. x.basicHandleRuntimeState = new(basicHandleRuntimeState)
  1401. }
  1402. return x.basicHandleRuntimeState.setExt(rt, tag, ext)
  1403. }
  1404. func (o extHandle) getExtForI(x interface{}) (v *extTypeTagFn) {
  1405. if len(o) > 0 {
  1406. v = o.getExt(i2rtid(x), true)
  1407. }
  1408. return
  1409. }
  1410. func (o extHandle) getExt(rtid uintptr, check bool) (v *extTypeTagFn) {
  1411. if !check {
  1412. return
  1413. }
  1414. for i := range o {
  1415. v = &o[i]
  1416. if v.rtid == rtid || v.rtidptr == rtid {
  1417. return
  1418. }
  1419. }
  1420. return nil
  1421. }
  1422. func (o extHandle) getExtForTag(tag uint64) (v *extTypeTagFn) {
  1423. for i := range o {
  1424. v = &o[i]
  1425. if v.tag == tag {
  1426. return
  1427. }
  1428. }
  1429. return nil
  1430. }
  1431. type intf2impl struct {
  1432. rtid uintptr // for intf
  1433. impl reflect.Type
  1434. }
  1435. type intf2impls []intf2impl
  1436. // Intf2Impl maps an interface to an implementing type.
  1437. // This allows us support infering the concrete type
  1438. // and populating it when passed an interface.
  1439. // e.g. var v io.Reader can be decoded as a bytes.Buffer, etc.
  1440. //
  1441. // Passing a nil impl will clear the mapping.
  1442. func (o *intf2impls) Intf2Impl(intf, impl reflect.Type) (err error) {
  1443. if impl != nil && !impl.Implements(intf) {
  1444. return fmt.Errorf("Intf2Impl: %v does not implement %v", impl, intf)
  1445. }
  1446. rtid := rt2id(intf)
  1447. o2 := *o
  1448. for i := range o2 {
  1449. v := &o2[i]
  1450. if v.rtid == rtid {
  1451. v.impl = impl
  1452. return
  1453. }
  1454. }
  1455. *o = append(o2, intf2impl{rtid, impl})
  1456. return
  1457. }
  1458. func (o intf2impls) intf2impl(rtid uintptr) (rv reflect.Value) {
  1459. for i := range o {
  1460. v := &o[i]
  1461. if v.rtid == rtid {
  1462. if v.impl == nil {
  1463. return
  1464. }
  1465. vkind := v.impl.Kind()
  1466. if vkind == reflect.Ptr {
  1467. return reflect.New(v.impl.Elem())
  1468. }
  1469. return rvZeroAddrK(v.impl, vkind)
  1470. }
  1471. }
  1472. return
  1473. }
  1474. // structFieldinfopathNode is a node in a tree, which allows us easily
  1475. // walk the anonymous path.
  1476. //
  1477. // In the typical case, the node is not embedded/anonymous, and thus the parent
  1478. // will be nil and this information becomes a value (not needing any indirection).
  1479. type structFieldInfoPathNode struct {
  1480. parent *structFieldInfoPathNode
  1481. offset uint16
  1482. index uint16
  1483. kind uint8
  1484. numderef uint8
  1485. // encNameAsciiAlphaNum and omitEmpty should be in structFieldInfo,
  1486. // but are kept here for tighter packaging.
  1487. encNameAsciiAlphaNum bool // the encName only contains ascii alphabet and numbers
  1488. omitEmpty bool
  1489. typ reflect.Type
  1490. }
  1491. // depth returns number of valid nodes in the hierachy
  1492. func (path *structFieldInfoPathNode) depth() (d int) {
  1493. TOP:
  1494. if path != nil {
  1495. d++
  1496. path = path.parent
  1497. goto TOP
  1498. }
  1499. return
  1500. }
  1501. // field returns the field of the struct.
  1502. func (path *structFieldInfoPathNode) field(v reflect.Value) (rv2 reflect.Value) {
  1503. if parent := path.parent; parent != nil {
  1504. v = parent.field(v)
  1505. for j, k := uint8(0), parent.numderef; j < k; j++ {
  1506. if rvIsNil(v) {
  1507. return
  1508. }
  1509. v = v.Elem()
  1510. }
  1511. }
  1512. return path.rvField(v)
  1513. }
  1514. // fieldAlloc returns the field of the struct.
  1515. // It allocates if a nil value was seen while searching.
  1516. func (path *structFieldInfoPathNode) fieldAlloc(v reflect.Value) (rv2 reflect.Value) {
  1517. if parent := path.parent; parent != nil {
  1518. v = parent.fieldAlloc(v)
  1519. for j, k := uint8(0), parent.numderef; j < k; j++ {
  1520. if rvIsNil(v) {
  1521. rvSetDirect(v, reflect.New(rvType(v).Elem()))
  1522. }
  1523. v = v.Elem()
  1524. }
  1525. }
  1526. return path.rvField(v)
  1527. }
  1528. type structFieldInfo struct {
  1529. encName string // encode name
  1530. // encNameHash uintptr
  1531. // fieldName string // currently unused
  1532. // encNameAsciiAlphaNum and omitEmpty should be here,
  1533. // but are stored in structFieldInfoPathNode for tighter packaging.
  1534. path structFieldInfoPathNode
  1535. }
  1536. func parseStructInfo(stag string) (toArray, omitEmpty bool, keytype valueType) {
  1537. keytype = valueTypeString // default
  1538. if stag == "" {
  1539. return
  1540. }
  1541. ss := strings.Split(stag, ",")
  1542. if len(ss) < 2 {
  1543. return
  1544. }
  1545. for _, s := range ss[1:] {
  1546. switch s {
  1547. case "omitempty":
  1548. omitEmpty = true
  1549. case "toarray":
  1550. toArray = true
  1551. case "int":
  1552. keytype = valueTypeInt
  1553. case "uint":
  1554. keytype = valueTypeUint
  1555. case "float":
  1556. keytype = valueTypeFloat
  1557. // case "bool":
  1558. // keytype = valueTypeBool
  1559. case "string":
  1560. keytype = valueTypeString
  1561. }
  1562. }
  1563. return
  1564. }
  1565. func (si *structFieldInfo) parseTag(stag string) {
  1566. if stag == "" {
  1567. return
  1568. }
  1569. for i, s := range strings.Split(stag, ",") {
  1570. if i == 0 {
  1571. if s != "" {
  1572. si.encName = s
  1573. }
  1574. } else {
  1575. switch s {
  1576. case "omitempty":
  1577. si.path.omitEmpty = true
  1578. }
  1579. }
  1580. }
  1581. }
  1582. type sfiSortedByEncName []*structFieldInfo
  1583. func (p sfiSortedByEncName) Len() int { return len(p) }
  1584. func (p sfiSortedByEncName) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
  1585. func (p sfiSortedByEncName) Less(i, j int) bool { return p[uint(i)].encName < p[uint(j)].encName }
  1586. // typeInfo4Container holds information that is only available for
  1587. // containers like map, array, chan, slice.
  1588. type typeInfo4Container struct {
  1589. elem reflect.Type
  1590. // key is:
  1591. // - if map kind: map key
  1592. // - if array kind: sliceOf(elem)
  1593. // - if chan kind: sliceof(elem)
  1594. key reflect.Type
  1595. // fastpathUnderlying is underlying type of a named slice/map/array, as defined by go spec,
  1596. // that is used by fastpath where we defined fastpath functions for the underlying type.
  1597. //
  1598. // for a map, it's a map; for a slice or array, it's a slice; else its nil.
  1599. fastpathUnderlying reflect.Type
  1600. tikey *typeInfo
  1601. tielem *typeInfo
  1602. }
  1603. // typeInfo keeps static (non-changing readonly)information
  1604. // about each (non-ptr) type referenced in the encode/decode sequence.
  1605. //
  1606. // During an encode/decode sequence, we work as below:
  1607. // - If base is a built in type, en/decode base value
  1608. // - If base is registered as an extension, en/decode base value
  1609. // - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
  1610. // - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
  1611. // - Else decode appropriately based on the reflect.Kind
  1612. type typeInfo struct {
  1613. rt reflect.Type
  1614. ptr reflect.Type
  1615. // pkgpath string
  1616. rtid uintptr
  1617. numMeth uint16 // number of methods
  1618. kind uint8
  1619. chandir uint8
  1620. anyOmitEmpty bool // true if a struct, and any of the fields are tagged "omitempty"
  1621. toArray bool // whether this (struct) type should be encoded as an array
  1622. keyType valueType // if struct, how is the field name stored in a stream? default is string
  1623. mbs bool // base type (T or *T) is a MapBySlice
  1624. sfi4Name map[string]*structFieldInfo // map. used for finding sfi given a name
  1625. *typeInfo4Container
  1626. // ---- cpu cache line boundary?
  1627. size, keysize, elemsize uint32
  1628. keykind, elemkind uint8
  1629. flagHasPkgPath bool // Type.PackagePath != ""
  1630. flagCustom bool // does this have custom implementation?
  1631. flagComparable bool
  1632. flagCanTransient bool
  1633. flagSelferViaCodecgen bool
  1634. // custom implementation flags
  1635. flagIsZeroer bool
  1636. flagIsZeroerPtr bool
  1637. flagIsCodecEmptyer bool
  1638. flagIsCodecEmptyerPtr bool
  1639. flagBinaryMarshaler bool
  1640. flagBinaryMarshalerPtr bool
  1641. flagBinaryUnmarshaler bool
  1642. flagBinaryUnmarshalerPtr bool
  1643. flagTextMarshaler bool
  1644. flagTextMarshalerPtr bool
  1645. flagTextUnmarshaler bool
  1646. flagTextUnmarshalerPtr bool
  1647. flagJsonMarshaler bool
  1648. flagJsonMarshalerPtr bool
  1649. flagJsonUnmarshaler bool
  1650. flagJsonUnmarshalerPtr bool
  1651. flagSelfer bool
  1652. flagSelferPtr bool
  1653. flagMissingFielder bool
  1654. flagMissingFielderPtr bool
  1655. infoFieldOmitempty bool
  1656. sfi structFieldInfos
  1657. }
  1658. func (ti *typeInfo) siForEncName(name []byte) (si *structFieldInfo) {
  1659. return ti.sfi4Name[string(name)]
  1660. }
  1661. func (ti *typeInfo) resolve(x []structFieldInfo, ss map[string]uint16) (n int) {
  1662. n = len(x)
  1663. for i := range x {
  1664. ui := uint16(i)
  1665. xn := x[i].encName
  1666. j, ok := ss[xn]
  1667. if ok {
  1668. i2clear := ui // index to be cleared
  1669. if x[i].path.depth() < x[j].path.depth() { // this one is shallower
  1670. ss[xn] = ui
  1671. i2clear = j
  1672. }
  1673. if x[i2clear].encName != "" {
  1674. x[i2clear].encName = ""
  1675. n--
  1676. }
  1677. } else {
  1678. ss[xn] = ui
  1679. }
  1680. }
  1681. return
  1682. }
  1683. func (ti *typeInfo) init(x []structFieldInfo, n int) {
  1684. var anyOmitEmpty bool
  1685. // remove all the nils (non-ready)
  1686. m := make(map[string]*structFieldInfo, n)
  1687. w := make([]structFieldInfo, n)
  1688. y := make([]*structFieldInfo, n+n)
  1689. z := y[n:]
  1690. y = y[:n]
  1691. n = 0
  1692. for i := range x {
  1693. if x[i].encName == "" {
  1694. continue
  1695. }
  1696. if !anyOmitEmpty && x[i].path.omitEmpty {
  1697. anyOmitEmpty = true
  1698. }
  1699. w[n] = x[i]
  1700. y[n] = &w[n]
  1701. m[x[i].encName] = &w[n]
  1702. n++
  1703. }
  1704. if n != len(y) {
  1705. halt.errorf("failure reading struct %v - expecting %d of %d valid fields, got %d", ti.rt, len(y), len(x), n)
  1706. }
  1707. copy(z, y)
  1708. sort.Sort(sfiSortedByEncName(z))
  1709. ti.anyOmitEmpty = anyOmitEmpty
  1710. ti.sfi.load(y, z)
  1711. ti.sfi4Name = m
  1712. }
  1713. // Handling flagCanTransient
  1714. //
  1715. // We support transient optimization if the kind of the type is
  1716. // a number, bool, string, or slice (of number/bool).
  1717. // In addition, we also support if the kind is struct or array,
  1718. // and the type does not contain any pointers recursively).
  1719. //
  1720. // Noteworthy that all reference types (string, slice, func, map, ptr, interface, etc) have pointers.
  1721. //
  1722. // If using transient for a type with a pointer, there is the potential for data corruption
  1723. // when GC tries to follow a "transient" pointer which may become a non-pointer soon after.
  1724. //
  1725. func transientBitsetFlags() *bitset32 {
  1726. if transientValueHasStringSlice {
  1727. return &numBoolStrSliceBitset
  1728. }
  1729. return &numBoolBitset
  1730. }
  1731. func isCanTransient(t reflect.Type, k reflect.Kind) (v bool) {
  1732. var bs = transientBitsetFlags()
  1733. if bs.isset(byte(k)) {
  1734. v = true
  1735. } else if k == reflect.Slice {
  1736. elem := t.Elem()
  1737. v = numBoolBitset.isset(byte(elem.Kind()))
  1738. } else if k == reflect.Array {
  1739. elem := t.Elem()
  1740. v = isCanTransient(elem, elem.Kind())
  1741. } else if k == reflect.Struct {
  1742. v = true
  1743. for j, jlen := 0, t.NumField(); j < jlen; j++ {
  1744. f := t.Field(j)
  1745. if !isCanTransient(f.Type, f.Type.Kind()) {
  1746. v = false
  1747. return
  1748. }
  1749. }
  1750. } else {
  1751. v = false
  1752. }
  1753. return
  1754. }
  1755. func (ti *typeInfo) doSetFlagCanTransient() {
  1756. if transientSizeMax > 0 {
  1757. ti.flagCanTransient = ti.size <= transientSizeMax
  1758. } else {
  1759. ti.flagCanTransient = true
  1760. }
  1761. if ti.flagCanTransient {
  1762. if !transientBitsetFlags().isset(ti.kind) {
  1763. ti.flagCanTransient = isCanTransient(ti.rt, reflect.Kind(ti.kind))
  1764. }
  1765. }
  1766. }
  1767. type rtid2ti struct {
  1768. rtid uintptr
  1769. ti *typeInfo
  1770. }
  1771. // TypeInfos caches typeInfo for each type on first inspection.
  1772. //
  1773. // It is configured with a set of tag keys, which are used to get
  1774. // configuration for the type.
  1775. type TypeInfos struct {
  1776. infos atomicTypeInfoSlice
  1777. mu sync.Mutex
  1778. _ uint64 // padding (cache-aligned)
  1779. tags []string
  1780. _ uint64 // padding (cache-aligned)
  1781. }
  1782. // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
  1783. //
  1784. // This allows users customize the struct tag keys which contain configuration
  1785. // of their types.
  1786. func NewTypeInfos(tags []string) *TypeInfos {
  1787. return &TypeInfos{tags: tags}
  1788. }
  1789. func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
  1790. // check for tags: codec, json, in that order.
  1791. // this allows seamless support for many configured structs.
  1792. for _, x := range x.tags {
  1793. s = t.Get(x)
  1794. if s != "" {
  1795. return s
  1796. }
  1797. }
  1798. return
  1799. }
  1800. func findTypeInfo(s []rtid2ti, rtid uintptr) (i uint, ti *typeInfo) {
  1801. // binary search. adapted from sort/search.go.
  1802. // Note: we use goto (instead of for loop) so this can be inlined.
  1803. var h uint
  1804. var j = uint(len(s))
  1805. LOOP:
  1806. if i < j {
  1807. h = (i + j) >> 1 // avoid overflow when computing h // h = i + (j-i)/2
  1808. if s[h].rtid < rtid {
  1809. i = h + 1
  1810. } else {
  1811. j = h
  1812. }
  1813. goto LOOP
  1814. }
  1815. if i < uint(len(s)) && s[i].rtid == rtid {
  1816. ti = s[i].ti
  1817. }
  1818. return
  1819. }
  1820. func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  1821. if pti = x.find(rtid); pti == nil {
  1822. pti = x.load(rt)
  1823. }
  1824. return
  1825. }
  1826. func (x *TypeInfos) find(rtid uintptr) (pti *typeInfo) {
  1827. sp := x.infos.load()
  1828. if sp != nil {
  1829. _, pti = findTypeInfo(sp, rtid)
  1830. }
  1831. return
  1832. }
  1833. func (x *TypeInfos) load(rt reflect.Type) (pti *typeInfo) {
  1834. rk := rt.Kind()
  1835. if rk == reflect.Ptr { // || (rk == reflect.Interface && rtid != intfTypId) {
  1836. halt.errorf("invalid kind passed to TypeInfos.get: %v - %v", rk, rt)
  1837. }
  1838. rtid := rt2id(rt)
  1839. // do not hold lock while computing this.
  1840. // it may lead to duplication, but that's ok.
  1841. ti := typeInfo{
  1842. rt: rt,
  1843. ptr: reflect.PtrTo(rt),
  1844. rtid: rtid,
  1845. kind: uint8(rk),
  1846. size: uint32(rt.Size()),
  1847. numMeth: uint16(rt.NumMethod()),
  1848. keyType: valueTypeString, // default it - so it's never 0
  1849. // pkgpath: rt.PkgPath(),
  1850. flagHasPkgPath: rt.PkgPath() != "",
  1851. }
  1852. // bset sets custom implementation flags
  1853. bset := func(when bool, b *bool) {
  1854. if when {
  1855. *b = true
  1856. ti.flagCustom = true
  1857. }
  1858. }
  1859. var b1, b2 bool
  1860. b1, b2 = implIntf(rt, binaryMarshalerTyp)
  1861. bset(b1, &ti.flagBinaryMarshaler)
  1862. bset(b2, &ti.flagBinaryMarshalerPtr)
  1863. b1, b2 = implIntf(rt, binaryUnmarshalerTyp)
  1864. bset(b1, &ti.flagBinaryUnmarshaler)
  1865. bset(b2, &ti.flagBinaryUnmarshalerPtr)
  1866. b1, b2 = implIntf(rt, textMarshalerTyp)
  1867. bset(b1, &ti.flagTextMarshaler)
  1868. bset(b2, &ti.flagTextMarshalerPtr)
  1869. b1, b2 = implIntf(rt, textUnmarshalerTyp)
  1870. bset(b1, &ti.flagTextUnmarshaler)
  1871. bset(b2, &ti.flagTextUnmarshalerPtr)
  1872. b1, b2 = implIntf(rt, jsonMarshalerTyp)
  1873. bset(b1, &ti.flagJsonMarshaler)
  1874. bset(b2, &ti.flagJsonMarshalerPtr)
  1875. b1, b2 = implIntf(rt, jsonUnmarshalerTyp)
  1876. bset(b1, &ti.flagJsonUnmarshaler)
  1877. bset(b2, &ti.flagJsonUnmarshalerPtr)
  1878. b1, b2 = implIntf(rt, selferTyp)
  1879. bset(b1, &ti.flagSelfer)
  1880. bset(b2, &ti.flagSelferPtr)
  1881. b1, b2 = implIntf(rt, missingFielderTyp)
  1882. bset(b1, &ti.flagMissingFielder)
  1883. bset(b2, &ti.flagMissingFielderPtr)
  1884. b1, b2 = implIntf(rt, iszeroTyp)
  1885. bset(b1, &ti.flagIsZeroer)
  1886. bset(b2, &ti.flagIsZeroerPtr)
  1887. b1, b2 = implIntf(rt, isCodecEmptyerTyp)
  1888. bset(b1, &ti.flagIsCodecEmptyer)
  1889. bset(b2, &ti.flagIsCodecEmptyerPtr)
  1890. b1, b2 = implIntf(rt, isSelferViaCodecgenerTyp)
  1891. ti.flagSelferViaCodecgen = b1 || b2
  1892. b1 = rt.Comparable()
  1893. // bset(b1, &ti.flagComparable)
  1894. ti.flagComparable = b1
  1895. ti.doSetFlagCanTransient()
  1896. var tt reflect.Type
  1897. switch rk {
  1898. case reflect.Struct:
  1899. var omitEmpty bool
  1900. if f, ok := rt.FieldByName(structInfoFieldName); ok {
  1901. ti.toArray, omitEmpty, ti.keyType = parseStructInfo(x.structTag(f.Tag))
  1902. ti.infoFieldOmitempty = omitEmpty
  1903. } else {
  1904. ti.keyType = valueTypeString
  1905. }
  1906. pp, pi := &pool4tiload, pool4tiload.Get()
  1907. pv := pi.(*typeInfoLoad)
  1908. pv.reset()
  1909. pv.etypes = append(pv.etypes, ti.rtid)
  1910. x.rget(rt, rtid, nil, pv, omitEmpty)
  1911. n := ti.resolve(pv.sfis, pv.sfiNames)
  1912. ti.init(pv.sfis, n)
  1913. pp.Put(pi)
  1914. case reflect.Map:
  1915. ti.typeInfo4Container = new(typeInfo4Container)
  1916. ti.elem = rt.Elem()
  1917. for tt = ti.elem; tt.Kind() == reflect.Ptr; tt = tt.Elem() {
  1918. }
  1919. ti.tielem = x.get(rt2id(tt), tt)
  1920. ti.elemkind = uint8(ti.elem.Kind())
  1921. ti.elemsize = uint32(ti.elem.Size())
  1922. ti.key = rt.Key()
  1923. for tt = ti.key; tt.Kind() == reflect.Ptr; tt = tt.Elem() {
  1924. }
  1925. ti.tikey = x.get(rt2id(tt), tt)
  1926. ti.keykind = uint8(ti.key.Kind())
  1927. ti.keysize = uint32(ti.key.Size())
  1928. if ti.flagHasPkgPath {
  1929. ti.fastpathUnderlying = reflect.MapOf(ti.key, ti.elem)
  1930. }
  1931. case reflect.Slice:
  1932. ti.typeInfo4Container = new(typeInfo4Container)
  1933. ti.mbs, b2 = implIntf(rt, mapBySliceTyp)
  1934. if !ti.mbs && b2 {
  1935. ti.mbs = b2
  1936. }
  1937. ti.elem = rt.Elem()
  1938. for tt = ti.elem; tt.Kind() == reflect.Ptr; tt = tt.Elem() {
  1939. }
  1940. ti.tielem = x.get(rt2id(tt), tt)
  1941. ti.elemkind = uint8(ti.elem.Kind())
  1942. ti.elemsize = uint32(ti.elem.Size())
  1943. if ti.flagHasPkgPath {
  1944. ti.fastpathUnderlying = reflect.SliceOf(ti.elem)
  1945. }
  1946. case reflect.Chan:
  1947. ti.typeInfo4Container = new(typeInfo4Container)
  1948. ti.elem = rt.Elem()
  1949. for tt = ti.elem; tt.Kind() == reflect.Ptr; tt = tt.Elem() {
  1950. }
  1951. ti.tielem = x.get(rt2id(tt), tt)
  1952. ti.elemkind = uint8(ti.elem.Kind())
  1953. ti.elemsize = uint32(ti.elem.Size())
  1954. ti.chandir = uint8(rt.ChanDir())
  1955. ti.key = reflect.SliceOf(ti.elem)
  1956. ti.keykind = uint8(reflect.Slice)
  1957. case reflect.Array:
  1958. ti.typeInfo4Container = new(typeInfo4Container)
  1959. ti.mbs, b2 = implIntf(rt, mapBySliceTyp)
  1960. if !ti.mbs && b2 {
  1961. ti.mbs = b2
  1962. }
  1963. ti.elem = rt.Elem()
  1964. ti.elemkind = uint8(ti.elem.Kind())
  1965. ti.elemsize = uint32(ti.elem.Size())
  1966. for tt = ti.elem; tt.Kind() == reflect.Ptr; tt = tt.Elem() {
  1967. }
  1968. ti.tielem = x.get(rt2id(tt), tt)
  1969. ti.key = reflect.SliceOf(ti.elem)
  1970. ti.keykind = uint8(reflect.Slice)
  1971. ti.keysize = uint32(ti.key.Size())
  1972. if ti.flagHasPkgPath {
  1973. ti.fastpathUnderlying = ti.key
  1974. }
  1975. // MARKER: reflect.Ptr cannot happen here, as we halt early if reflect.Ptr passed in
  1976. // case reflect.Ptr:
  1977. // ti.elem = rt.Elem()
  1978. // ti.elemkind = uint8(ti.elem.Kind())
  1979. // ti.elemsize = uint32(ti.elem.Size())
  1980. }
  1981. x.mu.Lock()
  1982. sp := x.infos.load()
  1983. // since this is an atomic load/store, we MUST use a different array each time,
  1984. // else we have a data race when a store is happening simultaneously with a findRtidFn call.
  1985. if sp == nil {
  1986. pti = &ti
  1987. sp = []rtid2ti{{rtid, pti}}
  1988. x.infos.store(sp)
  1989. } else {
  1990. var idx uint
  1991. idx, pti = findTypeInfo(sp, rtid)
  1992. if pti == nil {
  1993. pti = &ti
  1994. sp2 := make([]rtid2ti, len(sp)+1)
  1995. copy(sp2[idx+1:], sp[idx:])
  1996. copy(sp2, sp[:idx])
  1997. sp2[idx] = rtid2ti{rtid, pti}
  1998. x.infos.store(sp2)
  1999. }
  2000. }
  2001. x.mu.Unlock()
  2002. return
  2003. }
  2004. func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr,
  2005. path *structFieldInfoPathNode, pv *typeInfoLoad, omitEmpty bool) {
  2006. // Read up fields and store how to access the value.
  2007. //
  2008. // It uses go's rules for message selectors,
  2009. // which say that the field with the shallowest depth is selected.
  2010. //
  2011. // Note: we consciously use slices, not a map, to simulate a set.
  2012. // Typically, types have < 16 fields,
  2013. // and iteration using equals is faster than maps there
  2014. flen := rt.NumField()
  2015. LOOP:
  2016. for j, jlen := uint16(0), uint16(flen); j < jlen; j++ {
  2017. f := rt.Field(int(j))
  2018. fkind := f.Type.Kind()
  2019. // skip if a func type, or is unexported, or structTag value == "-"
  2020. switch fkind {
  2021. case reflect.Func, reflect.UnsafePointer:
  2022. continue LOOP
  2023. }
  2024. isUnexported := f.PkgPath != ""
  2025. if isUnexported && !f.Anonymous {
  2026. continue
  2027. }
  2028. stag := x.structTag(f.Tag)
  2029. if stag == "-" {
  2030. continue
  2031. }
  2032. var si structFieldInfo
  2033. var numderef uint8 = 0
  2034. for xft := f.Type; xft.Kind() == reflect.Ptr; xft = xft.Elem() {
  2035. numderef++
  2036. }
  2037. var parsed bool
  2038. // if anonymous and no struct tag (or it's blank),
  2039. // and a struct (or pointer to struct), inline it.
  2040. if f.Anonymous && fkind != reflect.Interface {
  2041. // ^^ redundant but ok: per go spec, an embedded pointer type cannot be to an interface
  2042. ft := f.Type
  2043. isPtr := ft.Kind() == reflect.Ptr
  2044. for ft.Kind() == reflect.Ptr {
  2045. ft = ft.Elem()
  2046. }
  2047. isStruct := ft.Kind() == reflect.Struct
  2048. // Ignore embedded fields of unexported non-struct types.
  2049. // Also, from go1.10, ignore pointers to unexported struct types
  2050. // because unmarshal cannot assign a new struct to an unexported field.
  2051. // See https://golang.org/issue/21357
  2052. if (isUnexported && !isStruct) || (!allowSetUnexportedEmbeddedPtr && isUnexported && isPtr) {
  2053. continue
  2054. }
  2055. doInline := stag == ""
  2056. if !doInline {
  2057. si.parseTag(stag)
  2058. parsed = true
  2059. doInline = si.encName == "" // si.isZero()
  2060. }
  2061. if doInline && isStruct {
  2062. // if etypes contains this, don't call rget again (as fields are already seen here)
  2063. ftid := rt2id(ft)
  2064. // We cannot recurse forever, but we need to track other field depths.
  2065. // So - we break if we see a type twice (not the first time).
  2066. // This should be sufficient to handle an embedded type that refers to its
  2067. // owning type, which then refers to its embedded type.
  2068. processIt := true
  2069. numk := 0
  2070. for _, k := range pv.etypes {
  2071. if k == ftid {
  2072. numk++
  2073. if numk == rgetMaxRecursion {
  2074. processIt = false
  2075. break
  2076. }
  2077. }
  2078. }
  2079. if processIt {
  2080. pv.etypes = append(pv.etypes, ftid)
  2081. path2 := &structFieldInfoPathNode{
  2082. parent: path,
  2083. typ: f.Type,
  2084. offset: uint16(f.Offset),
  2085. index: j,
  2086. kind: uint8(fkind),
  2087. numderef: numderef,
  2088. }
  2089. x.rget(ft, ftid, path2, pv, omitEmpty)
  2090. }
  2091. continue
  2092. }
  2093. }
  2094. // after the anonymous dance: if an unexported field, skip
  2095. if isUnexported || f.Name == "" { // f.Name cannot be "", but defensively handle it
  2096. continue
  2097. }
  2098. si.path = structFieldInfoPathNode{
  2099. parent: path,
  2100. typ: f.Type,
  2101. offset: uint16(f.Offset),
  2102. index: j,
  2103. kind: uint8(fkind),
  2104. numderef: numderef,
  2105. // set asciiAlphaNum to true (default); checked and may be set to false below
  2106. encNameAsciiAlphaNum: true,
  2107. // note: omitEmpty might have been set in an earlier parseTag call, etc - so carry it forward
  2108. omitEmpty: si.path.omitEmpty,
  2109. }
  2110. if !parsed {
  2111. si.encName = f.Name
  2112. si.parseTag(stag)
  2113. parsed = true
  2114. } else if si.encName == "" {
  2115. si.encName = f.Name
  2116. }
  2117. // si.encNameHash = maxUintptr() // hashShortString(bytesView(si.encName))
  2118. if omitEmpty {
  2119. si.path.omitEmpty = true
  2120. }
  2121. for i := len(si.encName) - 1; i >= 0; i-- { // bounds-check elimination
  2122. if !asciiAlphaNumBitset.isset(si.encName[i]) {
  2123. si.path.encNameAsciiAlphaNum = false
  2124. break
  2125. }
  2126. }
  2127. pv.sfis = append(pv.sfis, si)
  2128. }
  2129. }
  2130. func implIntf(rt, iTyp reflect.Type) (base bool, indir bool) {
  2131. // return rt.Implements(iTyp), reflect.PtrTo(rt).Implements(iTyp)
  2132. // if I's method is defined on T (ie T implements I), then *T implements I.
  2133. // The converse is not true.
  2134. // Type.Implements can be expensive, as it does a simulataneous linear search across 2 lists
  2135. // with alphanumeric string comparisons.
  2136. // If we can avoid running one of these 2 calls, we should.
  2137. base = rt.Implements(iTyp)
  2138. if base {
  2139. indir = true
  2140. } else {
  2141. indir = reflect.PtrTo(rt).Implements(iTyp)
  2142. }
  2143. return
  2144. }
  2145. func isSliceBoundsError(s string) bool {
  2146. return strings.Contains(s, "index out of range") ||
  2147. strings.Contains(s, "slice bounds out of range")
  2148. }
  2149. func sprintf(format string, v ...interface{}) string {
  2150. return fmt.Sprintf(format, v...)
  2151. }
  2152. func panicValToErr(h errDecorator, v interface{}, err *error) {
  2153. if v == *err {
  2154. return
  2155. }
  2156. switch xerr := v.(type) {
  2157. case nil:
  2158. case runtime.Error:
  2159. d, dok := h.(*Decoder)
  2160. if dok && d.bytes && isSliceBoundsError(xerr.Error()) {
  2161. *err = io.EOF
  2162. } else {
  2163. h.wrapErr(xerr, err)
  2164. }
  2165. case error:
  2166. switch xerr {
  2167. case nil:
  2168. case io.EOF, io.ErrUnexpectedEOF, errEncoderNotInitialized, errDecoderNotInitialized:
  2169. // treat as special (bubble up)
  2170. *err = xerr
  2171. default:
  2172. h.wrapErr(xerr, err)
  2173. }
  2174. default:
  2175. // we don't expect this to happen (as this library always panics with an error)
  2176. h.wrapErr(fmt.Errorf("%v", v), err)
  2177. }
  2178. }
  2179. func usableByteSlice(bs []byte, slen int) (out []byte, changed bool) {
  2180. const maxCap = 1024 * 1024 * 64 // 64MB
  2181. const skipMaxCap = false // allow to test
  2182. if slen <= 0 {
  2183. return []byte{}, true
  2184. }
  2185. if slen <= cap(bs) {
  2186. return bs[:slen], false
  2187. }
  2188. // slen > cap(bs) ... handle memory overload appropriately
  2189. if skipMaxCap || slen <= maxCap {
  2190. return make([]byte, slen), true
  2191. }
  2192. return make([]byte, maxCap), true
  2193. }
  2194. func mapKeyFastKindFor(k reflect.Kind) mapKeyFastKind {
  2195. return mapKeyFastKindVals[k&31]
  2196. }
  2197. // ----
  2198. type codecFnInfo struct {
  2199. ti *typeInfo
  2200. xfFn Ext
  2201. xfTag uint64
  2202. addrD bool
  2203. addrDf bool // force: if addrD, then decode function MUST take a ptr
  2204. addrE bool
  2205. // addrEf bool // force: if addrE, then encode function MUST take a ptr
  2206. }
  2207. // codecFn encapsulates the captured variables and the encode function.
  2208. // This way, we only do some calculations one times, and pass to the
  2209. // code block that should be called (encapsulated in a function)
  2210. // instead of executing the checks every time.
  2211. type codecFn struct {
  2212. i codecFnInfo
  2213. fe func(*Encoder, *codecFnInfo, reflect.Value)
  2214. fd func(*Decoder, *codecFnInfo, reflect.Value)
  2215. // _ [1]uint64 // padding (cache-aligned)
  2216. }
  2217. type codecRtidFn struct {
  2218. rtid uintptr
  2219. fn *codecFn
  2220. }
  2221. func makeExt(ext interface{}) Ext {
  2222. switch t := ext.(type) {
  2223. case Ext:
  2224. return t
  2225. case BytesExt:
  2226. return &bytesExtWrapper{BytesExt: t}
  2227. case InterfaceExt:
  2228. return &interfaceExtWrapper{InterfaceExt: t}
  2229. }
  2230. return &extFailWrapper{}
  2231. }
  2232. func baseRV(v interface{}) (rv reflect.Value) {
  2233. // use reflect.ValueOf, not rv4i, as of go 1.16beta, rv4i was not inlineable
  2234. for rv = reflect.ValueOf(v); rv.Kind() == reflect.Ptr; rv = rv.Elem() {
  2235. }
  2236. return
  2237. }
  2238. // ----
  2239. // these "checkOverflow" functions must be inlinable, and not call anybody.
  2240. // Overflow means that the value cannot be represented without wrapping/overflow.
  2241. // Overflow=false does not mean that the value can be represented without losing precision
  2242. // (especially for floating point).
  2243. type checkOverflow struct{}
  2244. func (checkOverflow) Float32(v float64) (overflow bool) {
  2245. if v < 0 {
  2246. v = -v
  2247. }
  2248. return math.MaxFloat32 < v && v <= math.MaxFloat64
  2249. }
  2250. func (checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
  2251. if v != 0 && v != (v<<(64-bitsize))>>(64-bitsize) {
  2252. overflow = true
  2253. }
  2254. return
  2255. }
  2256. func (checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
  2257. if v != 0 && v != (v<<(64-bitsize))>>(64-bitsize) {
  2258. overflow = true
  2259. }
  2260. return
  2261. }
  2262. func (checkOverflow) Uint2Int(v uint64, neg bool) (overflow bool) {
  2263. return (neg && v > 1<<63) || (!neg && v >= 1<<63)
  2264. }
  2265. func (checkOverflow) SignedInt(v uint64) (overflow bool) {
  2266. //e.g. -127 to 128 for int8
  2267. pos := (v >> 63) == 0
  2268. ui2 := v & 0x7fffffffffffffff
  2269. if pos {
  2270. if ui2 > math.MaxInt64 {
  2271. overflow = true
  2272. }
  2273. } else {
  2274. if ui2 > math.MaxInt64-1 {
  2275. overflow = true
  2276. }
  2277. }
  2278. return
  2279. }
  2280. func (x checkOverflow) Float32V(v float64) float64 {
  2281. if x.Float32(v) {
  2282. halt.errorf("float32 overflow: %v", v)
  2283. }
  2284. return v
  2285. }
  2286. func (x checkOverflow) UintV(v uint64, bitsize uint8) uint64 {
  2287. if x.Uint(v, bitsize) {
  2288. halt.errorf("uint64 overflow: %v", v)
  2289. }
  2290. return v
  2291. }
  2292. func (x checkOverflow) IntV(v int64, bitsize uint8) int64 {
  2293. if x.Int(v, bitsize) {
  2294. halt.errorf("int64 overflow: %v", v)
  2295. }
  2296. return v
  2297. }
  2298. func (x checkOverflow) SignedIntV(v uint64) int64 {
  2299. if x.SignedInt(v) {
  2300. halt.errorf("uint64 to int64 overflow: %v", v)
  2301. }
  2302. return int64(v)
  2303. }
  2304. // ------------------ FLOATING POINT -----------------
  2305. func isNaN64(f float64) bool { return f != f }
  2306. func isWhitespaceChar(v byte) bool {
  2307. // these are in order of speed below ...
  2308. return v < 33
  2309. // return v < 33 && whitespaceCharBitset64.isset(v)
  2310. // return v < 33 && (v == ' ' || v == '\n' || v == '\t' || v == '\r')
  2311. // return v == ' ' || v == '\n' || v == '\t' || v == '\r'
  2312. // return whitespaceCharBitset.isset(v)
  2313. }
  2314. func isNumberChar(v byte) bool {
  2315. // these are in order of speed below ...
  2316. return numCharBitset.isset(v)
  2317. // return v < 64 && numCharNoExpBitset64.isset(v) || v == 'e' || v == 'E'
  2318. // return v > 42 && v < 102 && numCharWithExpBitset64.isset(v-42)
  2319. }
  2320. // -----------------------
  2321. type ioFlusher interface {
  2322. Flush() error
  2323. }
  2324. type ioBuffered interface {
  2325. Buffered() int
  2326. }
  2327. // -----------------------
  2328. type sfiRv struct {
  2329. v *structFieldInfo
  2330. r reflect.Value
  2331. }
  2332. // ------
  2333. // bitset types are better than [256]bool, because they permit the whole
  2334. // bitset array being on a single cache line and use less memory.
  2335. //
  2336. // Also, since pos is a byte (0-255), there's no bounds checks on indexing (cheap).
  2337. //
  2338. // We previously had bitset128 [16]byte, and bitset32 [4]byte, but those introduces
  2339. // bounds checking, so we discarded them, and everyone uses bitset256.
  2340. //
  2341. // given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1).
  2342. // consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7
  2343. //
  2344. // Note that using >> or & is faster than using / or %, as division is quite expensive if not optimized.
  2345. // MARKER:
  2346. // We noticed a little performance degradation when using bitset256 as [32]byte (or bitset32 as uint32).
  2347. // For example, json encoding went from 188K ns/op to 168K ns/op (~ 10% reduction).
  2348. // Consequently, we are using a [NNN]bool for bitsetNNN.
  2349. // To eliminate bounds-checking, we use x % v as that is guaranteed to be within bounds.
  2350. // ----
  2351. type bitset32 [32]bool
  2352. func (x *bitset32) set(pos byte) *bitset32 {
  2353. x[pos&31] = true // x[pos%32] = true
  2354. return x
  2355. }
  2356. func (x *bitset32) isset(pos byte) bool {
  2357. return x[pos&31] // x[pos%32]
  2358. }
  2359. type bitset256 [256]bool
  2360. func (x *bitset256) set(pos byte) *bitset256 {
  2361. x[pos] = true
  2362. return x
  2363. }
  2364. func (x *bitset256) isset(pos byte) bool {
  2365. return x[pos]
  2366. }
  2367. // ------------
  2368. type panicHdl struct{}
  2369. // errorv will panic if err is defined (not nil)
  2370. func (panicHdl) onerror(err error) {
  2371. if err != nil {
  2372. panic(err)
  2373. }
  2374. }
  2375. // errorf will always panic, using the parameters passed.
  2376. //
  2377. // Note: it is ok to pass in a stringView, as it will just pass it directly
  2378. // to a fmt.Sprintf call and not hold onto it.
  2379. //
  2380. //go:noinline
  2381. func (panicHdl) errorf(format string, params ...interface{}) {
  2382. if format == "" {
  2383. panic(errPanicUndefined)
  2384. }
  2385. if len(params) == 0 {
  2386. panic(errors.New(format))
  2387. }
  2388. panic(fmt.Errorf(format, params...))
  2389. }
  2390. // ----------------------------------------------------
  2391. type errDecorator interface {
  2392. wrapErr(in error, out *error)
  2393. }
  2394. type errDecoratorDef struct{}
  2395. func (errDecoratorDef) wrapErr(v error, e *error) { *e = v }
  2396. // ----------------------------------------------------
  2397. type mustHdl struct{}
  2398. func (mustHdl) String(s string, err error) string {
  2399. halt.onerror(err)
  2400. return s
  2401. }
  2402. func (mustHdl) Int(s int64, err error) int64 {
  2403. halt.onerror(err)
  2404. return s
  2405. }
  2406. func (mustHdl) Uint(s uint64, err error) uint64 {
  2407. halt.onerror(err)
  2408. return s
  2409. }
  2410. func (mustHdl) Float(s float64, err error) float64 {
  2411. halt.onerror(err)
  2412. return s
  2413. }
  2414. // -------------------
  2415. func freelistCapacity(length int) (capacity int) {
  2416. for capacity = 8; capacity <= length; capacity *= 2 {
  2417. }
  2418. return
  2419. }
  2420. // bytesFreelist is a list of byte buffers, sorted by cap.
  2421. //
  2422. // In anecdotal testing (running go test -tsd 1..6), we couldn't get
  2423. // the length ofthe list > 4 at any time. So we believe a linear search
  2424. // without bounds checking is sufficient.
  2425. //
  2426. // Typical usage model:
  2427. // peek may go together with put, iff pop=true. peek gets largest byte slice temporarily.
  2428. // check is used to switch a []byte if necessary
  2429. // get/put go together
  2430. //
  2431. // Given that folks may get a []byte, and then append to it a lot which may re-allocate
  2432. // a new []byte, we should try to return both (one received from blist and new one allocated).
  2433. //
  2434. // Typical usage model for get/put, when we don't know whether we may need more than requested
  2435. // v0 := blist.get()
  2436. // v1 := v0
  2437. // ... use v1 ...
  2438. // blist.put(v1)
  2439. // if byteSliceAddr(v0) != byteSliceAddr(v1) {
  2440. // blist.put(v0)
  2441. // }
  2442. //
  2443. type bytesFreelist [][]byte
  2444. // peek returns a slice of possibly non-zero'ed bytes, with len=0,
  2445. // and with the largest capacity from the list.
  2446. func (x *bytesFreelist) peek(length int, pop bool) (out []byte) {
  2447. if bytesFreeListNoCache {
  2448. return make([]byte, 0, freelistCapacity(length))
  2449. }
  2450. y := *x
  2451. if len(y) > 0 {
  2452. out = y[len(y)-1]
  2453. }
  2454. // start buf with a minimum of 64 bytes
  2455. const minLenBytes = 64
  2456. if length < minLenBytes {
  2457. length = minLenBytes
  2458. }
  2459. if cap(out) < length {
  2460. out = make([]byte, 0, freelistCapacity(length))
  2461. y = append(y, out)
  2462. *x = y
  2463. }
  2464. if pop && len(y) > 0 {
  2465. y = y[:len(y)-1]
  2466. *x = y
  2467. }
  2468. return
  2469. }
  2470. // get returns a slice of possibly non-zero'ed bytes, with len=0,
  2471. // and with cap >= length requested.
  2472. func (x *bytesFreelist) get(length int) (out []byte) {
  2473. if bytesFreeListNoCache {
  2474. return make([]byte, 0, freelistCapacity(length))
  2475. }
  2476. y := *x
  2477. // MARKER: do not use range, as range is not currently inlineable as of go 1.16-beta
  2478. // for i, v := range y {
  2479. for i := 0; i < len(y); i++ {
  2480. v := y[i]
  2481. if cap(v) >= length {
  2482. // *x = append(y[:i], y[i+1:]...)
  2483. copy(y[i:], y[i+1:])
  2484. *x = y[:len(y)-1]
  2485. return v
  2486. }
  2487. }
  2488. return make([]byte, 0, freelistCapacity(length))
  2489. }
  2490. func (x *bytesFreelist) put(v []byte) {
  2491. if bytesFreeListNoCache || cap(v) == 0 {
  2492. return
  2493. }
  2494. if len(v) != 0 {
  2495. v = v[:0]
  2496. }
  2497. // append the new value, then try to put it in a better position
  2498. y := append(*x, v)
  2499. *x = y
  2500. // MARKER: do not use range, as range is not currently inlineable as of go 1.16-beta
  2501. // for i, z := range y[:len(y)-1] {
  2502. for i := 0; i < len(y)-1; i++ {
  2503. z := y[i]
  2504. if cap(z) > cap(v) {
  2505. copy(y[i+1:], y[i:])
  2506. y[i] = v
  2507. return
  2508. }
  2509. }
  2510. }
  2511. func (x *bytesFreelist) check(v []byte, length int) (out []byte) {
  2512. // ensure inlineable, by moving slow-path out to its own function
  2513. if cap(v) >= length {
  2514. return v[:0]
  2515. }
  2516. return x.checkPutGet(v, length)
  2517. }
  2518. func (x *bytesFreelist) checkPutGet(v []byte, length int) []byte {
  2519. // checkPutGet broken out into its own function, so check is inlineable in general case
  2520. const useSeparateCalls = false
  2521. if useSeparateCalls {
  2522. x.put(v)
  2523. return x.get(length)
  2524. }
  2525. if bytesFreeListNoCache {
  2526. return make([]byte, 0, freelistCapacity(length))
  2527. }
  2528. // assume cap(v) < length, so put must happen before get
  2529. y := *x
  2530. var put = cap(v) == 0 // if empty, consider it already put
  2531. if !put {
  2532. y = append(y, v)
  2533. *x = y
  2534. }
  2535. for i := 0; i < len(y); i++ {
  2536. z := y[i]
  2537. if put {
  2538. if cap(z) >= length {
  2539. copy(y[i:], y[i+1:])
  2540. y = y[:len(y)-1]
  2541. *x = y
  2542. return z
  2543. }
  2544. } else {
  2545. if cap(z) > cap(v) {
  2546. copy(y[i+1:], y[i:])
  2547. y[i] = v
  2548. put = true
  2549. }
  2550. }
  2551. }
  2552. return make([]byte, 0, freelistCapacity(length))
  2553. }
  2554. // -------------------------
  2555. // sfiRvFreelist is used by Encoder for encoding structs,
  2556. // where we have to gather the fields first and then
  2557. // analyze them for omitEmpty, before knowing the length of the array/map to encode.
  2558. //
  2559. // Typically, the length here will depend on the number of cycles e.g.
  2560. // if type T1 has reference to T1, or T1 has reference to type T2 which has reference to T1.
  2561. //
  2562. // In the general case, the length of this list at most times is 1,
  2563. // so linear search is fine.
  2564. type sfiRvFreelist [][]sfiRv
  2565. func (x *sfiRvFreelist) get(length int) (out []sfiRv) {
  2566. y := *x
  2567. // MARKER: do not use range, as range is not currently inlineable as of go 1.16-beta
  2568. // for i, v := range y {
  2569. for i := 0; i < len(y); i++ {
  2570. v := y[i]
  2571. if cap(v) >= length {
  2572. // *x = append(y[:i], y[i+1:]...)
  2573. copy(y[i:], y[i+1:])
  2574. *x = y[:len(y)-1]
  2575. return v
  2576. }
  2577. }
  2578. return make([]sfiRv, 0, freelistCapacity(length))
  2579. }
  2580. func (x *sfiRvFreelist) put(v []sfiRv) {
  2581. if len(v) != 0 {
  2582. v = v[:0]
  2583. }
  2584. // append the new value, then try to put it in a better position
  2585. y := append(*x, v)
  2586. *x = y
  2587. // MARKER: do not use range, as range is not currently inlineable as of go 1.16-beta
  2588. // for i, z := range y[:len(y)-1] {
  2589. for i := 0; i < len(y)-1; i++ {
  2590. z := y[i]
  2591. if cap(z) > cap(v) {
  2592. copy(y[i+1:], y[i:])
  2593. y[i] = v
  2594. return
  2595. }
  2596. }
  2597. }
  2598. // ---- multiple interner implementations ----
  2599. // Hard to tell which is most performant:
  2600. // - use a map[string]string - worst perf, no collisions, and unlimited entries
  2601. // - use a linear search with move to front heuristics - no collisions, and maxed at 64 entries
  2602. // - use a computationally-intensive hash - best performance, some collisions, maxed at 64 entries
  2603. const (
  2604. internMaxStrLen = 16 // if more than 16 bytes, faster to copy than compare bytes
  2605. internCap = 64 * 2 // 64 uses 1K bytes RAM, so 128 (anecdotal sweet spot) uses 2K bytes
  2606. )
  2607. type internerMap map[string]string
  2608. func (x *internerMap) init() {
  2609. *x = make(map[string]string, internCap)
  2610. }
  2611. func (x internerMap) string(v []byte) (s string) {
  2612. s, ok := x[string(v)] // no allocation here, per go implementation
  2613. if !ok {
  2614. s = string(v) // new allocation here
  2615. x[s] = s
  2616. }
  2617. return
  2618. }