@ndn/tlv
Version:
NDNts: TLV
84 lines (83 loc) • 2.88 kB
TypeScript
/** An object that knows how to prepend itself to an Encoder. */
export interface EncodableObj {
encodeTo: (encoder: Encoder) => void;
}
/**
* An encodable TLV structure.
*
* @remarks
* First item is a number for TLV-TYPE.
* Optional second item could be {@link Encoder.OmitEmpty} to omit the TLV if TLV-VALUE is empty.
* Subsequent items are `Encodable`s for TLV-VALUE.
*/
export type EncodableTlv = [type: number, ...Encodable[]] | [
type: number,
omitEmpty: typeof Encoder.OmitEmpty,
...Encodable[]
];
/**
* An object acceptable to {@link Encoder.encode}.
*
* @remarks
* - `Uint8Array`: prepended as is.
* - `undefined` and `false`: skipped.
* - `EncodableObj`: `.encodeTo(encoder)` is invoked.
* - `EncodableTlv`: passed to {@link Encoder.prependTlv}.
* - `Encodable[]`: passed to {@link Encoder.prependValue}.
*/
export type Encodable = Uint8Array | undefined | false | EncodableObj | EncodableTlv | readonly Encodable[];
/** TLV encoder that accepts objects in reverse order. */
export declare class Encoder {
constructor(initSize?: number);
private buf;
private off;
/** Return encoding output size. */
get size(): number;
/** Obtain encoding output. */
get output(): Uint8Array;
/**
* Make room to prepend an object.
* @param sizeofObject - Object size.
* @returns Room to write object.
*/
prependRoom(sizeofObject: number): Uint8Array;
/** Prepend TLV-TYPE and TLV-LENGTH. */
prependTypeLength(tlvType: number, tlvLength: number): void;
/**
* Prepend TLV-VALUE.
*
* @remarks
* Elements are prepended in the reverse order, so that they would appear in the output
* in the same order as the parameter order.
*/
prependValue(...tlvValue: Encodable[]): void;
/**
* Prepend TLV structure.
* @see {@link EncodableTlv}
*/
prependTlv(tlvType: number, ...tlvValue: Encodable[]): void;
/**
* Prepend TLV structure, but skip if TLV-VALUE is empty.
* @see {@link EncodableTlv}
*/
prependTlv(tlvType: number, omitEmpty: typeof Encoder.OmitEmpty, ...tlvValue: Encodable[]): void;
/** Prepend `Encodable`. */
encode(obj: Encodable): void;
private grow;
}
export declare namespace Encoder {
/**
* Indicate that TLV should be skipped if TLV-VALUE is empty.
* @see {@link EncodableTlv}
*/
const OmitEmpty: unique symbol;
/** Encode a single object into Uint8Array. */
function encode(obj: Encodable, initBufSize?: number): Uint8Array;
/**
* Extract the encoding output of an element while writing to a parent encoder.
* @param obj - Encodable element.
* @param cb - Function to receive the encoding output of `obj`.
* @returns Wrapped Encodable object.
*/
function extract(obj: Encodable, cb: (output: Uint8Array) => void): Encodable;
}