helper.go 72 KB

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