Files
h/sort-cli/content.go

85 lines
1.1 KiB
Go

package sortcli
import (
"bufio"
"errors"
"io"
"log"
"strings"
"golang.org/x/exp/slices"
)
// NL New line constant
const NL = "\n"
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(NL)
var sb strings.Builder
sb.Grow(n)
for i, line := range lines {
if i > 0 {
sb.WriteString(NL)
}
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)
}
}