helper.go 85 KB

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