helper.go 76 KB

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