()
| 37 | |
| 38 | |
| 39 | def main(): |
| 40 | p = argparse.ArgumentParser() |
| 41 | p.add_argument('corpus', metavar='FILE', nargs='+') |
| 42 | args = p.parse_args() |
| 43 | |
| 44 | # Get frequency counts of each byte. |
| 45 | freqs = Counter() |
| 46 | for i in range(0, 256): |
| 47 | freqs[i] = 0 |
| 48 | |
| 49 | eprint('reading entire corpus into memory') |
| 50 | corpus = [] |
| 51 | for fpath in args.corpus: |
| 52 | corpus.append(open(fpath, 'rb').read()) |
| 53 | |
| 54 | eprint('computing byte frequencies') |
| 55 | for c in corpus: |
| 56 | for byte in c: |
| 57 | freqs[byte] += 1.0 / float(len(c)) |
| 58 | |
| 59 | eprint('writing Rust code') |
| 60 | # Get the rank of each byte. A lower rank => lower relative frequency. |
| 61 | rank = [0] * 256 |
| 62 | for i, (byte, _) in enumerate(freqs.most_common()): |
| 63 | # print(byte) |
| 64 | rank[byte] = 255 - i |
| 65 | |
| 66 | # Forcefully set the highest rank possible for bytes that start multi-byte |
| 67 | # UTF-8 sequences. The idea here is that a continuation byte will be more |
| 68 | # discerning in a homogenous haystack. |
| 69 | for byte in range(0xC0, 0xFF + 1): |
| 70 | rank[byte] = 255 |
| 71 | |
| 72 | # Now write Rust. |
| 73 | olines = ['pub const BYTE_FREQUENCIES: [u8; 256] = ['] |
| 74 | for byte in range(256): |
| 75 | olines.append(' %3d, // %r' % (rank[byte], chr(byte))) |
| 76 | olines.append('];') |
| 77 | |
| 78 | print(preamble) |
| 79 | print('\n'.join(olines)) |
| 80 | |
| 81 | if __name__ == '__main__': |
| 82 | main() |
no test coverage detected