helper.go 77 KB

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