Skip to content

Commit ff51e07

Browse files
committed
pkg/strings: add ByteAt, ByteSlice, and Runes
To replace indexing and slicing of string types. Change-Id: I040966df5cd7a0367dac73bb1920ec81a42ff29a Reviewed-on: https://cue-review.googlesource.com/c/cue/+/2879 Reviewed-by: Marcel van Lohuizen <[email protected]>
1 parent 97a56d7 commit ff51e07

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

cue/builtin_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package cue
1717
import (
1818
"fmt"
1919
"math/big"
20+
"strconv"
2021
"strings"
2122
"testing"
2223
)
@@ -140,6 +141,15 @@ func TestBuiltins(t *testing.T) {
140141
}, {
141142
test("strings", `strings.Join([1, 2], " ")`),
142143
`_|_(invalid list element 0 in argument 0 to strings.Join: cannot use value 1 (type int) as string)`,
144+
}, {
145+
test("strings", `strings.ByteAt("a", 0)`),
146+
strconv.Itoa('a'),
147+
}, {
148+
test("strings", `strings.ByteSlice("Hello", 2, 5)`),
149+
`'llo'`,
150+
}, {
151+
test("strings", `strings.Runes("Café")`),
152+
strings.Replace(fmt.Sprint([]rune{'C', 'a', 'f', 'é'}), " ", ",", -1),
143153
}, {
144154
test("math/bits", `bits.Or(0x8, 0x1)`),
145155
`9`,

cue/builtins.go

Lines changed: 36 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pkg/strings/manual.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,33 @@
2626
package strings
2727

2828
import (
29+
"fmt"
2930
"strings"
3031
"unicode"
3132
)
3233

34+
// ByteAt reports the ith byte of the underlying strings or byte.
35+
func ByteAt(b []byte, i int) (byte, error) {
36+
if i < 0 || i >= len(b) {
37+
return 0, fmt.Errorf("index out of range")
38+
}
39+
return b[i], nil
40+
}
41+
42+
// ByteSlice reports the bytes of the underlying string data from the start
43+
// index up to but not including the end index.
44+
func ByteSlice(b []byte, start, end int) ([]byte, error) {
45+
if start < 0 || start > end || end > len(b) {
46+
return nil, fmt.Errorf("index out of range")
47+
}
48+
return b[start:end], nil
49+
}
50+
51+
// Runes returns the Unicode code points of the given string.
52+
func Runes(s string) []rune {
53+
return []rune(s)
54+
}
55+
3356
// MinRunes reports whether the number of runes (Unicode codepoints) in a string
3457
// is at least a certain minimum. MinRunes can be used a a field constraint to
3558
// except all strings for which this property holds.

0 commit comments

Comments
 (0)