File: fizz.py
   1 #!/usr/bin/python3
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2024 pacman64
   6 #
   7 # Permission is hereby granted, free of charge, to any person obtaining a copy
   8 # of this software and associated documentation files (the “Software”), to deal
   9 # in the Software without restriction, including without limitation the rights
  10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11 # copies of the Software, and to permit persons to whom the Software is
  12 # furnished to do so, subject to the following conditions:
  13 #
  14 # The above copyright notice and this permission notice shall be included in
  15 # all copies or substantial portions of the Software.
  16 #
  17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23 # SOFTWARE.
  24 
  25 
  26 # fizz [options...]
  27 #
  28 # Emit random output bytes, to help `fuzz-test` other tools.
  29 #
  30 # All (optional) leading options start with either single or double-dash,
  31 # and most of them change the style/color used. Some of the options are,
  32 # shown in their single-dash form:
  33 #
  34 #     -h          show this help message
  35 #     -help       show this help message
  36 #
  37 #     -n          use the next argument as the output byte-count
  38 #     -ascii      only emit bytes in the valid ASCII text-range
  39 #     -text       only emit bytes in the valid ASCII text-range
  40 
  41 
  42 from random import randint, seed
  43 from sys import argv, exit, stderr, stdout
  44 from time import time
  45 
  46 
  47 # info is the help message shown when asked to
  48 info = '''
  49 fizz [options...]
  50 
  51 Emit random output bytes, to help `fuzz-test` other tools.
  52 
  53 All (optional) leading options start with either single or double-dash,
  54 and most of them change the style/color used. Some of the options are,
  55 shown in their single-dash form:
  56 
  57     -h          show this help message
  58     -help       show this help message
  59 
  60     -n          use the next argument as the output byte-count
  61     -ascii      only emit bytes in the valid ASCII text-range
  62     -text       only emit bytes in the valid ASCII text-range
  63 '''.strip()
  64 
  65 # handle standard help cmd-line options, quitting right away in that case
  66 if len(argv) == 2 and argv[1] in ('-h', '--h', '-help', '--help'):
  67     print(info, file=stderr)
  68     exit(0)
  69 
  70 
  71 def fail(msg, code: int = 1) -> None:
  72     '''Show the error message given, and quit the app right away.'''
  73     print(f'\x1b[31m{msg}\x1b[0m', file=stderr)
  74     exit(code)
  75 
  76 
  77 def emit_bytes(w, n: int, low: int = 0, high: int = 255) -> None:
  78     '''Here's what the whole script comes down to.'''
  79 
  80     # prevent trying to create non-positive-sized byte-arrays; using
  81     # negative values in their constructor causes exceptions
  82     if n < 1:
  83         return
  84 
  85     # looking up global vars is slower in older versions of python,
  86     # and this func is repeatedly looked-up in loops, possibly
  87     # millions of times
  88     local_randint = randint
  89 
  90     # considerably speed-up the whole script, by minimizing calls to
  91     # func `write` via pre-filled `chunks` of random bytes; using
  92     # size 64 doesn't seem to speed things further, compared to 32
  93     chunk_size = 32
  94     chunk = bytearray(chunk_size)
  95     while n >= chunk_size:
  96         for i in range(chunk_size):
  97             chunk[i] = local_randint(low, high)
  98         w.write(chunk)
  99         n -= chunk_size
 100 
 101     # don't forget the last few output bytes
 102     chunk = bytearray(n)
 103     for i in range(n):
 104         chunk[i] = local_randint(low, high)
 105     w.write(chunk)
 106 
 107 
 108 # handle command-line options
 109 n = 1_024
 110 text_only = False
 111 start_args = 1
 112 if start_args < len(argv):
 113     try:
 114         n = int(float(argv[start_args]))
 115         if n < 0:
 116             n = -n
 117         start_args += 1
 118     except:
 119         pass
 120 while start_args < len(argv) and argv[start_args].startswith('-'):
 121     l = argv[start_args].lstrip('-').lower()
 122     if l in ('ascii', 'text'):
 123         text_only = True
 124         start_args += 1
 125         continue
 126     if l in ('n'):
 127         if start_args + 1 >= len(argv):
 128             fail('missing actual byte-count in cmd-line arguments', 1)
 129         try:
 130             n = int(float(argv[start_args + 1]))
 131             if n < 0:
 132                 n = -n
 133         except Exception as e:
 134             fail(e, 1)
 135         start_args += 2
 136         continue
 137     break
 138 args = argv[start_args:]
 139 
 140 try:
 141     seed(time())
 142     if text_only:
 143         emit_bytes(stdout.buffer, n, ord(' '), ord('~'))
 144     else:
 145         emit_bytes(stdout.buffer, n, 0, 255)
 146 except BrokenPipeError:
 147     # quit quietly, instead of showing a confusing error message
 148     stderr.flush()
 149     stderr.close()
 150 except KeyboardInterrupt:
 151     # quit quietly, instead of showing a confusing error message
 152     stderr.flush()
 153     stderr.close()
 154     exit(2)
 155 except Exception as e:
 156     fail(e, 1)