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): |
James Kuszmaul | 6b60929 | 2023-01-28 15:58:43 -0800 | [diff] [blame] | 11 | if len(argv) != 5: |
| 12 | print( |
| 13 | f"Incorrect number of arguments {len(argv)} to flatbuffers_static." |
| 14 | ) |
| 15 | print(argv) |
Austin Schuh | 0de30f3 | 2020-12-06 12:44:28 -0800 | [diff] [blame] | 16 | return 1 |
| 17 | |
| 18 | input_path = sys.argv[1] |
| 19 | output_path = sys.argv[2] |
| 20 | function = sys.argv[3].split("::") |
James Kuszmaul | 6b60929 | 2023-01-28 15:58:43 -0800 | [diff] [blame] | 21 | bfbs_name = sys.argv[4] |
| 22 | if bfbs_name != '-': |
| 23 | inputs = input_path.split(' ') |
| 24 | valid_paths = [path for path in inputs if path.endswith(bfbs_name)] |
| 25 | if len(valid_paths) != 1: |
| 26 | print( |
| 27 | f"Expected exactly one match for {bfbs_name}; got {valid_paths}." |
| 28 | ) |
| 29 | return 1 |
| 30 | input_path = valid_paths[0] |
Austin Schuh | 0de30f3 | 2020-12-06 12:44:28 -0800 | [diff] [blame] | 31 | include_guard = output_path.replace('/', '_').replace('-', '_').replace( |
| 32 | '.', '_').upper() + '_' |
| 33 | |
| 34 | output_prefix = [ |
| 35 | b'#ifndef ' + include_guard.encode(), |
| 36 | b'#define ' + include_guard.encode(), |
| 37 | b'', |
| 38 | b'#include "absl/types/span.h"', |
| 39 | b'', |
| 40 | ] |
| 41 | |
| 42 | for f in function[:-1]: |
| 43 | output_prefix.append(b'namespace ' + f.encode() + b' {') |
| 44 | |
| 45 | output_prefix.append(b'') |
| 46 | output_prefix.append(b'inline absl::Span<const uint8_t> ' + |
| 47 | function[-1].encode() + b'() {') |
| 48 | |
| 49 | output_suffix = [ |
| 50 | b' return absl::Span<const uint8_t>(reinterpret_cast<const uint8_t*>(kData), sizeof(kData));', |
| 51 | b'}' |
| 52 | ] |
| 53 | output_suffix.append(b'') |
| 54 | |
| 55 | for f in function[:-1]: |
| 56 | output_suffix.append(b'} // namespace ' + f.encode()) |
| 57 | |
| 58 | output_suffix.append(b'') |
| 59 | output_suffix.append(b'#endif // ' + include_guard.encode()) |
| 60 | |
| 61 | with open(input_path, 'rb') as binary_file: |
| 62 | bfbs = binary_file.read() |
| 63 | |
| 64 | # Write out the header file |
| 65 | with open(output_path, 'wb') as output: |
| 66 | for line in output_prefix: |
| 67 | output.write(line) |
| 68 | output.write(b'\n') |
| 69 | output.write(b' alignas(64) static constexpr char kData[] = "') |
| 70 | for byte in bfbs: |
| 71 | output.write(b'\\x' + (b'%x' % byte).zfill(2)) |
| 72 | output.write(b'";\n') |
| 73 | for line in output_suffix: |
| 74 | output.write(line) |
| 75 | output.write(b'\n') |
| 76 | |
| 77 | |
| 78 | if __name__ == '__main__': |
| 79 | sys.exit(main(sys.argv)) |