v2 / vlib / v / tests / shift_test.v
117 lines · 110 sloc · 2.54 KB · 39f1a9d7a344293798f3e07c3d434417f9d8af26
Raw
1type MyInt = int
2
3fn test_shift_left_precedence() {
4 x := u32(20)
5 base := u32(1)
6 shift := u32(3)
7 assert x + base << shift == (x + (base << shift)), '<< should have higher precedence than +'
8 assert x - base << shift == (x - (base << shift)), '<< should have higher precedence than -'
9}
10
11fn test_shift_right_precedence() {
12 x := u32(20)
13 base := u32(100)
14 shift := u32(2)
15 assert x + base >> shift == (x + (base >> shift)), '>> should have higher precedence than +'
16 assert x - base >> shift == (x - (base >> shift)), '>> should have higher precedence than -'
17}
18
19fn test_shift_operators() {
20 // check that shift works with all integer types
21 // as the right-hand side operand
22 a := 1
23 b := 1024
24 i := 10
25 assert b == a << i8(i)
26 assert b == a << u8(i)
27 assert b == a << i16(i)
28 assert b == a << u16(i)
29 assert b == a << int(i)
30 assert b == a << u32(i)
31 assert b == a << i64(i)
32 assert b == a << u64(i)
33 assert a == b >> i8(i)
34 assert a == b >> u8(i)
35 assert a == b >> i16(i)
36 assert a == b >> u16(i)
37 assert a == b >> int(i)
38 assert a == b >> u32(i)
39 assert a == b >> i64(i)
40 assert a == b >> u64(i)
41 // check that shift operation result type is
42 // the same as the type of the left-hand side operand
43 mut c := u64(0)
44 d := u64(1)
45 c = d << i8(63)
46 assert c == 9223372036854775808
47 // check that shift-assign works with all types
48 // of integers on the right-hand side
49 mut e := 1
50 e <<= i8(i)
51 assert e == b
52 e >>= i8(i)
53 assert e == a
54 e <<= i16(i)
55 assert e == b
56 e >>= i16(i)
57 assert e == a
58 e <<= int(i)
59 assert e == b
60 e >>= int(i)
61 assert e == a
62 mut e2 := i64(1)
63 e2 <<= i64(i)
64 assert e2 == b
65 e2 >>= i64(i)
66 assert e2 == a
67 e <<= u8(i)
68 assert e == b
69 e >>= u8(i)
70 assert e == a
71 e <<= u16(i)
72 assert e == b
73 e >>= u16(i)
74 assert e == a
75 mut e3 := u64(1)
76 e3 <<= u32(i)
77 assert e3 == u64(b)
78 e3 >>= u32(i)
79 assert e == a
80 e3 <<= u64(i)
81 assert e3 == u64(b)
82 e3 >>= u64(i)
83 assert e3 == u64(a)
84 // Test shifts with custom int types
85 x := MyInt(2)
86 assert x << 2 == 8
87}
88
89fn test_shift_assign_accepts_int_count_for_unsigned_left_operand() {
90 mut value := u64(1)
91 shift := int(3)
92 value <<= shift
93 assert value == u64(8)
94 value >>= shift
95 assert value == u64(1)
96}
97
98fn oversized_shift_count() u64 {
99 return u64(64)
100}
101
102fn test_runtime_oversized_shift_expr() {
103 bits := u64(9221120237041090561)
104 shift := oversized_shift_count()
105 assert bits >> shift == u64(0)
106 assert bits << shift == u64(0)
107}
108
109fn test_runtime_oversized_shift_assign() {
110 shift := oversized_shift_count()
111 mut left := u64(1)
112 left <<= shift
113 assert left == u64(0)
114 mut right := u64(1)
115 right >>= shift
116 assert right == u64(0)
117}
118