|
1 | 1 | # `json-pack` CBOR Codec |
2 | 2 |
|
| 3 | +`json-pack` implements fast [CBOR][cbor] encoder and decoder. It is written in TypeScript |
| 4 | +and has no external dependencies. |
| 5 | + |
| 6 | +[cbor]: https://cbor.io/ |
| 7 | + |
| 8 | +## Getting started |
| 9 | + |
| 10 | +To get started you need to import `CborEncoder` and `CborDecoder` classes like |
| 11 | +this: |
| 12 | + |
| 13 | +```ts |
| 14 | +import {CborEncoder} from 'json-joy/es2020/json-pack/cbor/CborEncoder'; |
| 15 | +import {CborDecoder} from 'json-joy/es2020/json-pack/cbor/CborDecoder'; |
| 16 | +``` |
| 17 | + |
| 18 | +The `CborDecoder` implements full decoding feature set including advanced |
| 19 | +features like value skipping and decoding one level at-a-time. Those features |
| 20 | +are not necessary for most use cases, to save on bundle size you can import |
| 21 | +the "base" decoder instead: |
| 22 | + |
| 23 | +```ts |
| 24 | +import {CborDecoderBase} from 'json-joy/es2020/json-pack/cbor/CborDecoderBase'; |
| 25 | +``` |
| 26 | + |
| 27 | +The base decoder implements all CBOR decoding features except for the advanced |
| 28 | +shallow decoding features, like skipping, one level at-a-time decoding. |
| 29 | + |
| 30 | +## Usage |
| 31 | + |
| 32 | +Encode a JavaScript POJO to CBOR: |
| 33 | + |
| 34 | +```ts |
| 35 | +const encoder = new CborEncoder(); |
| 36 | + |
| 37 | +const pojo = { |
| 38 | + id: 123, |
| 39 | + foo: 'bar', |
| 40 | + tags: ['a', 'b', 'c'], |
| 41 | + nested: { |
| 42 | + a: 1, |
| 43 | + b: 2, |
| 44 | + level2: { |
| 45 | + c: 3, |
| 46 | + } |
| 47 | + }, |
| 48 | +}; |
| 49 | + |
| 50 | +const encoded = encoder.encode(pojo); |
| 51 | +console.log(encoded); |
| 52 | +// Uint8Array(53) [ |
| 53 | +// 164, 98, 105, 100, 24, 123, 99, 102, 111, 111, |
| 54 | +// 99, 98, 97, 114, 100, 116, 97, 103, 115, 131, |
| 55 | +// 97, 97, 97, 98, 97, 99, 120, 6, 110, 101, |
| 56 | +// 115, 116, 101, 100, 163, 97, 97, 1, 97, 98, |
| 57 | +// 2, 120, 6, 108, 101, 118, 101, 108, 50, 161, |
| 58 | +// 97, 99, 3 |
| 59 | +// ] |
| 60 | +``` |
| 61 | + |
| 62 | +Decode CBOR back to JavaScript POJO: |
| 63 | + |
| 64 | +```ts |
| 65 | +const decoderBase = new CborDecoderBase(); |
| 66 | +const decoded = decoderBase.read(encoded); |
| 67 | + |
| 68 | +console.log(decoded); |
| 69 | +// { |
| 70 | +// id: 123, |
| 71 | +// foo: 'bar', |
| 72 | +// tags: ['a', 'b', 'c'], |
| 73 | +// nested: { |
| 74 | +// a: 1, |
| 75 | +// b: 2, |
| 76 | +// level2: { |
| 77 | +// c: 3, |
| 78 | +// } |
| 79 | +// }, |
| 80 | +// } |
| 81 | +``` |
3 | 82 |
|
4 | 83 | ## Implementation details |
5 | 84 |
|
|
0 commit comments