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