"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CffCharSet = void 0;
const bin_util_1 = require("@ot-builder/bin-util");
const errors_1 = require("@ot-builder/errors");
const primitive_1 = require("@ot-builder/primitive");
const FdSelectFormat0 = {
    ...(0, bin_util_1.Read)((view, sink) => {
        const nGlyphs = sink.getGlyphCount();
        for (let gid = 1; gid < nGlyphs; gid++) {
            const fd = view.uint16();
            sink.put(gid, fd);
        }
    })
};
const CffCharSetFormat12 = {
    ...(0, bin_util_1.Read)((view, sink, wdRest) => {
        const nGlyphs = sink.getGlyphCount();
        let nGlyphsCovered = 1;
        while (nGlyphsCovered < nGlyphs) {
            const sidFirst = view.uint16();
            const sidLeft = view.next(wdRest);
            for (let sid = 0; sid <= sidLeft; sid++) {
                sink.put(nGlyphsCovered + sid, sidFirst + sid);
            }
            nGlyphsCovered += 1 + sidLeft;
        }
    }),
    ...(0, bin_util_1.Write)((frag, format, values, wdRest) => {
        frag.uint8(format);
        let lastSid = -1;
        let rest = 0;
        const gidStart = 1;
        for (let gid = gidStart; gid < values.length; gid++) {
            if (gid === gidStart || lastSid + 1 !== values[gid] || rest >= wdRest.max) {
                if (gid > gidStart)
                    frag.push(wdRest, rest);
                frag.uint16(values[gid]);
                lastSid = values[gid];
                rest = 0;
            }
            else {
                lastSid = values[gid];
                rest++;
            }
        }
        frag.push(wdRest, rest);
    })
};
exports.CffCharSet = {
    ...(0, bin_util_1.Read)((view, ctx, sink) => {
        sink.put(0, 0);
        const format = view.uint8();
        switch (format) {
            case 0:
                return view.next(FdSelectFormat0, sink);
            case 1:
                return view.next(CffCharSetFormat12, sink, primitive_1.UInt8);
            case 2:
                return view.next(CffCharSetFormat12, sink, primitive_1.UInt16);
            default:
                throw errors_1.Errors.FormatNotSupported("CFF::CharSet", format);
        }
    }),
    ...(0, bin_util_1.Write)((frag, source, ctx) => {
        const charSetValues = source.getMappingList();
        errors_1.Assert.NoGap("CFF CharSet string ID list", charSetValues);
        const bFormat1 = bin_util_1.Frag.pack(bin_util_1.Frag.from(CffCharSetFormat12, 1, charSetValues, primitive_1.UInt8));
        const bFormat2 = bin_util_1.Frag.pack(bin_util_1.Frag.from(CffCharSetFormat12, 2, charSetValues, primitive_1.UInt16));
        if (bFormat1.byteLength < bFormat2.byteLength) {
            frag.bytes(bFormat1);
        }
        else {
            frag.bytes(bFormat2);
        }
    })
};
//# sourceMappingURL=io.js.map