v2 / vlib / builtin / gated_array_string_test.v
93 lines · 80 sloc · 2.16 KB · 6f52e7050ba621e04e3102ddfafcde1398db2b55
Raw
1fn test_gated_arrays() {
2 a := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3 assert a#[-1] == 9
4 assert a#[1] == 1
5 assert a#[-1..] == [9]
6 assert a#[..-9] == [0]
7 assert a#[-9..-7] == [1, 2]
8 assert a#[-2..] == [8, 9]
9 missing := a#[-11] or { 42 }
10 assert missing == 42
11
12 mut b := [1, 2, 3]
13 b#[-1] = 100
14 assert b == [1, 2, 100]
15
16 // fixed array
17 mut a1 := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]!
18 assert a1#[-1] == 9
19 assert a1#[-1..] == [9]
20 assert a1#[..-9] == [0]
21 assert a1#[-9..-7] == [1, 2]
22 assert a1#[-2..] == [8, 9]
23 a1#[-1] = 100
24 assert a1[9] == 100
25
26 // empty array
27 assert a#[-3..-4] == [] // start > end
28 assert a#[20..] == [] // start > array.len
29 assert a#[-20..-10] == [] // start+len < 0
30 assert a#[20..-9] == [] // start > end && start > end
31}
32
33fn test_gated_strings() {
34 a := '0123456789'
35 assert a#[-1] == `9`
36 assert a#[1] == `1`
37 assert a#[-1..] == '9'
38 assert a#[..-9] == '0'
39 assert a#[-9..-7] == '12'
40 assert a#[-2..] == '89'
41 missing := a#[-11] or { `x` }
42 assert missing == `x`
43
44 // empty string
45 assert a#[-3..-4] == '' // start > end
46 assert a#[20..] == '' // start > array.len
47 assert a#[-20..-10] == '' // start+len < 0
48 assert a#[20..-9] == '' // start > end && start > end
49
50 //
51 // test negative indexes in slices from github discussion
52 //
53 s := '0123456789'
54
55 // normal behaviour
56 assert s#[1..3] == '12'
57 assert s#[..3] == '012'
58 assert s#[8..] == '89'
59
60 // negative indexes behaviour
61 assert s#[-2..] == '89'
62 assert s#[..-8] == '01'
63 assert s#[2..-2] == '234567'
64 assert s#[-12..-16] == ''
65 assert s#[-8..-2] == '234567'
66
67 // out of bound both indexes
68 assert s#[12..14] == ''
69 assert s#[-12..16] == '0123456789'
70}
71
72fn test_gated_mixed_strings() {
73 //
74 // test negative indexes in slices
75 //
76 a := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
77
78 // normal behaviour
79 assert a#[1..3].str() == '[1, 2]'
80 assert a#[..3].str() == '[0, 1, 2]'
81 assert a#[8..].str() == '[8, 9]'
82
83 // negative indexes behaviour
84 assert a#[-2..].str() == '[8, 9]'
85 assert a#[..-8].str() == '[0, 1]'
86 assert a#[2..-2].str() == '[2, 3, 4, 5, 6, 7]'
87 assert a#[-12..-16].str() == '[]'
88 assert a#[-8..-2].str() == '[2, 3, 4, 5, 6, 7]'
89
90 // out of bound both indexes
91 assert a#[12..14].str() == '[]'
92 assert a#[-12..16].str() == a.str()
93}
94