@@ -44,48 +44,44 @@ def _ParseArgs():
4444 return parser .parse_args ()
4545
4646
47- def _FormatAsUint64LittleEndian (s ):
48- """Formats a string as uint64_t value in little endian order."""
49- for _ in range (len (s ), 8 ):
50- s += b'\0 '
51- s = s [::- 1 ] # Reverse the string
52- return '0x' + s .hex ()
47+ def _EmbedAsUint64Array (input_path , name , output_file ):
48+ """Embed file as uint64_t array using EmbeddedFile struct."""
5349
50+ output_file .write ("""\
51+ #ifdef MOZC_EMBEDDED_FILE_%(name)s
52+ #error "%(name)s was already included or defined elsewhere"
53+ #else
54+ #define MOZC_EMBEDDED_FILE_%(name)s
55+ constexpr uint64_t %(name)s_data[] = {
56+ """ % {'name' : name })
5457
55- def main ():
56- args = _ParseArgs ()
57- args .output .write (
58- '#ifdef MOZC_EMBEDDED_FILE_%(name)s\n '
59- '#error "%(name)s was already included or defined elsewhere"\n '
60- '#else\n '
61- '#define MOZC_EMBEDDED_FILE_%(name)s\n '
62- 'constexpr uint64_t %(name)s_data[] = {'
63- % {'name' : args .name }
64- )
58+ with open (input_path , 'rb' ) as infile :
59+ # Read in chunks of 32 bytes (representing one printed line of 4 uint64_t
60+ # values)
61+ while line_chunk := infile .read (32 ):
62+ # Split the 32-byte row into 8-byte chunks
63+ hex_strings = []
64+ for i in range (0 , len (line_chunk ), 8 ):
65+ chunk_bytes = line_chunk [i : i + 8 ]
66+ chunk_int = int .from_bytes (chunk_bytes , byteorder = 'little' )
67+ # Format C++ hexadecimal string literals for each chunk
68+ hex_strings .append (f'0x{ chunk_int :016x} ' )
69+ # Write the entire row to the output file (indenting with 2 spaces)
70+ output_file .write (' ' + ', ' .join (hex_strings ) + ',\n ' )
6571
66- with open (args .input , 'rb' ) as infile :
67- i = 0
68- while True :
69- chunk = infile .read (8 )
70- if not chunk :
71- break
72- if i % 4 == 0 :
73- args .output .write ('\n ' )
74- else :
75- args .output .write (' ' )
76- args .output .write (_FormatAsUint64LittleEndian (chunk ))
77- args .output .write (',' )
78- i = i + 1
72+ output_file .write ("""\
73+ };
74+ constexpr EmbeddedFile %(name)s = {
75+ %(name)s_data,
76+ %(size)d,
77+ };
78+ #endif // MOZC_EMBEDDED_FILE_%(name)s
79+ """ % {'name' : name , 'size' : os .stat (input_path ).st_size })
7980
80- args .output .write (
81- '\n };\n '
82- 'constexpr EmbeddedFile %(name)s = {\n '
83- ' %(name)s_data,\n '
84- ' %(size)d,\n '
85- '};\n '
86- '#endif // MOZC_EMBEDDED_FILE_%(name)s\n '
87- % {'name' : args .name , 'size' : os .stat (args .input ).st_size }
88- )
81+
82+ def main ():
83+ args = _ParseArgs ()
84+ _EmbedAsUint64Array (args .input , args .name , args .output )
8985
9086
9187if __name__ == '__main__' :
0 commit comments