Skip to content

Commit d653d2f

Browse files
committed
optimize: avoid allocations/printf for hex offset
27.7 ns/op
1 parent 859ebc4 commit d653d2f

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

xxd.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"io"
88
"os"
9+
"strconv"
910
)
1011

1112
func main() {
@@ -40,19 +41,24 @@ var (
4041
)
4142

4243
func XXD(r io.Reader, w io.Writer) error {
43-
line_offset := 0
44+
var line_offset int64
4445

4546
r = bufio.NewReader(r)
4647
buf := make([]byte, 16)
4748
hexChar := make([]byte, 2)
49+
zeroHeader := []byte("0000000: ")
50+
hexOffset := make([]byte, 6)
4851
for {
4952
n, err := io.ReadFull(r, buf)
5053
if n == 0 || err == io.EOF {
5154
break
5255
}
5356

5457
// Line offset
55-
fmt.Fprintf(w, "%06x0: ", line_offset)
58+
hexOffset = strconv.AppendInt(hexOffset[0:0], line_offset, 16)
59+
w.Write(zeroHeader[0:(6 - len(hexOffset))])
60+
w.Write(hexOffset)
61+
w.Write(zeroHeader[6:])
5662
line_offset++
5763

5864
// Hex values

0 commit comments

Comments
 (0)