cbor.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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. "math"
  6. "reflect"
  7. "time"
  8. )
  9. // major
  10. const (
  11. cborMajorUint byte = iota
  12. cborMajorNegInt
  13. cborMajorBytes
  14. cborMajorString
  15. cborMajorArray
  16. cborMajorMap
  17. cborMajorTag
  18. cborMajorSimpleOrFloat
  19. )
  20. // simple
  21. const (
  22. cborBdFalse byte = 0xf4 + iota
  23. cborBdTrue
  24. cborBdNil
  25. cborBdUndefined
  26. cborBdExt
  27. cborBdFloat16
  28. cborBdFloat32
  29. cborBdFloat64
  30. )
  31. // indefinite
  32. const (
  33. cborBdIndefiniteBytes byte = 0x5f
  34. cborBdIndefiniteString byte = 0x7f
  35. cborBdIndefiniteArray byte = 0x9f
  36. cborBdIndefiniteMap byte = 0xbf
  37. cborBdBreak byte = 0xff
  38. )
  39. // These define some in-stream descriptors for
  40. // manual encoding e.g. when doing explicit indefinite-length
  41. const (
  42. CborStreamBytes byte = 0x5f
  43. CborStreamString byte = 0x7f
  44. CborStreamArray byte = 0x9f
  45. CborStreamMap byte = 0xbf
  46. CborStreamBreak byte = 0xff
  47. )
  48. // base values
  49. const (
  50. cborBaseUint byte = 0x00
  51. cborBaseNegInt byte = 0x20
  52. cborBaseBytes byte = 0x40
  53. cborBaseString byte = 0x60
  54. cborBaseArray byte = 0x80
  55. cborBaseMap byte = 0xa0
  56. cborBaseTag byte = 0xc0
  57. cborBaseSimple byte = 0xe0
  58. )
  59. // const (
  60. // cborSelfDesrTag byte = 0xd9
  61. // cborSelfDesrTag2 byte = 0xd9
  62. // cborSelfDesrTag3 byte = 0xf7
  63. // )
  64. func cbordesc(bd byte) string {
  65. switch bd >> 5 {
  66. case cborMajorUint:
  67. return "(u)int"
  68. case cborMajorNegInt:
  69. return "int"
  70. case cborMajorBytes:
  71. return "bytes"
  72. case cborMajorString:
  73. return "string"
  74. case cborMajorArray:
  75. return "array"
  76. case cborMajorMap:
  77. return "map"
  78. case cborMajorTag:
  79. return "tag"
  80. case cborMajorSimpleOrFloat: // default
  81. switch bd {
  82. case cborBdNil:
  83. return "nil"
  84. case cborBdFalse:
  85. return "false"
  86. case cborBdTrue:
  87. return "true"
  88. case cborBdFloat16, cborBdFloat32, cborBdFloat64:
  89. return "float"
  90. case cborBdIndefiniteBytes:
  91. return "bytes*"
  92. case cborBdIndefiniteString:
  93. return "string*"
  94. case cborBdIndefiniteArray:
  95. return "array*"
  96. case cborBdIndefiniteMap:
  97. return "map*"
  98. default:
  99. return "unknown(simple)"
  100. }
  101. }
  102. return "unknown"
  103. }
  104. // -------------------
  105. type cborEncDriver struct {
  106. noBuiltInTypes
  107. encDriverNoopContainerWriter
  108. e *Encoder
  109. w *encWriterSwitch
  110. h *CborHandle
  111. x [8]byte
  112. // _ [3]uint64 // padding
  113. }
  114. func (e *cborEncDriver) EncodeNil() {
  115. e.w.writen1(cborBdNil)
  116. }
  117. func (e *cborEncDriver) EncodeBool(b bool) {
  118. if b {
  119. e.w.writen1(cborBdTrue)
  120. } else {
  121. e.w.writen1(cborBdFalse)
  122. }
  123. }
  124. func (e *cborEncDriver) EncodeFloat32(f float32) {
  125. e.w.writen1(cborBdFloat32)
  126. bigenHelper{e.x[:4], e.w}.writeUint32(math.Float32bits(f))
  127. }
  128. func (e *cborEncDriver) EncodeFloat64(f float64) {
  129. e.w.writen1(cborBdFloat64)
  130. bigenHelper{e.x[:8], e.w}.writeUint64(math.Float64bits(f))
  131. }
  132. func (e *cborEncDriver) encUint(v uint64, bd byte) {
  133. if v <= 0x17 {
  134. e.w.writen1(byte(v) + bd)
  135. } else if v <= math.MaxUint8 {
  136. e.w.writen2(bd+0x18, uint8(v))
  137. } else if v <= math.MaxUint16 {
  138. e.w.writen1(bd + 0x19)
  139. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(v))
  140. } else if v <= math.MaxUint32 {
  141. e.w.writen1(bd + 0x1a)
  142. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(v))
  143. } else { // if v <= math.MaxUint64 {
  144. e.w.writen1(bd + 0x1b)
  145. bigenHelper{e.x[:8], e.w}.writeUint64(v)
  146. }
  147. }
  148. func (e *cborEncDriver) EncodeInt(v int64) {
  149. if v < 0 {
  150. e.encUint(uint64(-1-v), cborBaseNegInt)
  151. } else {
  152. e.encUint(uint64(v), cborBaseUint)
  153. }
  154. }
  155. func (e *cborEncDriver) EncodeUint(v uint64) {
  156. e.encUint(v, cborBaseUint)
  157. }
  158. func (e *cborEncDriver) encLen(bd byte, length int) {
  159. e.encUint(uint64(length), bd)
  160. }
  161. func (e *cborEncDriver) EncodeTime(t time.Time) {
  162. if t.IsZero() {
  163. e.EncodeNil()
  164. } else if e.h.TimeRFC3339 {
  165. e.encUint(0, cborBaseTag)
  166. e.EncodeStringEnc(cUTF8, t.Format(time.RFC3339Nano))
  167. } else {
  168. e.encUint(1, cborBaseTag)
  169. t = t.UTC().Round(time.Microsecond)
  170. sec, nsec := t.Unix(), uint64(t.Nanosecond())
  171. if nsec == 0 {
  172. e.EncodeInt(sec)
  173. } else {
  174. e.EncodeFloat64(float64(sec) + float64(nsec)/1e9)
  175. }
  176. }
  177. }
  178. func (e *cborEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext) {
  179. e.encUint(uint64(xtag), cborBaseTag)
  180. if ext == SelfExt {
  181. rv2 := baseRV(rv)
  182. e.e.encodeValue(rv2, e.h.fnNoExt(rv2.Type()))
  183. } else if v := ext.ConvertExt(rv); v == nil {
  184. e.EncodeNil()
  185. } else {
  186. e.e.encode(v)
  187. }
  188. }
  189. func (e *cborEncDriver) EncodeRawExt(re *RawExt) {
  190. e.encUint(uint64(re.Tag), cborBaseTag)
  191. // only encodes re.Value (never re.Data)
  192. // if false && re.Data != nil {
  193. // en.encode(re.Data)
  194. // } else if re.Value != nil {
  195. if re.Value != nil {
  196. e.e.encode(re.Value)
  197. } else {
  198. e.EncodeNil()
  199. }
  200. }
  201. func (e *cborEncDriver) WriteArrayStart(length int) {
  202. if e.h.IndefiniteLength {
  203. e.w.writen1(cborBdIndefiniteArray)
  204. } else {
  205. e.encLen(cborBaseArray, length)
  206. }
  207. }
  208. func (e *cborEncDriver) WriteMapStart(length int) {
  209. if e.h.IndefiniteLength {
  210. e.w.writen1(cborBdIndefiniteMap)
  211. } else {
  212. e.encLen(cborBaseMap, length)
  213. }
  214. }
  215. func (e *cborEncDriver) WriteMapEnd() {
  216. if e.h.IndefiniteLength {
  217. e.w.writen1(cborBdBreak)
  218. }
  219. }
  220. func (e *cborEncDriver) WriteArrayEnd() {
  221. if e.h.IndefiniteLength {
  222. e.w.writen1(cborBdBreak)
  223. }
  224. }
  225. func (e *cborEncDriver) EncodeStringEnc(c charEncoding, v string) {
  226. e.encStringBytesS(cborBaseString, v)
  227. }
  228. func (e *cborEncDriver) EncodeStringBytesRaw(v []byte) {
  229. if v == nil {
  230. e.EncodeNil()
  231. } else {
  232. e.encStringBytesS(cborBaseBytes, stringView(v))
  233. }
  234. }
  235. func (e *cborEncDriver) encStringBytesS(bb byte, v string) {
  236. if e.h.IndefiniteLength {
  237. if bb == cborBaseBytes {
  238. e.w.writen1(cborBdIndefiniteBytes)
  239. } else {
  240. e.w.writen1(cborBdIndefiniteString)
  241. }
  242. var vlen uint = uint(len(v))
  243. blen := vlen / 4
  244. if blen == 0 {
  245. blen = 64
  246. } else if blen > 1024 {
  247. blen = 1024
  248. }
  249. for i := uint(0); i < vlen; {
  250. var v2 string
  251. i2 := i + blen
  252. if i2 >= i && i2 < vlen {
  253. v2 = v[i:i2]
  254. } else {
  255. v2 = v[i:]
  256. }
  257. e.encLen(bb, len(v2))
  258. e.w.writestr(v2)
  259. i = i2
  260. }
  261. e.w.writen1(cborBdBreak)
  262. } else {
  263. e.encLen(bb, len(v))
  264. e.w.writestr(v)
  265. }
  266. }
  267. // ----------------------
  268. type cborDecDriver struct {
  269. d *Decoder
  270. h *CborHandle
  271. r *decReaderSwitch
  272. br bool // bytes reader
  273. bdRead bool
  274. bd byte
  275. st bool // skip tags
  276. fnil bool // found nil
  277. noBuiltInTypes
  278. // decNoSeparator
  279. decDriverNoopContainerReader
  280. // _ [3]uint64 // padding
  281. }
  282. // func (d *cborDecDriver) readNextBdSkipTags() {
  283. // d.bd = d.r.readn1()
  284. // if d.h.SkipUnexpectedTags {
  285. // for d.bd >= cborBaseTag && d.bd < cborBaseSimple {
  286. // d.decUint()
  287. // d.bd = d.r.readn1()
  288. // }
  289. // }
  290. // d.bdRead = true
  291. // }
  292. // func (d *cborDecDriver) readNextBd() {
  293. // d.bd = d.r.readn1()
  294. // if d.handleCborSelfDesc && d.bd == cborSelfDesrTag {
  295. // if x := d.readn1(); x == cborSelfDesrTag2 {
  296. // if x = d.readn1(); x != cborSelfDesrTag3 {
  297. // d.d.errorf("mishandled self desc: expected 0xd9d9f7, got: 0xd9d9%x", x)
  298. // }
  299. // } else {
  300. // d.unreadn1()
  301. // }
  302. // }
  303. // d.bdRead = true
  304. // }
  305. func (d *cborDecDriver) readNextBd() {
  306. d.bd = d.r.readn1()
  307. d.bdRead = true
  308. }
  309. func (d *cborDecDriver) advanceNil() (null bool) {
  310. d.fnil = false
  311. if !d.bdRead {
  312. d.readNextBd()
  313. }
  314. if d.bd == cborBdNil || d.bd == cborBdUndefined {
  315. d.bdRead = false
  316. d.fnil = true
  317. null = true
  318. }
  319. return
  320. }
  321. // skipTags is called to skip any tags in the stream.
  322. //
  323. // Since any value can be tagged, then we should call skipTags
  324. // before any value is decoded.
  325. //
  326. // By definition, skipTags should not be called before
  327. // checking for break, or nil or undefined.
  328. func (d *cborDecDriver) skipTags() {
  329. for d.bd>>5 == cborMajorTag {
  330. d.decUint()
  331. d.bd = d.r.readn1()
  332. }
  333. }
  334. func (d *cborDecDriver) uncacheRead() {
  335. if d.bdRead {
  336. d.r.unreadn1()
  337. d.bdRead = false
  338. }
  339. }
  340. func (d *cborDecDriver) ContainerType() (vt valueType) {
  341. d.fnil = false
  342. if !d.bdRead {
  343. d.readNextBd()
  344. }
  345. if d.st {
  346. d.skipTags()
  347. }
  348. if d.bd == cborBdNil {
  349. d.bdRead = false // always consume nil after seeing it in container type
  350. d.fnil = true
  351. return valueTypeNil
  352. } else if d.bd == cborBdIndefiniteBytes || (d.bd>>5 == cborMajorBytes) {
  353. return valueTypeBytes
  354. } else if d.bd == cborBdIndefiniteString || (d.bd>>5 == cborMajorString) {
  355. return valueTypeString
  356. } else if d.bd == cborBdIndefiniteArray || (d.bd>>5 == cborMajorArray) {
  357. return valueTypeArray
  358. } else if d.bd == cborBdIndefiniteMap || (d.bd>>5 == cborMajorMap) {
  359. return valueTypeMap
  360. }
  361. // else {
  362. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  363. // }
  364. return valueTypeUnset
  365. }
  366. func (d *cborDecDriver) Nil() bool {
  367. return d.fnil
  368. }
  369. func (d *cborDecDriver) TryNil() bool {
  370. return d.advanceNil()
  371. }
  372. func (d *cborDecDriver) CheckBreak() (v bool) {
  373. if !d.bdRead {
  374. d.readNextBd()
  375. }
  376. if d.bd == cborBdBreak {
  377. d.bdRead = false
  378. v = true
  379. }
  380. return
  381. }
  382. func (d *cborDecDriver) decUint() (ui uint64) {
  383. v := d.bd & 0x1f
  384. if v <= 0x17 {
  385. ui = uint64(v)
  386. } else {
  387. if v == 0x18 {
  388. ui = uint64(d.r.readn1())
  389. } else if v == 0x19 {
  390. ui = uint64(bigen.Uint16(d.r.readx(2)))
  391. } else if v == 0x1a {
  392. ui = uint64(bigen.Uint32(d.r.readx(4)))
  393. } else if v == 0x1b {
  394. ui = uint64(bigen.Uint64(d.r.readx(8)))
  395. } else {
  396. d.d.errorf("invalid descriptor decoding uint: %x/%s", d.bd, cbordesc(d.bd))
  397. return
  398. }
  399. }
  400. return
  401. }
  402. func (d *cborDecDriver) decCheckInteger() (neg bool) {
  403. if d.st {
  404. d.skipTags()
  405. }
  406. major := d.bd >> 5
  407. if major == cborMajorUint {
  408. } else if major == cborMajorNegInt {
  409. neg = true
  410. } else {
  411. d.d.errorf("invalid integer; got major %v from descriptor %x/%s, expected %v or %v",
  412. major, d.bd, cbordesc(d.bd), cborMajorUint, cborMajorNegInt)
  413. }
  414. return
  415. }
  416. func cborDecInt64(ui uint64, neg bool) (i int64) {
  417. // check if this number can be converted to an int without overflow
  418. if neg {
  419. i = -(chkOvf.SignedIntV(ui + 1))
  420. } else {
  421. i = chkOvf.SignedIntV(ui)
  422. }
  423. return
  424. }
  425. func (d *cborDecDriver) decLen() int {
  426. return int(d.decUint())
  427. }
  428. func (d *cborDecDriver) decAppendIndefiniteBytes(bs []byte) []byte {
  429. d.bdRead = false
  430. for !d.CheckBreak() {
  431. if major := d.bd >> 5; major != cborMajorBytes && major != cborMajorString {
  432. d.d.errorf("invalid indefinite string/bytes; got major %v, expected %x/%s",
  433. major, d.bd, cbordesc(d.bd))
  434. }
  435. n := uint(d.decLen())
  436. oldLen := uint(len(bs))
  437. newLen := oldLen + n
  438. if newLen > uint(cap(bs)) {
  439. bs2 := make([]byte, newLen, 2*uint(cap(bs))+n)
  440. copy(bs2, bs)
  441. bs = bs2
  442. } else {
  443. bs = bs[:newLen]
  444. }
  445. d.r.readb(bs[oldLen:newLen])
  446. // bs = append(bs, d.r.readn()...)
  447. d.bdRead = false
  448. }
  449. d.bdRead = false
  450. return bs
  451. }
  452. func (d *cborDecDriver) DecodeInt64() (i int64) {
  453. if d.advanceNil() {
  454. return
  455. }
  456. neg := d.decCheckInteger()
  457. ui := d.decUint()
  458. d.bdRead = false
  459. return cborDecInt64(ui, neg)
  460. }
  461. func (d *cborDecDriver) DecodeUint64() (ui uint64) {
  462. if d.advanceNil() {
  463. return
  464. }
  465. if d.decCheckInteger() {
  466. d.d.errorf("cannot assign negative signed value to unsigned type")
  467. }
  468. ui = d.decUint()
  469. d.bdRead = false
  470. return
  471. }
  472. func (d *cborDecDriver) DecodeFloat64() (f float64) {
  473. if d.advanceNil() {
  474. return
  475. }
  476. if d.st {
  477. d.skipTags()
  478. }
  479. switch d.bd {
  480. case cborBdFloat16:
  481. f = float64(math.Float32frombits(halfFloatToFloatBits(bigen.Uint16(d.r.readx(2)))))
  482. case cborBdFloat32:
  483. f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4))))
  484. case cborBdFloat64:
  485. f = math.Float64frombits(bigen.Uint64(d.r.readx(8)))
  486. default:
  487. major := d.bd >> 5
  488. if major == cborMajorUint {
  489. f = float64(cborDecInt64(d.decUint(), false))
  490. } else if major == cborMajorNegInt {
  491. f = float64(cborDecInt64(d.decUint(), true))
  492. } else {
  493. d.d.errorf("invalid float descriptor; got %d/%s, expected float16/32/64 or (-)int",
  494. d.bd, cbordesc(d.bd))
  495. }
  496. }
  497. d.bdRead = false
  498. return
  499. }
  500. // bool can be decoded from bool only (single byte).
  501. func (d *cborDecDriver) DecodeBool() (b bool) {
  502. if d.advanceNil() {
  503. return
  504. }
  505. if d.st {
  506. d.skipTags()
  507. }
  508. if d.bd == cborBdTrue {
  509. b = true
  510. } else if d.bd == cborBdFalse {
  511. } else {
  512. d.d.errorf("not bool - %s %x/%s", msgBadDesc, d.bd, cbordesc(d.bd))
  513. return
  514. }
  515. d.bdRead = false
  516. return
  517. }
  518. func (d *cborDecDriver) ReadMapStart() (length int) {
  519. if d.advanceNil() {
  520. return decContainerLenNil
  521. }
  522. if d.st {
  523. d.skipTags()
  524. }
  525. d.bdRead = false
  526. if d.bd == cborBdIndefiniteMap {
  527. return decContainerLenUnknown
  528. }
  529. if d.bd>>5 != cborMajorMap {
  530. d.d.errorf("error reading map; got major type: %x, expected %x/%s",
  531. d.bd>>5, cborMajorMap, cbordesc(d.bd))
  532. }
  533. return d.decLen()
  534. }
  535. func (d *cborDecDriver) ReadArrayStart() (length int) {
  536. if d.advanceNil() {
  537. return decContainerLenNil
  538. }
  539. if d.st {
  540. d.skipTags()
  541. }
  542. d.bdRead = false
  543. if d.bd == cborBdIndefiniteArray {
  544. return decContainerLenUnknown
  545. }
  546. if d.bd>>5 != cborMajorArray {
  547. d.d.errorf("invalid array; got major type: %x, expect: %x/%s",
  548. d.bd>>5, cborMajorArray, cbordesc(d.bd))
  549. }
  550. return d.decLen()
  551. }
  552. func (d *cborDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  553. if d.advanceNil() {
  554. return
  555. }
  556. if d.st {
  557. d.skipTags()
  558. }
  559. if d.bd == cborBdIndefiniteBytes || d.bd == cborBdIndefiniteString {
  560. d.bdRead = false
  561. if bs == nil {
  562. if zerocopy {
  563. return d.decAppendIndefiniteBytes(d.d.b[:0])
  564. }
  565. return d.decAppendIndefiniteBytes(zeroByteSlice)
  566. }
  567. return d.decAppendIndefiniteBytes(bs[:0])
  568. }
  569. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  570. // if d.bd == cborBdIndefiniteArray || (d.bd >> 5 == cborMajorArray) {
  571. // bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  572. // return
  573. // }
  574. if d.bd == cborBdIndefiniteArray {
  575. d.bdRead = false
  576. if zerocopy && len(bs) == 0 {
  577. bs = d.d.b[:]
  578. }
  579. if bs == nil {
  580. bs = []byte{}
  581. } else {
  582. bs = bs[:0]
  583. }
  584. for !d.CheckBreak() {
  585. bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
  586. }
  587. return bs
  588. }
  589. if d.bd>>5 == cborMajorArray {
  590. d.bdRead = false
  591. if zerocopy && len(bs) == 0 {
  592. bs = d.d.b[:]
  593. }
  594. slen := d.decLen()
  595. bs = usableByteSlice(bs, slen)
  596. for i := 0; i < len(bs); i++ {
  597. bs[i] = uint8(chkOvf.UintV(d.DecodeUint64(), 8))
  598. }
  599. return bs
  600. }
  601. clen := d.decLen()
  602. d.bdRead = false
  603. if zerocopy {
  604. if d.br {
  605. return d.r.readx(uint(clen))
  606. } else if len(bs) == 0 {
  607. bs = d.d.b[:]
  608. }
  609. }
  610. return decByteSlice(d.r, clen, d.h.MaxInitLen, bs)
  611. }
  612. func (d *cborDecDriver) DecodeStringAsBytes() (s []byte) {
  613. return d.DecodeBytes(d.d.b[:], true)
  614. }
  615. func (d *cborDecDriver) DecodeTime() (t time.Time) {
  616. if d.advanceNil() {
  617. return
  618. }
  619. if d.bd>>5 != cborMajorTag {
  620. d.d.errorf("error reading tag; expected major type: %x, got: %x", cborMajorTag, d.bd>>5)
  621. }
  622. xtag := d.decUint()
  623. d.bdRead = false
  624. return d.decodeTime(xtag)
  625. }
  626. func (d *cborDecDriver) decodeTime(xtag uint64) (t time.Time) {
  627. switch xtag {
  628. case 0:
  629. var err error
  630. if t, err = time.Parse(time.RFC3339, stringView(d.DecodeStringAsBytes())); err != nil {
  631. d.d.errorv(err)
  632. }
  633. case 1:
  634. // if !d.bdRead {
  635. // d.readNextBd()
  636. // }
  637. // // decode an int64 or a float, and infer time.Time from there.
  638. // // for floats, round to microseconds, as that is what is guaranteed to fit well.
  639. // switch {
  640. // case d.bd == cborBdFloat16, d.bd == cborBdFloat32:
  641. // f1, f2 := math.Modf(d.DecodeFloat64())
  642. // t = time.Unix(int64(f1), int64(f2*1e9))
  643. // case d.bd == cborBdFloat64:
  644. // f1, f2 := math.Modf(d.DecodeFloat64())
  645. // t = time.Unix(int64(f1), int64(f2*1e9))
  646. // case d.bd >= cborBaseUint && d.bd < cborBaseBytes:
  647. // t = time.Unix(d.DecodeInt64(), 0)
  648. // default:
  649. // d.d.errorf("time.Time can only be decoded from a number (or RFC3339 string)")
  650. // }
  651. f1, f2 := math.Modf(d.DecodeFloat64())
  652. t = time.Unix(int64(f1), int64(f2*1e9))
  653. default:
  654. d.d.errorf("invalid tag for time.Time - expecting 0 or 1, got 0x%x", xtag)
  655. }
  656. t = t.UTC().Round(time.Microsecond)
  657. return
  658. }
  659. func (d *cborDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) {
  660. if d.advanceNil() {
  661. return
  662. }
  663. if d.bd>>5 != cborMajorTag {
  664. d.d.errorf("error reading tag; expected major type: %x, got: %x", cborMajorTag, d.bd>>5)
  665. }
  666. realxtag := d.decUint()
  667. d.bdRead = false
  668. if ext == nil {
  669. re := rv.(*RawExt)
  670. re.Tag = realxtag
  671. d.d.decode(&re.Value)
  672. } else if xtag != realxtag {
  673. d.d.errorf("Wrong extension tag. Got %b. Expecting: %v", realxtag, xtag)
  674. return
  675. } else if ext == SelfExt {
  676. rv2 := baseRV(rv)
  677. d.d.decodeValue(rv2, d.h.fnNoExt(rv2.Type()))
  678. } else {
  679. d.d.interfaceExtConvertAndDecode(rv, ext)
  680. }
  681. d.bdRead = false
  682. }
  683. func (d *cborDecDriver) DecodeNaked() {
  684. if !d.bdRead {
  685. d.readNextBd()
  686. }
  687. d.fnil = false
  688. n := d.d.naked()
  689. var decodeFurther bool
  690. switch d.bd >> 5 {
  691. case cborMajorUint:
  692. if d.h.SignedInteger {
  693. n.v = valueTypeInt
  694. n.i = d.DecodeInt64()
  695. } else {
  696. n.v = valueTypeUint
  697. n.u = d.DecodeUint64()
  698. }
  699. case cborMajorNegInt:
  700. n.v = valueTypeInt
  701. n.i = d.DecodeInt64()
  702. case cborMajorBytes:
  703. decNakedReadRawBytes(d, d.d, n, d.h.RawToString)
  704. case cborMajorString:
  705. n.v = valueTypeString
  706. n.s = string(d.DecodeStringAsBytes())
  707. case cborMajorArray:
  708. n.v = valueTypeArray
  709. decodeFurther = true
  710. case cborMajorMap:
  711. n.v = valueTypeMap
  712. decodeFurther = true
  713. case cborMajorTag:
  714. n.v = valueTypeExt
  715. n.u = d.decUint()
  716. n.l = nil
  717. if n.u == 0 || n.u == 1 {
  718. d.bdRead = false
  719. n.v = valueTypeTime
  720. n.t = d.decodeTime(n.u)
  721. } else if d.st && d.h.getExtForTag(n.u) == nil {
  722. // d.skipTags() // no need to call this - tags already skipped
  723. d.bdRead = false
  724. d.DecodeNaked()
  725. return // return when done (as true recursive function)
  726. }
  727. // d.bdRead = false
  728. // d.d.decode(&re.Value) // handled by decode itself.
  729. // decodeFurther = true
  730. case cborMajorSimpleOrFloat:
  731. switch d.bd {
  732. case cborBdNil, cborBdUndefined:
  733. n.v = valueTypeNil
  734. d.fnil = true
  735. case cborBdFalse:
  736. n.v = valueTypeBool
  737. n.b = false
  738. case cborBdTrue:
  739. n.v = valueTypeBool
  740. n.b = true
  741. case cborBdFloat16, cborBdFloat32, cborBdFloat64:
  742. n.v = valueTypeFloat
  743. n.f = d.DecodeFloat64()
  744. case cborBdIndefiniteBytes:
  745. decNakedReadRawBytes(d, d.d, n, d.h.RawToString)
  746. case cborBdIndefiniteString:
  747. n.v = valueTypeString
  748. n.s = string(d.DecodeStringAsBytes())
  749. case cborBdIndefiniteArray:
  750. n.v = valueTypeArray
  751. decodeFurther = true
  752. case cborBdIndefiniteMap:
  753. n.v = valueTypeMap
  754. decodeFurther = true
  755. default:
  756. d.d.errorf("decodeNaked: Unrecognized d.bd: 0x%x", d.bd)
  757. }
  758. default: // should never happen
  759. d.d.errorf("decodeNaked: Unrecognized d.bd: 0x%x", d.bd)
  760. }
  761. if !decodeFurther {
  762. d.bdRead = false
  763. }
  764. }
  765. // -------------------------
  766. // CborHandle is a Handle for the CBOR encoding format,
  767. // defined at http://tools.ietf.org/html/rfc7049 and documented further at http://cbor.io .
  768. //
  769. // CBOR is comprehensively supported, including support for:
  770. // - indefinite-length arrays/maps/bytes/strings
  771. // - (extension) tags in range 0..0xffff (0 .. 65535)
  772. // - half, single and double-precision floats
  773. // - all numbers (1, 2, 4 and 8-byte signed and unsigned integers)
  774. // - nil, true, false, ...
  775. // - arrays and maps, bytes and text strings
  776. //
  777. // None of the optional extensions (with tags) defined in the spec are supported out-of-the-box.
  778. // Users can implement them as needed (using SetExt), including spec-documented ones:
  779. // - timestamp, BigNum, BigFloat, Decimals,
  780. // - Encoded Text (e.g. URL, regexp, base64, MIME Message), etc.
  781. type CborHandle struct {
  782. binaryEncodingType
  783. noElemSeparators
  784. BasicHandle
  785. // IndefiniteLength=true, means that we encode using indefinitelength
  786. IndefiniteLength bool
  787. // TimeRFC3339 says to encode time.Time using RFC3339 format.
  788. // If unset, we encode time.Time using seconds past epoch.
  789. TimeRFC3339 bool
  790. // SkipUnexpectedTags says to skip over any tags for which extensions are
  791. // not defined. This is in keeping with the cbor spec on "Optional Tagging of Items".
  792. //
  793. // Furthermore, this allows the skipping over of the Self Describing Tag 0xd9d9f7.
  794. SkipUnexpectedTags bool
  795. _ [7]uint64 // padding (cache-aligned)
  796. }
  797. // Name returns the name of the handle: cbor
  798. func (h *CborHandle) Name() string { return "cbor" }
  799. // SetInterfaceExt sets an extension
  800. func (h *CborHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  801. return h.SetExt(rt, tag, makeExt(ext))
  802. }
  803. func (h *CborHandle) newEncDriver(e *Encoder) encDriver {
  804. return &cborEncDriver{e: e, w: e.w(), h: h}
  805. }
  806. func (h *CborHandle) newDecDriver(d *Decoder) decDriver {
  807. return &cborDecDriver{d: d, h: h, r: d.r(), br: d.bytes, st: h.SkipUnexpectedTags}
  808. }
  809. func (e *cborEncDriver) reset() {
  810. e.w = e.e.w()
  811. }
  812. func (d *cborDecDriver) reset() {
  813. d.r, d.br = d.d.r(), d.d.bytes
  814. d.bd = 0
  815. d.bdRead = false
  816. d.fnil = false
  817. d.st = d.h.SkipUnexpectedTags
  818. }
  819. var _ decDriver = (*cborDecDriver)(nil)
  820. var _ encDriver = (*cborEncDriver)(nil)