Skip to content

Commit

Permalink
Add example for encoding Buffer.
Browse files Browse the repository at this point in the history
Fixes #56
  • Loading branch information
hildjj committed Jan 6, 2025
1 parent d57b68d commit 84b725a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,15 @@ type. In this case, call `registerEncoder(type, encodeFunction)`. The
`toCBOR` above:

```js
import {Buffer} from 'node:buffer';
import {registerEncoder} from 'cbor2/encoder';

class Bar {
constructor() {
this.three = 3;
}
}
registerEncoder(Bar, (b, _writer, _options) => [NaN, b.three]);
registerEncoder(Buffer, b => [
// Don't write a tag
NaN,
// New view on the ArrayBuffer, without copying bytes
new Uint8Array(b.buffer, b.byteOffset, b.byteLength),
]);
```

## Adding new decoders
Expand Down
11 changes: 11 additions & 0 deletions examples/encodeOnly.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import 'cbor2/types';
import {encode, registerEncoder} from 'cbor2/encoder';
import {Buffer} from 'node:buffer';

class Bar {
constructor() {
this.today = new Date();
}
}
registerEncoder(Bar, b => [9999, b.today]);
registerEncoder(Buffer, b => [
// Don't write a tag
NaN,
// New view on the ArrayBuffer, without copying bytes
new Uint8Array(b.buffer, b.byteOffset, b.byteLength),
]);

console.log(encode(new Bar()));

const buf1 = Buffer.from('0102030405060708090a', 'hex');
const buf2 = buf1.subarray(2, 8);
console.log(encode(buf2));

0 comments on commit 84b725a

Please sign in to comment.