File: bitdump.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2020-2025 pacman64
   5 
   6 Permission is hereby granted, free of charge, to any person obtaining a copy of
   7 this software and associated documentation files (the “Software”), to deal
   8 in the Software without restriction, including without limitation the rights to
   9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10 of the Software, and to permit persons to whom the Software is furnished to do
  11 so, subject to the following conditions:
  12 
  13 The above copyright notice and this permission notice shall be included in all
  14 copies or substantial portions of the Software.
  15 
  16 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22 SOFTWARE.
  23 */
  24 
  25 /*
  26 Single-file source-code for bitdump.
  27 
  28 To compile a smaller-sized command-line app, you can use the `go` command as
  29 follows:
  30 
  31 go build -ldflags "-s -w" -trimpath bitdump.go
  32 */
  33 
  34 package main
  35 
  36 import (
  37     "bufio"
  38     "errors"
  39     "io"
  40     "os"
  41     "strconv"
  42 )
  43 
  44 // Note: the code is avoiding using the fmt package to save hundreds of
  45 // kilobytes on the resulting executable, which is a noticeable difference.
  46 
  47 const info = `
  48 bitdump [options...] [filenames...]
  49 
  50 
  51 Show all bits for all input bytes, starting each output line with the
  52 leading byte's offset.
  53 
  54 All (optional) leading options start with either single or double-dash:
  55 
  56     -h          show this help message
  57     -help       show this help message
  58 `
  59 
  60 const itemsPerLine = 8
  61 
  62 const errorStyle = "\x1b[31m"
  63 
  64 // errNoMoreOutput is a dummy error, whose message is ignored, and which
  65 // causes the app to quit immediately and successfully
  66 var errNoMoreOutput = errors.New(`no more output`)
  67 
  68 func main() {
  69     if len(os.Args) > 1 {
  70         switch os.Args[1] {
  71         case `-h`, `--h`, `-help`, `--help`:
  72             os.Stderr.WriteString(info[1:])
  73             return
  74         }
  75     }
  76 
  77     if err := run(os.Stdout, os.Args[1:]); isActualError(err) {
  78         os.Stderr.WriteString(errorStyle)
  79         os.Stderr.WriteString(err.Error())
  80         os.Stderr.WriteString("\x1b[0m\n")
  81         os.Exit(1)
  82     }
  83 }
  84 
  85 func run(w io.Writer, args []string) error {
  86     offset := 0
  87     bw := bufio.NewWriter(w)
  88     defer func() {
  89         if offset%itemsPerLine == 0 && offset > 0 {
  90             bw.WriteByte('\n')
  91         }
  92         bw.Flush()
  93     }()
  94 
  95     if len(args) == 0 {
  96         return bitdump(bw, os.Stdin, &offset)
  97     }
  98 
  99     for _, name := range args {
 100         if err := handleFile(bw, name, &offset); err != nil {
 101             return err
 102         }
 103     }
 104     return nil
 105 }
 106 
 107 func handleFile(w *bufio.Writer, name string, offset *int) error {
 108     if name == `` || name == `-` {
 109         return bitdump(w, os.Stdin, offset)
 110     }
 111 
 112     f, err := os.Open(name)
 113     if err != nil {
 114         return errors.New(`can't read from file named "` + name + `"`)
 115     }
 116     defer f.Close()
 117 
 118     return bitdump(w, f, offset)
 119 }
 120 
 121 // isActualError is to figure out whether not to ignore an error, and thus
 122 // show it as an error message
 123 func isActualError(err error) bool {
 124     return err != nil && err != io.EOF && err != errNoMoreOutput
 125 }
 126 
 127 func bitdump(w *bufio.Writer, r io.Reader, offset *int) error {
 128     var buf [16 * 1024]byte
 129     defer w.Flush()
 130 
 131     for {
 132         n, err := r.Read(buf[:])
 133         if n < 1 && err == io.EOF {
 134             return nil
 135         }
 136 
 137         if err != nil && err != io.EOF {
 138             return err
 139         }
 140 
 141         chunk := buf[:n]
 142 
 143         for len(chunk) >= itemsPerLine {
 144             if err := emitChunk(w, chunk[:itemsPerLine], offset); err != nil {
 145                 return err
 146             }
 147 
 148             chunk = chunk[itemsPerLine:]
 149             *offset += itemsPerLine
 150         }
 151 
 152         if len(chunk) > 0 {
 153             if err := emitChunk(w, chunk, offset); err != nil {
 154                 return err
 155             }
 156 
 157             *offset += len(chunk)
 158         }
 159     }
 160 }
 161 
 162 func emitChunk(w *bufio.Writer, chunk []byte, offset *int) error {
 163     const pad = `00000000`
 164     var str [24]byte
 165 
 166     if *offset%itemsPerLine == 0 {
 167         if *offset > 0 {
 168             if err := w.WriteByte('\n'); err != nil {
 169                 // assume a write error is the consequence of stdout
 170                 // being closed, perhaps by another app along a pipe
 171                 return errNoMoreOutput
 172             }
 173         }
 174 
 175         s := strconv.AppendInt(str[:0], int64(*offset), 10)
 176         // pad small offsets with leading zeros
 177         if len(s) < len(pad) {
 178             w.WriteString(pad[len(s):])
 179         }
 180         w.Write(s)
 181     }
 182 
 183     for _, b := range chunk {
 184         w.WriteByte(' ')
 185         w.WriteString(bits[b])
 186     }
 187     return nil
 188 }
 189 
 190 /*
 191 tlp = '(f"{bin(v)[2:]:>08}" for v in range(256))' | lineup 6 |
 192 gsub '\t' '`, `' | tlp 'f"\t`{l}`,"'
 193 */
 194 var bits = [256]string{
 195     `00000000`, `00000001`, `00000010`, `00000011`, `00000100`, `00000101`,
 196     `00000110`, `00000111`, `00001000`, `00001001`, `00001010`, `00001011`,
 197     `00001100`, `00001101`, `00001110`, `00001111`, `00010000`, `00010001`,
 198     `00010010`, `00010011`, `00010100`, `00010101`, `00010110`, `00010111`,
 199     `00011000`, `00011001`, `00011010`, `00011011`, `00011100`, `00011101`,
 200     `00011110`, `00011111`, `00100000`, `00100001`, `00100010`, `00100011`,
 201     `00100100`, `00100101`, `00100110`, `00100111`, `00101000`, `00101001`,
 202     `00101010`, `00101011`, `00101100`, `00101101`, `00101110`, `00101111`,
 203     `00110000`, `00110001`, `00110010`, `00110011`, `00110100`, `00110101`,
 204     `00110110`, `00110111`, `00111000`, `00111001`, `00111010`, `00111011`,
 205     `00111100`, `00111101`, `00111110`, `00111111`, `01000000`, `01000001`,
 206     `01000010`, `01000011`, `01000100`, `01000101`, `01000110`, `01000111`,
 207     `01001000`, `01001001`, `01001010`, `01001011`, `01001100`, `01001101`,
 208     `01001110`, `01001111`, `01010000`, `01010001`, `01010010`, `01010011`,
 209     `01010100`, `01010101`, `01010110`, `01010111`, `01011000`, `01011001`,
 210     `01011010`, `01011011`, `01011100`, `01011101`, `01011110`, `01011111`,
 211     `01100000`, `01100001`, `01100010`, `01100011`, `01100100`, `01100101`,
 212     `01100110`, `01100111`, `01101000`, `01101001`, `01101010`, `01101011`,
 213     `01101100`, `01101101`, `01101110`, `01101111`, `01110000`, `01110001`,
 214     `01110010`, `01110011`, `01110100`, `01110101`, `01110110`, `01110111`,
 215     `01111000`, `01111001`, `01111010`, `01111011`, `01111100`, `01111101`,
 216     `01111110`, `01111111`, `10000000`, `10000001`, `10000010`, `10000011`,
 217     `10000100`, `10000101`, `10000110`, `10000111`, `10001000`, `10001001`,
 218     `10001010`, `10001011`, `10001100`, `10001101`, `10001110`, `10001111`,
 219     `10010000`, `10010001`, `10010010`, `10010011`, `10010100`, `10010101`,
 220     `10010110`, `10010111`, `10011000`, `10011001`, `10011010`, `10011011`,
 221     `10011100`, `10011101`, `10011110`, `10011111`, `10100000`, `10100001`,
 222     `10100010`, `10100011`, `10100100`, `10100101`, `10100110`, `10100111`,
 223     `10101000`, `10101001`, `10101010`, `10101011`, `10101100`, `10101101`,
 224     `10101110`, `10101111`, `10110000`, `10110001`, `10110010`, `10110011`,
 225     `10110100`, `10110101`, `10110110`, `10110111`, `10111000`, `10111001`,
 226     `10111010`, `10111011`, `10111100`, `10111101`, `10111110`, `10111111`,
 227     `11000000`, `11000001`, `11000010`, `11000011`, `11000100`, `11000101`,
 228     `11000110`, `11000111`, `11001000`, `11001001`, `11001010`, `11001011`,
 229     `11001100`, `11001101`, `11001110`, `11001111`, `11010000`, `11010001`,
 230     `11010010`, `11010011`, `11010100`, `11010101`, `11010110`, `11010111`,
 231     `11011000`, `11011001`, `11011010`, `11011011`, `11011100`, `11011101`,
 232     `11011110`, `11011111`, `11100000`, `11100001`, `11100010`, `11100011`,
 233     `11100100`, `11100101`, `11100110`, `11100111`, `11101000`, `11101001`,
 234     `11101010`, `11101011`, `11101100`, `11101101`, `11101110`, `11101111`,
 235     `11110000`, `11110001`, `11110010`, `11110011`, `11110100`, `11110101`,
 236     `11110110`, `11110111`, `11111000`, `11111001`, `11111010`, `11111011`,
 237     `11111100`, `11111101`, `11111110`, `11111111`,
 238 }