zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

test_pointer_arithmetic.zig (1014B) - Raw


      1 const expect = @import("std").testing.expect;
      2 
      3 test "pointer arithmetic with many-item pointer" {
      4     const array = [_]i32{ 1, 2, 3, 4 };
      5     var ptr: [*]const i32 = &array;
      6 
      7     try expect(ptr[0] == 1);
      8     ptr += 1;
      9     try expect(ptr[0] == 2);
     10 
     11     // slicing a many-item pointer without an end is equivalent to
     12     // pointer arithmetic: `ptr[start..] == ptr + start`
     13     try expect(ptr[1..] == ptr + 1);
     14 
     15     // subtraction between any two pointers except slices based on element size is supported
     16     try expect(&ptr[1] - &ptr[0] == 1);
     17 }
     18 
     19 test "pointer arithmetic with slices" {
     20     var array = [_]i32{ 1, 2, 3, 4 };
     21     var length: usize = 0; // var to make it runtime-known
     22     _ = &length; // suppress 'var is never mutated' error
     23     var slice = array[length..array.len];
     24 
     25     try expect(slice[0] == 1);
     26     try expect(slice.len == 4);
     27 
     28     slice.ptr += 1;
     29     // now the slice is in an bad state since len has not been updated
     30 
     31     try expect(slice[0] == 2);
     32     try expect(slice.len == 4);
     33 }
     34 
     35 // test