cbor.go 20 KB

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