Skip to content

Commit

Permalink
cmds/exp/freq: reduce allocations, simplify printing
Browse files Browse the repository at this point in the history
Signed-off-by: Siarhiej Siemianczuk <pdp.eleven11@gmail.com>
  • Loading branch information
binjip978 committed Oct 28, 2023
1 parent f57368a commit 801320f
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions cmds/exp/freq/freq.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ import (
"io"
"log"
"os"
"unicode/utf8"
"sort"
"unicode"
)

type params struct {
Expand All @@ -48,8 +49,8 @@ type cmd struct {
stdin io.Reader
stdout io.Writer
stderr io.Writer
freq map[rune]uint64
args []string
freq [utf8.MaxRune + 1]uint64
params
}

Expand All @@ -62,6 +63,7 @@ func command(stdin io.Reader, stdout io.Writer, stderr io.Writer, p params, args
stdin: stdin,
stdout: stdout,
stderr: stderr,
freq: make(map[rune]uint64),
params: p,
args: args,
}
Expand All @@ -81,30 +83,36 @@ func (c *cmd) run() error {
c.doFreq(c.stdin)
}

keys := make([]rune, 0, len(c.freq))
for k := range c.freq {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return keys[i] < keys[j]
})

b := bufio.NewWriterSize(c.stdout, 8192*4)
for i, v := range c.freq {
if v == 0 {
continue
}
for _, r := range keys {
count := c.freq[r]

if c.dec {
fmt.Fprintf(b, "%3d ", i)
fmt.Fprintf(b, "%3d ", r)
}
if c.oct {
fmt.Fprintf(b, "%.3o ", i)
fmt.Fprintf(b, "%.3o ", r)
}
if c.hex {
fmt.Fprintf(b, "%.2x ", i)
fmt.Fprintf(b, "%.2x ", r)
}
if c.chr {
if i <= 0x20 || (i >= 0x7f && i < 0xa0) || (i > 0xff && !(c.utf)) {
b.WriteString("- ")
} else {
b.WriteRune(rune(i))
if unicode.IsPrint(r) {
b.WriteRune(r)
b.WriteString(" ")
} else {
b.WriteString("- ")
}
}
fmt.Fprintf(b, "%8d\n", v)
fmt.Fprintf(b, "%8d\n", count)
}
return b.Flush()
}
Expand Down Expand Up @@ -135,7 +143,7 @@ func (c *cmd) doFreq(f io.Reader) {
}
return
}
c.freq[ch]++
c.freq[rune(ch)]++
}
}
}
Expand Down

0 comments on commit 801320f

Please sign in to comment.