std

source of std::deflate

1// Deflate (RFC 1951) and gzip (RFC 1952): inflating what a server or a2// PNG compressed, its Huffman codes looked up nine bits at a time, and3// compressing what a program writes about as zlib's best level does4// (repeats found through chains of hashes and looked for again a byte5// on, blocks of their own Huffman codes).6//7// ```alloy8// import std::vector;9// import std::result;10//11// const text = "a line, a line, a line, a line";12// const packed = gzip(&text);13// expect(packed.length() < text.length() + 18);14// if (gunzip(&packed.view(), 1000) is ::Ok |&back|) {15//     expect(back.view() == text);16// } else {17//     expect(false);18// }19// expect(gunzip(&packed.view(), 10) == Result<Vector<u8>, InflateError>::Err(InflateError::TooLarge));20// ```2122import std::option;23import std::result;24import std::sort;25import std::vector;2627// Why inflating stopped.28exp type InflateError = enum {29    Damaged, // the data is not a whole stream30    TooLarge // it inflates past the limit given31};3233// Inflates the deflate stream into `out`, whose bytes it writes from the34// start, growing it past its length when it must, up to `limit` bytes:35// how many it wrote.36exp fn inflate(data: &[u8], out: &var Vector<u8>, limit: u64) -> Result<u64, InflateError> {37    var b = Bits { .bytes = &data, .at = 0, .held = 0, .count = 0 };38    var o = Output { .bytes = &var out, .length = 0, .limit = limit, .over = false };39    if (b.blocks(&var o)) {40        return ::Ok(o.length);41    }42    return ::Err(if (o.over) InflateError::TooLarge else InflateError::Damaged);43}4445// The data of the gzip members, one after another (RFC 1952, 2.2),46// inflated up to `limit` bytes in all, each member's length and CRC-3247// checked.48exp fn gunzip(data: &[u8], limit: u64) -> Result<Vector<u8>, InflateError> {49    var out = Vector<u8>::filled(0, min(limit, data.length() * 4));50    var length: u64 = 0;51    var at: u64 = 0;52    while (true) {53        const start = if (member_start(&data, at) is ::Some |s|) s else {54            return ::Err(::Damaged);55        };56        var b = Bits { .bytes = &data[start..], .at = 0, .held = 0, .count = 0 };57        var o = Output { .bytes = &var out, .length = length, .limit = limit, .over = false };58        if (!b.blocks(&var o)) {59            return ::Err(if (o.over) InflateError::TooLarge else InflateError::Damaged);60        }61        const end = start + b.taken();62        if (63            end + 8 > data.length()64            || crc32(&o.bytes.view()[length..o.length]) != little32(&data, end)65            || ((o.length - length) & 0xFFFFFFFF) to u32 != little32(&data, end + 4)66        ) {67            return ::Err(::Damaged);68        }69        length = o.length;70        at = end + 8;71        if (at == data.length()) {72            break;73        }74    }75    out.truncate(length);76    return ::Ok(move out);77}7879// Where the deflate data of the gzip member at `at` starts, past its80// header: magic, method 8, flags, time, extra flags, system, then the81// parts the flags add. None when no member starts there.82fn member_start(data: &[u8], at: u64) -> Option<u64> {83    if (84        at + 18 > data.length()85        || data[at] != 0x1F86        || data[at + 1] != 0x8B87        || data[at + 2] != 888    ) {89        return ::None;90    }91    const flags = data[at + 3];92    var start = at + 10;93    if ((flags & 4) != 0) {94        // extra fields95        start += 2 + (data[start] to u64 | data[start + 1] to u64 << 8);96    }97    for ([8 to u8, 16]) |flag| {98        // a name, a comment: text up to a zero byte99        if ((flags & flag) != 0) {100            while (start < data.length() && data[start] != 0) {101                start += 1;102            }103            start += 1;104        }105    }106    if ((flags & 2) != 0) {107        start += 2; // the header's CRC108    }109    if (start + 8 > data.length()) {110        return ::None;111    }112    return ::Some(start);113}114115// The data compressed as a gzip member, with no name nor time.116exp fn gzip(data: &[u8]) -> Vector<u8> {117    var out = Vector<u8>::from(&[0x1F to u8, 0x8B, 8, 0, 0, 0, 0, 0, 0, 255]);118    out.append(&deflate(&data).view());119    for ([crc32(&data), (data.length() & 0xFFFFFFFF) to u32]) |word| {120        for ([0 to u32, 8, 16, 24]) |shift| {121            out.push(((word >> shift) & 0xFF) to u8);122        }123    }124    return move out;125}126127// The data compressed: each repeat of three bytes or more the longest128// among the last 64 places of the same hash in the window, kept only129// when the byte after it starts no longer one (zlib's lazy matching),130// in blocks of 16384 literals and repeats, each written with its own131// Huffman codes, the fixed codes or stored, whichever is shortest.132//133// ```alloy134// import std::vector;135// import std::result;136//137// var text = Vector<u8>::empty();138// for ([..200 to u64]) {139//     text.append(&"a line again, ");140// }141// const packed = deflate(&text.view());142// expect(packed.length() < 100);143// var back = Vector<u8>::empty();144// const length = Result<u64, InflateError>::Ok(text.length());145// expect(inflate(&packed.view(), &var back, text.length()) == length);146// expect(back.view() == text.view());147// ```148exp fn deflate(data: &[u8]) -> Vector<u8> {149    var w = BitWriter { .out = Vector<u8>::empty(), .held = 0, .count = 0 };150    var m = Matcher {151        .data = &data,152        .head = Vector<u64>::filled(0, 1 << 15),153        .previous = Vector<u64>::filled(0, WINDOW)154    };155    var tokens = Vector<Token>::with_capacity(BLOCK_TOKENS + 1);156    var start: u64 = 0;157    var at: u64 = 0;158    while (at < data.length()) {159        var found = m.find(at, 2);160        var hashed = at + 1; // the places hashed end there161        if (found.length >= 3 && found.length < 258 && at + 4 <= data.length()) {162            const next = m.find(at + 1, found.length);163            hashed = at + 2;164            if (next.length > found.length) {165                tokens.push(Token::Literal(data[at]));166                at += 1;167                found = next;168            }169        }170        if (found.length < 3) {171            tokens.push(Token::Literal(data[at]));172            at += 1;173        } else {174            tokens.push(Token::Repeat(found));175            for ([hashed..min(at + found.length, data.length() - 2)]) |k| {176                m.insert(k);177            }178            at += found.length;179        }180        if (tokens.length() >= BLOCK_TOKENS) {181            w.block(&tokens.view(), &data[start..at], false);182            tokens.clear();183            start = at;184        }185    }186    w.block(&tokens.view(), &data[start..], true);187    w.put(0, 7); // to the byte188    return move w.out;189}190191// The CRC-32 of gzip, PNG and zip (the reflected polynomial 0xEDB88320).192exp fn crc32(data: &[u8]) -> u32 {193    var crc: u32 = 0xFFFFFFFF;194    for (data) |byte| {195        crc = CRC_TABLE[((crc ^ byte to u32) & 0xFF) to u64] ^ (crc >> 8);196    }197    return ~crc;198}199200const CRC_TABLE: [u32 : 256] = crc_table();201202fn crc_table() -> [u32 : 256] {203    var table: [u32 : 256] = [0 : 256];204    for ([..256 to u64]) |n| {205        var c = n to u32;206        for ([..8 to u64]) {207            c = if ((c & 1) != 0) 0xEDB88320 ^ (c >> 1) else c >> 1;208        }209        table[n] = c;210    }211    return table;212}213214fn little32(bytes: &[u8], at: u64) -> u32 {215    return bytes[at] to u32 | bytes[216        at + 1217    ] to u32 << 8 | bytes[at + 2] to u32 << 16 | bytes[at + 3] to u32 << 24;218}219220fn min(a: u64, b: u64) -> u64 => if (a < b) a else b;221222/* --- Inflating --- */223224// The stream's bits, least significant first, up to 64 of them held.225type Bits = struct {226    bytes: &[u8],227    at: u64, // the next byte to hold; past the end, zeros are held228    held: u64,229    count: u32 // how many bits are held230};231232fn fill(self b: &var Bits) {233    while (b.count <= 56) {234        if (b.at < b.bytes.length()) {235            b.held |= b.bytes[b.at] to u64 << b.count to u64;236        }237        b.at += 1;238        b.count += 8;239    }240}241242fn take(self b: &var Bits, count: u32) -> u32 {243    if (b.count < count) {244        b.fill();245    }246    const value = (b.held & ((1 to u64 << count to u64) - 1)) to u32;247    b.held >>= count to u64;248    b.count -= count;249    return value;250}251252// The bytes the bits taken came from, the last one's unused bits with it.253fn taken(self b: &Bits) -> u64 => (b.at * 8 - b.count to u64 + 7) / 8;254255// Whether more bits were taken than the stream has.256fn overran(self b: &Bits) -> bool => b.at * 8 - b.count to u64 > b.bytes.length() * 8;257258// A canonical Huffman code: codes of up to nine bits found in `fast` by259// the next nine bits (its length << 9 | its symbol, 0 for none), longer260// ones by comparing against each length's last code, as stb_image does.261type Huffman = struct {262    fast: [u16 : 512],263    first_code: [u32 : 16],264    first_symbol: [u32 : 16],265    limit: [u32 : 17], // past the last code of each length, on 16 bits266    symbols: [u16 : 288] // in the codes' order267};268269// The code of the symbols' lengths, None when they are too many for270// their lengths.271fn Huffman::of(lengths: &[u8]) -> Option<Huffman> {272    var h = Huffman {273        .fast = [0 : 512],274        .first_code = [0 : 16],275        .first_symbol = [0 : 16],276        .limit = [0 : 17],277        .symbols = [0 : 288]278    };279    var counts: [u32 : 16] = [0 : 16];280    for (lengths) |length| {281        counts[length to u64] += 1;282    }283    counts[0] = 0;284    var next: [u32 : 16] = [0 : 16];285    var code: u32 = 0;286    var symbol: u32 = 0;287    for ([1..16 to u64]) |length| {288        next[length] = code;289        h.first_code[length] = code;290        h.first_symbol[length] = symbol;291        code += counts[length];292        if (counts[length] != 0 && code - 1 >= 1 << length to u32) {293            return ::None;294        }295        h.limit[length] = code << (16 - length to u32);296        code <<= 1;297        symbol += counts[length];298    }299    h.limit[16] = 0x10000;300    for (lengths, [..lengths.length()]) |length, s| {301        if (length == 0) {302            continue;303        }304        const l = length to u64;305        const at = next[l] - h.first_code[l] + h.first_symbol[l];306        h.symbols[at to u64] = s to u16;307        if (length <= 9) {308            const entry = (length to u16 << 9) | s to u16;309            var k = reverse(next[l], length to u32) to u64;310            while (k < 512) {311                h.fast[k] = entry;312                k += 1 << l;313            }314        }315        next[l] += 1;316    }317    return ::Some(h);318}319320// The code's bits in the other order.321fn reverse(code: u32, length: u32) -> u32 {322    var n = code;323    n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);324    n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);325    n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);326    n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);327    return n >> (16 - length);328}329330// The next symbol, if the code has one.331fn decode(self b: &var Bits, h: &Huffman) -> Option<u32> {332    if (b.count < 16) {333        b.fill();334    }335    const entry = h.fast[(b.held & 511) to u64];336    if (entry != 0) {337        const length = (entry >> 9) to u32;338        b.held >>= length to u64;339        b.count -= length;340        return ::Some((entry & 511) to u32);341    }342    const k = reverse((b.held & 0xFFFF) to u32, 16);343    var length: u32 = 10;344    while (length < 16 && k >= h.limit[length to u64]) {345        length += 1;346    }347    if (length >= 16) {348        return ::None;349    }350    const at = (k >> (16 - length)) - h.first_code[length to u64] + h.first_symbol[length to u64];351    if (at >= 288) {352        return ::None;353    }354    b.held >>= length to u64;355    b.count -= length;356    return ::Some(h.symbols[at to u64] to u32);357}358359const LENGTH_BASE: [u16 : 29] = [360    3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115,361    131, 163, 195, 227, 258362];363const LENGTH_EXTRA: [u8 : 29] = [364    0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0365];366const DISTANCE_BASE: [u16 : 30] = [367    1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,368    2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577369];370const DISTANCE_EXTRA: [u8 : 30] = [371    0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13,372    13373];374// the order the code lengths' code gives its lengths in375const CODE_LENGTH_ORDER: [u8 : 19] = [376    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15377];378379// The lengths of the fixed codes (RFC 1951, 3.2.6).380fn fixed_lengths() -> [u8 : 320] {381    var lengths: [u8 : 320] = [8 : 320];382    for ([144..280 to u64]) |k| {383        lengths[k] = if (k < 256) 9 else 7;384    }385    for ([288..320 to u64]) |k| {386        lengths[k] = 5;387    }388    return lengths;389}390391// The blocks up to the last; false when the stream is damaged or gives392// more than the output's limit.393fn blocks(self b: &var Bits, o: &var Output) -> bool {394    var last: u32 = 0;395    while (last == 0) {396        last = b.take(1);397        match (b.take(2)) {398            0 {399                // stored: to the byte, a length and its complement, the bytes400                b.take(b.count % 8);401                const length = b.take(16) to u64;402                const complement = b.take(16) to u64;403                const start = b.at - (b.count / 8) to u64;404                if (405                    complement != (length ^ 0xFFFF)406                    || start + length > b.bytes.length()407                    || !o.room(length)408                ) {409                    return false;410                }411                o.bytes.items()[o.length..o.length + length] = b.bytes[start..start + length];412                o.length += length;413                b.at = start + length;414                b.held = 0;415                b.count = 0;416            }417            1 {418                const all = fixed_lengths();419                const literals = if (Huffman::of(&all[..288]) is ::Some |h|) h else {420                    return false;421                };422                const distances = if (Huffman::of(&all[288..]) is ::Some |h|) h else {423                    return false;424                };425                if (!b.block(&literals, &distances, &var o)) {426                    return false;427                }428            }429            2 {430                if (!b.dynamic_block(&var o)) {431                    return false;432                }433            }434            else {435                return false;436            }437        }438        if (b.overran()) {439            return false;440        }441    }442    return true;443}444445// Where inflated bytes go.446type Output = struct {447    bytes: &var Vector<u8>,448    length: u64,449    limit: u64,450    over: bool // past the limit451};452453// Grows the output so that `more` bytes fit past its length; false past454// its limit.455fn room(self o: &var Output, more: u64) -> bool {456    const needed = o.length + more;457    if (needed > o.limit) {458        o.over = true;459        return false;460    }461    if (needed > o.bytes.length()) {462        var grown = o.bytes.length() * 2;463        if (grown < needed) {464            grown = needed;465        }466        if (grown > o.limit) {467            grown = o.limit;468        }469        o.bytes.append(&Vector<u8>::filled(0, grown - o.bytes.length()).view());470    }471    return true;472}473474// A block with its own codes, which come first, coded themselves.475fn dynamic_block(self b: &var Bits, o: &var Output) -> bool {476    const literal_count = (b.take(5) + 257) to u64;477    const distance_count = (b.take(5) + 1) to u64;478    const code_count = (b.take(4) + 4) to u64;479    var code_lengths: [u8 : 19] = [0 : 19];480    for (CODE_LENGTH_ORDER[..code_count]) |k| {481        code_lengths[k to u64] = b.take(3) to u8;482    }483    const codes = if (Huffman::of(&code_lengths[..]) is ::Some |h|) h else {484        return false;485    };486    var lengths: [u8 : 320] = [0 : 320];487    const total = literal_count + distance_count;488    var n: u64 = 0;489    while (n < total) {490        const symbol = if (b.decode(&codes) is ::Some |s|) s else {491            return false;492        };493        if (symbol < 16) {494            lengths[n] = symbol to u8;495            n += 1;496            continue;497        }498        // a run of the last length, or of zeros499        var repeated: u8 = 0;500        var times: u64 = 0;501        match (symbol) {502            16 {503                if (n == 0) {504                    return false;505                }506                repeated = lengths[n - 1];507                times = (3 + b.take(2)) to u64;508            }509            17 {510                times = (3 + b.take(3)) to u64;511            }512            else {513                times = (11 + b.take(7)) to u64;514            }515        }516        if (n + times > total) {517            return false;518        }519        for ([n..n + times]) |k| {520            lengths[k] = repeated;521        }522        n += times;523    }524    const literals = if (Huffman::of(&lengths[..literal_count]) is ::Some |h|) h else {525        return false;526    };527    const distances = if (Huffman::of(&lengths[literal_count..total]) is ::Some |h|) h else {528        return false;529    };530    return b.block(&literals, &distances, &var o);531}532533fn block(self b: &var Bits, literals: &Huffman, distances: &Huffman, o: &var Output) -> bool {534    while (true) {535        const symbol = if (b.decode(&literals) is ::Some |s|) s else {536            return false;537        };538        if (symbol < 256) {539            // past the stream's end only zeros come, which must not go on540            if (!o.room(1) || b.at > b.bytes.length() + 8) {541                return false;542            }543            o.bytes.items()[o.length] = symbol to u8;544            o.length += 1;545            continue;546        }547        if (symbol == 256) {548            return true;549        }550        const k = (symbol - 257) to u64;551        if (k >= 29) {552            return false;553        }554        const length = (LENGTH_BASE[k] to u32 + b.take(LENGTH_EXTRA[k] to u32)) to u64;555        const d = if (b.decode(&distances) is ::Some |code| && code < 30) code to u64 else {556            return false;557        };558        const distance = (DISTANCE_BASE[d] to u32 + b.take(DISTANCE_EXTRA[d] to u32)) to u64;559        if (distance > o.length || b.overran() || !o.room(length)) {560            return false;561        }562        const bytes = &var o.bytes.items();563        const at = o.length;564        if (distance >= length) {565            bytes[at..at + length] = bytes[at - distance..at - distance + length];566        } else {567            for ([at..at + length]) |i| {568                bytes[i] = bytes[i - distance];569            }570        }571        o.length += length;572    }573}574575/* --- Compressing --- */576577const WINDOW: u64 = 32768; // how far back a repeat may start578const CHAIN: u64 = 64; // the places tried for each repeat579const BLOCK_TOKENS: u64 = 16384;580581// What a block gives: a byte, or bytes repeated from before.582type Token = enum {583    Literal: u8,584    Repeat: Earlier585};586587// Bytes repeated: how many, from how far back.588type Earlier = struct {589    length: u64,590    distance: u64591};592593// Where repeats are looked for: for each hash of three bytes the last594// place it was seen + 1, 0 for none, and for each place, by its offset595// in the window, the place + 1 seen before it with the same hash.596type Matcher = struct {597    data: &[u8],598    head: Vector<u64>,599    previous: Vector<u64>600};601602fn hash(self m: &Matcher, at: u64) -> u64 {603    const a = m.data[at] to u32 *% 506832829;604    const b = m.data[at + 1] to u32 *% 2654435761;605    return ((a +% b +% m.data[at + 2] to u32) >> 17) to u64 & 0x7FFF;606}607608// Hashes the three bytes at the place: the last place + 1 seen before609// with the same hash.610fn insert(self m: &var Matcher, at: u64) -> u64 {611    const h = m.hash(at);612    const last = m.head.get(h);613    m.previous.get_var(at % WINDOW) = last;614    m.head.get_var(h) = at + 1;615    return last;616}617618// Hashes the place and gives its longest repeat longer than `shorter`619// bytes, length 0 when it has none.620fn find(self m: &var Matcher, at: u64, shorter: u64) -> Earlier {621    var best = Earlier { .length = 0, .distance = 0 };622    if (at + 3 > m.data.length()) {623        return best;624    }625    const data = &m.data;626    var candidate = m.insert(at);627    const most = min(258, data.length() - at);628    var longest = shorter;629    var tries = CHAIN;630    while (candidate > 0 && tries > 0 && longest < most) {631        const from = candidate - 1;632        if (at - from > WINDOW) {633            break;634        }635        // only a repeat matching one byte past the longest so far can be636        // longer637        if (data[from + longest] == data[at + longest]) {638            var length: u64 = 0;639            while (length < most && data[from + length] == data[at + length]) {640                length += 1;641            }642            if (length > longest) {643                longest = length;644                best = Earlier { .length = length, .distance = at - from };645            }646        }647        // a place overwritten since in the window ends the chain648        const before = m.previous.get(from % WINDOW);649        if (before >= candidate) {650            break;651        }652        candidate = before;653        tries -= 1;654    }655    return best;656}657658// The length code of each repeat's length.659const LENGTH_CODES: [u8 : 259] = length_codes();660661fn length_codes() -> [u8 : 259] {662    var codes: [u8 : 259] = [0 : 259];663    var k: u64 = 0;664    for ([3..259 to u64]) |length| {665        while (k < 28 && LENGTH_BASE[k + 1] to u64 <= length) {666            k += 1;667        }668        codes[length] = k to u8;669    }670    return codes;671}672673fn distance_code(distance: u64) -> u64 {674    var d: u64 = 29;675    while (DISTANCE_BASE[d] to u64 > distance) {676        d -= 1;677    }678    return d;679}680681// A prefix code to write symbols in: each one's length, 0 for none, and682// its bits in the order written.683type Code = struct {684    lengths: [u8 : 288],685    bits: [u16 : 288]686};687688// The canonical code of the lengths (RFC 1951, 3.2.2).689fn Code::of(lengths: &[u8]) -> Code {690    var c = Code { .lengths = [0 : 288], .bits = [0 : 288] };691    var counts: [u32 : 16] = [0 : 16];692    for (lengths) |length| {693        counts[length to u64] += 1;694    }695    counts[0] = 0;696    var next: [u32 : 16] = [0 : 16];697    var code: u32 = 0;698    for ([1..16 to u64]) |length| {699        code = (code + counts[length - 1]) << 1;700        next[length] = code;701    }702    for (lengths, [..lengths.length()]) |length, s| {703        c.lengths[s] = length;704        if (length > 0) {705            c.bits[s] = reverse(next[length to u64], length to u32) to u16;706            next[length to u64] += 1;707        }708    }709    return c;710}711712// A Huffman code for the counts with no code longer than the limit: the713// symbols counted most the shortest codes, none for a symbol not714// counted, one bit for one alone.715fn Code::fitted(counts: &[u32], limit: u64) -> Code {716    var lengths: [u8 : 288] = [0 : 288];717    // the symbols counted, the fewest first718    var keys: [u64 : 288] = [0 : 288];719    var n: u64 = 0;720    for (counts, [..counts.length()]) |count, s| {721        if (count > 0) {722            keys[n] = count to u64 << 16 | s;723            n += 1;724        }725    }726    sort(&var keys[..n]);727    if (n == 1) {728        lengths[keys[0] & 0xFFFF] = 1;729    }730    if (n >= 2) {731        // Huffman's tree from two queues, the leaves by weight and the732        // nodes as they are made, which come out by weight too733        var weights: [u64 : 575] = [0 : 575];734        var parents: [u64 : 575] = [0 : 575];735        for ([..n]) |k| {736            weights[k] = keys[k] >> 16;737        }738        var leaf: u64 = 0;739        var node = n;740        var made = n;741        while (made < 2 * n - 1) {742            for ([..2 to u64]) {743                var lightest = node;744                if (leaf < n && (node == made || weights[leaf] <= weights[node])) {745                    lightest = leaf;746                    leaf += 1;747                } else {748                    node += 1;749                }750                parents[lightest] = made;751                weights[made] += weights[lightest];752            }753            made += 1;754        }755        // the leaves' depths, from the root down (a node is made after756        // its children), counted per length757        var depths: [u64 : 575] = [0 : 575];758        var per_length: [u64 : 288] = [0 : 288];759        var k = 2 * n - 2;760        while (k > 0) {761            k -= 1;762            depths[k] = depths[parents[k]] + 1;763        }764        for (depths[..n]) |depth| {765            per_length[depth] += 1;766        }767        // codes too long shortened as JPEG does (ITU T.81, K.3): two768        // leaves at the longest length go, one becoming their parent's769        // place and a shorter leaf the parent of both770        var longest = n - 1;771        while (longest > limit) {772            if (per_length[longest] == 0) {773                longest -= 1;774                continue;775            }776            var j = longest - 2;777            while (per_length[j] == 0) {778                j -= 1;779            }780            per_length[longest] -= 2;781            per_length[longest - 1] += 1;782            per_length[j + 1] += 2;783            per_length[j] -= 1;784        }785        var s = n;786        for ([1..limit + 1]) |length| {787            for ([..per_length[length]]) {788                s -= 1;789                lengths[keys[s] & 0xFFFF] = length to u8;790            }791        }792    }793    return Code::of(&lengths[..counts.length()]);794}795796// The bits the symbols counted take in the code.797fn cost(self c: &Code, counts: &[u32]) -> u64 {798    var bits: u64 = 0;799    for (counts, c.lengths[..counts.length()]) |count, length| {800        bits += count to u64 * length to u64;801    }802    return bits;803}804805// A block's own codes as its header gives them (RFC 1951, 3.2.7): their806// lengths one after the other in runs, coded by the code lengths' code.807type Header = struct {808    literals: u64, // how many literal and length codes it gives809    distances: u64,810    symbols: [u8 : 316], // the runs: a length, 16 repeating the last, 17 and 18 zeros811    extras: [u8 : 316], // how many more times a run's symbol repeats812    runs: u64,813    code: Code, // the code lengths' code814    lengths: u64 // how many of its lengths it gives, in CODE_LENGTH_ORDER815};816817fn Header::of(literals: &Code, distances: &Code) -> Header {818    var h = Header {819        .literals = 286,820        .distances = 30,821        .symbols = [0 : 316],822        .extras = [0 : 316],823        .runs = 0,824        .code = Code { .lengths = [0 : 288], .bits = [0 : 288] },825        .lengths = 19826    };827    while (h.literals > 257 && literals.lengths[h.literals - 1] == 0) {828        h.literals -= 1;829    }830    while (h.distances > 1 && distances.lengths[h.distances - 1] == 0) {831        h.distances -= 1;832    }833    var all: [u8 : 316] = [0 : 316];834    const total = h.literals + h.distances;835    all[..h.literals] = literals.lengths[..h.literals];836    all[h.literals..total] = distances.lengths[..h.distances];837    var k: u64 = 0;838    while (k < total) {839        const length = all[k];840        var run: u64 = 1;841        while (k + run < total && all[k + run] == length) {842            run += 1;843        }844        k += run;845        if (length == 0) {846            while (run >= 11) {847                const n = min(run, 138);848                h.add(18, n - 11);849                run -= n;850            }851            if (run >= 3) {852                h.add(17, run - 3);853                run = 0;854            }855        } else {856            h.add(length, 0);857            run -= 1;858            while (run >= 3) {859                const n = min(run, 6);860                h.add(16, n - 3);861                run -= n;862            }863        }864        for ([..run]) {865            h.add(length, 0);866        }867    }868    var counts: [u32 : 19] = [0 : 19];869    for (h.symbols[..h.runs]) |symbol| {870        counts[symbol to u64] += 1;871    }872    h.code = Code::fitted(&counts, 7);873    while (h.lengths > 4 && h.code.lengths[CODE_LENGTH_ORDER[h.lengths - 1] to u64] == 0) {874        h.lengths -= 1;875    }876    return h;877}878879fn add(self h: &var Header, symbol: u8, extra: u64) {880    h.symbols[h.runs] = symbol;881    h.extras[h.runs] = extra to u8;882    h.runs += 1;883}884885// The bits a run's symbol has after its code.886fn run_extra(symbol: u8) -> u32 => match (symbol) {887    16 2;888    17 3;889    18 7;890    else 0;891};892893// The header's bits.894fn bits(self h: &Header) -> u64 {895    var bits = 14 + 3 * h.lengths;896    for (h.symbols[..h.runs]) |symbol| {897        bits += (h.code.lengths[symbol to u64] to u32 + run_extra(symbol)) to u64;898    }899    return bits;900}901902/* Writing */903904// Bits written least significant first.905type BitWriter = struct {906    out: Vector<u8>,907    held: u64,908    count: u32909};910911fn put(self w: &var BitWriter, value: u32, count: u32) {912    w.held |= value to u64 << w.count to u64;913    w.count += count;914    while (w.count >= 8) {915        w.out.push((w.held & 0xFF) to u8);916        w.held >>= 8;917        w.count -= 8;918    }919}920921fn write(self w: &var BitWriter, c: &Code, symbol: u64) {922    w.put(c.bits[symbol] to u32, c.lengths[symbol] to u32);923}924925// The tokens as one block, the bytes they give: with codes of its own,926// the fixed codes or stored, whichever is shortest.927fn block(self w: &var BitWriter, tokens: &[Token], bytes: &[u8], last: bool) {928    var literal_counts: [u32 : 286] = [0 : 286];929    var distance_counts: [u32 : 30] = [0 : 30];930    var extra: u64 = 0; // the bits after the codes931    var repeats: u64 = 0;932    for (tokens) |&t| {933        match (t) {934            ::Literal |b| {935                literal_counts[b to u64] += 1;936            }937            ::Repeat |&r| {938                const k = LENGTH_CODES[r.length] to u64;939                const d = distance_code(r.distance);940                repeats += 1;941                literal_counts[257 + k] += 1;942                distance_counts[d] += 1;943                extra += (LENGTH_EXTRA[k] + DISTANCE_EXTRA[d]) to u64;944            }945        }946    }947    literal_counts[256] = 1;948    const literals = Code::fitted(&literal_counts, 15);949    // a block with no repeat still gives a distance code950    var distances = Code::of(&[1 to u8]);951    if (repeats > 0) {952        distances = Code::fitted(&distance_counts, 15);953    }954    const header = Header::of(&literals, &distances);955    const all = fixed_lengths();956    const fixed_literals = Code::of(&all[..288]);957    const fixed_distances = Code::of(&all[288..]);958    var own = 3 + extra + header.bits();959    own += literals.cost(&literal_counts) + distances.cost(&distance_counts);960    var fixed = 3 + extra + fixed_literals.cost(&literal_counts);961    fixed += fixed_distances.cost(&distance_counts);962    // each piece of up to 65535 bytes: 3 bits, up to 7 to the byte and 32963    // of lengths964    const stored = (bytes.length() / 65535 + 1) * 42 + bytes.length() * 8;965    if (stored < own && stored < fixed) {966        w.stored(&bytes, last);967        return;968    }969    w.put(if (last) 1 else 0, 1);970    if (fixed <= own) {971        w.put(1, 2);972        w.tokens(&tokens, &fixed_literals, &fixed_distances);973        return;974    }975    w.put(2, 2);976    w.put((header.literals - 257) to u32, 5);977    w.put((header.distances - 1) to u32, 5);978    w.put((header.lengths - 4) to u32, 4);979    for (CODE_LENGTH_ORDER[..header.lengths]) |symbol| {980        w.put(header.code.lengths[symbol to u64] to u32, 3);981    }982    for (header.symbols[..header.runs], header.extras[..header.runs]) |symbol, more| {983        w.write(&header.code, symbol to u64);984        w.put(more to u32, run_extra(symbol));985    }986    w.tokens(&tokens, &literals, &distances);987}988989fn tokens(self w: &var BitWriter, tokens: &[Token], literals: &Code, distances: &Code) {990    for (tokens) |&t| {991        match (t) {992            ::Literal |b| {993                w.write(&literals, b to u64);994            }995            ::Repeat |&r| {996                const k = LENGTH_CODES[r.length] to u64;997                w.write(&literals, 257 + k);998                w.put((r.length - LENGTH_BASE[k] to u64) to u32, LENGTH_EXTRA[k] to u32);999                const d = distance_code(r.distance);1000                w.write(&distances, d);1001                w.put((r.distance - DISTANCE_BASE[d] to u64) to u32, DISTANCE_EXTRA[d] to u32);1002            }1003        }1004    }1005    w.write(&literals, 256);1006}10071008// The bytes as stored blocks of up to 65535 bytes, each after its length1009// and the length's complement.1010fn stored(self w: &var BitWriter, bytes: &[u8], last: bool) {1011    var at: u64 = 0;1012    while (true) {1013        const length = min(bytes.length() - at, 65535);1014        const ends = at + length == bytes.length();1015        w.put(if (last && ends) 1 else 0, 1);1016        w.put(0, 2);1017        if (w.count > 0) {1018            w.put(0, 8 - w.count);1019        }1020        w.put(length to u32, 16);1021        w.put((length ^ 0xFFFF) to u32, 16);1022        w.out.append(&bytes[at..at + length]);1023        at += length;1024        if (ends) {1025            break;1026        }1027    }1028}