array: add `array.trim()`

pull/3761/head
prime31 2020-02-17 11:31:40 -08:00 committed by GitHub
parent 6849a4e770
commit a2838ae6f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 0 deletions

View File

@ -152,6 +152,14 @@ pub fn (a mut array) clear() {
a.len = 0
}
// trims the array length to "index" without modifying the allocated data. If "index" is greater
// than len nothing will be changed
pub fn (a mut array) trim(index int) {
if index < a.len {
a.len = index
}
}
// Private function. Used to implement array[] operator
fn (a array) get(i int) voidptr {
$if !no_bounds_checking? {

View File

@ -592,3 +592,20 @@ fn test_clear() {
arr.clear()
assert arr.len == 0
}
fn test_trim() {
mut arr := [1,2,3,4,5,6,7,8,9]
assert arr.len == 9
arr.trim(9)
assert arr.len == 9
assert arr.last() == 9
arr.trim(7)
assert arr.len == 7
assert arr.last() == 7
arr.trim(2)
assert arr.len == 2
assert arr.last() == 2
}