authorgravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2020-11-18 13:06:35+02:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-11-18 17:31:11-07:00
log1add7c616f2e8fed2329f282b634c51dd6250b66
treee62777abe95269bba7e1278169a8a2e9f660fdf8
parent5f9a664de958cd17fd5d5e0f3f8fa797bb4f25de

Merge pull request #7084 from xackus/mem-volatile

std.mem: make sliceAsBytes, etc. respect volatile

1 files changed, 88 insertions(+), 35 deletions(-)

lib/std/mem.zig+88-35
......@@ -7,13 +7,14 @@ const std = @import("std.zig");
77const debug = std.debug;
88const assert = debug.assert;
99const math = std.math;
10const builtin = @import("builtin");
10const builtin = std.builtin;
1111const mem = @This();
1212const meta = std.meta;
1313const trait = meta.trait;
1414const testing = std.testing;
1515
16/// https://github.com/ziglang/zig/issues/2564
16/// Compile time known minimum page size.
17/// https://github.com/ziglang/zig/issues/4082
1718pub const page_size = switch (builtin.arch) {
1819 .wasm32, .wasm64 => 64 * 1024,
1920 .aarch64 => switch (builtin.os.tag) {
......@@ -139,7 +140,7 @@ test "mem.Allocator basics" {
139140
140141/// Copy all of source into dest at position 0.
141142/// dest.len must be >= source.len.
142/// dest.ptr must be <= src.ptr.
143/// If the slices overlap, dest.ptr must be <= src.ptr.
143144pub fn copy(comptime T: type, dest: []T, source: []const T) void {
144145 // TODO instead of manually doing this check for the whole array
145146 // and turning off runtime safety, the compiler should detect loops like
......@@ -152,7 +153,7 @@ pub fn copy(comptime T: type, dest: []T, source: []const T) void {
152153
153154/// Copy all of source into dest at position 0.
154155/// dest.len must be >= source.len.
155/// dest.ptr must be >= src.ptr.
156/// If the slices overlap, dest.ptr must be >= src.ptr.
156157pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void {
157158 // TODO instead of manually doing this check for the whole array
158159 // and turning off runtime safety, the compiler should detect loops like
......@@ -1936,25 +1937,31 @@ pub fn nativeToBig(comptime T: type, x: T) T {
19361937 };
19371938}
19381939
1940fn CopyPtrAttrs(comptime source: type, comptime size: builtin.TypeInfo.Pointer.Size, comptime child: type) type {
1941 const info = @typeInfo(source).Pointer;
1942 return @Type(.{
1943 .Pointer = .{
1944 .size = size,
1945 .is_const = info.is_const,
1946 .is_volatile = info.is_volatile,
1947 .is_allowzero = info.is_allowzero,
1948 .alignment = info.alignment,
1949 .child = child,
1950 .sentinel = null,
1951 },
1952 });
1953}
1954
19391955fn AsBytesReturnType(comptime P: type) type {
19401956 if (!trait.isSingleItemPtr(P))
19411957 @compileError("expected single item pointer, passed " ++ @typeName(P));
19421958
19431959 const size = @sizeOf(meta.Child(P));
1944 const alignment = meta.alignment(P);
19451960
1946 if (alignment == 0) {
1947 if (trait.isConstPtr(P))
1948 return *const [size]u8;
1949 return *[size]u8;
1950 }
1951
1952 if (trait.isConstPtr(P))
1953 return *align(alignment) const [size]u8;
1954 return *align(alignment) [size]u8;
1961 return CopyPtrAttrs(P, .One, [size]u8);
19551962}
19561963
1957/// Given a pointer to a single item, returns a slice of the underlying bytes, preserving constness.
1964/// Given a pointer to a single item, returns a slice of the underlying bytes, preserving pointer attributes.
19581965pub fn asBytes(ptr: anytype) AsBytesReturnType(@TypeOf(ptr)) {
19591966 const P = @TypeOf(ptr);
19601967 return @ptrCast(AsBytesReturnType(P), ptr);
......@@ -1994,6 +2001,20 @@ test "asBytes" {
19942001 testing.expect(eql(u8, asBytes(&zero), ""));
19952002}
19962003
2004test "asBytes preserves pointer attributes" {
2005 const inArr: u32 align(16) = 0xDEADBEEF;
2006 const inPtr = @ptrCast(*align(16) const volatile u32, &inArr);
2007 const outSlice = asBytes(inPtr);
2008
2009 const in = @typeInfo(@TypeOf(inPtr)).Pointer;
2010 const out = @typeInfo(@TypeOf(outSlice)).Pointer;
2011
2012 testing.expectEqual(in.is_const, out.is_const);
2013 testing.expectEqual(in.is_volatile, out.is_volatile);
2014 testing.expectEqual(in.is_allowzero, out.is_allowzero);
2015 testing.expectEqual(in.alignment, out.alignment);
2016}
2017
19972018/// Given any value, returns a copy of its bytes in an array.
19982019pub fn toBytes(value: anytype) [@sizeOf(@TypeOf(value))]u8 {
19992020 return asBytes(&value).*;
......@@ -2023,13 +2044,11 @@ fn BytesAsValueReturnType(comptime T: type, comptime B: type) type {
20232044 @compileError(std.fmt.bufPrint(&buf, "expected *[{}]u8, passed " ++ @typeName(B), .{size}) catch unreachable);
20242045 }
20252046
2026 const alignment = comptime meta.alignment(B);
2027
2028 return if (comptime trait.isConstPtr(B)) *align(alignment) const T else *align(alignment) T;
2047 return CopyPtrAttrs(B, .One, T);
20292048}
20302049
20312050/// Given a pointer to an array of bytes, returns a pointer to a value of the specified type
2032/// backed by those bytes, preserving constness.
2051/// backed by those bytes, preserving pointer attributes.
20332052pub fn bytesAsValue(comptime T: type, bytes: anytype) BytesAsValueReturnType(T, @TypeOf(bytes)) {
20342053 return @ptrCast(BytesAsValueReturnType(T, @TypeOf(bytes)), bytes);
20352054}
......@@ -2071,6 +2090,20 @@ test "bytesAsValue" {
20712090 testing.expect(meta.eql(inst, inst2.*));
20722091}
20732092
2093test "bytesAsValue preserves pointer attributes" {
2094 const inArr align(16) = [4]u8{ 0xDE, 0xAD, 0xBE, 0xEF };
2095 const inSlice = @ptrCast(*align(16) const volatile [4]u8, &inArr)[0..];
2096 const outPtr = bytesAsValue(u32, inSlice);
2097
2098 const in = @typeInfo(@TypeOf(inSlice)).Pointer;
2099 const out = @typeInfo(@TypeOf(outPtr)).Pointer;
2100
2101 testing.expectEqual(in.is_const, out.is_const);
2102 testing.expectEqual(in.is_volatile, out.is_volatile);
2103 testing.expectEqual(in.is_allowzero, out.is_allowzero);
2104 testing.expectEqual(in.alignment, out.alignment);
2105}
2106
20742107/// Given a pointer to an array of bytes, returns a value of the specified type backed by a
20752108/// copy of those bytes.
20762109pub fn bytesToValue(comptime T: type, bytes: anytype) T {
......@@ -2086,9 +2119,8 @@ test "bytesToValue" {
20862119 testing.expect(deadbeef == @as(u32, 0xDEADBEEF));
20872120}
20882121
2089//TODO copy also is_volatile, etc. I tried to use @typeInfo, modify child type, use @Type, but ran into issues.
20902122fn BytesAsSliceReturnType(comptime T: type, comptime bytesType: type) type {
2091 if (!(trait.isSlice(bytesType) and meta.Child(bytesType) == u8) and !(trait.isPtrTo(.Array)(bytesType) and meta.Child(meta.Child(bytesType)) == u8)) {
2123 if (!(trait.isSlice(bytesType) or trait.isPtrTo(.Array)(bytesType)) or meta.Elem(bytesType) != u8) {
20922124 @compileError("expected []u8 or *[_]u8, passed " ++ @typeName(bytesType));
20932125 }
20942126
......@@ -2096,11 +2128,11 @@ fn BytesAsSliceReturnType(comptime T: type, comptime bytesType: type) type {
20962128 @compileError("number of bytes in " ++ @typeName(bytesType) ++ " is not divisible by size of " ++ @typeName(T));
20972129 }
20982130
2099 const alignment = meta.alignment(bytesType);
2100
2101 return if (trait.isConstPtr(bytesType)) []align(alignment) const T else []align(alignment) T;
2131 return CopyPtrAttrs(bytesType, .Slice, T);
21022132}
21032133
2134/// Given a slice of bytes, returns a slice of the specified type
2135/// backed by those bytes, preserving pointer attributes.
21042136pub fn bytesAsSlice(comptime T: type, bytes: anytype) BytesAsSliceReturnType(T, @TypeOf(bytes)) {
21052137 // let's not give an undefined pointer to @ptrCast
21062138 // it may be equal to zero and fail a null check
......@@ -2108,10 +2140,7 @@ pub fn bytesAsSlice(comptime T: type, bytes: anytype) BytesAsSliceReturnType(T,
21082140 return &[0]T{};
21092141 }
21102142
2111 const Bytes = @TypeOf(bytes);
2112 const alignment = comptime meta.alignment(Bytes);
2113
2114 const cast_target = if (comptime trait.isConstPtr(Bytes)) [*]align(alignment) const T else [*]align(alignment) T;
2143 const cast_target = CopyPtrAttrs(@TypeOf(bytes), .Many, T);
21152144
21162145 return @ptrCast(cast_target, bytes)[0..@divExact(bytes.len, @sizeOf(T))];
21172146}
......@@ -2169,17 +2198,29 @@ test "bytesAsSlice with specified alignment" {
21692198 testing.expect(slice[0] == 0x33333333);
21702199}
21712200
2172//TODO copy also is_volatile, etc. I tried to use @typeInfo, modify child type, use @Type, but ran into issues.
2201test "bytesAsSlice preserves pointer attributes" {
2202 const inArr align(16) = [4]u8{ 0xDE, 0xAD, 0xBE, 0xEF };
2203 const inSlice = @ptrCast(*align(16) const volatile [4]u8, &inArr)[0..];
2204 const outSlice = bytesAsSlice(u16, inSlice);
2205
2206 const in = @typeInfo(@TypeOf(inSlice)).Pointer;
2207 const out = @typeInfo(@TypeOf(outSlice)).Pointer;
2208
2209 testing.expectEqual(in.is_const, out.is_const);
2210 testing.expectEqual(in.is_volatile, out.is_volatile);
2211 testing.expectEqual(in.is_allowzero, out.is_allowzero);
2212 testing.expectEqual(in.alignment, out.alignment);
2213}
2214
21732215fn SliceAsBytesReturnType(comptime sliceType: type) type {
21742216 if (!trait.isSlice(sliceType) and !trait.isPtrTo(.Array)(sliceType)) {
21752217 @compileError("expected []T or *[_]T, passed " ++ @typeName(sliceType));
21762218 }
21772219
2178 const alignment = meta.alignment(sliceType);
2179
2180 return if (trait.isConstPtr(sliceType)) []align(alignment) const u8 else []align(alignment) u8;
2220 return CopyPtrAttrs(sliceType, .Slice, u8);
21812221}
21822222
2223/// Given a slice, returns a slice of the underlying bytes, preserving pointer attributes.
21832224pub fn sliceAsBytes(slice: anytype) SliceAsBytesReturnType(@TypeOf(slice)) {
21842225 const Slice = @TypeOf(slice);
21852226
......@@ -2189,9 +2230,7 @@ pub fn sliceAsBytes(slice: anytype) SliceAsBytesReturnType(@TypeOf(slice)) {
21892230 return &[0]u8{};
21902231 }
21912232
2192 const alignment = comptime meta.alignment(Slice);
2193
2194 const cast_target = if (comptime trait.isConstPtr(Slice)) [*]align(alignment) const u8 else [*]align(alignment) u8;
2233 const cast_target = CopyPtrAttrs(Slice, .Many, u8);
21952234
21962235 return @ptrCast(cast_target, slice)[0 .. slice.len * @sizeOf(meta.Elem(Slice))];
21972236}
......@@ -2263,6 +2302,20 @@ test "sliceAsBytes and bytesAsSlice back" {
22632302 testing.expect(bytes[11] == math.maxInt(u8));
22642303}
22652304
2305test "sliceAsBytes preserves pointer attributes" {
2306 const inArr align(16) = [2]u16{ 0xDEAD, 0xBEEF };
2307 const inSlice = @ptrCast(*align(16) const volatile [2]u16, &inArr)[0..];
2308 const outSlice = sliceAsBytes(inSlice);
2309
2310 const in = @typeInfo(@TypeOf(inSlice)).Pointer;
2311 const out = @typeInfo(@TypeOf(outSlice)).Pointer;
2312
2313 testing.expectEqual(in.is_const, out.is_const);
2314 testing.expectEqual(in.is_volatile, out.is_volatile);
2315 testing.expectEqual(in.is_allowzero, out.is_allowzero);
2316 testing.expectEqual(in.alignment, out.alignment);
2317}
2318
22662319/// Round an address up to the nearest aligned address
22672320/// The alignment must be a power of 2 and greater than 0.
22682321pub fn alignForward(addr: usize, alignment: usize) usize {