Skip to content

Commit

Permalink
Merge pull request #554 from streamich/cbor-packed-value-fix
Browse files Browse the repository at this point in the history
Support pre-packed values in CBOR codec
  • Loading branch information
streamich authored Mar 17, 2024
2 parents be415a2 + 48e341d commit 94c6e2c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/json-pack/cbor/CborEncoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {isFloat32} from '../../util/buffers/isFloat32';
import {JsonPackExtension} from '../JsonPackExtension';
import {CborEncoderFast} from './CborEncoderFast';
import type {IWriter, IWriterGrowable} from '../../util/buffers';
import {JsonPackValue} from '../JsonPackValue';

export class CborEncoder<W extends IWriter & IWriterGrowable = IWriter & IWriterGrowable> extends CborEncoderFast<W> {
/**
Expand Down Expand Up @@ -35,6 +36,9 @@ export class CborEncoder<W extends IWriter & IWriterGrowable = IWriter & IWriter
return this.writeMap(value as Map<unknown, unknown>);
case JsonPackExtension:
return this.writeTag((<JsonPackExtension>value).tag, (<JsonPackExtension>value).val);
case JsonPackValue:
const buf = (value as JsonPackValue).val;
return this.writer.buf(buf, buf.length);
default:
return this.writeUnknown(value);
}
Expand Down
13 changes: 13 additions & 0 deletions src/json-pack/cbor/__tests__/CborEncoder.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {Writer} from '../../../util/buffers/Writer';
import {JsonPackValue} from '../../JsonPackValue';
import {CborEncoder} from '../CborEncoder';
import {decode} from 'cbor';

Expand Down Expand Up @@ -398,3 +399,15 @@ describe('tokens (simple values)', () => {
testJsTokens(null);
testJsTokens(undefined);
});

describe('JsonPackValue', () => {
test('can encode pre-packed value', () => {
const internal = encoder.encode({foo: 'bar'});
const val = new JsonPackValue(internal);
const data = {boo: [1, val, 2]};
const encoded = encoder.encode(data);
expect(decode(encoded)).toEqual({
boo: [1, {foo: 'bar'}, 2],
});
});
});

0 comments on commit 94c6e2c

Please sign in to comment.