| 1 | const std = @import("std"); |
| 2 | const expectEqual = std.testing.expectEqual; |
| 3 | |
| 4 | test "Basic vector usage" { |
| 5 | // Vectors have a compile-time known length and base type. |
| 6 | const a = @Vector(4, i32){ 1, 2, 3, 4 }; |
| 7 | const b = @Vector(4, i32){ 5, 6, 7, 8 }; |
| 8 | |
| 9 | // Math operations take place element-wise. |
| 10 | const c = a + b; |
| 11 | |
| 12 | // Individual vector elements can be accessed using array indexing syntax. |
| 13 | try expectEqual(6, c[0]); |
| 14 | try expectEqual(8, c[1]); |
| 15 | try expectEqual(10, c[2]); |
| 16 | try expectEqual(12, c[3]); |
| 17 | } |
| 18 | |
| 19 | test "Conversion between vectors, arrays, and slices" { |
| 20 | // Vectors can be coerced to arrays, and vice versa. |
| 21 | const arr1: [4]f32 = [_]f32{ 1.1, 3.2, 4.5, 5.6 }; |
| 22 | const vec: @Vector(4, f32) = arr1; |
| 23 | const arr2: [4]f32 = vec; |
| 24 | try expectEqual(arr1, arr2); |
| 25 | |
| 26 | // You can also assign from a slice with comptime-known length to a vector using .* |
| 27 | const vec2: @Vector(2, f32) = arr1[1..3].*; |
| 28 | |
| 29 | const slice: []const f32 = &arr1; |
| 30 | var offset: u32 = 1; // var to make it runtime-known |
| 31 | _ = &offset; // suppress 'var is never mutated' error |
| 32 | // To extract a comptime-known length from a runtime-known offset, |
| 33 | // first extract a new slice from the starting offset, then an array of |
| 34 | // comptime-known length |
| 35 | const vec3: @Vector(2, f32) = slice[offset..][0..2].*; |
| 36 | try expectEqual(slice[offset], vec2[0]); |
| 37 | try expectEqual(slice[offset + 1], vec2[1]); |
| 38 | try expectEqual(vec2, vec3); |
| 39 | } |
| 40 | |
| 41 | // test |