Class StructBuilder<U>

Helper to build a base class that represents a TLV structure.

StructBuilder allows you to define the typing, constructor, encoder, and decoder, while writing each field only once. To be compatible with StructBuilder, the TLV structure being described shall contain a sequence of sub-TLV elements with distinct TLV-TYPE numbers, where each sub-TLV-TYPE appears zero, one, or multiple times.

To use StructBuilder, calling code should follow these steps:

  1. Invoke .add() method successively to define sub-TLV elements.
  2. Obtain a base class via .baseClass() method, which contains one field for each sub-TLV-TYPE as defined, along with constructor, encoding, and decoding functions.
  3. Declare a subclass deriving from this base class, to add more functionality.
  4. Assign the subclass constructor to .subclass property of the builder.

Type Parameters

  • U extends {}

Constructors

  • Constructor.

    Type Parameters

    • U extends {}

    Parameters

    • typeName: string

      Type name, used in error messages.

    • OptionaltopTT: number

      If specified, encode as complete TLV; otherwise, encode as TLV-VALUE only.

    Returns StructBuilder<U>

Properties

subclass?: Constructor<U, []> & Decodable<U>

Subclass constructor. This must be assigned, otherwise decoding function will not work.

topTT?: number

If specified, encode as complete TLV; otherwise, encode as TLV-VALUE only.

typeName: string

Type name, used in error messages.

Methods

  • Add a field.

    Type Parameters

    • T
    • K extends string
    • Required extends boolean = false
    • Repeat extends boolean = false
    • FlagPrefix extends string = K
    • FlagBit extends string = never

    Parameters

    • tt: number

      TLV-TYPE number.

    • key: IfNever<
          FlagBit,
          K,
          Repeat extends true
              ? "ERROR: can only define flags on a non-repeatable number field"
              : T extends number
                  ? K
                  : "ERROR: can only define flags on a non-repeatable number field",
      >

      Field name on the base class.

    • type: StructFieldType<T>

      Field type.

    • opts: Options<Required, Repeat, FlagPrefix, FlagBit> = {}

      Field options.

    Returns StructBuilder<
        {
            [KeyType in string
            | number
            | symbol]: (
                U & AddField<K, T, Required, Repeat> & AddFlags<FlagPrefix, FlagBit>
            )[KeyType]
        },
    >

    StructBuilder annotated with field typing.