Skip to content

Commit

Permalink
optimize: avoid allocations/printf for hex offset
Browse files Browse the repository at this point in the history
27.7 ns/op
  • Loading branch information
felixge committed Jan 11, 2015
1 parent 859ebc4 commit d653d2f
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions xxd.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"os"
"strconv"
)

func main() {
Expand Down Expand Up @@ -40,19 +41,24 @@ var (
)

func XXD(r io.Reader, w io.Writer) error {
line_offset := 0
var line_offset int64

r = bufio.NewReader(r)
buf := make([]byte, 16)
hexChar := make([]byte, 2)
zeroHeader := []byte("0000000: ")
hexOffset := make([]byte, 6)
for {
n, err := io.ReadFull(r, buf)
if n == 0 || err == io.EOF {
break
}

// Line offset
fmt.Fprintf(w, "%06x0: ", line_offset)
hexOffset = strconv.AppendInt(hexOffset[0:0], line_offset, 16)
w.Write(zeroHeader[0:(6 - len(hexOffset))])
w.Write(hexOffset)
w.Write(zeroHeader[6:])
line_offset++

// Hex values
Expand Down

0 comments on commit d653d2f

Please sign in to comment.