• @Peek decorator moves the cursor to a specified address to read/write the decorated property, then moves back the cursor to its original position.

    The @Peek decorator shares similar functionality with the Offset decorator, but with a key difference: @Peek will automatically reset the cursor to its original position after reading or writing the decorated class or property.

    Type Parameters

    • This extends object

      The type of the class the decorator is applied to.

    • Args extends string

    Parameters

    • Optionaloffset: number | StringFormattedRecursiveKeyOf<This, Args> | ((instance: This, cursor: Cursor) => number)

      The offset to move the cursor to before reading or writing the decorated property. It can be:

      • A static number, indicating a fixed offset.
      • A string that refer to a property of the current instance.
      • A function that computes the offset dynamically based on the current instance and cursor.
    • Optionalopt: Partial<PrePostOptions>

      Optional configution.

    Returns ClassAndPropertyDecoratorType<This>

    The class or property decorator function.

    A use case where the @Peek decorator could be used instead of @Offset is if you need to apply some form of processing to the value of the property to know decide on the structure that value follows.

    In the following example the structure of the bitfield is only known based on the value of the most significant bit. For this I use @Peek to check the content of the next value and then I properly read it in the correct form.

    class BitfieldB {
    ...
    }

    class BitfieldA {
    ...
    }

    class Protocol {
    // Use `@Peek` to check the MSB but restore the cursor position
    @Peek()
    @Transform(x => x & 0x80)
    @Relation(PrimitiveSymbol.u8)
    peeked: number

    @IfThen(_ => _.peeked > 0, BitfieldA)
    @Else(BitfieldB)
    bitfield: BitfieldA | BitfieldB
    }

    You can also use the @Peek decorator with a dynamic offset that depends on the class instance and the current cursor position:

    class Protocol {
    @Relation(PrimitiveSymbol.u8)
    offset: number

    @Peek((instance, cursor) => cursor.offset() + instance.offset)
    @Relation(PrimitiveSymbol.u8)
    peeked: number
    }

    If you don’t need to return the cursor to its original position or know the exact position of the next read/write operation, use @Offset.