diff options
| author | Robin Voetter <robin@voetter.nl> | 2021-10-24 16:34:42 +0200 |
|---|---|---|
| committer | Robin Voetter <robin@voetter.nl> | 2021-10-25 20:41:15 +0200 |
| commit | 0942bf73c90eabf87d0ca965b50beb0fd9a8fc8c (patch) | |
| tree | 52576cb867ea0baad15b87d0a4ca4591d7226f02 /test/behavior/slice.zig | |
| parent | ed7328119f2194f1b64085c08c88a5a656bfc597 (diff) | |
| download | zig-0942bf73c90eabf87d0ca965b50beb0fd9a8fc8c.tar.gz zig-0942bf73c90eabf87d0ca965b50beb0fd9a8fc8c.zip | |
stage2: improve slicing
* Allow slicing many- and c-pointers.
* Allow comptime pointer arithmetic on undefined values.
* Return the correct type for slicing of slices.
Diffstat (limited to 'test/behavior/slice.zig')
| -rw-r--r-- | test/behavior/slice.zig | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/test/behavior/slice.zig b/test/behavior/slice.zig index 19c9e7e773..dfe2b39297 100644 --- a/test/behavior/slice.zig +++ b/test/behavior/slice.zig @@ -109,3 +109,51 @@ test "slice of type" { } } } + +test "generic malloc free" { + const a = memAlloc(u8, 10) catch unreachable; + memFree(u8, a); +} +var some_mem: [100]u8 = undefined; +fn memAlloc(comptime T: type, n: usize) anyerror![]T { + return @ptrCast([*]T, &some_mem[0])[0..n]; +} +fn memFree(comptime T: type, memory: []T) void { + _ = memory; +} + +test "slice of hardcoded address to pointer" { + const S = struct { + fn doTheTest() !void { + const pointer = @intToPtr([*]u8, 0x04)[0..2]; + comptime try expect(@TypeOf(pointer) == *[2]u8); + const slice: []const u8 = pointer; + try expect(@ptrToInt(slice.ptr) == 4); + try expect(slice.len == 2); + } + }; + + try S.doTheTest(); +} + +test "comptime slice of pointer preserves comptime var" { + comptime { + var buff: [10]u8 = undefined; + var a = @ptrCast([*]u8, &buff); + a[0..1][0] = 1; + try expect(buff[0..][0..][0] == 1); + } +} + +test "comptime pointer cast array and then slice" { + const array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8 }; + + const ptrA: [*]const u8 = @ptrCast([*]const u8, &array); + const sliceA: []const u8 = ptrA[0..2]; + + const ptrB: [*]const u8 = &array; + const sliceB: []const u8 = ptrB[0..2]; + + try expect(sliceA[1] == 2); + try expect(sliceB[1] == 2); +} |
