sort-cli: rework
This commit is contained in:
80
sort-cli/content.go
Normal file
80
sort-cli/content.go
Normal file
@ -0,0 +1,80 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"golang.org/x/exp/slices"
|
||||
"io"
|
||||
"log"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type content [][]byte
|
||||
|
||||
func (c *content) Sort(reverse bool) {
|
||||
slices.SortFunc(*c, func(a, b []byte) int {
|
||||
if reverse {
|
||||
a, b = b, a
|
||||
}
|
||||
|
||||
return slices.Compare(a, b)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *content) Uniques() {
|
||||
m := make(map[string]struct{}, len(*c))
|
||||
|
||||
*c = slices.DeleteFunc[content, []byte](*c, func(line []byte) bool {
|
||||
if _, ok := m[string(line)]; !ok {
|
||||
m[string(line)] = struct{}{}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (c *content) String() string {
|
||||
lines := *c
|
||||
|
||||
var n int
|
||||
for _, line := range lines {
|
||||
n += len(line)
|
||||
}
|
||||
n += len(lines) * len("\n")
|
||||
|
||||
var sb strings.Builder
|
||||
sb.Grow(n)
|
||||
|
||||
for i, line := range lines {
|
||||
if i > 0 {
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
|
||||
for _, rn := range line {
|
||||
sb.WriteByte(rn)
|
||||
}
|
||||
}
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func (c *content) Load(r io.Reader) {
|
||||
br := bufio.NewReader(r)
|
||||
|
||||
for {
|
||||
line, _, err := br.ReadLine()
|
||||
if err != nil {
|
||||
if errors.Is(io.EOF, err) {
|
||||
*c = append(*c, line)
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
log.Fatalf("can't read line: %s", err)
|
||||
}
|
||||
|
||||
*c = append(*c, line)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user