BC-DCBOR TypeScript Library - v1.0.0-alpha.13
    Preparing search index...

    Interface CborCodable<T>

    Interface for types that can be both encoded to and decoded from CBOR.

    This interface is a convenience marker for types that implement both CborEncodable and CborDecodable. It serves to indicate full CBOR serialization support.

    // Custom type that implements both conversion directions
    class Person implements CborCodable<Person> {
    constructor(public name: string = '', public age: number = 0) {}

    // Implement encoding to CBOR
    toCbor(): Cbor {
    const map = new CborMap();
    map.set(cbor('name'), cbor(this.name));
    map.set(cbor('age'), cbor(this.age));
    return cbor(map);
    }

    toCborData(): Uint8Array {
    return cborData(this.toCbor());
    }

    // Implement decoding from CBOR
    static fromCbor(cbor: Cbor): Person {
    if (cbor.type !== MajorType.Map) {
    throw new Error('Expected a CBOR map');
    }
    const map = cbor.value as CborMap;
    const name = extractCbor(map.get(cbor('name'))!) as string;
    const age = extractCbor(map.get(cbor('age'))!) as number;
    return new Person(name, age);
    }

    tryFromCbor(cbor: Cbor): Person {
    return Person.fromCbor(cbor);
    }
    }

    // Person now implements CborCodable
    const person = new Person('Alice', 30);
    const cborValue = person.toCbor(); // Using CborEncodable

    // Create a round-trip copy
    const personCopy = Person.fromCbor(cborValue); // Using CborDecodable
    interface CborCodable<T> {
        toCbor(): Cbor;
        toCborData(): Uint8Array;
        tryFromCbor(cbor: Cbor): T;
    }

    Type Parameters

    • T

      The type being encoded/decoded

    Hierarchy (View Summary)

    Index

    Methods

    • Converts this value directly to binary CBOR data.

      This is a shorthand for cborData(this.toCbor()).

      Returns Uint8Array

      Binary CBOR data