refactor: internal package
This commit is contained in:
33
internal/stringx/stringx.go
Normal file
33
internal/stringx/stringx.go
Normal file
@@ -0,0 +1,33 @@
|
||||
// Package stringx provides helper functions for working with strings.
|
||||
package stringx
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
var compactRE = regexp.MustCompile(`\s+`)
|
||||
|
||||
// Shorten shortens a string to a specified number of characters.
|
||||
func Shorten(s string, maxlen int) string {
|
||||
var short = []rune(s)
|
||||
if len(short) > maxlen {
|
||||
short = short[:maxlen]
|
||||
short = append(short, []rune(" [truncated]")...)
|
||||
}
|
||||
return string(short)
|
||||
}
|
||||
|
||||
// Compact replaces consecutive whitespaces with a single space.
|
||||
func Compact(s string) string {
|
||||
return compactRE.ReplaceAllString(string(s), " ")
|
||||
}
|
||||
|
||||
// RandString generates a random string.
|
||||
// length must be even.
|
||||
func RandString(length int) string {
|
||||
b := make([]byte, length/2)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
51
internal/stringx/stringx_test.go
Normal file
51
internal/stringx/stringx_test.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package stringx
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestShorten(t *testing.T) {
|
||||
t.Run("shorten", func(t *testing.T) {
|
||||
const src = "Hello, World!"
|
||||
const want = "Hello [truncated]"
|
||||
got := Shorten(src, 5)
|
||||
if got != want {
|
||||
t.Errorf("expected %q, got %q", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("ignore", func(t *testing.T) {
|
||||
const src = "Hello, World!"
|
||||
const want = src
|
||||
got := Shorten(src, 20)
|
||||
if got != want {
|
||||
t.Errorf("expected %q, got %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCompact(t *testing.T) {
|
||||
t.Run("compact", func(t *testing.T) {
|
||||
const src = "go\nis awesome"
|
||||
const want = "go is awesome"
|
||||
got := Compact(src)
|
||||
if got != want {
|
||||
t.Errorf("expected %q, got %q", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("ignore", func(t *testing.T) {
|
||||
const src = "go is awesome"
|
||||
const want = src
|
||||
got := Compact(src)
|
||||
if got != want {
|
||||
t.Errorf("expected %q, got %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRandString(t *testing.T) {
|
||||
lengths := []int{2, 4, 6, 8, 10}
|
||||
for _, n := range lengths {
|
||||
s := RandString(n)
|
||||
if len(s) != n {
|
||||
t.Errorf("%d: expected len(s) = %d, got %d", n, n, len(s))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user