1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

all: support slices with negative indexes #[start..end] (gated arrays) (#12914)

This commit is contained in:
penguindark
2021-12-22 14:34:02 +01:00
committed by GitHub
parent 2b9f993574
commit 278c08704c
13 changed files with 250 additions and 16 deletions

View File

@@ -384,6 +384,57 @@ fn (a array) slice(start int, _end int) array {
return res
}
// slice_ni returns an array using the same buffer as original array
// but starting from the `start` element and ending with the element before
// the `end` element of the original array.
// This function can use negative indexes `a.slice_ni(-3, a.len)`
// that get the last 3 elements of the array otherwise it return an empty array.
// This function always return a valid array.
fn (a array) slice_ni(_start int, _end int) array {
mut end := _end
mut start := _start
if start < 0 {
start = a.len + start
if start < 0 {
start = 0
}
}
if end < 0 {
end = a.len + end
if end < 0 {
end = 0
}
}
if end >= a.len {
end = a.len
}
if start >= a.len || start > end {
res := array{
element_size: a.element_size
data: a.data
offset: 0
len: 0
cap: 0
}
return res
}
offset := start * a.element_size
data := unsafe { &byte(a.data) + offset }
l := end - start
res := array{
element_size: a.element_size
data: data
offset: a.offset + offset
len: l
cap: l
}
return res
}
// used internally for [2..4]
fn (a array) slice2(start int, _end int, end_max bool) array {
end := if end_max { a.len } else { _end }