| 1 | // Tests that `time.Time` auto-tags as RFC 8949 tag 1 (epoch seconds) |
| 2 | // on encode and accepts both tag 0 (RFC 3339 text) and tag 1 (epoch |
| 3 | // seconds, integer or float) on decode. |
| 4 | module main |
| 5 | |
| 6 | import encoding.cbor |
| 7 | import encoding.hex |
| 8 | import time |
| 9 | |
| 10 | fn h(s string) []u8 { |
| 11 | return hex.decode(s) or { panic('invalid hex: ${s}') } |
| 12 | } |
| 13 | |
| 14 | fn test_time_encode_tag1() { |
| 15 | t := time.unix(1363896240) |
| 16 | bytes := cbor.encode[time.Time](t, cbor.EncodeOpts{})! |
| 17 | // Wire form: c1 (tag 1) + 1a 51 4b 67 b0 (4-byte uint). |
| 18 | assert bytes == h('c11a514b67b0'), 'got ${hex.encode(bytes)}' |
| 19 | } |
| 20 | |
| 21 | fn test_time_decode_tag1() { |
| 22 | got := cbor.decode[time.Time](h('c11a514b67b0'), cbor.DecodeOpts{})! |
| 23 | assert got.unix() == 1363896240 |
| 24 | } |
| 25 | |
| 26 | fn test_time_decode_tag0_iso8601() { |
| 27 | // Tag 0 + text "2013-03-21T20:04:00Z". |
| 28 | got := |
| 29 | cbor.decode[time.Time](h('c074323031332d30332d32315432303a30343a30305a'), cbor.DecodeOpts{})! |
| 30 | assert got.unix() == 1363896240 |
| 31 | } |
| 32 | |
| 33 | fn test_time_decode_tag1_float() { |
| 34 | got := cbor.decode[time.Time](h('c1fb41d452d9ec200000'), cbor.DecodeOpts{})! |
| 35 | // 1363896240.5 — half-second offset. |
| 36 | assert got.unix() == 1363896240 |
| 37 | // Sub-second component is non-zero (~500ms). |
| 38 | assert got.nanosecond > 0 |
| 39 | } |
| 40 | |