#!/usr/bin/env python

from __future__ import absolute_import, division, print_function

import datetime


RUST_FILE = '''
// DO NOT EDIT THIS FILE!
// IT IS AUTOMATICALLY GENERATED BY scripts/gen-tag-lookup-table
// Generated at {now}

pub const TAG_LOOKUP_TABLE: [u16; 256] = [
{table}
];
'''


# N.B. See the docs on TagLookupTable in src/decompress.rs for the bit layout
# details. Keep a copy of the Snappy format specification handy!
def entry(byte):
    tag = byte & 0b00000011
    if tag == 0b00:
        lit_len = (byte >> 2) + 1
        if lit_len <= 60:
            return lit_len
        else:
            assert lit_len <= 64
            return (lit_len - 60) << 11
    elif tag == 0b01:
        length = 4 + ((byte >> 2) & 0b111)
        offset = (byte >> 5) & 0b111
        return (1 << 11) | (offset << 8) | length
    elif tag == 0b10:
        length = 1 + (byte >> 2)
        return (2 << 11) | length
    else:
        assert tag == 0b11
        length = 1 + (byte >> 2)
        return (4 << 11) | length


def main():
    table = []
    stamp = datetime.datetime.now()
    for byte in range(0, 256):
        table.append('    0x%04x,' % entry(byte))
    print(RUST_FILE.format(now=stamp, table='\n'.join(table)))


if __name__ == '__main__':
    main()
