length: add MinLengthBytes / MaxLengthBytes
CI / test (pull_request) Successful in 34s
CI / test (push) Successful in 37s

MinLength/MaxLength now count runes, leaving no way to bound a string by
its byte size -- still wanted for fixed-width columns and wire-format
fields. Add the byte-counting pair alongside them, with their own "%d
bytes" sentinels (ErrMustHaveMoreBytes / ErrMustHaveFewerBytes).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit was merged in pull request #11.
This commit is contained in:
2026-09-07 16:48:29 +01:00
co-authored by Claude Sonnet 5
parent 4e2e05c1b9
commit 164dcbf367
3 changed files with 96 additions and 3 deletions
+66
View File
@@ -73,3 +73,69 @@ func TestMinLength(t *testing.T) {
}
}
}
func ExampleMaxLengthBytes() {
testMaxLengthBytes := MaxLengthBytes(8)
fmt.Println(testMaxLengthBytes("cafés round the world"))
// Output: must have no more than 8 bytes
}
func ExampleMinLengthBytes() {
testMinLengthBytes := MinLengthBytes(8)
fmt.Println(testMinLengthBytes("2short"))
// Output: must have at least 8 bytes
}
func TestMaxLengthBytes(t *testing.T) {
testCases := map[int]map[string]error{
8: {
"abcd": nil,
"abcdefgh": nil,
"abcdéfg": nil, // 7 runes, 8 bytes
"abcdéfgh": ErrMustHaveFewerBytes.With(8), // 8 runes, 9 bytes
"abcdefghi": ErrMustHaveFewerBytes.With(8),
},
}
for setup, values := range testCases {
testMaxLengthBytes := MaxLengthBytes(setup)
for input, want := range values {
t.Run(fmt.Sprintf("%d/%s", setup, input), func(t *testing.T) {
got := testMaxLengthBytes(input)
if !errors.Is(got, want) {
t.Error("got", got)
t.Error("want", want)
}
})
}
}
}
func TestMinLengthBytes(t *testing.T) {
testCases := map[int]map[string]error{
8: {
"abcd": ErrMustHaveMoreBytes.With(8),
"abcdefg": ErrMustHaveMoreBytes.With(8),
"abcdéf": ErrMustHaveMoreBytes.With(8), // 6 runes, 7 bytes
"abcdéfg": nil, // 7 runes, 8 bytes
"abcdefgh": nil,
},
}
for setup, values := range testCases {
testMinLengthBytes := MinLengthBytes(setup)
for input, want := range values {
t.Run(fmt.Sprintf("%d/%s", setup, input), func(t *testing.T) {
got := testMinLengthBytes(input)
if !errors.Is(got, want) {
t.Error("got", got)
t.Error("want", want)
}
})
}
}
}