blob: 3bd28fe0c8fce7f67bf5c099e29d35d86c3d2599 [file] [log] [blame]
Austin Schuh0de30f32020-12-06 12:44:28 -08001#!/usr/bin/python3
2
3# Application to generate C++ code with a binary flatbuffer file embedded in it
4# as a Span.
5
6import sys
7from pathlib import Path
8
9
10def main(argv):
James Kuszmaul6b609292023-01-28 15:58:43 -080011 if len(argv) != 5:
12 print(
13 f"Incorrect number of arguments {len(argv)} to flatbuffers_static."
14 )
15 print(argv)
Austin Schuh0de30f32020-12-06 12:44:28 -080016 return 1
17
18 input_path = sys.argv[1]
19 output_path = sys.argv[2]
20 function = sys.argv[3].split("::")
James Kuszmaul6b609292023-01-28 15:58:43 -080021 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 Schuh0de30f32020-12-06 12:44:28 -080031 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
78if __name__ == '__main__':
79 sys.exit(main(sys.argv))