helper.go 64 KB

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