helper.go 76 KB

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