#!/usr/bin/env python3

from contextlib import redirect_stdout


def format_array(array):
    result = []
    for value in array:
        if value < 0 or value == 0x80:
            result.append('0x80')
        else:
            result.append(str(value))

    return ', '.join(result)


def assure_array_length(array, size, value=0x80):
    while len(array) < size:
        array.append(value)


def utf32_to_utf16le():
    for mask in range(16):
        src = 0
        arr = []
        for bit in [0x01, 0x02, 0x04, 0x08]:
            if mask & bit:
                arr.append(src + 0)
                arr.append(src + 1)
                arr.append(src + 2)
                arr.append(src + 3)
            else:
                arr.append(src + 0)
                arr.append(src + 1)

            src += 4

        assure_array_length(arr, 16)

        yield arr


def utf32_to_utf16be():
    for mask in range(16):
        src = 0
        arr = []
        for bit in [0x01, 0x02, 0x04, 0x08]:
            if mask & bit:
                arr.append(src + 1)
                arr.append(src + 0)
                arr.append(src + 3)
                arr.append(src + 2)
            else:
                arr.append(src + 1)
                arr.append(src + 0)

            src += 4

        assure_array_length(arr, 16)

        yield arr


CPP_HEADER = """// file generated by scripts/sse_convert_utf32_to_utf16.py
#ifndef SIMDUTF_UTF32_TO_UTF16_TABLES_H
#define SIMDUTF_UTF32_TO_UTF16_TABLES_H

namespace simdutf {
namespace {
namespace tables {
namespace utf32_to_utf16 {
"""

CPP_FOOTER = """} // utf16_to_utf8 namespace
} // tables namespace
} // unnamed namespace
} // namespace simdutf

#endif // SIMDUTF_UTF16_TO_UTF8_TABLES_H
"""


def main():
    with open('utf32_to_utf16_tables.h', 'wt') as f:
        with redirect_stdout(f):
            print(CPP_HEADER)

            print("const uint8_t pack_utf32_to_utf16le[16][16] = {")
            for row in utf32_to_utf16le():
                print("{%s}," % format_array(row))
            print("};")

            print()

            print("const uint8_t pack_utf32_to_utf16be[16][16] = {")
            for row in utf32_to_utf16be():
                print("{%s}," % format_array(row))
            print("};")

            print()
            print(CPP_FOOTER)


if __name__ == '__main__':
    main()
