Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions packages/candid/src/idl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -698,3 +698,31 @@ test('should decode matching optional fields if wire type contains additional fi
b: ['123'],
});
});


test('IDL opt variant decoding', () => {
testDecode(
IDL.Record({a: IDL.Opt(IDL.Variant({ x: IDL.Null, y: IDL.Null, z: IDL.Null }))}),
{a: [{ x: null }]},
'4449444c036c0161016e026b03787f797f7a7f01000100', // Motoko: {a = ?#x} : {a : ?{#x;#y;#z}}
'same variant under opt x',
);
testDecode(
IDL.Record({a: IDL.Opt(IDL.Variant({ x: IDL.Null, y: IDL.Null, z: IDL.Null }))}),
{a: [{ z: null}]},
'4449444c036c0161016e026b03787f797f7a7f01000102', // Motoko: {a = ?#z} : {a : ?{#x;#y;#z}}
'same variant under opt z',
);
testDecode(
IDL.Record({a: IDL.Opt(IDL.Variant({ x: IDL.Null, y: IDL.Null }))}),
{a: [{ x: null }]},
'4449444c036c0161016e026b03787f797f7a7f01000100', // Motoko: {a = ?#x} : {a : ?{#x;#y;#z}}
'extended variant under opt expected tag',
);
testDecode(
IDL.Record({a: IDL.Opt(IDL.Variant({ x: IDL.Null, y: IDL.Null }))}),
{a: []},
'4449444c036c0161016e026b03787f797f7a7f01000102', // Motoko: {a = ?#z} : {a : ?{#x;#y;#z}}
'extended variant under opt unexpected tag - defaulting',
);
});
15 changes: 13 additions & 2 deletions packages/candid/src/idl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -921,8 +921,19 @@ export class OptClass<T> extends ConstructType<[T] | []> {
switch (safeReadUint8(b)) {
case 0:
return [];
case 1:
return [this._type.decodeValue(b, opt._type)];
case 1: {
const checkpoint = b.save();
try {
const v = this._type.decodeValue(b, opt._type)
return [v];
} catch (e : any) {
b.restore(checkpoint);
// skip value at wire type (to advance b)
const v = opt._type.decodeValue(b, opt._type)
// retun none
return [];
}
}
default:
throw new Error('Not an option value');
}
Expand Down
15 changes: 15 additions & 0 deletions packages/candid/src/utils/buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,21 @@ export class PipeArrayBuffer {
*/
private _view: Uint8Array;

/**
* Save a checkpoint of the reading view (for backtracking)
*/
public save() : Uint8Array {
return this._view;
}

/**
* Restore a checkpoint of the reading view (for backtracking)
* @param checkPoint a previously saved checkpoint
*/
public restore(checkPoint: Uint8Array) {
this._view = checkPoint;
}

/**
* The actual buffer containing the bytes.
* @private
Expand Down
Loading