Austin Schuh | 0de30f3 | 2020-12-06 12:44:28 -0800 | [diff] [blame^] | 1 | #!/usr/bin/python3 |
| 2 | |
| 3 | # Application to generate C++ code with a binary flatbuffer file embedded in it |
| 4 | # as a Span. |
| 5 | |
| 6 | import sys |
| 7 | from pathlib import Path |
| 8 | |
| 9 | |
| 10 | def main(argv): |
| 11 | if len(argv) != 4: |
| 12 | return 1 |
| 13 | |
| 14 | input_path = sys.argv[1] |
| 15 | output_path = sys.argv[2] |
| 16 | function = sys.argv[3].split("::") |
| 17 | include_guard = output_path.replace('/', '_').replace('-', '_').replace( |
| 18 | '.', '_').upper() + '_' |
| 19 | |
| 20 | output_prefix = [ |
| 21 | b'#ifndef ' + include_guard.encode(), |
| 22 | b'#define ' + include_guard.encode(), |
| 23 | b'', |
| 24 | b'#include "absl/types/span.h"', |
| 25 | b'', |
| 26 | ] |
| 27 | |
| 28 | for f in function[:-1]: |
| 29 | output_prefix.append(b'namespace ' + f.encode() + b' {') |
| 30 | |
| 31 | output_prefix.append(b'') |
| 32 | output_prefix.append(b'inline absl::Span<const uint8_t> ' + |
| 33 | function[-1].encode() + b'() {') |
| 34 | |
| 35 | output_suffix = [ |
| 36 | b' return absl::Span<const uint8_t>(reinterpret_cast<const uint8_t*>(kData), sizeof(kData));', |
| 37 | b'}' |
| 38 | ] |
| 39 | output_suffix.append(b'') |
| 40 | |
| 41 | for f in function[:-1]: |
| 42 | output_suffix.append(b'} // namespace ' + f.encode()) |
| 43 | |
| 44 | output_suffix.append(b'') |
| 45 | output_suffix.append(b'#endif // ' + include_guard.encode()) |
| 46 | |
| 47 | with open(input_path, 'rb') as binary_file: |
| 48 | bfbs = binary_file.read() |
| 49 | |
| 50 | # Write out the header file |
| 51 | with open(output_path, 'wb') as output: |
| 52 | for line in output_prefix: |
| 53 | output.write(line) |
| 54 | output.write(b'\n') |
| 55 | output.write(b' alignas(64) static constexpr char kData[] = "') |
| 56 | for byte in bfbs: |
| 57 | output.write(b'\\x' + (b'%x' % byte).zfill(2)) |
| 58 | output.write(b'";\n') |
| 59 | for line in output_suffix: |
| 60 | output.write(line) |
| 61 | output.write(b'\n') |
| 62 | |
| 63 | |
| 64 | if __name__ == '__main__': |
| 65 | sys.exit(main(sys.argv)) |