cbor.go 20 KB

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