"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.readTlvs = void 0;
const bufio_1 = require("@node-dlc/bufio");
/**
 * Reads TLVs from a reader until the entire stream is processed. The handler is
 * responsible for doing something with the data bytes.
 * @param reader
 * @param handler
 */
function readTlvs(reader, handler) {
    let lastType;
    while (!reader.eof) {
        const type = reader.readBigSize();
        const len = reader.readBigSize();
        const value = reader.readBytes(Number(len));
        const valueReader = new bufio_1.BufferReader(value);
        if (type <= lastType) {
            throw new Error('Invalid TLV stream');
        }
        const isEven = type % BigInt(2) === BigInt(0);
        const wasHandled = handler(type, valueReader);
        if (!wasHandled && isEven) {
            throw new Error('Unknown even type');
        }
        if (wasHandled && !valueReader.eof) {
            throw new Error('Non-canonical length');
        }
        lastType = type;
    }
}
exports.readTlvs = readTlvs;
//# sourceMappingURL=readTlvs.js.map