mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
all: add string range OrExpr (#13189)
This commit is contained in:
@ -818,6 +818,32 @@ pub fn (s string) substr(start int, end int) string {
|
||||
return res
|
||||
}
|
||||
|
||||
// version of `substr()` that is used in `a[start..end] or {`
|
||||
// return an error when the index is out of range
|
||||
[direct_array_access]
|
||||
pub fn (s string) substr_with_check(start int, end int) ?string {
|
||||
if start > end || start > s.len || end > s.len || start < 0 || end < 0 {
|
||||
return error('substr($start, $end) out of bounds (len=$s.len)')
|
||||
}
|
||||
len := end - start
|
||||
if len == s.len {
|
||||
return s.clone()
|
||||
}
|
||||
mut res := string{
|
||||
str: unsafe { malloc_noscan(len + 1) }
|
||||
len: len
|
||||
}
|
||||
for i in 0 .. len {
|
||||
unsafe {
|
||||
res.str[i] = s.str[start + i]
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
res.str[len] = 0
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// substr_ni returns the string between index positions `start` and `end` allowing negative indexes
|
||||
// This function always return a valid string.
|
||||
[direct_array_access]
|
||||
|
@ -120,6 +120,34 @@ fn test_sort_reverse() {
|
||||
assert vals[3] == 'arr'
|
||||
}
|
||||
|
||||
fn test_ranges() {
|
||||
s := 'test'
|
||||
s1 := s[0..20] or { 'both' }
|
||||
s2 := s[..20] or { 'last' }
|
||||
s3 := s[10..] or { 'first' }
|
||||
s4 := ranges_propagate_both(s) or { 'both' }
|
||||
s5 := ranges_propagate_last(s) or { 'last' }
|
||||
s6 := ranges_propagate_first(s) or { 'first' }
|
||||
assert s1 == 'both'
|
||||
assert s2 == 'last'
|
||||
assert s3 == 'first'
|
||||
assert s4 == 'both'
|
||||
assert s5 == 'last'
|
||||
assert s6 == 'first'
|
||||
}
|
||||
|
||||
fn ranges_propagate_first(s string) ?string {
|
||||
return s[10..] ?
|
||||
}
|
||||
|
||||
fn ranges_propagate_last(s string) ?string {
|
||||
return s[..20] ?
|
||||
}
|
||||
|
||||
fn ranges_propagate_both(s string) ?string {
|
||||
return s[1..20] ?
|
||||
}
|
||||
|
||||
fn test_split_nth() {
|
||||
a := '1,2,3'
|
||||
assert a.split(',').len == 3
|
||||
|
Reference in New Issue
Block a user