decode.go 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632
  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. import (
  5. "encoding"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "reflect"
  10. "strconv"
  11. "sync"
  12. "time"
  13. )
  14. // Some tagging information for error messages.
  15. const (
  16. msgBadDesc = "unrecognized descriptor byte"
  17. msgDecCannotExpandArr = "cannot expand go array from %v to stream length: %v"
  18. )
  19. const (
  20. decDefSliceCap = 8
  21. decDefChanCap = 64 // should be large, as cap cannot be expanded
  22. decScratchByteArrayLen = cacheLineSize - 8
  23. )
  24. var (
  25. errstrOnlyMapOrArrayCanDecodeIntoStruct = "only encoded map or array can be decoded into a struct"
  26. errstrCannotDecodeIntoNil = "cannot decode into nil"
  27. errmsgExpandSliceOverflow = "expand slice: slice overflow"
  28. errmsgExpandSliceCannotChange = "expand slice: cannot change"
  29. errDecoderNotInitialized = errors.New("Decoder not initialized")
  30. errDecUnreadByteNothingToRead = errors.New("cannot unread - nothing has been read")
  31. errDecUnreadByteLastByteNotRead = errors.New("cannot unread - last byte has not been read")
  32. errDecUnreadByteUnknown = errors.New("cannot unread - reason unknown")
  33. )
  34. // decReader abstracts the reading source, allowing implementations that can
  35. // read from an io.Reader or directly off a byte slice with zero-copying.
  36. type decReader interface {
  37. unreadn1()
  38. // readx will use the implementation scratch buffer if possible i.e. n < len(scratchbuf), OR
  39. // just return a view of the []byte being decoded from.
  40. // Ensure you call detachZeroCopyBytes later if this needs to be sent outside codec control.
  41. readx(n int) []byte
  42. readb([]byte)
  43. readn1() uint8
  44. numread() int // number of bytes read
  45. track()
  46. stopTrack() []byte
  47. // skip will skip any byte that matches, and return the first non-matching byte
  48. skip(accept *bitset256) (token byte)
  49. // readTo will read any byte that matches, stopping once no-longer matching.
  50. readTo(in []byte, accept *bitset256) (out []byte)
  51. // readUntil will read, only stopping once it matches the 'stop' byte.
  52. readUntil(in []byte, stop byte) (out []byte)
  53. }
  54. type decDriver interface {
  55. // this will check if the next token is a break.
  56. CheckBreak() bool
  57. // TryDecodeAsNil tries to decode as nil.
  58. // Note: TryDecodeAsNil should be careful not to share any temporary []byte with
  59. // the rest of the decDriver. This is because sometimes, we optimize by holding onto
  60. // a transient []byte, and ensuring the only other call we make to the decDriver
  61. // during that time is maybe a TryDecodeAsNil() call.
  62. TryDecodeAsNil() bool
  63. // ContainerType returns one of: Bytes, String, Nil, Slice or Map. Return unSet if not known.
  64. ContainerType() (vt valueType)
  65. // IsBuiltinType(rt uintptr) bool
  66. // DecodeNaked will decode primitives (number, bool, string, []byte) and RawExt.
  67. // For maps and arrays, it will not do the decoding in-band, but will signal
  68. // the decoder, so that is done later, by setting the decNaked.valueType field.
  69. //
  70. // Note: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types).
  71. // for extensions, DecodeNaked must read the tag and the []byte if it exists.
  72. // if the []byte is not read, then kInterfaceNaked will treat it as a Handle
  73. // that stores the subsequent value in-band, and complete reading the RawExt.
  74. //
  75. // extensions should also use readx to decode them, for efficiency.
  76. // kInterface will extract the detached byte slice if it has to pass it outside its realm.
  77. DecodeNaked()
  78. // Deprecated: use DecodeInt64 and DecodeUint64 instead
  79. // DecodeInt(bitsize uint8) (i int64)
  80. // DecodeUint(bitsize uint8) (ui uint64)
  81. DecodeInt64() (i int64)
  82. DecodeUint64() (ui uint64)
  83. DecodeFloat64() (f float64)
  84. DecodeBool() (b bool)
  85. // DecodeString can also decode symbols.
  86. // It looks redundant as DecodeBytes is available.
  87. // However, some codecs (e.g. binc) support symbols and can
  88. // return a pre-stored string value, meaning that it can bypass
  89. // the cost of []byte->string conversion.
  90. DecodeString() (s string)
  91. DecodeStringAsBytes() (v []byte)
  92. // DecodeBytes may be called directly, without going through reflection.
  93. // Consequently, it must be designed to handle possible nil.
  94. DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte)
  95. // DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte)
  96. // decodeExt will decode into a *RawExt or into an extension.
  97. DecodeExt(v interface{}, xtag uint64, ext Ext) (realxtag uint64)
  98. // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte)
  99. DecodeTime() (t time.Time)
  100. ReadArrayStart() int
  101. ReadArrayElem()
  102. ReadArrayEnd()
  103. ReadMapStart() int
  104. ReadMapElemKey()
  105. ReadMapElemValue()
  106. ReadMapEnd()
  107. reset()
  108. uncacheRead()
  109. }
  110. type decodeError struct {
  111. codecError
  112. pos int
  113. }
  114. func (d decodeError) Error() string {
  115. return fmt.Sprintf("%s decode error [pos %d]: %v", d.name, d.pos, d.err)
  116. }
  117. type decDriverNoopContainerReader struct{}
  118. func (x decDriverNoopContainerReader) ReadArrayStart() (v int) { return }
  119. func (x decDriverNoopContainerReader) ReadArrayElem() {}
  120. func (x decDriverNoopContainerReader) ReadArrayEnd() {}
  121. func (x decDriverNoopContainerReader) ReadMapStart() (v int) { return }
  122. func (x decDriverNoopContainerReader) ReadMapElemKey() {}
  123. func (x decDriverNoopContainerReader) ReadMapElemValue() {}
  124. func (x decDriverNoopContainerReader) ReadMapEnd() {}
  125. func (x decDriverNoopContainerReader) CheckBreak() (v bool) { return }
  126. // func (x decNoSeparator) uncacheRead() {}
  127. // DecodeOptions captures configuration options during decode.
  128. type DecodeOptions struct {
  129. // MapType specifies type to use during schema-less decoding of a map in the stream.
  130. // If nil (unset), we default to map[string]interface{} iff json handle and MapStringAsKey=true,
  131. // else map[interface{}]interface{}.
  132. MapType reflect.Type
  133. // SliceType specifies type to use during schema-less decoding of an array in the stream.
  134. // If nil (unset), we default to []interface{} for all formats.
  135. SliceType reflect.Type
  136. // MaxInitLen defines the maxinum initial length that we "make" a collection
  137. // (string, slice, map, chan). If 0 or negative, we default to a sensible value
  138. // based on the size of an element in the collection.
  139. //
  140. // For example, when decoding, a stream may say that it has 2^64 elements.
  141. // We should not auto-matically provision a slice of that size, to prevent Out-Of-Memory crash.
  142. // Instead, we provision up to MaxInitLen, fill that up, and start appending after that.
  143. MaxInitLen int
  144. // ReaderBufferSize is the size of the buffer used when reading.
  145. //
  146. // if > 0, we use a smart buffer internally for performance purposes.
  147. ReaderBufferSize int
  148. // If ErrorIfNoField, return an error when decoding a map
  149. // from a codec stream into a struct, and no matching struct field is found.
  150. ErrorIfNoField bool
  151. // If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded.
  152. // For example, the stream contains an array of 8 items, but you are decoding into a [4]T array,
  153. // or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set).
  154. ErrorIfNoArrayExpand bool
  155. // If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64).
  156. SignedInteger bool
  157. // MapValueReset controls how we decode into a map value.
  158. //
  159. // By default, we MAY retrieve the mapping for a key, and then decode into that.
  160. // However, especially with big maps, that retrieval may be expensive and unnecessary
  161. // if the stream already contains all that is necessary to recreate the value.
  162. //
  163. // If true, we will never retrieve the previous mapping,
  164. // but rather decode into a new value and set that in the map.
  165. //
  166. // If false, we will retrieve the previous mapping if necessary e.g.
  167. // the previous mapping is a pointer, or is a struct or array with pre-set state,
  168. // or is an interface.
  169. MapValueReset bool
  170. // SliceElementReset: on decoding a slice, reset the element to a zero value first.
  171. //
  172. // concern: if the slice already contained some garbage, we will decode into that garbage.
  173. SliceElementReset bool
  174. // InterfaceReset controls how we decode into an interface.
  175. //
  176. // By default, when we see a field that is an interface{...},
  177. // or a map with interface{...} value, we will attempt decoding into the
  178. // "contained" value.
  179. //
  180. // However, this prevents us from reading a string into an interface{}
  181. // that formerly contained a number.
  182. //
  183. // If true, we will decode into a new "blank" value, and set that in the interface.
  184. // If false, we will decode into whatever is contained in the interface.
  185. InterfaceReset bool
  186. // InternString controls interning of strings during decoding.
  187. //
  188. // Some handles, e.g. json, typically will read map keys as strings.
  189. // If the set of keys are finite, it may help reduce allocation to
  190. // look them up from a map (than to allocate them afresh).
  191. //
  192. // Note: Handles will be smart when using the intern functionality.
  193. // Every string should not be interned.
  194. // An excellent use-case for interning is struct field names,
  195. // or map keys where key type is string.
  196. InternString bool
  197. // PreferArrayOverSlice controls whether to decode to an array or a slice.
  198. //
  199. // This only impacts decoding into a nil interface{}.
  200. // Consequently, it has no effect on codecgen.
  201. //
  202. // *Note*: This only applies if using go1.5 and above,
  203. // as it requires reflect.ArrayOf support which was absent before go1.5.
  204. PreferArrayOverSlice bool
  205. // DeleteOnNilMapValue controls how to decode a nil value in the stream.
  206. //
  207. // If true, we will delete the mapping of the key.
  208. // Else, just set the mapping to the zero value of the type.
  209. DeleteOnNilMapValue bool
  210. }
  211. // ------------------------------------
  212. type bufioDecReader struct {
  213. buf []byte
  214. r io.Reader
  215. c int // cursor
  216. n int // num read
  217. err error
  218. tr []byte
  219. trb bool
  220. b [4]byte
  221. }
  222. func (z *bufioDecReader) reset(r io.Reader) {
  223. z.r, z.c, z.n, z.err, z.trb = r, 0, 0, nil, false
  224. if z.tr != nil {
  225. z.tr = z.tr[:0]
  226. }
  227. }
  228. func (z *bufioDecReader) Read(p []byte) (n int, err error) {
  229. if z.err != nil {
  230. return 0, z.err
  231. }
  232. p0 := p
  233. n = copy(p, z.buf[z.c:])
  234. z.c += n
  235. if z.c == len(z.buf) {
  236. z.c = 0
  237. }
  238. z.n += n
  239. if len(p) == n {
  240. if z.c == 0 {
  241. z.buf = z.buf[:1]
  242. z.buf[0] = p[len(p)-1]
  243. z.c = 1
  244. }
  245. if z.trb {
  246. z.tr = append(z.tr, p0[:n]...)
  247. }
  248. return
  249. }
  250. p = p[n:]
  251. var n2 int
  252. // if we are here, then z.buf is all read
  253. if len(p) > len(z.buf) {
  254. n2, err = decReadFull(z.r, p)
  255. n += n2
  256. z.n += n2
  257. z.err = err
  258. // don't return EOF if some bytes were read. keep for next time.
  259. if n > 0 && err == io.EOF {
  260. err = nil
  261. }
  262. // always keep last byte in z.buf
  263. z.buf = z.buf[:1]
  264. z.buf[0] = p[len(p)-1]
  265. z.c = 1
  266. if z.trb {
  267. z.tr = append(z.tr, p0[:n]...)
  268. }
  269. return
  270. }
  271. // z.c is now 0, and len(p) <= len(z.buf)
  272. for len(p) > 0 && z.err == nil {
  273. // println("len(p) loop starting ... ")
  274. z.c = 0
  275. z.buf = z.buf[0:cap(z.buf)]
  276. n2, err = z.r.Read(z.buf)
  277. if n2 > 0 {
  278. if err == io.EOF {
  279. err = nil
  280. }
  281. z.buf = z.buf[:n2]
  282. n2 = copy(p, z.buf)
  283. z.c = n2
  284. n += n2
  285. z.n += n2
  286. p = p[n2:]
  287. }
  288. z.err = err
  289. // println("... len(p) loop done")
  290. }
  291. if z.c == 0 {
  292. z.buf = z.buf[:1]
  293. z.buf[0] = p[len(p)-1]
  294. z.c = 1
  295. }
  296. if z.trb {
  297. z.tr = append(z.tr, p0[:n]...)
  298. }
  299. return
  300. }
  301. func (z *bufioDecReader) ReadByte() (b byte, err error) {
  302. z.b[0] = 0
  303. _, err = z.Read(z.b[:1])
  304. b = z.b[0]
  305. return
  306. }
  307. func (z *bufioDecReader) UnreadByte() (err error) {
  308. if z.err != nil {
  309. return z.err
  310. }
  311. if z.c > 0 {
  312. z.c--
  313. z.n--
  314. if z.trb {
  315. z.tr = z.tr[:len(z.tr)-1]
  316. }
  317. return
  318. }
  319. return errDecUnreadByteNothingToRead
  320. }
  321. func (z *bufioDecReader) numread() int {
  322. return z.n
  323. }
  324. func (z *bufioDecReader) readx(n int) (bs []byte) {
  325. if n <= 0 || z.err != nil {
  326. return
  327. }
  328. if z.c+n <= len(z.buf) {
  329. bs = z.buf[z.c : z.c+n]
  330. z.n += n
  331. z.c += n
  332. if z.trb {
  333. z.tr = append(z.tr, bs...)
  334. }
  335. return
  336. }
  337. bs = make([]byte, n)
  338. _, err := z.Read(bs)
  339. if err != nil {
  340. panic(err)
  341. }
  342. return
  343. }
  344. func (z *bufioDecReader) readb(bs []byte) {
  345. _, err := z.Read(bs)
  346. if err != nil {
  347. panic(err)
  348. }
  349. }
  350. // func (z *bufioDecReader) readn1eof() (b uint8, eof bool) {
  351. // b, err := z.ReadByte()
  352. // if err != nil {
  353. // if err == io.EOF {
  354. // eof = true
  355. // } else {
  356. // panic(err)
  357. // }
  358. // }
  359. // return
  360. // }
  361. func (z *bufioDecReader) readn1() (b uint8) {
  362. b, err := z.ReadByte()
  363. if err != nil {
  364. panic(err)
  365. }
  366. return
  367. }
  368. func (z *bufioDecReader) search(in []byte, accept *bitset256, stop, flag uint8) (token byte, out []byte) {
  369. // flag: 1 (skip), 2 (readTo), 4 (readUntil)
  370. if flag == 4 {
  371. for i := z.c; i < len(z.buf); i++ {
  372. if z.buf[i] == stop {
  373. token = z.buf[i]
  374. z.n = z.n + (i - z.c) - 1
  375. i++
  376. out = z.buf[z.c:i]
  377. if z.trb {
  378. z.tr = append(z.tr, z.buf[z.c:i]...)
  379. }
  380. z.c = i
  381. return
  382. }
  383. }
  384. } else {
  385. for i := z.c; i < len(z.buf); i++ {
  386. if !accept.isset(z.buf[i]) {
  387. token = z.buf[i]
  388. z.n = z.n + (i - z.c) - 1
  389. if flag == 1 {
  390. i++
  391. } else {
  392. out = z.buf[z.c:i]
  393. }
  394. if z.trb {
  395. z.tr = append(z.tr, z.buf[z.c:i]...)
  396. }
  397. z.c = i
  398. return
  399. }
  400. }
  401. }
  402. z.n += len(z.buf) - z.c
  403. if flag != 1 {
  404. out = append(in, z.buf[z.c:]...)
  405. }
  406. if z.trb {
  407. z.tr = append(z.tr, z.buf[z.c:]...)
  408. }
  409. var n2 int
  410. if z.err != nil {
  411. return
  412. }
  413. for {
  414. z.c = 0
  415. z.buf = z.buf[0:cap(z.buf)]
  416. n2, z.err = z.r.Read(z.buf)
  417. if n2 > 0 && z.err != nil {
  418. z.err = nil
  419. }
  420. z.buf = z.buf[:n2]
  421. if flag == 4 {
  422. for i := 0; i < n2; i++ {
  423. if z.buf[i] == stop {
  424. token = z.buf[i]
  425. z.n += i - 1
  426. i++
  427. out = append(out, z.buf[z.c:i]...)
  428. if z.trb {
  429. z.tr = append(z.tr, z.buf[z.c:i]...)
  430. }
  431. z.c = i
  432. return
  433. }
  434. }
  435. } else {
  436. for i := 0; i < n2; i++ {
  437. if !accept.isset(z.buf[i]) {
  438. token = z.buf[i]
  439. z.n += i - 1
  440. if flag == 1 {
  441. i++
  442. }
  443. if flag != 1 {
  444. out = append(out, z.buf[z.c:i]...)
  445. }
  446. if z.trb {
  447. z.tr = append(z.tr, z.buf[z.c:i]...)
  448. }
  449. z.c = i
  450. return
  451. }
  452. }
  453. }
  454. if flag != 1 {
  455. out = append(out, z.buf[:n2]...)
  456. }
  457. z.n += n2
  458. if z.err != nil {
  459. return
  460. }
  461. if z.trb {
  462. z.tr = append(z.tr, z.buf[:n2]...)
  463. }
  464. }
  465. }
  466. func (z *bufioDecReader) skip(accept *bitset256) (token byte) {
  467. token, _ = z.search(nil, accept, 0, 1)
  468. return
  469. }
  470. func (z *bufioDecReader) readTo(in []byte, accept *bitset256) (out []byte) {
  471. _, out = z.search(in, accept, 0, 2)
  472. return
  473. }
  474. func (z *bufioDecReader) readUntil(in []byte, stop byte) (out []byte) {
  475. _, out = z.search(in, nil, stop, 4)
  476. return
  477. }
  478. func (z *bufioDecReader) unreadn1() {
  479. err := z.UnreadByte()
  480. if err != nil {
  481. panic(err)
  482. }
  483. }
  484. func (z *bufioDecReader) track() {
  485. if z.tr != nil {
  486. z.tr = z.tr[:0]
  487. }
  488. z.trb = true
  489. }
  490. func (z *bufioDecReader) stopTrack() (bs []byte) {
  491. z.trb = false
  492. return z.tr
  493. }
  494. // ioDecReader is a decReader that reads off an io.Reader.
  495. //
  496. // It also has a fallback implementation of ByteScanner if needed.
  497. type ioDecReader struct {
  498. r io.Reader // the reader passed in
  499. rr io.Reader
  500. br io.ByteScanner
  501. l byte // last byte
  502. ls byte // last byte status. 0: init-canDoNothing, 1: canRead, 2: canUnread
  503. trb bool // tracking bytes turned on
  504. _ bool
  505. b [4]byte // tiny buffer for reading single bytes
  506. x [scratchByteArrayLen]byte // for: get struct field name, swallow valueTypeBytes, etc
  507. n int // num read
  508. tr []byte // tracking bytes read
  509. }
  510. func (z *ioDecReader) reset(r io.Reader) {
  511. z.r = r
  512. z.rr = r
  513. z.l, z.ls, z.n, z.trb = 0, 0, 0, false
  514. if z.tr != nil {
  515. z.tr = z.tr[:0]
  516. }
  517. var ok bool
  518. if z.br, ok = r.(io.ByteScanner); !ok {
  519. z.br = z
  520. z.rr = z
  521. }
  522. }
  523. func (z *ioDecReader) Read(p []byte) (n int, err error) {
  524. if len(p) == 0 {
  525. return
  526. }
  527. var firstByte bool
  528. if z.ls == 1 {
  529. z.ls = 2
  530. p[0] = z.l
  531. if len(p) == 1 {
  532. n = 1
  533. return
  534. }
  535. firstByte = true
  536. p = p[1:]
  537. }
  538. n, err = z.r.Read(p)
  539. if n > 0 {
  540. if err == io.EOF && n == len(p) {
  541. err = nil // read was successful, so postpone EOF (till next time)
  542. }
  543. z.l = p[n-1]
  544. z.ls = 2
  545. }
  546. if firstByte {
  547. n++
  548. }
  549. return
  550. }
  551. func (z *ioDecReader) ReadByte() (c byte, err error) {
  552. n, err := z.Read(z.b[:1])
  553. if n == 1 {
  554. c = z.b[0]
  555. if err == io.EOF {
  556. err = nil // read was successful, so postpone EOF (till next time)
  557. }
  558. }
  559. return
  560. }
  561. func (z *ioDecReader) UnreadByte() (err error) {
  562. switch z.ls {
  563. case 2:
  564. z.ls = 1
  565. case 0:
  566. err = errDecUnreadByteNothingToRead
  567. case 1:
  568. err = errDecUnreadByteLastByteNotRead
  569. default:
  570. err = errDecUnreadByteUnknown
  571. }
  572. return
  573. }
  574. func (z *ioDecReader) numread() int {
  575. return z.n
  576. }
  577. func (z *ioDecReader) readx(n int) (bs []byte) {
  578. if n <= 0 {
  579. return
  580. }
  581. if n < len(z.x) {
  582. bs = z.x[:n]
  583. } else {
  584. bs = make([]byte, n)
  585. }
  586. if _, err := decReadFull(z.rr, bs); err != nil {
  587. panic(err)
  588. }
  589. z.n += len(bs)
  590. if z.trb {
  591. z.tr = append(z.tr, bs...)
  592. }
  593. return
  594. }
  595. func (z *ioDecReader) readb(bs []byte) {
  596. // if len(bs) == 0 {
  597. // return
  598. // }
  599. if _, err := decReadFull(z.rr, bs); err != nil {
  600. panic(err)
  601. }
  602. z.n += len(bs)
  603. if z.trb {
  604. z.tr = append(z.tr, bs...)
  605. }
  606. }
  607. func (z *ioDecReader) readn1eof() (b uint8, eof bool) {
  608. b, err := z.br.ReadByte()
  609. if err == nil {
  610. z.n++
  611. if z.trb {
  612. z.tr = append(z.tr, b)
  613. }
  614. } else if err == io.EOF {
  615. eof = true
  616. } else {
  617. panic(err)
  618. }
  619. return
  620. }
  621. func (z *ioDecReader) readn1() (b uint8) {
  622. var err error
  623. if b, err = z.br.ReadByte(); err == nil {
  624. z.n++
  625. if z.trb {
  626. z.tr = append(z.tr, b)
  627. }
  628. return
  629. }
  630. panic(err)
  631. }
  632. func (z *ioDecReader) skip(accept *bitset256) (token byte) {
  633. for {
  634. var eof bool
  635. token, eof = z.readn1eof()
  636. if eof {
  637. return
  638. }
  639. if accept.isset(token) {
  640. continue
  641. }
  642. return
  643. }
  644. }
  645. func (z *ioDecReader) readTo(in []byte, accept *bitset256) (out []byte) {
  646. out = in
  647. for {
  648. token, eof := z.readn1eof()
  649. if eof {
  650. return
  651. }
  652. if accept.isset(token) {
  653. out = append(out, token)
  654. } else {
  655. z.unreadn1()
  656. return
  657. }
  658. }
  659. }
  660. func (z *ioDecReader) readUntil(in []byte, stop byte) (out []byte) {
  661. out = in
  662. for {
  663. token, eof := z.readn1eof()
  664. if eof {
  665. panic(io.EOF)
  666. }
  667. out = append(out, token)
  668. if token == stop {
  669. return
  670. }
  671. }
  672. }
  673. func (z *ioDecReader) unreadn1() {
  674. err := z.br.UnreadByte()
  675. if err != nil {
  676. panic(err)
  677. }
  678. z.n--
  679. if z.trb {
  680. if l := len(z.tr) - 1; l >= 0 {
  681. z.tr = z.tr[:l]
  682. }
  683. }
  684. }
  685. func (z *ioDecReader) track() {
  686. if z.tr != nil {
  687. z.tr = z.tr[:0]
  688. }
  689. z.trb = true
  690. }
  691. func (z *ioDecReader) stopTrack() (bs []byte) {
  692. z.trb = false
  693. return z.tr
  694. }
  695. // ------------------------------------
  696. var errBytesDecReaderCannotUnread = errors.New("cannot unread last byte read")
  697. // bytesDecReader is a decReader that reads off a byte slice with zero copying
  698. type bytesDecReader struct {
  699. b []byte // data
  700. c int // cursor
  701. a int // available
  702. t int // track start
  703. }
  704. func (z *bytesDecReader) reset(in []byte) {
  705. z.b = in
  706. z.a = len(in)
  707. z.c = 0
  708. z.t = 0
  709. }
  710. func (z *bytesDecReader) numread() int {
  711. return z.c
  712. }
  713. func (z *bytesDecReader) unreadn1() {
  714. if z.c == 0 || len(z.b) == 0 {
  715. panic(errBytesDecReaderCannotUnread)
  716. }
  717. z.c--
  718. z.a++
  719. return
  720. }
  721. func (z *bytesDecReader) readx(n int) (bs []byte) {
  722. // slicing from a non-constant start position is more expensive,
  723. // as more computation is required to decipher the pointer start position.
  724. // However, we do it only once, and it's better than reslicing both z.b and return value.
  725. if n <= 0 {
  726. } else if z.a == 0 {
  727. panic(io.EOF)
  728. } else if n > z.a {
  729. panic(io.ErrUnexpectedEOF)
  730. } else {
  731. c0 := z.c
  732. z.c = c0 + n
  733. z.a = z.a - n
  734. bs = z.b[c0:z.c]
  735. }
  736. return
  737. }
  738. func (z *bytesDecReader) readb(bs []byte) {
  739. copy(bs, z.readx(len(bs)))
  740. }
  741. func (z *bytesDecReader) readn1() (v uint8) {
  742. if z.a == 0 {
  743. panic(io.EOF)
  744. }
  745. v = z.b[z.c]
  746. z.c++
  747. z.a--
  748. return
  749. }
  750. // func (z *bytesDecReader) readn1eof() (v uint8, eof bool) {
  751. // if z.a == 0 {
  752. // eof = true
  753. // return
  754. // }
  755. // v = z.b[z.c]
  756. // z.c++
  757. // z.a--
  758. // return
  759. // }
  760. func (z *bytesDecReader) skip(accept *bitset256) (token byte) {
  761. if z.a == 0 {
  762. return
  763. }
  764. blen := len(z.b)
  765. for i := z.c; i < blen; i++ {
  766. if !accept.isset(z.b[i]) {
  767. token = z.b[i]
  768. i++
  769. z.a -= (i - z.c)
  770. z.c = i
  771. return
  772. }
  773. }
  774. z.a, z.c = 0, blen
  775. return
  776. }
  777. func (z *bytesDecReader) readTo(_ []byte, accept *bitset256) (out []byte) {
  778. if z.a == 0 {
  779. return
  780. }
  781. blen := len(z.b)
  782. for i := z.c; i < blen; i++ {
  783. if !accept.isset(z.b[i]) {
  784. out = z.b[z.c:i]
  785. z.a -= (i - z.c)
  786. z.c = i
  787. return
  788. }
  789. }
  790. out = z.b[z.c:]
  791. z.a, z.c = 0, blen
  792. return
  793. }
  794. func (z *bytesDecReader) readUntil(_ []byte, stop byte) (out []byte) {
  795. if z.a == 0 {
  796. panic(io.EOF)
  797. }
  798. blen := len(z.b)
  799. for i := z.c; i < blen; i++ {
  800. if z.b[i] == stop {
  801. i++
  802. out = z.b[z.c:i]
  803. z.a -= (i - z.c)
  804. z.c = i
  805. return
  806. }
  807. }
  808. z.a, z.c = 0, blen
  809. panic(io.EOF)
  810. }
  811. func (z *bytesDecReader) track() {
  812. z.t = z.c
  813. }
  814. func (z *bytesDecReader) stopTrack() (bs []byte) {
  815. return z.b[z.t:z.c]
  816. }
  817. // ----------------------------------------
  818. // func (d *Decoder) builtin(f *codecFnInfo, rv reflect.Value) {
  819. // d.d.DecodeBuiltin(f.ti.rtid, rv2i(rv))
  820. // }
  821. func (d *Decoder) rawExt(f *codecFnInfo, rv reflect.Value) {
  822. d.d.DecodeExt(rv2i(rv), 0, nil)
  823. }
  824. func (d *Decoder) ext(f *codecFnInfo, rv reflect.Value) {
  825. d.d.DecodeExt(rv2i(rv), f.xfTag, f.xfFn)
  826. }
  827. func (d *Decoder) selferUnmarshal(f *codecFnInfo, rv reflect.Value) {
  828. rv2i(rv).(Selfer).CodecDecodeSelf(d)
  829. }
  830. func (d *Decoder) binaryUnmarshal(f *codecFnInfo, rv reflect.Value) {
  831. bm := rv2i(rv).(encoding.BinaryUnmarshaler)
  832. xbs := d.d.DecodeBytes(nil, true)
  833. if fnerr := bm.UnmarshalBinary(xbs); fnerr != nil {
  834. panic(fnerr)
  835. }
  836. }
  837. func (d *Decoder) textUnmarshal(f *codecFnInfo, rv reflect.Value) {
  838. tm := rv2i(rv).(encoding.TextUnmarshaler)
  839. fnerr := tm.UnmarshalText(d.d.DecodeStringAsBytes())
  840. if fnerr != nil {
  841. panic(fnerr)
  842. }
  843. }
  844. func (d *Decoder) jsonUnmarshal(f *codecFnInfo, rv reflect.Value) {
  845. tm := rv2i(rv).(jsonUnmarshaler)
  846. // bs := d.d.DecodeBytes(d.b[:], true, true)
  847. // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself.
  848. fnerr := tm.UnmarshalJSON(d.nextValueBytes())
  849. if fnerr != nil {
  850. panic(fnerr)
  851. }
  852. }
  853. func (d *Decoder) kErr(f *codecFnInfo, rv reflect.Value) {
  854. d.errorf("no decoding function defined for kind %v", rv.Kind())
  855. }
  856. // var kIntfCtr uint64
  857. func (d *Decoder) kInterfaceNaked(f *codecFnInfo) (rvn reflect.Value) {
  858. // nil interface:
  859. // use some hieristics to decode it appropriately
  860. // based on the detected next value in the stream.
  861. n := d.naked()
  862. d.d.DecodeNaked()
  863. if n.v == valueTypeNil {
  864. return
  865. }
  866. // We cannot decode non-nil stream value into nil interface with methods (e.g. io.Reader).
  867. if f.ti.numMeth > 0 {
  868. d.errorf("cannot decode non-nil codec value into nil %v (%v methods)", f.ti.rt, f.ti.numMeth)
  869. return
  870. }
  871. // var useRvn bool
  872. switch n.v {
  873. case valueTypeMap:
  874. // if json, default to a map type with string keys
  875. mtid := d.mtid
  876. if mtid == 0 {
  877. if d.jsms {
  878. mtid = mapStrIntfTypId
  879. } else {
  880. mtid = mapIntfIntfTypId
  881. }
  882. }
  883. if mtid == mapIntfIntfTypId {
  884. n.initContainers()
  885. if n.lm < arrayCacheLen {
  886. n.ma[n.lm] = nil
  887. rvn = n.rma[n.lm]
  888. n.lm++
  889. d.decode(&n.ma[n.lm-1])
  890. n.lm--
  891. } else {
  892. var v2 map[interface{}]interface{}
  893. d.decode(&v2)
  894. rvn = reflect.ValueOf(&v2).Elem()
  895. }
  896. } else if mtid == mapStrIntfTypId { // for json performance
  897. n.initContainers()
  898. if n.ln < arrayCacheLen {
  899. n.na[n.ln] = nil
  900. rvn = n.rna[n.ln]
  901. n.ln++
  902. d.decode(&n.na[n.ln-1])
  903. n.ln--
  904. } else {
  905. var v2 map[string]interface{}
  906. d.decode(&v2)
  907. rvn = reflect.ValueOf(&v2).Elem()
  908. }
  909. } else {
  910. if d.mtr {
  911. rvn = reflect.New(d.h.MapType)
  912. d.decode(rv2i(rvn))
  913. rvn = rvn.Elem()
  914. } else {
  915. rvn = reflect.New(d.h.MapType).Elem()
  916. d.decodeValue(rvn, nil, true)
  917. }
  918. }
  919. case valueTypeArray:
  920. if d.stid == 0 || d.stid == intfSliceTypId {
  921. n.initContainers()
  922. if n.ls < arrayCacheLen {
  923. n.sa[n.ls] = nil
  924. rvn = n.rsa[n.ls]
  925. n.ls++
  926. d.decode(&n.sa[n.ls-1])
  927. n.ls--
  928. } else {
  929. var v2 []interface{}
  930. d.decode(&v2)
  931. rvn = reflect.ValueOf(&v2).Elem()
  932. }
  933. if reflectArrayOfSupported && d.stid == 0 && d.h.PreferArrayOverSlice {
  934. rvn2 := reflect.New(reflectArrayOf(rvn.Len(), intfTyp)).Elem()
  935. reflect.Copy(rvn2, rvn)
  936. rvn = rvn2
  937. }
  938. } else {
  939. if d.str {
  940. rvn = reflect.New(d.h.SliceType)
  941. d.decode(rv2i(rvn))
  942. rvn = rvn.Elem()
  943. } else {
  944. rvn = reflect.New(d.h.SliceType).Elem()
  945. d.decodeValue(rvn, nil, true)
  946. }
  947. }
  948. case valueTypeExt:
  949. var v interface{}
  950. tag, bytes := n.u, n.l // calling decode below might taint the values
  951. if bytes == nil {
  952. n.initContainers()
  953. if n.li < arrayCacheLen {
  954. n.ia[n.li] = nil
  955. n.li++
  956. d.decode(&n.ia[n.li-1])
  957. // v = *(&n.ia[l])
  958. n.li--
  959. v = n.ia[n.li]
  960. n.ia[n.li] = nil
  961. } else {
  962. d.decode(&v)
  963. }
  964. }
  965. bfn := d.h.getExtForTag(tag)
  966. if bfn == nil {
  967. var re RawExt
  968. re.Tag = tag
  969. re.Data = detachZeroCopyBytes(d.bytes, nil, bytes)
  970. re.Value = v
  971. rvn = reflect.ValueOf(&re).Elem()
  972. } else {
  973. rvnA := reflect.New(bfn.rt)
  974. if bytes != nil {
  975. bfn.ext.ReadExt(rv2i(rvnA), bytes)
  976. } else {
  977. bfn.ext.UpdateExt(rv2i(rvnA), v)
  978. }
  979. rvn = rvnA.Elem()
  980. }
  981. case valueTypeNil:
  982. // no-op
  983. case valueTypeInt:
  984. rvn = n.ri
  985. case valueTypeUint:
  986. rvn = n.ru
  987. case valueTypeFloat:
  988. rvn = n.rf
  989. case valueTypeBool:
  990. rvn = n.rb
  991. case valueTypeString, valueTypeSymbol:
  992. rvn = n.rs
  993. case valueTypeBytes:
  994. rvn = n.rl
  995. case valueTypeTime:
  996. rvn = n.rt
  997. default:
  998. panicv.errorf("kInterfaceNaked: unexpected valueType: %d", n.v)
  999. }
  1000. return
  1001. }
  1002. func (d *Decoder) kInterface(f *codecFnInfo, rv reflect.Value) {
  1003. // Note:
  1004. // A consequence of how kInterface works, is that
  1005. // if an interface already contains something, we try
  1006. // to decode into what was there before.
  1007. // We do not replace with a generic value (as got from decodeNaked).
  1008. // every interface passed here MUST be settable.
  1009. var rvn reflect.Value
  1010. if rv.IsNil() || d.h.InterfaceReset {
  1011. // check if mapping to a type: if so, initialize it and move on
  1012. rvn = d.h.intf2impl(f.ti.rtid)
  1013. if rvn.IsValid() {
  1014. rv.Set(rvn)
  1015. } else {
  1016. rvn = d.kInterfaceNaked(f)
  1017. if rvn.IsValid() {
  1018. rv.Set(rvn)
  1019. } else if d.h.InterfaceReset {
  1020. // reset to zero value based on current type in there.
  1021. rv.Set(reflect.Zero(rv.Elem().Type()))
  1022. }
  1023. return
  1024. }
  1025. } else {
  1026. // now we have a non-nil interface value, meaning it contains a type
  1027. rvn = rv.Elem()
  1028. }
  1029. if d.d.TryDecodeAsNil() {
  1030. rv.Set(reflect.Zero(rvn.Type()))
  1031. return
  1032. }
  1033. // Note: interface{} is settable, but underlying type may not be.
  1034. // Consequently, we MAY have to create a decodable value out of the underlying value,
  1035. // decode into it, and reset the interface itself.
  1036. // fmt.Printf(">>>> kInterface: rvn type: %v, rv type: %v\n", rvn.Type(), rv.Type())
  1037. rvn2, canDecode := isDecodeable(rvn)
  1038. if canDecode {
  1039. d.decodeValue(rvn2, nil, true)
  1040. return
  1041. }
  1042. rvn2 = reflect.New(rvn.Type()).Elem()
  1043. rvn2.Set(rvn)
  1044. d.decodeValue(rvn2, nil, true)
  1045. rv.Set(rvn2)
  1046. }
  1047. func decStructFieldKey(dd decDriver, keyType valueType, b *[decScratchByteArrayLen]byte) (rvkencname []byte) {
  1048. // use if-else-if, not switch (which compiles to binary-search)
  1049. // since keyType is typically valueTypeString, branch prediction is pretty good.
  1050. if keyType == valueTypeString {
  1051. rvkencname = dd.DecodeStringAsBytes()
  1052. } else if keyType == valueTypeInt {
  1053. rvkencname = strconv.AppendInt(b[:0], dd.DecodeInt64(), 10)
  1054. } else if keyType == valueTypeUint {
  1055. rvkencname = strconv.AppendUint(b[:0], dd.DecodeUint64(), 10)
  1056. } else if keyType == valueTypeFloat {
  1057. rvkencname = strconv.AppendFloat(b[:0], dd.DecodeFloat64(), 'f', -1, 64)
  1058. } else {
  1059. rvkencname = dd.DecodeStringAsBytes()
  1060. }
  1061. return rvkencname
  1062. }
  1063. func (d *Decoder) kStruct(f *codecFnInfo, rv reflect.Value) {
  1064. fti := f.ti
  1065. dd := d.d
  1066. elemsep := d.esep
  1067. sfn := structFieldNode{v: rv, update: true}
  1068. ctyp := dd.ContainerType()
  1069. var mf MissingFielder
  1070. if fti.mf {
  1071. mf = rv2i(rv).(MissingFielder)
  1072. } else if fti.mfp {
  1073. mf = rv2i(rv.Addr()).(MissingFielder)
  1074. }
  1075. if ctyp == valueTypeMap {
  1076. containerLen := dd.ReadMapStart()
  1077. if containerLen == 0 {
  1078. dd.ReadMapEnd()
  1079. return
  1080. }
  1081. tisfi := fti.sfiSort
  1082. hasLen := containerLen >= 0
  1083. var rvkencname []byte
  1084. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1085. if elemsep {
  1086. dd.ReadMapElemKey()
  1087. }
  1088. rvkencname = decStructFieldKey(dd, fti.keyType, &d.b)
  1089. if elemsep {
  1090. dd.ReadMapElemValue()
  1091. }
  1092. if k := fti.indexForEncName(rvkencname); k > -1 {
  1093. si := tisfi[k]
  1094. if dd.TryDecodeAsNil() {
  1095. si.setToZeroValue(rv)
  1096. } else {
  1097. d.decodeValue(sfn.field(si), nil, true)
  1098. }
  1099. } else if mf != nil {
  1100. var f interface{}
  1101. d.decode(&f)
  1102. if !mf.CodecMissingField(rvkencname, f) && d.h.ErrorIfNoField {
  1103. d.errorf("no matching struct field found when decoding stream map with key " + stringView(rvkencname))
  1104. }
  1105. } else {
  1106. d.structFieldNotFound(-1, stringView(rvkencname))
  1107. }
  1108. // keepAlive4StringView(rvkencnameB) // not needed, as reference is outside loop
  1109. }
  1110. dd.ReadMapEnd()
  1111. } else if ctyp == valueTypeArray {
  1112. containerLen := dd.ReadArrayStart()
  1113. if containerLen == 0 {
  1114. dd.ReadArrayEnd()
  1115. return
  1116. }
  1117. // Not much gain from doing it two ways for array.
  1118. // Arrays are not used as much for structs.
  1119. hasLen := containerLen >= 0
  1120. var checkbreak bool
  1121. for j, si := range fti.sfiSrc {
  1122. if hasLen && j == containerLen {
  1123. break
  1124. }
  1125. if !hasLen && dd.CheckBreak() {
  1126. checkbreak = true
  1127. break
  1128. }
  1129. if elemsep {
  1130. dd.ReadArrayElem()
  1131. }
  1132. if dd.TryDecodeAsNil() {
  1133. si.setToZeroValue(rv)
  1134. } else {
  1135. d.decodeValue(sfn.field(si), nil, true)
  1136. }
  1137. }
  1138. if (hasLen && containerLen > len(fti.sfiSrc)) || (!hasLen && !checkbreak) {
  1139. // read remaining values and throw away
  1140. for j := len(fti.sfiSrc); ; j++ {
  1141. if (hasLen && j == containerLen) || (!hasLen && dd.CheckBreak()) {
  1142. break
  1143. }
  1144. if elemsep {
  1145. dd.ReadArrayElem()
  1146. }
  1147. d.structFieldNotFound(j, "")
  1148. }
  1149. }
  1150. dd.ReadArrayEnd()
  1151. } else {
  1152. d.errorstr(errstrOnlyMapOrArrayCanDecodeIntoStruct)
  1153. return
  1154. }
  1155. }
  1156. func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) {
  1157. // A slice can be set from a map or array in stream.
  1158. // This way, the order can be kept (as order is lost with map).
  1159. ti := f.ti
  1160. if f.seq == seqTypeChan && ti.chandir&uint8(reflect.SendDir) == 0 {
  1161. d.errorf("receive-only channel cannot be decoded")
  1162. }
  1163. dd := d.d
  1164. rtelem0 := ti.elem
  1165. ctyp := dd.ContainerType()
  1166. if ctyp == valueTypeBytes || ctyp == valueTypeString {
  1167. // you can only decode bytes or string in the stream into a slice or array of bytes
  1168. if !(ti.rtid == uint8SliceTypId || rtelem0.Kind() == reflect.Uint8) {
  1169. d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", ti.rt)
  1170. }
  1171. if f.seq == seqTypeChan {
  1172. bs2 := dd.DecodeBytes(nil, true)
  1173. irv := rv2i(rv)
  1174. ch, ok := irv.(chan<- byte)
  1175. if !ok {
  1176. ch = irv.(chan byte)
  1177. }
  1178. for _, b := range bs2 {
  1179. ch <- b
  1180. }
  1181. } else {
  1182. rvbs := rv.Bytes()
  1183. bs2 := dd.DecodeBytes(rvbs, false)
  1184. // if rvbs == nil && bs2 != nil || rvbs != nil && bs2 == nil || len(bs2) != len(rvbs) {
  1185. if !(len(bs2) > 0 && len(bs2) == len(rvbs) && &bs2[0] == &rvbs[0]) {
  1186. if rv.CanSet() {
  1187. rv.SetBytes(bs2)
  1188. } else if len(rvbs) > 0 && len(bs2) > 0 {
  1189. copy(rvbs, bs2)
  1190. }
  1191. }
  1192. }
  1193. return
  1194. }
  1195. // array := f.seq == seqTypeChan
  1196. slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map)
  1197. // an array can never return a nil slice. so no need to check f.array here.
  1198. if containerLenS == 0 {
  1199. if rv.CanSet() {
  1200. if f.seq == seqTypeSlice {
  1201. if rv.IsNil() {
  1202. rv.Set(reflect.MakeSlice(ti.rt, 0, 0))
  1203. } else {
  1204. rv.SetLen(0)
  1205. }
  1206. } else if f.seq == seqTypeChan {
  1207. if rv.IsNil() {
  1208. rv.Set(reflect.MakeChan(ti.rt, 0))
  1209. }
  1210. }
  1211. }
  1212. slh.End()
  1213. return
  1214. }
  1215. rtelem0Size := int(rtelem0.Size())
  1216. rtElem0Kind := rtelem0.Kind()
  1217. rtelem0Mut := !isImmutableKind(rtElem0Kind)
  1218. rtelem := rtelem0
  1219. rtelemkind := rtelem.Kind()
  1220. for rtelemkind == reflect.Ptr {
  1221. rtelem = rtelem.Elem()
  1222. rtelemkind = rtelem.Kind()
  1223. }
  1224. var fn *codecFn
  1225. var rvCanset = rv.CanSet()
  1226. var rvChanged bool
  1227. var rv0 = rv
  1228. var rv9 reflect.Value
  1229. rvlen := rv.Len()
  1230. rvcap := rv.Cap()
  1231. hasLen := containerLenS > 0
  1232. if hasLen && f.seq == seqTypeSlice {
  1233. if containerLenS > rvcap {
  1234. oldRvlenGtZero := rvlen > 0
  1235. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(rtelem0.Size()))
  1236. if rvlen <= rvcap {
  1237. if rvCanset {
  1238. rv.SetLen(rvlen)
  1239. }
  1240. } else if rvCanset {
  1241. rv = reflect.MakeSlice(ti.rt, rvlen, rvlen)
  1242. rvcap = rvlen
  1243. rvChanged = true
  1244. } else {
  1245. d.errorf("cannot decode into non-settable slice")
  1246. }
  1247. if rvChanged && oldRvlenGtZero && !isImmutableKind(rtelem0.Kind()) {
  1248. reflect.Copy(rv, rv0) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap)
  1249. }
  1250. } else if containerLenS != rvlen {
  1251. rvlen = containerLenS
  1252. if rvCanset {
  1253. rv.SetLen(rvlen)
  1254. }
  1255. // else {
  1256. // rv = rv.Slice(0, rvlen)
  1257. // rvChanged = true
  1258. // d.errorf("cannot decode into non-settable slice")
  1259. // }
  1260. }
  1261. }
  1262. // consider creating new element once, and just decoding into it.
  1263. var rtelem0Zero reflect.Value
  1264. var rtelem0ZeroValid bool
  1265. var decodeAsNil bool
  1266. var j int
  1267. d.cfer()
  1268. for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ {
  1269. if j == 0 && (f.seq == seqTypeSlice || f.seq == seqTypeChan) && rv.IsNil() {
  1270. if hasLen {
  1271. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, rtelem0Size)
  1272. } else if f.seq == seqTypeSlice {
  1273. rvlen = decDefSliceCap
  1274. } else {
  1275. rvlen = decDefChanCap
  1276. }
  1277. if rvCanset {
  1278. if f.seq == seqTypeSlice {
  1279. rv = reflect.MakeSlice(ti.rt, rvlen, rvlen)
  1280. rvChanged = true
  1281. } else { // chan
  1282. rv = reflect.MakeChan(ti.rt, rvlen)
  1283. rvChanged = true
  1284. }
  1285. } else {
  1286. d.errorf("cannot decode into non-settable slice")
  1287. }
  1288. }
  1289. slh.ElemContainerState(j)
  1290. decodeAsNil = dd.TryDecodeAsNil()
  1291. if f.seq == seqTypeChan {
  1292. if decodeAsNil {
  1293. rv.Send(reflect.Zero(rtelem0))
  1294. continue
  1295. }
  1296. if rtelem0Mut || !rv9.IsValid() { // || (rtElem0Kind == reflect.Ptr && rv9.IsNil()) {
  1297. rv9 = reflect.New(rtelem0).Elem()
  1298. }
  1299. if fn == nil {
  1300. fn = d.cf.get(rtelem, true, true)
  1301. }
  1302. d.decodeValue(rv9, fn, true)
  1303. rv.Send(rv9)
  1304. } else {
  1305. // if indefinite, etc, then expand the slice if necessary
  1306. var decodeIntoBlank bool
  1307. if j >= rvlen {
  1308. if f.seq == seqTypeArray {
  1309. d.arrayCannotExpand(rvlen, j+1)
  1310. decodeIntoBlank = true
  1311. } else { // if f.seq == seqTypeSlice
  1312. // rv = reflect.Append(rv, reflect.Zero(rtelem0)) // append logic + varargs
  1313. var rvcap2 int
  1314. var rvErrmsg2 string
  1315. rv9, rvcap2, rvChanged, rvErrmsg2 =
  1316. expandSliceRV(rv, ti.rt, rvCanset, rtelem0Size, 1, rvlen, rvcap)
  1317. if rvErrmsg2 != "" {
  1318. d.errorf(rvErrmsg2)
  1319. }
  1320. rvlen++
  1321. if rvChanged {
  1322. rv = rv9
  1323. rvcap = rvcap2
  1324. }
  1325. }
  1326. }
  1327. if decodeIntoBlank {
  1328. if !decodeAsNil {
  1329. d.swallow()
  1330. }
  1331. } else {
  1332. rv9 = rv.Index(j)
  1333. if d.h.SliceElementReset || decodeAsNil {
  1334. if !rtelem0ZeroValid {
  1335. rtelem0ZeroValid = true
  1336. rtelem0Zero = reflect.Zero(rtelem0)
  1337. }
  1338. rv9.Set(rtelem0Zero)
  1339. if decodeAsNil {
  1340. continue
  1341. }
  1342. }
  1343. if fn == nil {
  1344. fn = d.cf.get(rtelem, true, true)
  1345. }
  1346. d.decodeValue(rv9, fn, true)
  1347. }
  1348. }
  1349. }
  1350. if f.seq == seqTypeSlice {
  1351. if j < rvlen {
  1352. if rv.CanSet() {
  1353. rv.SetLen(j)
  1354. } else if rvCanset {
  1355. rv = rv.Slice(0, j)
  1356. rvChanged = true
  1357. } // else { d.errorf("kSlice: cannot change non-settable slice") }
  1358. rvlen = j
  1359. } else if j == 0 && rv.IsNil() {
  1360. if rvCanset {
  1361. rv = reflect.MakeSlice(ti.rt, 0, 0)
  1362. rvChanged = true
  1363. } // else { d.errorf("kSlice: cannot change non-settable slice") }
  1364. }
  1365. }
  1366. slh.End()
  1367. if rvChanged { // infers rvCanset=true, so it can be reset
  1368. rv0.Set(rv)
  1369. }
  1370. }
  1371. // func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) {
  1372. // // d.decodeValueFn(rv.Slice(0, rv.Len()))
  1373. // f.kSlice(rv.Slice(0, rv.Len()))
  1374. // }
  1375. func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) {
  1376. dd := d.d
  1377. containerLen := dd.ReadMapStart()
  1378. elemsep := d.esep
  1379. ti := f.ti
  1380. if rv.IsNil() {
  1381. rv.Set(makeMapReflect(ti.rt, containerLen))
  1382. }
  1383. if containerLen == 0 {
  1384. dd.ReadMapEnd()
  1385. return
  1386. }
  1387. ktype, vtype := ti.key, ti.elem
  1388. ktypeId := rt2id(ktype)
  1389. vtypeKind := vtype.Kind()
  1390. var keyFn, valFn *codecFn
  1391. var ktypeLo, vtypeLo reflect.Type
  1392. for ktypeLo = ktype; ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() {
  1393. }
  1394. for vtypeLo = vtype; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() {
  1395. }
  1396. var mapGet, mapSet bool
  1397. rvvImmut := isImmutableKind(vtypeKind)
  1398. if !d.h.MapValueReset {
  1399. // if pointer, mapGet = true
  1400. // if interface, mapGet = true if !DecodeNakedAlways (else false)
  1401. // if builtin, mapGet = false
  1402. // else mapGet = true
  1403. if vtypeKind == reflect.Ptr {
  1404. mapGet = true
  1405. } else if vtypeKind == reflect.Interface {
  1406. if !d.h.InterfaceReset {
  1407. mapGet = true
  1408. }
  1409. } else if !rvvImmut {
  1410. mapGet = true
  1411. }
  1412. }
  1413. var rvk, rvkp, rvv, rvz reflect.Value
  1414. rvkMut := !isImmutableKind(ktype.Kind()) // if ktype is immutable, then re-use the same rvk.
  1415. ktypeIsString := ktypeId == stringTypId
  1416. ktypeIsIntf := ktypeId == intfTypId
  1417. hasLen := containerLen > 0
  1418. var kstrbs []byte
  1419. d.cfer()
  1420. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1421. if rvkMut || !rvkp.IsValid() {
  1422. rvkp = reflect.New(ktype)
  1423. rvk = rvkp.Elem()
  1424. }
  1425. if elemsep {
  1426. dd.ReadMapElemKey()
  1427. }
  1428. // if false && dd.TryDecodeAsNil() { // nil cannot be a map key, so disregard this block
  1429. // // Previously, if a nil key, we just ignored the mapped value and continued.
  1430. // // However, that makes the result of encoding and then decoding map[intf]intf{nil:nil}
  1431. // // to be an empty map.
  1432. // // Instead, we treat a nil key as the zero value of the type.
  1433. // rvk.Set(reflect.Zero(ktype))
  1434. // } else if ktypeIsString {
  1435. if ktypeIsString {
  1436. kstrbs = dd.DecodeStringAsBytes()
  1437. rvk.SetString(stringView(kstrbs))
  1438. // NOTE: if doing an insert, you MUST use a real string (not stringview)
  1439. } else {
  1440. if keyFn == nil {
  1441. keyFn = d.cf.get(ktypeLo, true, true)
  1442. }
  1443. d.decodeValue(rvk, keyFn, true)
  1444. }
  1445. // special case if a byte array.
  1446. if ktypeIsIntf {
  1447. if rvk2 := rvk.Elem(); rvk2.IsValid() {
  1448. if rvk2.Type() == uint8SliceTyp {
  1449. rvk = reflect.ValueOf(d.string(rvk2.Bytes()))
  1450. } else {
  1451. rvk = rvk2
  1452. }
  1453. }
  1454. }
  1455. if elemsep {
  1456. dd.ReadMapElemValue()
  1457. }
  1458. // Brittle, but OK per TryDecodeAsNil() contract.
  1459. // i.e. TryDecodeAsNil never shares slices with other decDriver procedures
  1460. if dd.TryDecodeAsNil() {
  1461. if ktypeIsString {
  1462. rvk.SetString(d.string(kstrbs))
  1463. }
  1464. if d.h.DeleteOnNilMapValue {
  1465. rv.SetMapIndex(rvk, reflect.Value{})
  1466. } else {
  1467. rv.SetMapIndex(rvk, reflect.Zero(vtype))
  1468. }
  1469. continue
  1470. }
  1471. mapSet = true // set to false if u do a get, and its a non-nil pointer
  1472. if mapGet {
  1473. // mapGet true only in case where kind=Ptr|Interface or kind is otherwise mutable.
  1474. rvv = rv.MapIndex(rvk)
  1475. if !rvv.IsValid() {
  1476. rvv = reflect.New(vtype).Elem()
  1477. } else if vtypeKind == reflect.Ptr {
  1478. if rvv.IsNil() {
  1479. rvv = reflect.New(vtype).Elem()
  1480. } else {
  1481. mapSet = false
  1482. }
  1483. } else if vtypeKind == reflect.Interface {
  1484. // not addressable, and thus not settable.
  1485. // e MUST create a settable/addressable variant
  1486. rvv2 := reflect.New(rvv.Type()).Elem()
  1487. if !rvv.IsNil() {
  1488. rvv2.Set(rvv)
  1489. }
  1490. rvv = rvv2
  1491. }
  1492. // else it is ~mutable, and we can just decode into it directly
  1493. } else if rvvImmut {
  1494. if !rvz.IsValid() {
  1495. rvz = reflect.New(vtype).Elem()
  1496. }
  1497. rvv = rvz
  1498. } else {
  1499. rvv = reflect.New(vtype).Elem()
  1500. }
  1501. // We MUST be done with the stringview of the key, before decoding the value
  1502. // so that we don't bastardize the reused byte array.
  1503. if mapSet && ktypeIsString {
  1504. rvk.SetString(d.string(kstrbs))
  1505. }
  1506. if valFn == nil {
  1507. valFn = d.cf.get(vtypeLo, true, true)
  1508. }
  1509. d.decodeValue(rvv, valFn, true)
  1510. // d.decodeValueFn(rvv, valFn)
  1511. if mapSet {
  1512. rv.SetMapIndex(rvk, rvv)
  1513. }
  1514. // if ktypeIsString {
  1515. // // keepAlive4StringView(kstrbs) // not needed, as reference is outside loop
  1516. // }
  1517. }
  1518. dd.ReadMapEnd()
  1519. }
  1520. // decNaked is used to keep track of the primitives decoded.
  1521. // Without it, we would have to decode each primitive and wrap it
  1522. // in an interface{}, causing an allocation.
  1523. // In this model, the primitives are decoded in a "pseudo-atomic" fashion,
  1524. // so we can rest assured that no other decoding happens while these
  1525. // primitives are being decoded.
  1526. //
  1527. // maps and arrays are not handled by this mechanism.
  1528. // However, RawExt is, and we accommodate for extensions that decode
  1529. // RawExt from DecodeNaked, but need to decode the value subsequently.
  1530. // kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat.
  1531. //
  1532. // However, decNaked also keeps some arrays of default maps and slices
  1533. // used in DecodeNaked. This way, we can get a pointer to it
  1534. // without causing a new heap allocation.
  1535. //
  1536. // kInterfaceNaked will ensure that there is no allocation for the common
  1537. // uses.
  1538. type decNakedContainers struct {
  1539. // array/stacks for reducing allocation
  1540. // keep arrays at the bottom? Chance is that they are not used much.
  1541. ia [arrayCacheLen]interface{}
  1542. ma [arrayCacheLen]map[interface{}]interface{}
  1543. na [arrayCacheLen]map[string]interface{}
  1544. sa [arrayCacheLen][]interface{}
  1545. // ria [arrayCacheLen]reflect.Value // not needed, as we decode directly into &ia[n]
  1546. rma, rna, rsa [arrayCacheLen]reflect.Value // reflect.Value mapping to above
  1547. }
  1548. func (n *decNakedContainers) init() {
  1549. for i := 0; i < arrayCacheLen; i++ {
  1550. // n.ria[i] = reflect.ValueOf(&(n.ia[i])).Elem()
  1551. n.rma[i] = reflect.ValueOf(&(n.ma[i])).Elem()
  1552. n.rna[i] = reflect.ValueOf(&(n.na[i])).Elem()
  1553. n.rsa[i] = reflect.ValueOf(&(n.sa[i])).Elem()
  1554. }
  1555. }
  1556. type decNaked struct {
  1557. // r RawExt // used for RawExt, uint, []byte.
  1558. // primitives below
  1559. u uint64
  1560. i int64
  1561. f float64
  1562. l []byte
  1563. s string
  1564. // ---- cpu cache line boundary?
  1565. t time.Time
  1566. b bool
  1567. // state
  1568. v valueType
  1569. li, lm, ln, ls int8
  1570. inited bool
  1571. *decNakedContainers
  1572. ru, ri, rf, rl, rs, rb, rt reflect.Value // mapping to the primitives above
  1573. // _ [6]uint64 // padding // no padding - rt goes into next cache line
  1574. }
  1575. func (n *decNaked) init() {
  1576. if n.inited {
  1577. return
  1578. }
  1579. n.ru = reflect.ValueOf(&n.u).Elem()
  1580. n.ri = reflect.ValueOf(&n.i).Elem()
  1581. n.rf = reflect.ValueOf(&n.f).Elem()
  1582. n.rl = reflect.ValueOf(&n.l).Elem()
  1583. n.rs = reflect.ValueOf(&n.s).Elem()
  1584. n.rt = reflect.ValueOf(&n.t).Elem()
  1585. n.rb = reflect.ValueOf(&n.b).Elem()
  1586. n.inited = true
  1587. // n.rr[] = reflect.ValueOf(&n.)
  1588. }
  1589. func (n *decNaked) initContainers() {
  1590. if n.decNakedContainers == nil {
  1591. n.decNakedContainers = new(decNakedContainers)
  1592. n.decNakedContainers.init()
  1593. }
  1594. }
  1595. func (n *decNaked) reset() {
  1596. if n == nil {
  1597. return
  1598. }
  1599. n.li, n.lm, n.ln, n.ls = 0, 0, 0, 0
  1600. }
  1601. type rtid2rv struct {
  1602. rtid uintptr
  1603. rv reflect.Value
  1604. }
  1605. // --------------
  1606. type decReaderSwitch struct {
  1607. rb bytesDecReader
  1608. // ---- cpu cache line boundary?
  1609. ri *ioDecReader
  1610. bi *bufioDecReader
  1611. mtr, str bool // whether maptype or slicetype are known types
  1612. be bool // is binary encoding
  1613. bytes bool // is bytes reader
  1614. js bool // is json handle
  1615. jsms bool // is json handle, and MapKeyAsString
  1616. esep bool // has elem separators
  1617. bufio bool // is this a bufioDecReader?
  1618. }
  1619. /*
  1620. func (z *decReaderSwitch) unreadn1() {
  1621. if z.bytes {
  1622. z.rb.unreadn1()
  1623. } else if z.bufio {
  1624. z.bi.unreadn1()
  1625. } else {
  1626. z.ri.unreadn1()
  1627. }
  1628. }
  1629. func (z *decReaderSwitch) readx(n int) []byte {
  1630. if z.bytes {
  1631. return z.rb.readx(n)
  1632. } else if z.bufio {
  1633. return z.bi.readx(n)
  1634. }
  1635. return z.ri.readx(n)
  1636. }
  1637. func (z *decReaderSwitch) readb(s []byte) {
  1638. if z.bytes {
  1639. z.rb.readb(s)
  1640. } else if z.bufio {
  1641. z.bi.readb(s)
  1642. } else {
  1643. z.ri.readb(s)
  1644. }
  1645. }
  1646. func (z *decReaderSwitch) readn1() uint8 {
  1647. if z.bytes {
  1648. return z.rb.readn1()
  1649. } else if z.bufio {
  1650. return z.bi.readn1()
  1651. }
  1652. return z.ri.readn1()
  1653. }
  1654. func (z *decReaderSwitch) numread() int {
  1655. if z.bytes {
  1656. return z.rb.numread()
  1657. } else if z.bufio {
  1658. return z.bi.numread()
  1659. }
  1660. return z.ri.numread()
  1661. }
  1662. func (z *decReaderSwitch) track() {
  1663. if z.bytes {
  1664. z.rb.track()
  1665. } else if z.bufio {
  1666. z.bi.track()
  1667. } else {
  1668. z.ri.track()
  1669. }
  1670. }
  1671. func (z *decReaderSwitch) stopTrack() []byte {
  1672. if z.bytes {
  1673. return z.rb.stopTrack()
  1674. } else if z.bufio {
  1675. return z.bi.stopTrack()
  1676. }
  1677. return z.ri.stopTrack()
  1678. }
  1679. func (z *decReaderSwitch) skip(accept *bitset256) (token byte) {
  1680. if z.bytes {
  1681. return z.rb.skip(accept)
  1682. } else if z.bufio {
  1683. return z.bi.skip(accept)
  1684. }
  1685. return z.ri.skip(accept)
  1686. }
  1687. func (z *decReaderSwitch) readTo(in []byte, accept *bitset256) (out []byte) {
  1688. if z.bytes {
  1689. return z.rb.readTo(in, accept)
  1690. } else if z.bufio {
  1691. return z.bi.readTo(in, accept)
  1692. }
  1693. return z.ri.readTo(in, accept)
  1694. }
  1695. func (z *decReaderSwitch) readUntil(in []byte, stop byte) (out []byte) {
  1696. if z.bytes {
  1697. return z.rb.readUntil(in, stop)
  1698. } else if z.bufio {
  1699. return z.bi.readUntil(in, stop)
  1700. }
  1701. return z.ri.readUntil(in, stop)
  1702. }
  1703. */
  1704. // A Decoder reads and decodes an object from an input stream in the codec format.
  1705. type Decoder struct {
  1706. panicHdl
  1707. // hopefully, reduce derefencing cost by laying the decReader inside the Decoder.
  1708. // Try to put things that go together to fit within a cache line (8 words).
  1709. d decDriver
  1710. // NOTE: Decoder shouldn't call it's read methods,
  1711. // as the handler MAY need to do some coordination.
  1712. r decReader
  1713. // bi *bufioDecReader
  1714. // cache the mapTypeId and sliceTypeId for faster comparisons
  1715. mtid uintptr
  1716. stid uintptr
  1717. n *decNaked
  1718. nsp *sync.Pool
  1719. // ---- cpu cache line boundary?
  1720. decReaderSwitch
  1721. // ---- cpu cache line boundary?
  1722. codecFnPooler
  1723. // cr containerStateRecv
  1724. err error
  1725. h *BasicHandle
  1726. _ [1]uint64 // padding
  1727. // ---- cpu cache line boundary?
  1728. b [decScratchByteArrayLen]byte // scratch buffer, used by Decoder and xxxEncDrivers
  1729. is map[string]string // used for interning strings
  1730. // padding - false sharing help // modify 232 if Decoder struct changes.
  1731. // _ [cacheLineSize - 232%cacheLineSize]byte
  1732. }
  1733. // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
  1734. //
  1735. // For efficiency, Users are encouraged to pass in a memory buffered reader
  1736. // (eg bufio.Reader, bytes.Buffer).
  1737. func NewDecoder(r io.Reader, h Handle) *Decoder {
  1738. d := newDecoder(h)
  1739. d.Reset(r)
  1740. return d
  1741. }
  1742. // NewDecoderBytes returns a Decoder which efficiently decodes directly
  1743. // from a byte slice with zero copying.
  1744. func NewDecoderBytes(in []byte, h Handle) *Decoder {
  1745. d := newDecoder(h)
  1746. d.ResetBytes(in)
  1747. return d
  1748. }
  1749. var defaultDecNaked decNaked
  1750. func newDecoder(h Handle) *Decoder {
  1751. d := &Decoder{h: h.getBasicHandle(), err: errDecoderNotInitialized}
  1752. d.hh = h
  1753. d.be = h.isBinary()
  1754. // NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
  1755. var jh *JsonHandle
  1756. jh, d.js = h.(*JsonHandle)
  1757. if d.js {
  1758. d.jsms = jh.MapKeyAsString
  1759. }
  1760. d.esep = d.hh.hasElemSeparators()
  1761. if d.h.InternString {
  1762. d.is = make(map[string]string, 32)
  1763. }
  1764. d.d = h.newDecDriver(d)
  1765. // d.cr, _ = d.d.(containerStateRecv)
  1766. return d
  1767. }
  1768. func (d *Decoder) resetCommon() {
  1769. // d.r = &d.decReaderSwitch
  1770. d.n.reset()
  1771. d.d.reset()
  1772. d.err = nil
  1773. // reset all things which were cached from the Handle, but could change
  1774. d.mtid, d.stid = 0, 0
  1775. d.mtr, d.str = false, false
  1776. if d.h.MapType != nil {
  1777. d.mtid = rt2id(d.h.MapType)
  1778. d.mtr = fastpathAV.index(d.mtid) != -1
  1779. }
  1780. if d.h.SliceType != nil {
  1781. d.stid = rt2id(d.h.SliceType)
  1782. d.str = fastpathAV.index(d.stid) != -1
  1783. }
  1784. }
  1785. // Reset the Decoder with a new Reader to decode from,
  1786. // clearing all state from last run(s).
  1787. func (d *Decoder) Reset(r io.Reader) {
  1788. if r == nil {
  1789. return
  1790. }
  1791. d.bytes = false
  1792. if d.h.ReaderBufferSize > 0 {
  1793. if d.bi == nil {
  1794. d.bi = new(bufioDecReader)
  1795. }
  1796. if cap(d.bi.buf) < d.h.ReaderBufferSize {
  1797. d.bi.buf = make([]byte, 0, d.h.ReaderBufferSize)
  1798. } else {
  1799. d.bi.buf = d.bi.buf[:0]
  1800. }
  1801. d.bi.reset(r)
  1802. d.r = d.bi
  1803. d.bufio = true
  1804. } else {
  1805. // d.ri.x = &d.b
  1806. // d.s = d.sa[:0]
  1807. if d.ri == nil {
  1808. d.ri = new(ioDecReader)
  1809. }
  1810. d.ri.reset(r)
  1811. d.r = d.ri
  1812. d.bufio = false
  1813. }
  1814. d.resetCommon()
  1815. }
  1816. // ResetBytes resets the Decoder with a new []byte to decode from,
  1817. // clearing all state from last run(s).
  1818. func (d *Decoder) ResetBytes(in []byte) {
  1819. if in == nil {
  1820. return
  1821. }
  1822. d.bytes = true
  1823. d.rb.reset(in)
  1824. d.r = &d.rb
  1825. d.resetCommon()
  1826. }
  1827. // naked must be called before each call to .DecodeNaked,
  1828. // as they will use it.
  1829. func (d *Decoder) naked() *decNaked {
  1830. if d.n == nil {
  1831. // consider one of:
  1832. // - get from sync.Pool (if GC is frequent, there's no value here)
  1833. // - new alloc (safest. only init'ed if it a naked decode will be done)
  1834. // - field in Decoder (makes the Decoder struct very big)
  1835. // To support using a decoder where a DecodeNaked is not needed,
  1836. // we prefer #1 or #2.
  1837. // d.n = new(decNaked) // &d.nv // new(decNaked) // grab from a sync.Pool
  1838. // d.n.init()
  1839. var v interface{}
  1840. d.nsp, v = pool.decNaked()
  1841. d.n = v.(*decNaked)
  1842. }
  1843. return d.n
  1844. }
  1845. // Decode decodes the stream from reader and stores the result in the
  1846. // value pointed to by v. v cannot be a nil pointer. v can also be
  1847. // a reflect.Value of a pointer.
  1848. //
  1849. // Note that a pointer to a nil interface is not a nil pointer.
  1850. // If you do not know what type of stream it is, pass in a pointer to a nil interface.
  1851. // We will decode and store a value in that nil interface.
  1852. //
  1853. // Sample usages:
  1854. // // Decoding into a non-nil typed value
  1855. // var f float32
  1856. // err = codec.NewDecoder(r, handle).Decode(&f)
  1857. //
  1858. // // Decoding into nil interface
  1859. // var v interface{}
  1860. // dec := codec.NewDecoder(r, handle)
  1861. // err = dec.Decode(&v)
  1862. //
  1863. // When decoding into a nil interface{}, we will decode into an appropriate value based
  1864. // on the contents of the stream:
  1865. // - Numbers are decoded as float64, int64 or uint64.
  1866. // - Other values are decoded appropriately depending on the type:
  1867. // bool, string, []byte, time.Time, etc
  1868. // - Extensions are decoded as RawExt (if no ext function registered for the tag)
  1869. // Configurations exist on the Handle to override defaults
  1870. // (e.g. for MapType, SliceType and how to decode raw bytes).
  1871. //
  1872. // When decoding into a non-nil interface{} value, the mode of encoding is based on the
  1873. // type of the value. When a value is seen:
  1874. // - If an extension is registered for it, call that extension function
  1875. // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
  1876. // - Else decode it based on its reflect.Kind
  1877. //
  1878. // There are some special rules when decoding into containers (slice/array/map/struct).
  1879. // Decode will typically use the stream contents to UPDATE the container i.e. the values
  1880. // in these containers will not be zero'ed before decoding.
  1881. // - A map can be decoded from a stream map, by updating matching keys.
  1882. // - A slice can be decoded from a stream array,
  1883. // by updating the first n elements, where n is length of the stream.
  1884. // - A slice can be decoded from a stream map, by decoding as if
  1885. // it contains a sequence of key-value pairs.
  1886. // - A struct can be decoded from a stream map, by updating matching fields.
  1887. // - A struct can be decoded from a stream array,
  1888. // by updating fields as they occur in the struct (by index).
  1889. //
  1890. // This in-place update maintains consistency in the decoding philosophy (i.e. we ALWAYS update
  1891. // in place by default). However, the consequence of this is that values in slices or maps
  1892. // which are not zero'ed before hand, will have part of the prior values in place after decode
  1893. // if the stream doesn't contain an update for those parts.
  1894. //
  1895. // This in-place update can be disabled by configuring the MapValueReset and SliceElementReset
  1896. // decode options available on every handle.
  1897. //
  1898. // Furthermore, when decoding a stream map or array with length of 0 into a nil map or slice,
  1899. // we reset the destination map or slice to a zero-length value.
  1900. //
  1901. // However, when decoding a stream nil, we reset the destination container
  1902. // to its "zero" value (e.g. nil for slice/map, etc).
  1903. //
  1904. // Note: we allow nil values in the stream anywhere except for map keys.
  1905. // A nil value in the encoded stream where a map key is expected is treated as an error.
  1906. func (d *Decoder) Decode(v interface{}) (err error) {
  1907. defer d.deferred(&err)
  1908. d.MustDecode(v)
  1909. return
  1910. }
  1911. // MustDecode is like Decode, but panics if unable to Decode.
  1912. // This provides insight to the code location that triggered the error.
  1913. func (d *Decoder) MustDecode(v interface{}) {
  1914. // TODO: Top-level: ensure that v is a pointer and not nil.
  1915. if d.err != nil {
  1916. panic(d.err)
  1917. }
  1918. if d.d.TryDecodeAsNil() {
  1919. setZero(v)
  1920. } else {
  1921. d.decode(v)
  1922. }
  1923. d.alwaysAtEnd()
  1924. // xprintf(">>>>>>>> >>>>>>>> num decFns: %v\n", d.cf.sn)
  1925. }
  1926. func (d *Decoder) deferred(err1 *error) {
  1927. d.alwaysAtEnd()
  1928. if recoverPanicToErr {
  1929. if x := recover(); x != nil {
  1930. panicValToErr(d, x, err1)
  1931. panicValToErr(d, x, &d.err)
  1932. }
  1933. }
  1934. }
  1935. func (d *Decoder) alwaysAtEnd() {
  1936. if d.n != nil {
  1937. // if n != nil, then nsp != nil (they are always set together)
  1938. d.nsp.Put(d.n)
  1939. d.n, d.nsp = nil, nil
  1940. }
  1941. d.codecFnPooler.alwaysAtEnd()
  1942. }
  1943. // // this is not a smart swallow, as it allocates objects and does unnecessary work.
  1944. // func (d *Decoder) swallowViaHammer() {
  1945. // var blank interface{}
  1946. // d.decodeValueNoFn(reflect.ValueOf(&blank).Elem())
  1947. // }
  1948. func (d *Decoder) swallow() {
  1949. // smarter decode that just swallows the content
  1950. dd := d.d
  1951. if dd.TryDecodeAsNil() {
  1952. return
  1953. }
  1954. elemsep := d.esep
  1955. switch dd.ContainerType() {
  1956. case valueTypeMap:
  1957. containerLen := dd.ReadMapStart()
  1958. hasLen := containerLen >= 0
  1959. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1960. // if clenGtEqualZero {if j >= containerLen {break} } else if dd.CheckBreak() {break}
  1961. if elemsep {
  1962. dd.ReadMapElemKey()
  1963. }
  1964. d.swallow()
  1965. if elemsep {
  1966. dd.ReadMapElemValue()
  1967. }
  1968. d.swallow()
  1969. }
  1970. dd.ReadMapEnd()
  1971. case valueTypeArray:
  1972. containerLen := dd.ReadArrayStart()
  1973. hasLen := containerLen >= 0
  1974. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1975. if elemsep {
  1976. dd.ReadArrayElem()
  1977. }
  1978. d.swallow()
  1979. }
  1980. dd.ReadArrayEnd()
  1981. case valueTypeBytes:
  1982. dd.DecodeBytes(d.b[:], true)
  1983. case valueTypeString:
  1984. dd.DecodeStringAsBytes()
  1985. default:
  1986. // these are all primitives, which we can get from decodeNaked
  1987. // if RawExt using Value, complete the processing.
  1988. n := d.naked()
  1989. dd.DecodeNaked()
  1990. if n.v == valueTypeExt && n.l == nil {
  1991. n.initContainers()
  1992. if n.li < arrayCacheLen {
  1993. n.ia[n.li] = nil
  1994. n.li++
  1995. d.decode(&n.ia[n.li-1])
  1996. n.ia[n.li-1] = nil
  1997. n.li--
  1998. } else {
  1999. var v2 interface{}
  2000. d.decode(&v2)
  2001. }
  2002. }
  2003. }
  2004. }
  2005. func setZero(iv interface{}) {
  2006. if iv == nil || definitelyNil(iv) {
  2007. return
  2008. }
  2009. var canDecode bool
  2010. switch v := iv.(type) {
  2011. case *string:
  2012. *v = ""
  2013. case *bool:
  2014. *v = false
  2015. case *int:
  2016. *v = 0
  2017. case *int8:
  2018. *v = 0
  2019. case *int16:
  2020. *v = 0
  2021. case *int32:
  2022. *v = 0
  2023. case *int64:
  2024. *v = 0
  2025. case *uint:
  2026. *v = 0
  2027. case *uint8:
  2028. *v = 0
  2029. case *uint16:
  2030. *v = 0
  2031. case *uint32:
  2032. *v = 0
  2033. case *uint64:
  2034. *v = 0
  2035. case *float32:
  2036. *v = 0
  2037. case *float64:
  2038. *v = 0
  2039. case *[]uint8:
  2040. *v = nil
  2041. case *Raw:
  2042. *v = nil
  2043. case *time.Time:
  2044. *v = time.Time{}
  2045. case reflect.Value:
  2046. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  2047. v.Set(reflect.Zero(v.Type()))
  2048. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  2049. default:
  2050. if !fastpathDecodeSetZeroTypeSwitch(iv) {
  2051. v := reflect.ValueOf(iv)
  2052. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  2053. v.Set(reflect.Zero(v.Type()))
  2054. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  2055. }
  2056. }
  2057. }
  2058. func (d *Decoder) decode(iv interface{}) {
  2059. // check nil and interfaces explicitly,
  2060. // so that type switches just have a run of constant non-interface types.
  2061. if iv == nil {
  2062. d.errorstr(errstrCannotDecodeIntoNil)
  2063. return
  2064. }
  2065. if v, ok := iv.(Selfer); ok {
  2066. v.CodecDecodeSelf(d)
  2067. return
  2068. }
  2069. switch v := iv.(type) {
  2070. // case nil:
  2071. // case Selfer:
  2072. case reflect.Value:
  2073. v = d.ensureDecodeable(v)
  2074. d.decodeValue(v, nil, true)
  2075. case *string:
  2076. *v = d.d.DecodeString()
  2077. case *bool:
  2078. *v = d.d.DecodeBool()
  2079. case *int:
  2080. *v = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize))
  2081. case *int8:
  2082. *v = int8(chkOvf.IntV(d.d.DecodeInt64(), 8))
  2083. case *int16:
  2084. *v = int16(chkOvf.IntV(d.d.DecodeInt64(), 16))
  2085. case *int32:
  2086. *v = int32(chkOvf.IntV(d.d.DecodeInt64(), 32))
  2087. case *int64:
  2088. *v = d.d.DecodeInt64()
  2089. case *uint:
  2090. *v = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize))
  2091. case *uint8:
  2092. *v = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8))
  2093. case *uint16:
  2094. *v = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16))
  2095. case *uint32:
  2096. *v = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32))
  2097. case *uint64:
  2098. *v = d.d.DecodeUint64()
  2099. case *float32:
  2100. f64 := d.d.DecodeFloat64()
  2101. if chkOvf.Float32(f64) {
  2102. d.errorf("float32 overflow: %v", f64)
  2103. }
  2104. *v = float32(f64)
  2105. case *float64:
  2106. *v = d.d.DecodeFloat64()
  2107. case *[]uint8:
  2108. *v = d.d.DecodeBytes(*v, false)
  2109. case []uint8:
  2110. b := d.d.DecodeBytes(v, false)
  2111. if !(len(b) > 0 && len(b) == len(v) && &b[0] == &v[0]) {
  2112. copy(v, b)
  2113. }
  2114. case *time.Time:
  2115. *v = d.d.DecodeTime()
  2116. case *Raw:
  2117. *v = d.rawBytes()
  2118. case *interface{}:
  2119. d.decodeValue(reflect.ValueOf(iv).Elem(), nil, true)
  2120. // d.decodeValueNotNil(reflect.ValueOf(iv).Elem())
  2121. default:
  2122. if !fastpathDecodeTypeSwitch(iv, d) {
  2123. v := reflect.ValueOf(iv)
  2124. v = d.ensureDecodeable(v)
  2125. d.decodeValue(v, nil, false)
  2126. // d.decodeValueFallback(v)
  2127. }
  2128. }
  2129. }
  2130. func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn, chkAll bool) {
  2131. // If stream is not containing a nil value, then we can deref to the base
  2132. // non-pointer value, and decode into that.
  2133. var rvp reflect.Value
  2134. var rvpValid bool
  2135. if rv.Kind() == reflect.Ptr {
  2136. rvpValid = true
  2137. for {
  2138. if rv.IsNil() {
  2139. rv.Set(reflect.New(rv.Type().Elem()))
  2140. }
  2141. rvp = rv
  2142. rv = rv.Elem()
  2143. if rv.Kind() != reflect.Ptr {
  2144. break
  2145. }
  2146. }
  2147. }
  2148. if fn == nil {
  2149. // always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer
  2150. fn = d.cfer().get(rv.Type(), chkAll, true) // chkAll, chkAll)
  2151. }
  2152. if fn.i.addrD {
  2153. if rvpValid {
  2154. fn.fd(d, &fn.i, rvp)
  2155. } else if rv.CanAddr() {
  2156. fn.fd(d, &fn.i, rv.Addr())
  2157. } else if !fn.i.addrF {
  2158. fn.fd(d, &fn.i, rv)
  2159. } else {
  2160. d.errorf("cannot decode into a non-pointer value")
  2161. }
  2162. } else {
  2163. fn.fd(d, &fn.i, rv)
  2164. }
  2165. // return rv
  2166. }
  2167. func (d *Decoder) structFieldNotFound(index int, rvkencname string) {
  2168. // NOTE: rvkencname may be a stringView, so don't pass it to another function.
  2169. if d.h.ErrorIfNoField {
  2170. if index >= 0 {
  2171. d.errorf("no matching struct field found when decoding stream array at index %v", index)
  2172. return
  2173. } else if rvkencname != "" {
  2174. d.errorf("no matching struct field found when decoding stream map with key " + rvkencname)
  2175. return
  2176. }
  2177. }
  2178. d.swallow()
  2179. }
  2180. func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) {
  2181. if d.h.ErrorIfNoArrayExpand {
  2182. d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen)
  2183. }
  2184. }
  2185. func isDecodeable(rv reflect.Value) (rv2 reflect.Value, canDecode bool) {
  2186. switch rv.Kind() {
  2187. case reflect.Array:
  2188. return rv, rv.CanAddr()
  2189. case reflect.Ptr:
  2190. if !rv.IsNil() {
  2191. return rv.Elem(), true
  2192. }
  2193. case reflect.Slice, reflect.Chan, reflect.Map:
  2194. if !rv.IsNil() {
  2195. return rv, true
  2196. }
  2197. }
  2198. return
  2199. }
  2200. func (d *Decoder) ensureDecodeable(rv reflect.Value) (rv2 reflect.Value) {
  2201. // decode can take any reflect.Value that is a inherently addressable i.e.
  2202. // - array
  2203. // - non-nil chan (we will SEND to it)
  2204. // - non-nil slice (we will set its elements)
  2205. // - non-nil map (we will put into it)
  2206. // - non-nil pointer (we can "update" it)
  2207. rv2, canDecode := isDecodeable(rv)
  2208. if canDecode {
  2209. return
  2210. }
  2211. if !rv.IsValid() {
  2212. d.errorstr(errstrCannotDecodeIntoNil)
  2213. return
  2214. }
  2215. if !rv.CanInterface() {
  2216. d.errorf("cannot decode into a value without an interface: %v", rv)
  2217. return
  2218. }
  2219. rvi := rv2i(rv)
  2220. rvk := rv.Kind()
  2221. d.errorf("cannot decode into value of kind: %v, type: %T, %v", rvk, rvi, rvi)
  2222. return
  2223. }
  2224. // Possibly get an interned version of a string
  2225. //
  2226. // This should mostly be used for map keys, where the key type is string.
  2227. // This is because keys of a map/struct are typically reused across many objects.
  2228. func (d *Decoder) string(v []byte) (s string) {
  2229. if d.is == nil {
  2230. return string(v) // don't return stringView, as we need a real string here.
  2231. }
  2232. s, ok := d.is[string(v)] // no allocation here, per go implementation
  2233. if !ok {
  2234. s = string(v) // new allocation here
  2235. d.is[s] = s
  2236. }
  2237. return s
  2238. }
  2239. // nextValueBytes returns the next value in the stream as a set of bytes.
  2240. func (d *Decoder) nextValueBytes() (bs []byte) {
  2241. d.d.uncacheRead()
  2242. d.r.track()
  2243. d.swallow()
  2244. bs = d.r.stopTrack()
  2245. return
  2246. }
  2247. func (d *Decoder) rawBytes() []byte {
  2248. // ensure that this is not a view into the bytes
  2249. // i.e. make new copy always.
  2250. bs := d.nextValueBytes()
  2251. bs2 := make([]byte, len(bs))
  2252. copy(bs2, bs)
  2253. return bs2
  2254. }
  2255. func (d *Decoder) wrapErr(v interface{}, err *error) {
  2256. *err = decodeError{codecError: codecError{name: d.hh.Name(), err: v}, pos: d.r.numread()}
  2257. }
  2258. // NumBytesRead returns the number of bytes read
  2259. func (d *Decoder) NumBytesRead() int {
  2260. return d.r.numread()
  2261. }
  2262. // --------------------------------------------------
  2263. // decSliceHelper assists when decoding into a slice, from a map or an array in the stream.
  2264. // A slice can be set from a map or array in stream. This supports the MapBySlice interface.
  2265. type decSliceHelper struct {
  2266. d *Decoder
  2267. // ct valueType
  2268. array bool
  2269. }
  2270. func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) {
  2271. dd := d.d
  2272. ctyp := dd.ContainerType()
  2273. switch ctyp {
  2274. case valueTypeArray:
  2275. x.array = true
  2276. clen = dd.ReadArrayStart()
  2277. case valueTypeMap:
  2278. clen = dd.ReadMapStart() * 2
  2279. default:
  2280. d.errorf("only encoded map or array can be decoded into a slice (%d)", ctyp)
  2281. }
  2282. // x.ct = ctyp
  2283. x.d = d
  2284. return
  2285. }
  2286. func (x decSliceHelper) End() {
  2287. if x.array {
  2288. x.d.d.ReadArrayEnd()
  2289. } else {
  2290. x.d.d.ReadMapEnd()
  2291. }
  2292. }
  2293. func (x decSliceHelper) ElemContainerState(index int) {
  2294. if x.array {
  2295. x.d.d.ReadArrayElem()
  2296. } else if index%2 == 0 {
  2297. x.d.d.ReadMapElemKey()
  2298. } else {
  2299. x.d.d.ReadMapElemValue()
  2300. }
  2301. }
  2302. func decByteSlice(r decReader, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  2303. if clen == 0 {
  2304. return zeroByteSlice
  2305. }
  2306. if len(bs) == clen {
  2307. bsOut = bs
  2308. r.readb(bsOut)
  2309. } else if cap(bs) >= clen {
  2310. bsOut = bs[:clen]
  2311. r.readb(bsOut)
  2312. } else {
  2313. // bsOut = make([]byte, clen)
  2314. len2 := decInferLen(clen, maxInitLen, 1)
  2315. bsOut = make([]byte, len2)
  2316. r.readb(bsOut)
  2317. for len2 < clen {
  2318. len3 := decInferLen(clen-len2, maxInitLen, 1)
  2319. bs3 := bsOut
  2320. bsOut = make([]byte, len2+len3)
  2321. copy(bsOut, bs3)
  2322. r.readb(bsOut[len2:])
  2323. len2 += len3
  2324. }
  2325. }
  2326. return
  2327. }
  2328. func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) {
  2329. if xlen := len(in); xlen > 0 {
  2330. if isBytesReader || xlen <= scratchByteArrayLen {
  2331. if cap(dest) >= xlen {
  2332. out = dest[:xlen]
  2333. } else {
  2334. out = make([]byte, xlen)
  2335. }
  2336. copy(out, in)
  2337. return
  2338. }
  2339. }
  2340. return in
  2341. }
  2342. // decInferLen will infer a sensible length, given the following:
  2343. // - clen: length wanted.
  2344. // - maxlen: max length to be returned.
  2345. // if <= 0, it is unset, and we infer it based on the unit size
  2346. // - unit: number of bytes for each element of the collection
  2347. func decInferLen(clen, maxlen, unit int) (rvlen int) {
  2348. // handle when maxlen is not set i.e. <= 0
  2349. if clen <= 0 {
  2350. return
  2351. }
  2352. if unit == 0 {
  2353. return clen
  2354. }
  2355. if maxlen <= 0 {
  2356. // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items.
  2357. // maxlen = 256 * 1024 / unit
  2358. // if maxlen < (4 * 1024) {
  2359. // maxlen = 4 * 1024
  2360. // }
  2361. if unit < (256 / 4) {
  2362. maxlen = 256 * 1024 / unit
  2363. } else {
  2364. maxlen = 4 * 1024
  2365. }
  2366. }
  2367. if clen > maxlen {
  2368. rvlen = maxlen
  2369. } else {
  2370. rvlen = clen
  2371. }
  2372. return
  2373. }
  2374. func expandSliceRV(s reflect.Value, st reflect.Type, canChange bool, stElemSize, num, slen, scap int) (
  2375. s2 reflect.Value, scap2 int, changed bool, err string) {
  2376. l1 := slen + num // new slice length
  2377. if l1 < slen {
  2378. err = errmsgExpandSliceOverflow
  2379. return
  2380. }
  2381. if l1 <= scap {
  2382. if s.CanSet() {
  2383. s.SetLen(l1)
  2384. } else if canChange {
  2385. s2 = s.Slice(0, l1)
  2386. scap2 = scap
  2387. changed = true
  2388. } else {
  2389. err = errmsgExpandSliceCannotChange
  2390. return
  2391. }
  2392. return
  2393. }
  2394. if !canChange {
  2395. err = errmsgExpandSliceCannotChange
  2396. return
  2397. }
  2398. scap2 = growCap(scap, stElemSize, num)
  2399. s2 = reflect.MakeSlice(st, l1, scap2)
  2400. changed = true
  2401. reflect.Copy(s2, s)
  2402. return
  2403. }
  2404. func decReadFull(r io.Reader, bs []byte) (n int, err error) {
  2405. var nn int
  2406. for n < len(bs) && err == nil {
  2407. nn, err = r.Read(bs[n:])
  2408. if nn > 0 {
  2409. if err == io.EOF {
  2410. // leave EOF for next time
  2411. err = nil
  2412. }
  2413. n += nn
  2414. }
  2415. }
  2416. // do not do this - it serves no purpose
  2417. // if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF }
  2418. return
  2419. }