Skip to content

Commit

Permalink
pkg/strings: add SliceRunes
Browse files Browse the repository at this point in the history
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 <cueckoo@gmail.com>
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
  • Loading branch information
eonpatapon authored and mpvl committed Jul 4, 2020
1 parent 9ebfa80 commit f01cfc5
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions cue/builtin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,9 @@ func TestBuiltins(t *testing.T) {
}, {
test("strings", `strings.ByteSlice("Hello", 2, 5)`),
`'llo'`,
}, {
test("strings", `strings.SliceRunes("✓ Hello", 0, 3)`),
`"✓ H"`,
}, {
test("strings", `strings.Runes("Café")`),
strings.Replace(fmt.Sprint([]rune{'C', 'a', 'f', 'é'}), " ", ",", -1),
Expand Down
16 changes: 16 additions & 0 deletions cue/builtins.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions pkg/strings/manual.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,13 @@ func ToCamel(s string) string {
},
s)
}

// SliceRunes returns a string of the underlying string data from the start index
// up to but not including the end index.
func SliceRunes(s string, start, end int) (string, error) {
runes := []rune(s)
if start < 0 || start > end || end > len(runes) {
return "", fmt.Errorf("index out of range")
}
return string(runes[start:end]), nil
}

0 comments on commit f01cfc5

Please sign in to comment.