Damien George | 55baff4 | 2014-01-21 21:40:13 +0000 | [diff] [blame] | 1 | import argparse |
| 2 | import re |
| 3 | |
| 4 | # this must match the equivalent function in qstr.c |
| 5 | def compute_hash(qstr): |
| 6 | hash = 0 |
| 7 | for char in qstr: |
| 8 | hash += ord(char) |
| 9 | return hash & 0xffff |
| 10 | |
| 11 | def do_work(infiles): |
| 12 | # read the qstrs in from the input files |
| 13 | qstrs = [] |
| 14 | for infile in infiles: |
| 15 | with open(infile, 'rt') as f: |
| 16 | line_number = 0 |
| 17 | for line in f: |
| 18 | line_number += 1 |
| 19 | line = line.strip() |
| 20 | |
| 21 | # ignore blank lines and comments |
| 22 | if len(line) == 0 or line.startswith('//'): |
| 23 | continue |
| 24 | |
| 25 | # verify line is of the correct form |
| 26 | match = re.match(r'Q\(([0-9A-Za-z_]+)\)$', line) |
| 27 | if not match: |
| 28 | print('({}:{}) bad qstr format, got {}'.format(infile, line_number, line)) |
| 29 | return False |
| 30 | |
| 31 | # get the qstr value |
| 32 | qstr = match.group(1) |
| 33 | |
| 34 | # don't add duplicates |
| 35 | if qstr in qstrs: |
| 36 | continue |
| 37 | |
| 38 | # add the qstr to the list |
| 39 | qstrs.append(qstr) |
| 40 | |
| 41 | # process the qstrs, printing out the generated C header file |
| 42 | print('// This file was automatically generated by makeqstrdata.py') |
Dave Hylands | 7a996b1 | 2014-01-21 15:28:27 -0800 | [diff] [blame] | 43 | print('') |
Damien George | 55baff4 | 2014-01-21 21:40:13 +0000 | [diff] [blame] | 44 | for qstr in qstrs: |
| 45 | qhash = compute_hash(qstr) |
| 46 | qlen = len(qstr) |
| 47 | print('Q({}, (const byte*)"\\x{:02x}\\x{:02x}\\x{:02x}\\x{:02x}" "{}")'.format(qstr, qhash & 0xff, (qhash >> 8) & 0xff, qlen & 0xff, (qlen >> 8) & 0xff, qstr)) |
| 48 | |
| 49 | return True |
| 50 | |
| 51 | def main(): |
| 52 | arg_parser = argparse.ArgumentParser(description='Process raw qstr file and output qstr data with length, hash and data bytes') |
| 53 | arg_parser.add_argument('files', nargs='+', help='input file(s)') |
| 54 | args = arg_parser.parse_args() |
| 55 | |
| 56 | result = do_work(args.files) |
| 57 | if not result: |
| 58 | print('exiting with error code') |
| 59 | exit(1) |
| 60 | |
| 61 | if __name__ == "__main__": |
| 62 | main() |