roulette/cmd/utils.go

103 lines
1.6 KiB
Go

/*
Copyright © 2022 Seednode <seednode@seedno.de>
*/
package cmd
import (
"bufio"
"os"
"strings"
)
type Exit struct{ Code int }
func Chunks(s string, chunkSize int) []string {
if len(s) == 0 {
return nil
}
if chunkSize >= len(s) {
return []string{s}
}
var chunks []string = make([]string, 0, (len(s)-1)/chunkSize+1)
currentLen := 0
currentStart := 0
for i := range s {
if currentLen == chunkSize {
chunks = append(chunks, s[currentStart:i])
currentLen = 0
currentStart = i
}
currentLen++
}
chunks = append(chunks, s[currentStart:])
return chunks
}
func CollectOutputs(output chan string, outputs chan<- []string) {
o := []string{}
for r := range output {
o = append(o, r)
}
outputs <- o
close(outputs)
}
func FirstN(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
func HandleExit() {
if e := recover(); e != nil {
if exit, ok := e.(Exit); ok == true {
os.Exit(exit.Code)
}
panic(e)
}
}
func ScanFile(dbfile string) (func(), *bufio.Scanner, error) {
readFile, err := os.Open(dbfile)
if err != nil {
return func() {}, nil, err
}
fileScanner := bufio.NewScanner(readFile)
buffer := make([]byte, 0, 64*1024)
fileScanner.Buffer(buffer, 1024*1024)
return func() { _ = readFile.Close() }, fileScanner, nil
}
func Strip(s string) string {
var result strings.Builder
for i := 0; i < len(s); i++ {
b := s[i]
if ('a' <= b && b <= 'z') ||
('A' <= b && b <= 'Z') ||
('0' <= b && b <= '9') {
result.WriteByte(b)
}
}
return result.String()
}