authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-01-30 18:21:19-08:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-02-06 14:23:23-08:00
log5c638845390fed5cf1c504ac013a4f75c3b7c690
treed4f27fdd5056e7a1b12e7fa1799039cfff09b0f4
parent4913de3c88d61637490bb450690d769b324508b5

add std.mem.Alignment API


1 files changed, 54 insertions(+), 0 deletions(-)

lib/std/mem.zig+54
......@@ -18,6 +18,60 @@ pub const byte_size_in_bits = 8;
1818
1919pub const Allocator = @import("mem/Allocator.zig");
2020
21/// Stored as a power-of-two.
22pub const Alignment = enum(math.Log2Int(usize)) {
23 @"1" = 0,
24 @"2" = 1,
25 @"4" = 2,
26 @"8" = 3,
27 @"16" = 4,
28 @"32" = 5,
29 @"64" = 6,
30 _,
31
32 pub fn toByteUnits(a: Alignment) usize {
33 return @as(usize, 1) << @intFromEnum(a);
34 }
35
36 pub fn fromByteUnits(n: usize) Alignment {
37 assert(std.math.isPowerOfTwo(n));
38 return @enumFromInt(@ctz(n));
39 }
40
41 pub fn order(lhs: Alignment, rhs: Alignment) std.math.Order {
42 return std.math.order(@intFromEnum(lhs), @intFromEnum(rhs));
43 }
44
45 pub fn compare(lhs: Alignment, op: std.math.CompareOperator, rhs: Alignment) bool {
46 return std.math.compare(@intFromEnum(lhs), op, @intFromEnum(rhs));
47 }
48
49 pub fn max(lhs: Alignment, rhs: Alignment) Alignment {
50 return @enumFromInt(@max(@intFromEnum(lhs), @intFromEnum(rhs)));
51 }
52
53 pub fn min(lhs: Alignment, rhs: Alignment) Alignment {
54 return @enumFromInt(@min(@intFromEnum(lhs), @intFromEnum(rhs)));
55 }
56
57 /// Return next address with this alignment.
58 pub fn forward(a: Alignment, address: usize) usize {
59 const x = (@as(usize, 1) << @intFromEnum(a)) - 1;
60 return (address + x) & ~x;
61 }
62
63 /// Return previous address with this alignment.
64 pub fn backward(a: Alignment, address: usize) usize {
65 const x = (@as(usize, 1) << @intFromEnum(a)) - 1;
66 return address & ~x;
67 }
68
69 /// Return whether address is aligned to this amount.
70 pub fn check(a: Alignment, address: usize) bool {
71 return @ctz(address) >= @intFromEnum(a);
72 }
73};
74
2175/// Detects and asserts if the std.mem.Allocator interface is violated by the caller
2276/// or the allocator.
2377pub fn ValidationAllocator(comptime T: type) type {