|
| 1 | +package internal |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | +) |
| 7 | + |
| 8 | +func Hexdump(data []byte) string { |
| 9 | + prevRow := make([]byte, 16) |
| 10 | + |
| 11 | + var buf bytes.Buffer |
| 12 | + var dupWritten bool |
| 13 | + for i := 0; i < len(data); i += 16 { |
| 14 | + row := make([]byte, 16) |
| 15 | + copy(row, data[i:]) |
| 16 | + |
| 17 | + // Write out one line of asterisks to show that we just have duplicate rows. |
| 18 | + if i != 0 && i+16 < len(data) && bytes.Equal(row, prevRow) { |
| 19 | + if !dupWritten { |
| 20 | + dupWritten = true |
| 21 | + fmt.Fprintln(&buf, "***") |
| 22 | + } |
| 23 | + continue |
| 24 | + } |
| 25 | + |
| 26 | + // Track previous row so we know when we have duplicates. |
| 27 | + copy(prevRow, row) |
| 28 | + dupWritten = false |
| 29 | + |
| 30 | + fmt.Fprintf(&buf, "%08x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x |%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s|\n", i, |
| 31 | + row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], |
| 32 | + row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[15], |
| 33 | + toChar(row[0]), toChar(row[1]), toChar(row[2]), toChar(row[3]), toChar(row[4]), toChar(row[5]), toChar(row[6]), toChar(row[7]), |
| 34 | + toChar(row[8]), toChar(row[9]), toChar(row[10]), toChar(row[11]), toChar(row[12]), toChar(row[13]), toChar(row[14]), toChar(row[15]), |
| 35 | + ) |
| 36 | + } |
| 37 | + return buf.String() |
| 38 | +} |
| 39 | + |
| 40 | +func toChar(b byte) string { |
| 41 | + if b < 32 || b > 126 { |
| 42 | + return "." |
| 43 | + } |
| 44 | + return string(b) |
| 45 | +} |
0 commit comments