1const std = @import("std");
2const expectEqual = std.testing.expectEqual;
3const expectEqualStrings = std.testing.expectEqualStrings;
4const expectEqualSlices = std.testing.expectEqualSlices;
5
6// You can assign constant pointers to arrays to a slice with
7// const modifier on the element type. Useful in particular for
8// String literals.
9test "*const [N]T to []const T" {
10 const x1: []const u8 = "hello";
11 const x2: []const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
12 try expectEqualStrings(x1, x2);
13
14 const y: []const f32 = &[2]f32{ 1.2, 3.4 };
15 try expectEqual(1.2, y[0]);
16}
17
18// Likewise, it works when the destination type is an error union.
19test "*const [N]T to E![]const T" {
20 const x1: anyerror![]const u8 = "hello";
21 const x2: anyerror![]const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
22 try expectEqualStrings(try x1, try x2);
23
24 const y: anyerror![]const f32 = &[2]f32{ 1.2, 3.4 };
25 try expectEqual(1.2, (try y)[0]);
26}
27
28// Likewise, it works when the destination type is an optional.
29test "*const [N]T to ?[]const T" {
30 const x1: ?[]const u8 = "hello";
31 const x2: ?[]const u8 = &[5]u8{ 'h', 'e', 'l', 'l', 111 };
32 try expectEqualStrings(x1.?, x2.?);
33
34 const y: ?[]const f32 = &[2]f32{ 1.2, 3.4 };
35 try expectEqual(1.2, y.?[0]);
36}
37
38// In this cast, the array length becomes the slice length.
39test "*[N]T to []T" {
40 var buf: [5]u8 = "hello".*;
41 const x: []u8 = &buf;
42 try expectEqualStrings("hello", x);
43
44 const buf2 = [2]f32{ 1.2, 3.4 };
45 const x2: []const f32 = &buf2;
46 try expectEqualSlices(f32, &[2]f32{ 1.2, 3.4 }, x2);
47}
48
49// Single-item pointers to arrays can be coerced to many-item pointers.
50test "*[N]T to [*]T" {
51 var buf: [5]u8 = "hello".*;
52 const x: [*]u8 = &buf;
53 try expectEqual('o', x[4]);
54 // x[5] would be an uncaught out of bounds pointer dereference!
55}
56
57// Likewise, it works when the destination type is an optional.
58test "*[N]T to ?[*]T" {
59 var buf: [5]u8 = "hello".*;
60 const x: ?[*]u8 = &buf;
61 try expectEqual('o', x.?[4]);
62}
63
64// Single-item pointers can be cast to len-1 single-item arrays.
65test "*T to *[1]T" {
66 var x: i32 = 1234;
67 const y: *[1]i32 = &x;
68 const z: [*]i32 = y;
69 try expectEqual(1234, z[0]);
70}
71
72// Sentinel-terminated slices can be coerced into sentinel-terminated pointers
73test "[:x]T to [*:x]T" {
74 const buf: [:0]const u8 = "hello";
75 const buf2: [*:0]const u8 = buf;
76 try expectEqual('o', buf2[4]);
77}
78
79// test