Skip to content

Commit f01cfc5

Browse files
eonpataponmpvl
authored andcommitted
pkg/strings: add SliceRunes
There was some discussions on slack about this and turns out there is no real solution to slice strings easily in cue. Added a builtin which works internally on runes to work properly on strings with unicode chars. Not sure about the name of the builtin. Closes #424 cuelang/cue#424 GitOrigin-RevId: 55640e7cfdf8878e5a90b386fc43b9650656d1bc Change-Id: I40293d2e1646d1eee2e9074af9954a4be339de78 Reviewed-on: https://cue-review.googlesource.com/c/cue/+/6400 Reviewed-by: CUE cueckoo <[email protected]> Reviewed-by: Marcel van Lohuizen <[email protected]>
1 parent 9ebfa80 commit f01cfc5

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

cue/builtin_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,9 @@ func TestBuiltins(t *testing.T) {
394394
}, {
395395
test("strings", `strings.ByteSlice("Hello", 2, 5)`),
396396
`'llo'`,
397+
}, {
398+
test("strings", `strings.SliceRunes("✓ Hello", 0, 3)`),
399+
`"✓ H"`,
397400
}, {
398401
test("strings", `strings.Runes("Café")`),
399402
strings.Replace(fmt.Sprint([]rune{'C', 'a', 'f', 'é'}), " ", ",", -1),

cue/builtins.go

Lines changed: 16 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: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,13 @@ func ToCamel(s string) string {
108108
},
109109
s)
110110
}
111+
112+
// SliceRunes returns a string of the underlying string data from the start index
113+
// up to but not including the end index.
114+
func SliceRunes(s string, start, end int) (string, error) {
115+
runes := []rune(s)
116+
if start < 0 || start > end || end > len(runes) {
117+
return "", fmt.Errorf("index out of range")
118+
}
119+
return string(runes[start:end]), nil
120+
}

0 commit comments

Comments
 (0)