authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-04-11 17:55:25-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-04-13 02:20:32-04:00
logf32a5d349d2c359a2a1f627aa70e1a7a6f6330ea
tree05a0fe7de04e6aa91775e954f78dd1a478d7e675
parentec2888858102035f296c01df5aacbd255c35d06f

std: eradicate u29 and embrace std.mem.Alignment


32 files changed, 153 insertions(+), 156 deletions(-)

lib/compiler/aro/aro/Parser.zig+2-2
...@@ -101,7 +101,7 @@ value_map: Tree.ValueMap,...@@ -101,7 +101,7 @@ value_map: Tree.ValueMap,
101101
102// buffers used during compilation102// buffers used during compilation
103syms: SymbolStack = .{},103syms: SymbolStack = .{},
104strings: std.ArrayListAligned(u8, 4),104strings: std.ArrayListAligned(u8, .@"4"),
105labels: std.ArrayList(Label),105labels: std.ArrayList(Label),
106list_buf: NodeList,106list_buf: NodeList,
107decl_buf: NodeList,107decl_buf: NodeList,
...@@ -693,7 +693,7 @@ pub fn parse(pp: *Preprocessor) Compilation.Error!Tree {...@@ -693,7 +693,7 @@ pub fn parse(pp: *Preprocessor) Compilation.Error!Tree {
693 .gpa = pp.comp.gpa,693 .gpa = pp.comp.gpa,
694 .arena = arena.allocator(),694 .arena = arena.allocator(),
695 .tok_ids = pp.tokens.items(.id),695 .tok_ids = pp.tokens.items(.id),
696 .strings = std.ArrayListAligned(u8, 4).init(pp.comp.gpa),696 .strings = std.ArrayListAligned(u8, .@"4").init(pp.comp.gpa),
697 .value_map = Tree.ValueMap.init(pp.comp.gpa),697 .value_map = Tree.ValueMap.init(pp.comp.gpa),
698 .data = NodeList.init(pp.comp.gpa),698 .data = NodeList.init(pp.comp.gpa),
699 .labels = std.ArrayList(Label).init(pp.comp.gpa),699 .labels = std.ArrayList(Label).init(pp.comp.gpa),
lib/compiler/aro/aro/Preprocessor.zig+1-1
...@@ -983,7 +983,7 @@ fn expr(pp: *Preprocessor, tokenizer: *Tokenizer) MacroError!bool {...@@ -983,7 +983,7 @@ fn expr(pp: *Preprocessor, tokenizer: *Tokenizer) MacroError!bool {
983 .tok_i = @intCast(token_state.tokens_len),983 .tok_i = @intCast(token_state.tokens_len),
984 .arena = pp.arena.allocator(),984 .arena = pp.arena.allocator(),
985 .in_macro = true,985 .in_macro = true,
986 .strings = std.ArrayListAligned(u8, 4).init(pp.comp.gpa),986 .strings = std.ArrayListAligned(u8, .@"4").init(pp.comp.gpa),
987987
988 .data = undefined,988 .data = undefined,
989 .value_map = undefined,989 .value_map = undefined,
lib/compiler/objcopy.zig+5-5
...@@ -841,12 +841,12 @@ fn ElfFile(comptime is_64: bool) type {...@@ -841,12 +841,12 @@ fn ElfFile(comptime is_64: bool) type {
841 arena: std.heap.ArenaAllocator,841 arena: std.heap.ArenaAllocator,
842842
843 const SectionCategory = ElfFileHelper.SectionCategory;843 const SectionCategory = ElfFileHelper.SectionCategory;
844 const section_memory_align = @alignOf(Elf_Sym); // most restrictive of what we may load in memory844 const section_memory_align: std.mem.Alignment = .of(Elf_Sym); // most restrictive of what we may load in memory
845 const Section = struct {845 const Section = struct {
846 section: Elf_Shdr,846 section: Elf_Shdr,
847 name: []const u8 = "",847 name: []const u8 = "",
848 segment: ?*const Elf_Phdr = null, // if the section is used by a program segment (there can be more than one)848 segment: ?*const Elf_Phdr = null, // if the section is used by a program segment (there can be more than one)
849 payload: ?[]align(section_memory_align) const u8 = null, // if we need the data in memory849 payload: ?[]align(section_memory_align.toByteUnits()) const u8 = null, // if we need the data in memory
850 category: SectionCategory = .none, // should the section be kept in the exe or stripped to the debug database, or both.850 category: SectionCategory = .none, // should the section be kept in the exe or stripped to the debug database, or both.
851 };851 };
852852
...@@ -999,7 +999,7 @@ fn ElfFile(comptime is_64: bool) type {...@@ -999,7 +999,7 @@ fn ElfFile(comptime is_64: bool) type {
999 remap_idx: u16,999 remap_idx: u16,
10001000
1001 // optionally overrides the payload from the source file1001 // optionally overrides the payload from the source file
1002 payload: ?[]align(section_memory_align) const u8 = null,1002 payload: ?[]align(section_memory_align.toByteUnits()) const u8 = null,
1003 section: ?Elf_Shdr = null,1003 section: ?Elf_Shdr = null,
1004 };1004 };
1005 const sections_update = try allocator.alloc(Update, self.sections.len);1005 const sections_update = try allocator.alloc(Update, self.sections.len);
...@@ -1219,7 +1219,7 @@ fn ElfFile(comptime is_64: bool) type {...@@ -1219,7 +1219,7 @@ fn ElfFile(comptime is_64: bool) type {
1219 if (options.debuglink) |link| {1219 if (options.debuglink) |link| {
1220 const payload = payload: {1220 const payload = payload: {
1221 const crc_offset = std.mem.alignForward(usize, link.name.len + 1, 4);1221 const crc_offset = std.mem.alignForward(usize, link.name.len + 1, 4);
1222 const buf = try allocator.alignedAlloc(u8, 4, crc_offset + 4);1222 const buf = try allocator.alignedAlloc(u8, .@"4", crc_offset + 4);
1223 @memcpy(buf[0..link.name.len], link.name);1223 @memcpy(buf[0..link.name.len], link.name);
1224 @memset(buf[link.name.len..crc_offset], 0);1224 @memset(buf[link.name.len..crc_offset], 0);
1225 @memcpy(buf[crc_offset..], std.mem.asBytes(&link.crc32));1225 @memcpy(buf[crc_offset..], std.mem.asBytes(&link.crc32));
...@@ -1498,7 +1498,7 @@ const ElfFileHelper = struct {...@@ -1498,7 +1498,7 @@ const ElfFileHelper = struct {
1498 var section_reader = std.io.limitedReader(in_file.reader(), size);1498 var section_reader = std.io.limitedReader(in_file.reader(), size);
14991499
1500 // allocate as large as decompressed data. if the compression doesn't fit, keep the data uncompressed.1500 // allocate as large as decompressed data. if the compression doesn't fit, keep the data uncompressed.
1501 const compressed_data = try allocator.alignedAlloc(u8, 8, @intCast(size));1501 const compressed_data = try allocator.alignedAlloc(u8, .@"8", @intCast(size));
1502 var compressed_stream = std.io.fixedBufferStream(compressed_data);1502 var compressed_stream = std.io.fixedBufferStream(compressed_data);
15031503
1504 try compressed_stream.writer().writeAll(prefix);1504 try compressed_stream.writer().writeAll(prefix);
lib/std/Build/Step/CheckObject.zig+1-1
...@@ -563,7 +563,7 @@ fn make(step: *Step, make_options: Step.MakeOptions) !void {...@@ -563,7 +563,7 @@ fn make(step: *Step, make_options: Step.MakeOptions) !void {
563 src_path.sub_path,563 src_path.sub_path,
564 check_object.max_bytes,564 check_object.max_bytes,
565 null,565 null,
566 @alignOf(u64),566 .of(u64),
567 null,567 null,
568 ) catch |err| return step.fail("unable to read '{'}': {s}", .{ src_path, @errorName(err) });568 ) catch |err| return step.fail("unable to read '{'}': {s}", .{ src_path, @errorName(err) });
569569
lib/std/Build/Watch.zig+1-1
...@@ -56,7 +56,7 @@ const Os = switch (builtin.os.tag) {...@@ -56,7 +56,7 @@ const Os = switch (builtin.os.tag) {
56 const bytes = lfh.slice();56 const bytes = lfh.slice();
57 const new_ptr = try gpa.alignedAlloc(57 const new_ptr = try gpa.alignedAlloc(
58 u8,58 u8,
59 @alignOf(std.os.linux.file_handle),59 .of(std.os.linux.file_handle),
60 @sizeOf(std.os.linux.file_handle) + bytes.len,60 @sizeOf(std.os.linux.file_handle) + bytes.len,
61 );61 );
62 const new_header: *std.os.linux.file_handle = @ptrCast(new_ptr);62 const new_header: *std.os.linux.file_handle = @ptrCast(new_ptr);
lib/std/array_hash_map.zig+1-1
...@@ -2129,7 +2129,7 @@ const IndexHeader = struct {...@@ -2129,7 +2129,7 @@ const IndexHeader = struct {
2129 const len = @as(usize, 1) << @as(math.Log2Int(usize), @intCast(new_bit_index));2129 const len = @as(usize, 1) << @as(math.Log2Int(usize), @intCast(new_bit_index));
2130 const index_size = hash_map.capacityIndexSize(new_bit_index);2130 const index_size = hash_map.capacityIndexSize(new_bit_index);
2131 const nbytes = @sizeOf(IndexHeader) + index_size * len;2131 const nbytes = @sizeOf(IndexHeader) + index_size * len;
2132 const bytes = try gpa.alignedAlloc(u8, @alignOf(IndexHeader), nbytes);2132 const bytes = try gpa.alignedAlloc(u8, .of(IndexHeader), nbytes);
2133 @memset(bytes[@sizeOf(IndexHeader)..], 0xff);2133 @memset(bytes[@sizeOf(IndexHeader)..], 0xff);
2134 const result: *IndexHeader = @alignCast(@ptrCast(bytes.ptr));2134 const result: *IndexHeader = @alignCast(@ptrCast(bytes.ptr));
2135 result.* = .{2135 result.* = .{
lib/std/array_list.zig+12-12
...@@ -22,9 +22,9 @@ pub fn ArrayList(comptime T: type) type {...@@ -22,9 +22,9 @@ pub fn ArrayList(comptime T: type) type {
22///22///
23/// This struct internally stores a `std.mem.Allocator` for memory management.23/// This struct internally stores a `std.mem.Allocator` for memory management.
24/// To manually specify an allocator with each function call see `ArrayListAlignedUnmanaged`.24/// To manually specify an allocator with each function call see `ArrayListAlignedUnmanaged`.
25pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {25pub fn ArrayListAligned(comptime T: type, comptime alignment: ?mem.Alignment) type {
26 if (alignment) |a| {26 if (alignment) |a| {
27 if (a == @alignOf(T)) {27 if (a.toByteUnits() == @alignOf(T)) {
28 return ArrayListAligned(T, null);28 return ArrayListAligned(T, null);
29 }29 }
30 }30 }
...@@ -43,10 +43,10 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {...@@ -43,10 +43,10 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
43 capacity: usize,43 capacity: usize,
44 allocator: Allocator,44 allocator: Allocator,
4545
46 pub const Slice = if (alignment) |a| ([]align(a) T) else []T;46 pub const Slice = if (alignment) |a| ([]align(a.toByteUnits()) T) else []T;
4747
48 pub fn SentinelSlice(comptime s: T) type {48 pub fn SentinelSlice(comptime s: T) type {
49 return if (alignment) |a| ([:s]align(a) T) else [:s]T;49 return if (alignment) |a| ([:s]align(a.toByteUnits()) T) else [:s]T;
50 }50 }
5151
52 /// Deinitialize with `deinit` or use `toOwnedSlice`.52 /// Deinitialize with `deinit` or use `toOwnedSlice`.
...@@ -611,9 +611,9 @@ pub fn ArrayListUnmanaged(comptime T: type) type {...@@ -611,9 +611,9 @@ pub fn ArrayListUnmanaged(comptime T: type) type {
611/// or use `toOwnedSlice`.611/// or use `toOwnedSlice`.
612///612///
613/// Default initialization of this struct is deprecated; use `.empty` instead.613/// Default initialization of this struct is deprecated; use `.empty` instead.
614pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) type {614pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?mem.Alignment) type {
615 if (alignment) |a| {615 if (alignment) |a| {
616 if (a == @alignOf(T)) {616 if (a.toByteUnits() == @alignOf(T)) {
617 return ArrayListAlignedUnmanaged(T, null);617 return ArrayListAlignedUnmanaged(T, null);
618 }618 }
619 }619 }
...@@ -637,10 +637,10 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ...@@ -637,10 +637,10 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
637 .capacity = 0,637 .capacity = 0,
638 };638 };
639639
640 pub const Slice = if (alignment) |a| ([]align(a) T) else []T;640 pub const Slice = if (alignment) |a| ([]align(a.toByteUnits()) T) else []T;
641641
642 pub fn SentinelSlice(comptime s: T) type {642 pub fn SentinelSlice(comptime s: T) type {
643 return if (alignment) |a| ([:s]align(a) T) else [:s]T;643 return if (alignment) |a| ([:s]align(a.toByteUnits()) T) else [:s]T;
644 }644 }
645645
646 /// Initialize with capacity to hold `num` elements.646 /// Initialize with capacity to hold `num` elements.
...@@ -1913,7 +1913,7 @@ test "ArrayList(u8) implements writer" {...@@ -1913,7 +1913,7 @@ test "ArrayList(u8) implements writer" {
1913 try testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.items);1913 try testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.items);
1914 }1914 }
1915 {1915 {
1916 var list = ArrayListAligned(u8, 2).init(a);1916 var list = ArrayListAligned(u8, .@"2").init(a);
1917 defer list.deinit();1917 defer list.deinit();
19181918
1919 const writer = list.writer();1919 const writer = list.writer();
...@@ -1940,7 +1940,7 @@ test "ArrayListUnmanaged(u8) implements writer" {...@@ -1940,7 +1940,7 @@ test "ArrayListUnmanaged(u8) implements writer" {
1940 try testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.items);1940 try testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.items);
1941 }1941 }
1942 {1942 {
1943 var list: ArrayListAlignedUnmanaged(u8, 2) = .empty;1943 var list: ArrayListAlignedUnmanaged(u8, .@"2") = .empty;
1944 defer list.deinit(a);1944 defer list.deinit(a);
19451945
1946 const writer = list.writer(a);1946 const writer = list.writer(a);
...@@ -2126,7 +2126,7 @@ test "toOwnedSliceSentinel" {...@@ -2126,7 +2126,7 @@ test "toOwnedSliceSentinel" {
2126test "accepts unaligned slices" {2126test "accepts unaligned slices" {
2127 const a = testing.allocator;2127 const a = testing.allocator;
2128 {2128 {
2129 var list = std.ArrayListAligned(u8, 8).init(a);2129 var list = std.ArrayListAligned(u8, .@"8").init(a);
2130 defer list.deinit();2130 defer list.deinit();
21312131
2132 try list.appendSlice(&.{ 0, 1, 2, 3 });2132 try list.appendSlice(&.{ 0, 1, 2, 3 });
...@@ -2136,7 +2136,7 @@ test "accepts unaligned slices" {...@@ -2136,7 +2136,7 @@ test "accepts unaligned slices" {
2136 try testing.expectEqualSlices(u8, list.items, &.{ 0, 8, 9, 6, 7, 2, 3 });2136 try testing.expectEqualSlices(u8, list.items, &.{ 0, 8, 9, 6, 7, 2, 3 });
2137 }2137 }
2138 {2138 {
2139 var list: std.ArrayListAlignedUnmanaged(u8, 8) = .empty;2139 var list: std.ArrayListAlignedUnmanaged(u8, .@"8") = .empty;
2140 defer list.deinit(a);2140 defer list.deinit(a);
21412141
2142 try list.appendSlice(a, &.{ 0, 1, 2, 3 });2142 try list.appendSlice(a, &.{ 0, 1, 2, 3 });
lib/std/bounded_array.zig+11-10
...@@ -2,6 +2,7 @@ const std = @import("std.zig");...@@ -2,6 +2,7 @@ const std = @import("std.zig");
2const assert = std.debug.assert;2const assert = std.debug.assert;
3const mem = std.mem;3const mem = std.mem;
4const testing = std.testing;4const testing = std.testing;
5const Alignment = std.mem.Alignment;
56
6/// A structure with an array and a length, that can be used as a slice.7/// A structure with an array and a length, that can be used as a slice.
7///8///
...@@ -16,7 +17,7 @@ const testing = std.testing;...@@ -16,7 +17,7 @@ const testing = std.testing;
16/// var a_clone = a; // creates a copy - the structure doesn't use any internal pointers17/// var a_clone = a; // creates a copy - the structure doesn't use any internal pointers
17/// ```18/// ```
18pub fn BoundedArray(comptime T: type, comptime buffer_capacity: usize) type {19pub fn BoundedArray(comptime T: type, comptime buffer_capacity: usize) type {
19 return BoundedArrayAligned(T, @alignOf(T), buffer_capacity);20 return BoundedArrayAligned(T, .of(T), buffer_capacity);
20}21}
2122
22/// A structure with an array, length and alignment, that can be used as a23/// A structure with an array, length and alignment, that can be used as a
...@@ -34,12 +35,12 @@ pub fn BoundedArray(comptime T: type, comptime buffer_capacity: usize) type {...@@ -34,12 +35,12 @@ pub fn BoundedArray(comptime T: type, comptime buffer_capacity: usize) type {
34/// ```35/// ```
35pub fn BoundedArrayAligned(36pub fn BoundedArrayAligned(
36 comptime T: type,37 comptime T: type,
37 comptime alignment: u29,38 comptime alignment: Alignment,
38 comptime buffer_capacity: usize,39 comptime buffer_capacity: usize,
39) type {40) type {
40 return struct {41 return struct {
41 const Self = @This();42 const Self = @This();
42 buffer: [buffer_capacity]T align(alignment) = undefined,43 buffer: [buffer_capacity]T align(alignment.toByteUnits()) = undefined,
43 len: usize = 0,44 len: usize = 0,
4445
45 /// Set the actual length of the slice.46 /// Set the actual length of the slice.
...@@ -51,15 +52,15 @@ pub fn BoundedArrayAligned(...@@ -51,15 +52,15 @@ pub fn BoundedArrayAligned(
5152
52 /// View the internal array as a slice whose size was previously set.53 /// View the internal array as a slice whose size was previously set.
53 pub fn slice(self: anytype) switch (@TypeOf(&self.buffer)) {54 pub fn slice(self: anytype) switch (@TypeOf(&self.buffer)) {
54 *align(alignment) [buffer_capacity]T => []align(alignment) T,55 *align(alignment.toByteUnits()) [buffer_capacity]T => []align(alignment.toByteUnits()) T,
55 *align(alignment) const [buffer_capacity]T => []align(alignment) const T,56 *align(alignment.toByteUnits()) const [buffer_capacity]T => []align(alignment.toByteUnits()) const T,
56 else => unreachable,57 else => unreachable,
57 } {58 } {
58 return self.buffer[0..self.len];59 return self.buffer[0..self.len];
59 }60 }
6061
61 /// View the internal array as a constant slice whose size was previously set.62 /// View the internal array as a constant slice whose size was previously set.
62 pub fn constSlice(self: *const Self) []align(alignment) const T {63 pub fn constSlice(self: *const Self) []align(alignment.toByteUnits()) const T {
63 return self.slice();64 return self.slice();
64 }65 }
6566
...@@ -120,7 +121,7 @@ pub fn BoundedArrayAligned(...@@ -120,7 +121,7 @@ pub fn BoundedArrayAligned(
120121
121 /// Resize the slice, adding `n` new elements, which have `undefined` values.122 /// Resize the slice, adding `n` new elements, which have `undefined` values.
122 /// The return value is a pointer to the array of uninitialized elements.123 /// The return value is a pointer to the array of uninitialized elements.
123 pub fn addManyAsArray(self: *Self, comptime n: usize) error{Overflow}!*align(alignment) [n]T {124 pub fn addManyAsArray(self: *Self, comptime n: usize) error{Overflow}!*align(alignment.toByteUnits()) [n]T {
124 const prev_len = self.len;125 const prev_len = self.len;
125 try self.resize(self.len + n);126 try self.resize(self.len + n);
126 return self.slice()[prev_len..][0..n];127 return self.slice()[prev_len..][0..n];
...@@ -128,7 +129,7 @@ pub fn BoundedArrayAligned(...@@ -128,7 +129,7 @@ pub fn BoundedArrayAligned(
128129
129 /// Resize the slice, adding `n` new elements, which have `undefined` values.130 /// Resize the slice, adding `n` new elements, which have `undefined` values.
130 /// The return value is a slice pointing to the uninitialized elements.131 /// The return value is a slice pointing to the uninitialized elements.
131 pub fn addManyAsSlice(self: *Self, n: usize) error{Overflow}![]align(alignment) T {132 pub fn addManyAsSlice(self: *Self, n: usize) error{Overflow}![]align(alignment.toByteUnits()) T {
132 const prev_len = self.len;133 const prev_len = self.len;
133 try self.resize(self.len + n);134 try self.resize(self.len + n);
134 return self.slice()[prev_len..][0..n];135 return self.slice()[prev_len..][0..n];
...@@ -146,7 +147,7 @@ pub fn BoundedArrayAligned(...@@ -146,7 +147,7 @@ pub fn BoundedArrayAligned(
146 /// This can be useful for writing directly into it.147 /// This can be useful for writing directly into it.
147 /// Note that such an operation must be followed up with a148 /// Note that such an operation must be followed up with a
148 /// call to `resize()`149 /// call to `resize()`
149 pub fn unusedCapacitySlice(self: *Self) []align(alignment) T {150 pub fn unusedCapacitySlice(self: *Self) []align(alignment.toByteUnits()) T {
150 return self.buffer[self.len..];151 return self.buffer[self.len..];
151 }152 }
152153
...@@ -399,7 +400,7 @@ test BoundedArray {...@@ -399,7 +400,7 @@ test BoundedArray {
399}400}
400401
401test "BoundedArrayAligned" {402test "BoundedArrayAligned" {
402 var a = try BoundedArrayAligned(u8, 16, 4).init(0);403 var a = try BoundedArrayAligned(u8, .@"16", 4).init(0);
403 try a.append(0);404 try a.append(0);
404 try a.append(0);405 try a.append(0);
405 try a.append(255);406 try a.append(255);
lib/std/crypto/argon2.zig+1-1
...@@ -14,7 +14,7 @@ const pwhash = crypto.pwhash;...@@ -14,7 +14,7 @@ const pwhash = crypto.pwhash;
1414
15const Thread = std.Thread;15const Thread = std.Thread;
16const Blake2b512 = blake2.Blake2b512;16const Blake2b512 = blake2.Blake2b512;
17const Blocks = std.ArrayListAligned([block_length]u64, 16);17const Blocks = std.ArrayListAligned([block_length]u64, .@"16");
18const H0 = [Blake2b512.digest_length + 8]u8;18const H0 = [Blake2b512.digest_length + 8]u8;
1919
20const EncodingError = crypto.errors.EncodingError;20const EncodingError = crypto.errors.EncodingError;
lib/std/crypto/scrypt.zig+3-3
...@@ -195,11 +195,11 @@ pub fn kdf(...@@ -195,11 +195,11 @@ pub fn kdf(
195 params.r > max_int / 256 or195 params.r > max_int / 256 or
196 n > max_int / 128 / @as(u64, params.r)) return KdfError.WeakParameters;196 n > max_int / 128 / @as(u64, params.r)) return KdfError.WeakParameters;
197197
198 const xy = try allocator.alignedAlloc(u32, 16, 64 * params.r);198 const xy = try allocator.alignedAlloc(u32, .@"16", 64 * params.r);
199 defer allocator.free(xy);199 defer allocator.free(xy);
200 const v = try allocator.alignedAlloc(u32, 16, 32 * n * params.r);200 const v = try allocator.alignedAlloc(u32, .@"16", 32 * n * params.r);
201 defer allocator.free(v);201 defer allocator.free(v);
202 var dk = try allocator.alignedAlloc(u8, 16, params.p * 128 * params.r);202 var dk = try allocator.alignedAlloc(u8, .@"16", params.p * 128 * params.r);
203 defer allocator.free(dk);203 defer allocator.free(dk);
204204
205 try pwhash.pbkdf2(dk, password, salt, 1, HmacSha256);205 try pwhash.pbkdf2(dk, password, salt, 1, HmacSha256);
lib/std/fs/Dir.zig+3-3
...@@ -1960,7 +1960,7 @@ pub fn readFile(self: Dir, file_path: []const u8, buffer: []u8) ![]u8 {...@@ -1960,7 +1960,7 @@ pub fn readFile(self: Dir, file_path: []const u8, buffer: []u8) ![]u8 {
1960/// On WASI, `file_path` should be encoded as valid UTF-8.1960/// On WASI, `file_path` should be encoded as valid UTF-8.
1961/// On other platforms, `file_path` is an opaque sequence of bytes with no particular encoding.1961/// On other platforms, `file_path` is an opaque sequence of bytes with no particular encoding.
1962pub fn readFileAlloc(self: Dir, allocator: mem.Allocator, file_path: []const u8, max_bytes: usize) ![]u8 {1962pub fn readFileAlloc(self: Dir, allocator: mem.Allocator, file_path: []const u8, max_bytes: usize) ![]u8 {
1963 return self.readFileAllocOptions(allocator, file_path, max_bytes, null, @alignOf(u8), null);1963 return self.readFileAllocOptions(allocator, file_path, max_bytes, null, .of(u8), null);
1964}1964}
19651965
1966/// On success, caller owns returned buffer.1966/// On success, caller owns returned buffer.
...@@ -1977,9 +1977,9 @@ pub fn readFileAllocOptions(...@@ -1977,9 +1977,9 @@ pub fn readFileAllocOptions(
1977 file_path: []const u8,1977 file_path: []const u8,
1978 max_bytes: usize,1978 max_bytes: usize,
1979 size_hint: ?usize,1979 size_hint: ?usize,
1980 comptime alignment: u29,1980 comptime alignment: std.mem.Alignment,
1981 comptime optional_sentinel: ?u8,1981 comptime optional_sentinel: ?u8,
1982) !(if (optional_sentinel) |s| [:s]align(alignment) u8 else []align(alignment) u8) {1982) !(if (optional_sentinel) |s| [:s]align(alignment.toByteUnits()) u8 else []align(alignment.toByteUnits()) u8) {
1983 var file = try self.openFile(file_path, .{});1983 var file = try self.openFile(file_path, .{});
1984 defer file.close();1984 defer file.close();
19851985
lib/std/fs/File.zig+4-3
...@@ -1133,7 +1133,7 @@ pub fn updateTimes(...@@ -1133,7 +1133,7 @@ pub fn updateTimes(
1133/// On success, caller owns returned buffer.1133/// On success, caller owns returned buffer.
1134/// If the file is larger than `max_bytes`, returns `error.FileTooBig`.1134/// If the file is larger than `max_bytes`, returns `error.FileTooBig`.
1135pub fn readToEndAlloc(self: File, allocator: Allocator, max_bytes: usize) ![]u8 {1135pub fn readToEndAlloc(self: File, allocator: Allocator, max_bytes: usize) ![]u8 {
1136 return self.readToEndAllocOptions(allocator, max_bytes, null, @alignOf(u8), null);1136 return self.readToEndAllocOptions(allocator, max_bytes, null, .of(u8), null);
1137}1137}
11381138
1139/// Reads all the bytes from the current position to the end of the file.1139/// Reads all the bytes from the current position to the end of the file.
...@@ -1147,9 +1147,9 @@ pub fn readToEndAllocOptions(...@@ -1147,9 +1147,9 @@ pub fn readToEndAllocOptions(
1147 allocator: Allocator,1147 allocator: Allocator,
1148 max_bytes: usize,1148 max_bytes: usize,
1149 size_hint: ?usize,1149 size_hint: ?usize,
1150 comptime alignment: u29,1150 comptime alignment: Alignment,
1151 comptime optional_sentinel: ?u8,1151 comptime optional_sentinel: ?u8,
1152) !(if (optional_sentinel) |s| [:s]align(alignment) u8 else []align(alignment) u8) {1152) !(if (optional_sentinel) |s| [:s]align(alignment.toByteUnits()) u8 else []align(alignment.toByteUnits()) u8) {
1153 // If no size hint is provided fall back to the size=0 code path1153 // If no size hint is provided fall back to the size=0 code path
1154 const size = size_hint orelse 0;1154 const size = size_hint orelse 0;
11551155
...@@ -1782,3 +1782,4 @@ const windows = std.os.windows;...@@ -1782,3 +1782,4 @@ const windows = std.os.windows;
1782const Os = std.builtin.Os;1782const Os = std.builtin.Os;
1783const maxInt = std.math.maxInt;1783const maxInt = std.math.maxInt;
1784const is_windows = builtin.os.tag == .windows;1784const is_windows = builtin.os.tag == .windows;
1785const Alignment = std.mem.Alignment;
lib/std/hash_map.zig+3-2
...@@ -6,6 +6,7 @@ const math = std.math;...@@ -6,6 +6,7 @@ const math = std.math;
6const mem = std.mem;6const mem = std.mem;
7const Allocator = mem.Allocator;7const Allocator = mem.Allocator;
8const Wyhash = std.hash.Wyhash;8const Wyhash = std.hash.Wyhash;
9const Alignment = std.mem.Alignment;
910
10pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) u64) {11pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) u64) {
11 comptime {12 comptime {
...@@ -1460,7 +1461,7 @@ pub fn HashMapUnmanaged(...@@ -1460,7 +1461,7 @@ pub fn HashMapUnmanaged(
1460 const header_align = @alignOf(Header);1461 const header_align = @alignOf(Header);
1461 const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K);1462 const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K);
1462 const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V);1463 const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V);
1463 const max_align = comptime @max(header_align, key_align, val_align);1464 const max_align: Alignment = comptime .fromByteUnits(@max(header_align, key_align, val_align));
14641465
1465 const new_cap: usize = new_capacity;1466 const new_cap: usize = new_capacity;
1466 const meta_size = @sizeOf(Header) + new_cap * @sizeOf(Metadata);1467 const meta_size = @sizeOf(Header) + new_cap * @sizeOf(Metadata);
...@@ -1472,7 +1473,7 @@ pub fn HashMapUnmanaged(...@@ -1472,7 +1473,7 @@ pub fn HashMapUnmanaged(
1472 const vals_start = std.mem.alignForward(usize, keys_end, val_align);1473 const vals_start = std.mem.alignForward(usize, keys_end, val_align);
1473 const vals_end = vals_start + new_cap * @sizeOf(V);1474 const vals_end = vals_start + new_cap * @sizeOf(V);
14741475
1475 const total_size = std.mem.alignForward(usize, vals_end, max_align);1476 const total_size = max_align.forward(vals_end);
14761477
1477 const slice = try allocator.alignedAlloc(u8, max_align, total_size);1478 const slice = try allocator.alignedAlloc(u8, max_align, total_size);
1478 const ptr: [*]u8 = @ptrCast(slice.ptr);1479 const ptr: [*]u8 = @ptrCast(slice.ptr);
lib/std/heap.zig+19-18
...@@ -7,6 +7,7 @@ const mem = std.mem;...@@ -7,6 +7,7 @@ const mem = std.mem;
7const c = std.c;7const c = std.c;
8const Allocator = std.mem.Allocator;8const Allocator = std.mem.Allocator;
9const windows = std.os.windows;9const windows = std.os.windows;
10const Alignment = std.mem.Alignment;
1011
11pub const ArenaAllocator = @import("heap/arena_allocator.zig").ArenaAllocator;12pub const ArenaAllocator = @import("heap/arena_allocator.zig").ArenaAllocator;
12pub const SmpAllocator = @import("heap/SmpAllocator.zig");13pub const SmpAllocator = @import("heap/SmpAllocator.zig");
...@@ -153,7 +154,7 @@ const CAllocator = struct {...@@ -153,7 +154,7 @@ const CAllocator = struct {
153 return @alignCast(@ptrCast(ptr - @sizeOf(usize)));154 return @alignCast(@ptrCast(ptr - @sizeOf(usize)));
154 }155 }
155156
156 fn alignedAlloc(len: usize, alignment: mem.Alignment) ?[*]u8 {157 fn alignedAlloc(len: usize, alignment: Alignment) ?[*]u8 {
157 const alignment_bytes = alignment.toByteUnits();158 const alignment_bytes = alignment.toByteUnits();
158 if (supports_posix_memalign) {159 if (supports_posix_memalign) {
159 // The posix_memalign only accepts alignment values that are a160 // The posix_memalign only accepts alignment values that are a
...@@ -201,7 +202,7 @@ const CAllocator = struct {...@@ -201,7 +202,7 @@ const CAllocator = struct {
201 fn alloc(202 fn alloc(
202 _: *anyopaque,203 _: *anyopaque,
203 len: usize,204 len: usize,
204 alignment: mem.Alignment,205 alignment: Alignment,
205 return_address: usize,206 return_address: usize,
206 ) ?[*]u8 {207 ) ?[*]u8 {
207 _ = return_address;208 _ = return_address;
...@@ -212,7 +213,7 @@ const CAllocator = struct {...@@ -212,7 +213,7 @@ const CAllocator = struct {
212 fn resize(213 fn resize(
213 _: *anyopaque,214 _: *anyopaque,
214 buf: []u8,215 buf: []u8,
215 alignment: mem.Alignment,216 alignment: Alignment,
216 new_len: usize,217 new_len: usize,
217 return_address: usize,218 return_address: usize,
218 ) bool {219 ) bool {
...@@ -233,7 +234,7 @@ const CAllocator = struct {...@@ -233,7 +234,7 @@ const CAllocator = struct {
233 fn remap(234 fn remap(
234 context: *anyopaque,235 context: *anyopaque,
235 memory: []u8,236 memory: []u8,
236 alignment: mem.Alignment,237 alignment: Alignment,
237 new_len: usize,238 new_len: usize,
238 return_address: usize,239 return_address: usize,
239 ) ?[*]u8 {240 ) ?[*]u8 {
...@@ -245,7 +246,7 @@ const CAllocator = struct {...@@ -245,7 +246,7 @@ const CAllocator = struct {
245 fn free(246 fn free(
246 _: *anyopaque,247 _: *anyopaque,
247 buf: []u8,248 buf: []u8,
248 alignment: mem.Alignment,249 alignment: Alignment,
249 return_address: usize,250 return_address: usize,
250 ) void {251 ) void {
251 _ = alignment;252 _ = alignment;
...@@ -281,7 +282,7 @@ const raw_c_allocator_vtable: Allocator.VTable = .{...@@ -281,7 +282,7 @@ const raw_c_allocator_vtable: Allocator.VTable = .{
281fn rawCAlloc(282fn rawCAlloc(
282 context: *anyopaque,283 context: *anyopaque,
283 len: usize,284 len: usize,
284 alignment: mem.Alignment,285 alignment: Alignment,
285 return_address: usize,286 return_address: usize,
286) ?[*]u8 {287) ?[*]u8 {
287 _ = context;288 _ = context;
...@@ -299,7 +300,7 @@ fn rawCAlloc(...@@ -299,7 +300,7 @@ fn rawCAlloc(
299fn rawCResize(300fn rawCResize(
300 context: *anyopaque,301 context: *anyopaque,
301 memory: []u8,302 memory: []u8,
302 alignment: mem.Alignment,303 alignment: Alignment,
303 new_len: usize,304 new_len: usize,
304 return_address: usize,305 return_address: usize,
305) bool {306) bool {
...@@ -314,7 +315,7 @@ fn rawCResize(...@@ -314,7 +315,7 @@ fn rawCResize(
314fn rawCRemap(315fn rawCRemap(
315 context: *anyopaque,316 context: *anyopaque,
316 memory: []u8,317 memory: []u8,
317 alignment: mem.Alignment,318 alignment: Alignment,
318 new_len: usize,319 new_len: usize,
319 return_address: usize,320 return_address: usize,
320) ?[*]u8 {321) ?[*]u8 {
...@@ -327,7 +328,7 @@ fn rawCRemap(...@@ -327,7 +328,7 @@ fn rawCRemap(
327fn rawCFree(328fn rawCFree(
328 context: *anyopaque,329 context: *anyopaque,
329 memory: []u8,330 memory: []u8,
330 alignment: mem.Alignment,331 alignment: Alignment,
331 return_address: usize,332 return_address: usize,
332) void {333) void {
333 _ = context;334 _ = context;
...@@ -425,7 +426,7 @@ pub fn StackFallbackAllocator(comptime size: usize) type {...@@ -425,7 +426,7 @@ pub fn StackFallbackAllocator(comptime size: usize) type {
425 fn alloc(426 fn alloc(
426 ctx: *anyopaque,427 ctx: *anyopaque,
427 len: usize,428 len: usize,
428 alignment: mem.Alignment,429 alignment: Alignment,
429 ra: usize,430 ra: usize,
430 ) ?[*]u8 {431 ) ?[*]u8 {
431 const self: *Self = @ptrCast(@alignCast(ctx));432 const self: *Self = @ptrCast(@alignCast(ctx));
...@@ -436,7 +437,7 @@ pub fn StackFallbackAllocator(comptime size: usize) type {...@@ -436,7 +437,7 @@ pub fn StackFallbackAllocator(comptime size: usize) type {
436 fn resize(437 fn resize(
437 ctx: *anyopaque,438 ctx: *anyopaque,
438 buf: []u8,439 buf: []u8,
439 alignment: mem.Alignment,440 alignment: Alignment,
440 new_len: usize,441 new_len: usize,
441 ra: usize,442 ra: usize,
442 ) bool {443 ) bool {
...@@ -451,7 +452,7 @@ pub fn StackFallbackAllocator(comptime size: usize) type {...@@ -451,7 +452,7 @@ pub fn StackFallbackAllocator(comptime size: usize) type {
451 fn remap(452 fn remap(
452 context: *anyopaque,453 context: *anyopaque,
453 memory: []u8,454 memory: []u8,
454 alignment: mem.Alignment,455 alignment: Alignment,
455 new_len: usize,456 new_len: usize,
456 return_address: usize,457 return_address: usize,
457 ) ?[*]u8 {458 ) ?[*]u8 {
...@@ -466,7 +467,7 @@ pub fn StackFallbackAllocator(comptime size: usize) type {...@@ -466,7 +467,7 @@ pub fn StackFallbackAllocator(comptime size: usize) type {
466 fn free(467 fn free(
467 ctx: *anyopaque,468 ctx: *anyopaque,
468 buf: []u8,469 buf: []u8,
469 alignment: mem.Alignment,470 alignment: Alignment,
470 ra: usize,471 ra: usize,
471 ) void {472 ) void {
472 const self: *Self = @ptrCast(@alignCast(ctx));473 const self: *Self = @ptrCast(@alignCast(ctx));
...@@ -512,7 +513,7 @@ test PageAllocator {...@@ -512,7 +513,7 @@ test PageAllocator {
512 }513 }
513514
514 if (builtin.os.tag == .windows) {515 if (builtin.os.tag == .windows) {
515 const slice = try allocator.alignedAlloc(u8, page_size_min, 128);516 const slice = try allocator.alignedAlloc(u8, .fromByteUnits(page_size_min), 128);
516 slice[0] = 0x12;517 slice[0] = 0x12;
517 slice[127] = 0x34;518 slice[127] = 0x34;
518 allocator.free(slice);519 allocator.free(slice);
...@@ -609,7 +610,7 @@ pub fn testAllocatorAligned(base_allocator: mem.Allocator) !void {...@@ -609,7 +610,7 @@ pub fn testAllocatorAligned(base_allocator: mem.Allocator) !void {
609 const allocator = validationAllocator.allocator();610 const allocator = validationAllocator.allocator();
610611
611 // Test a few alignment values, smaller and bigger than the type's one612 // Test a few alignment values, smaller and bigger than the type's one
612 inline for ([_]u29{ 1, 2, 4, 8, 16, 32, 64 }) |alignment| {613 inline for ([_]Alignment{ .@"1", .@"2", .@"4", .@"8", .@"16", .@"32", .@"64" }) |alignment| {
613 // initial614 // initial
614 var slice = try allocator.alignedAlloc(u8, alignment, 10);615 var slice = try allocator.alignedAlloc(u8, alignment, 10);
615 try testing.expect(slice.len == 10);616 try testing.expect(slice.len == 10);
...@@ -640,7 +641,7 @@ pub fn testAllocatorLargeAlignment(base_allocator: mem.Allocator) !void {...@@ -640,7 +641,7 @@ pub fn testAllocatorLargeAlignment(base_allocator: mem.Allocator) !void {
640 var align_mask: usize = undefined;641 var align_mask: usize = undefined;
641 align_mask = @shlWithOverflow(~@as(usize, 0), @as(Allocator.Log2Align, @ctz(large_align)))[0];642 align_mask = @shlWithOverflow(~@as(usize, 0), @as(Allocator.Log2Align, @ctz(large_align)))[0];
642643
643 var slice = try allocator.alignedAlloc(u8, large_align, 500);644 var slice = try allocator.alignedAlloc(u8, .fromByteUnits(large_align), 500);
644 try testing.expect(@intFromPtr(slice.ptr) & align_mask == @intFromPtr(slice.ptr));645 try testing.expect(@intFromPtr(slice.ptr) & align_mask == @intFromPtr(slice.ptr));
645646
646 if (allocator.resize(slice, 100)) {647 if (allocator.resize(slice, 100)) {
...@@ -669,7 +670,7 @@ pub fn testAllocatorAlignedShrink(base_allocator: mem.Allocator) !void {...@@ -669,7 +670,7 @@ pub fn testAllocatorAlignedShrink(base_allocator: mem.Allocator) !void {
669 const debug_allocator = fib.allocator();670 const debug_allocator = fib.allocator();
670671
671 const alloc_size = pageSize() * 2 + 50;672 const alloc_size = pageSize() * 2 + 50;
672 var slice = try allocator.alignedAlloc(u8, 16, alloc_size);673 var slice = try allocator.alignedAlloc(u8, .@"16", alloc_size);
673 defer allocator.free(slice);674 defer allocator.free(slice);
674675
675 var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator);676 var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator);
...@@ -679,7 +680,7 @@ pub fn testAllocatorAlignedShrink(base_allocator: mem.Allocator) !void {...@@ -679,7 +680,7 @@ pub fn testAllocatorAlignedShrink(base_allocator: mem.Allocator) !void {
679 // fail, because of this high over-alignment we want to have.680 // fail, because of this high over-alignment we want to have.
680 while (@intFromPtr(slice.ptr) == mem.alignForward(usize, @intFromPtr(slice.ptr), pageSize() * 32)) {681 while (@intFromPtr(slice.ptr) == mem.alignForward(usize, @intFromPtr(slice.ptr), pageSize() * 32)) {
681 try stuff_to_free.append(slice);682 try stuff_to_free.append(slice);
682 slice = try allocator.alignedAlloc(u8, 16, alloc_size);683 slice = try allocator.alignedAlloc(u8, .@"16", alloc_size);
683 }684 }
684 while (stuff_to_free.pop()) |item| {685 while (stuff_to_free.pop()) |item| {
685 allocator.free(item);686 allocator.free(item);
lib/std/heap/WasmAllocator.zig+1-1
...@@ -218,7 +218,7 @@ test "very large allocation" {...@@ -218,7 +218,7 @@ test "very large allocation" {
218}218}
219219
220test "realloc" {220test "realloc" {
221 var slice = try test_ally.alignedAlloc(u8, @alignOf(u32), 1);221 var slice = try test_ally.alignedAlloc(u8, .of(u32), 1);
222 defer test_ally.free(slice);222 defer test_ally.free(slice);
223 slice[0] = 0x12;223 slice[0] = 0x12;
224224
lib/std/heap/arena_allocator.zig+8-7
...@@ -2,6 +2,7 @@ const std = @import("../std.zig");...@@ -2,6 +2,7 @@ const std = @import("../std.zig");
2const assert = std.debug.assert;2const assert = std.debug.assert;
3const mem = std.mem;3const mem = std.mem;
4const Allocator = std.mem.Allocator;4const Allocator = std.mem.Allocator;
5const Alignment = std.mem.Alignment;
56
6/// This allocator takes an existing allocator, wraps it, and provides an interface where7/// This allocator takes an existing allocator, wraps it, and provides an interface where
7/// you can allocate and then free it all together. Calls to free an individual item only8/// you can allocate and then free it all together. Calls to free an individual item only
...@@ -41,7 +42,7 @@ pub const ArenaAllocator = struct {...@@ -41,7 +42,7 @@ pub const ArenaAllocator = struct {
41 data: usize,42 data: usize,
42 node: std.SinglyLinkedList.Node = .{},43 node: std.SinglyLinkedList.Node = .{},
43 };44 };
44 const BufNode_alignment: mem.Alignment = .fromByteUnits(@alignOf(BufNode));45 const BufNode_alignment: Alignment = .fromByteUnits(@alignOf(BufNode));
4546
46 pub fn init(child_allocator: Allocator) ArenaAllocator {47 pub fn init(child_allocator: Allocator) ArenaAllocator {
47 return (State{}).promote(child_allocator);48 return (State{}).promote(child_allocator);
...@@ -181,7 +182,7 @@ pub const ArenaAllocator = struct {...@@ -181,7 +182,7 @@ pub const ArenaAllocator = struct {
181 return buf_node;182 return buf_node;
182 }183 }
183184
184 fn alloc(ctx: *anyopaque, n: usize, alignment: mem.Alignment, ra: usize) ?[*]u8 {185 fn alloc(ctx: *anyopaque, n: usize, alignment: Alignment, ra: usize) ?[*]u8 {
185 const self: *ArenaAllocator = @ptrCast(@alignCast(ctx));186 const self: *ArenaAllocator = @ptrCast(@alignCast(ctx));
186 _ = ra;187 _ = ra;
187188
...@@ -214,7 +215,7 @@ pub const ArenaAllocator = struct {...@@ -214,7 +215,7 @@ pub const ArenaAllocator = struct {
214 }215 }
215 }216 }
216217
217 fn resize(ctx: *anyopaque, buf: []u8, alignment: mem.Alignment, new_len: usize, ret_addr: usize) bool {218 fn resize(ctx: *anyopaque, buf: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool {
218 const self: *ArenaAllocator = @ptrCast(@alignCast(ctx));219 const self: *ArenaAllocator = @ptrCast(@alignCast(ctx));
219 _ = alignment;220 _ = alignment;
220 _ = ret_addr;221 _ = ret_addr;
...@@ -242,14 +243,14 @@ pub const ArenaAllocator = struct {...@@ -242,14 +243,14 @@ pub const ArenaAllocator = struct {
242 fn remap(243 fn remap(
243 context: *anyopaque,244 context: *anyopaque,
244 memory: []u8,245 memory: []u8,
245 alignment: mem.Alignment,246 alignment: Alignment,
246 new_len: usize,247 new_len: usize,
247 return_address: usize,248 return_address: usize,
248 ) ?[*]u8 {249 ) ?[*]u8 {
249 return if (resize(context, memory, alignment, new_len, return_address)) memory.ptr else null;250 return if (resize(context, memory, alignment, new_len, return_address)) memory.ptr else null;
250 }251 }
251252
252 fn free(ctx: *anyopaque, buf: []u8, alignment: mem.Alignment, ret_addr: usize) void {253 fn free(ctx: *anyopaque, buf: []u8, alignment: Alignment, ret_addr: usize) void {
253 _ = alignment;254 _ = alignment;
254 _ = ret_addr;255 _ = ret_addr;
255256
...@@ -279,9 +280,9 @@ test "reset with preheating" {...@@ -279,9 +280,9 @@ test "reset with preheating" {
279 const total_size: usize = random.intRangeAtMost(usize, 256, 16384);280 const total_size: usize = random.intRangeAtMost(usize, 256, 16384);
280 while (alloced_bytes < total_size) {281 while (alloced_bytes < total_size) {
281 const size = random.intRangeAtMost(usize, 16, 256);282 const size = random.intRangeAtMost(usize, 16, 256);
282 const alignment = 32;283 const alignment: Alignment = .@"32";
283 const slice = try arena_allocator.allocator().alignedAlloc(u8, alignment, size);284 const slice = try arena_allocator.allocator().alignedAlloc(u8, alignment, size);
284 try std.testing.expect(std.mem.isAligned(@intFromPtr(slice.ptr), alignment));285 try std.testing.expect(alignment.check(@intFromPtr(slice.ptr)));
285 try std.testing.expectEqual(size, slice.len);286 try std.testing.expectEqual(size, slice.len);
286 alloced_bytes += slice.len;287 alloced_bytes += slice.len;
287 }288 }
lib/std/heap/debug_allocator.zig+6-6
...@@ -1120,7 +1120,7 @@ test "realloc" {...@@ -1120,7 +1120,7 @@ test "realloc" {
1120 defer std.testing.expect(gpa.deinit() == .ok) catch @panic("leak");1120 defer std.testing.expect(gpa.deinit() == .ok) catch @panic("leak");
1121 const allocator = gpa.allocator();1121 const allocator = gpa.allocator();
11221122
1123 var slice = try allocator.alignedAlloc(u8, @alignOf(u32), 1);1123 var slice = try allocator.alignedAlloc(u8, .of(u32), 1);
1124 defer allocator.free(slice);1124 defer allocator.free(slice);
1125 slice[0] = 0x12;1125 slice[0] = 0x12;
11261126
...@@ -1234,7 +1234,7 @@ test "shrink large object to large object with larger alignment" {...@@ -1234,7 +1234,7 @@ test "shrink large object to large object with larger alignment" {
1234 const debug_allocator = fba.allocator();1234 const debug_allocator = fba.allocator();
12351235
1236 const alloc_size = default_page_size * 2 + 50;1236 const alloc_size = default_page_size * 2 + 50;
1237 var slice = try allocator.alignedAlloc(u8, 16, alloc_size);1237 var slice = try allocator.alignedAlloc(u8, .@"16", alloc_size);
1238 defer allocator.free(slice);1238 defer allocator.free(slice);
12391239
1240 const big_alignment: usize = default_page_size * 2;1240 const big_alignment: usize = default_page_size * 2;
...@@ -1244,7 +1244,7 @@ test "shrink large object to large object with larger alignment" {...@@ -1244,7 +1244,7 @@ test "shrink large object to large object with larger alignment" {
1244 var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator);1244 var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator);
1245 while (mem.isAligned(@intFromPtr(slice.ptr), big_alignment)) {1245 while (mem.isAligned(@intFromPtr(slice.ptr), big_alignment)) {
1246 try stuff_to_free.append(slice);1246 try stuff_to_free.append(slice);
1247 slice = try allocator.alignedAlloc(u8, 16, alloc_size);1247 slice = try allocator.alignedAlloc(u8, .@"16", alloc_size);
1248 }1248 }
1249 while (stuff_to_free.pop()) |item| {1249 while (stuff_to_free.pop()) |item| {
1250 allocator.free(item);1250 allocator.free(item);
...@@ -1308,7 +1308,7 @@ test "realloc large object to larger alignment" {...@@ -1308,7 +1308,7 @@ test "realloc large object to larger alignment" {
1308 var fba = std.heap.FixedBufferAllocator.init(&debug_buffer);1308 var fba = std.heap.FixedBufferAllocator.init(&debug_buffer);
1309 const debug_allocator = fba.allocator();1309 const debug_allocator = fba.allocator();
13101310
1311 var slice = try allocator.alignedAlloc(u8, 16, default_page_size * 2 + 50);1311 var slice = try allocator.alignedAlloc(u8, .@"16", default_page_size * 2 + 50);
1312 defer allocator.free(slice);1312 defer allocator.free(slice);
13131313
1314 const big_alignment: usize = default_page_size * 2;1314 const big_alignment: usize = default_page_size * 2;
...@@ -1316,7 +1316,7 @@ test "realloc large object to larger alignment" {...@@ -1316,7 +1316,7 @@ test "realloc large object to larger alignment" {
1316 var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator);1316 var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator);
1317 while (mem.isAligned(@intFromPtr(slice.ptr), big_alignment)) {1317 while (mem.isAligned(@intFromPtr(slice.ptr), big_alignment)) {
1318 try stuff_to_free.append(slice);1318 try stuff_to_free.append(slice);
1319 slice = try allocator.alignedAlloc(u8, 16, default_page_size * 2 + 50);1319 slice = try allocator.alignedAlloc(u8, .@"16", default_page_size * 2 + 50);
1320 }1320 }
1321 while (stuff_to_free.pop()) |item| {1321 while (stuff_to_free.pop()) |item| {
1322 allocator.free(item);1322 allocator.free(item);
...@@ -1402,7 +1402,7 @@ test "large allocations count requested size not backing size" {...@@ -1402,7 +1402,7 @@ test "large allocations count requested size not backing size" {
1402 var gpa: DebugAllocator(.{ .enable_memory_limit = true }) = .{};1402 var gpa: DebugAllocator(.{ .enable_memory_limit = true }) = .{};
1403 const allocator = gpa.allocator();1403 const allocator = gpa.allocator();
14041404
1405 var buf = try allocator.alignedAlloc(u8, 1, default_page_size + 1);1405 var buf = try allocator.alignedAlloc(u8, .@"1", default_page_size + 1);
1406 try std.testing.expectEqual(default_page_size + 1, gpa.total_requested_bytes);1406 try std.testing.expectEqual(default_page_size + 1, gpa.total_requested_bytes);
1407 buf = try allocator.realloc(buf, 1);1407 buf = try allocator.realloc(buf, 1);
1408 try std.testing.expectEqual(1, gpa.total_requested_bytes);1408 try std.testing.expectEqual(1, gpa.total_requested_bytes);
lib/std/heap/memory_pool.zig+12-11
...@@ -1,4 +1,5 @@...@@ -1,4 +1,5 @@
1const std = @import("../std.zig");1const std = @import("../std.zig");
2const Alignment = std.mem.Alignment;
23
3const debug_mode = @import("builtin").mode == .Debug;4const debug_mode = @import("builtin").mode == .Debug;
45
...@@ -8,14 +9,14 @@ pub const MemoryPoolError = error{OutOfMemory};...@@ -8,14 +9,14 @@ pub const MemoryPoolError = error{OutOfMemory};
8/// Use this when you need to allocate a lot of objects of the same type,9/// Use this when you need to allocate a lot of objects of the same type,
9/// because It outperforms general purpose allocators.10/// because It outperforms general purpose allocators.
10pub fn MemoryPool(comptime Item: type) type {11pub fn MemoryPool(comptime Item: type) type {
11 return MemoryPoolAligned(Item, @alignOf(Item));12 return MemoryPoolAligned(Item, .of(Item));
12}13}
1314
14/// A memory pool that can allocate objects of a single type very quickly.15/// A memory pool that can allocate objects of a single type very quickly.
15/// Use this when you need to allocate a lot of objects of the same type,16/// Use this when you need to allocate a lot of objects of the same type,
16/// because It outperforms general purpose allocators.17/// because It outperforms general purpose allocators.
17pub fn MemoryPoolAligned(comptime Item: type, comptime alignment: u29) type {18pub fn MemoryPoolAligned(comptime Item: type, comptime alignment: Alignment) type {
18 if (@alignOf(Item) == alignment) {19 if (@alignOf(Item) == comptime alignment.toByteUnits()) {
19 return MemoryPoolExtra(Item, .{});20 return MemoryPoolExtra(Item, .{});
20 } else {21 } else {
21 return MemoryPoolExtra(Item, .{ .alignment = alignment });22 return MemoryPoolExtra(Item, .{ .alignment = alignment });
...@@ -24,7 +25,7 @@ pub fn MemoryPoolAligned(comptime Item: type, comptime alignment: u29) type {...@@ -24,7 +25,7 @@ pub fn MemoryPoolAligned(comptime Item: type, comptime alignment: u29) type {
2425
25pub const Options = struct {26pub const Options = struct {
26 /// The alignment of the memory pool items. Use `null` for natural alignment.27 /// The alignment of the memory pool items. Use `null` for natural alignment.
27 alignment: ?u29 = null,28 alignment: ?Alignment = null,
2829
29 /// If `true`, the memory pool can allocate additional items after a initial setup.30 /// If `true`, the memory pool can allocate additional items after a initial setup.
30 /// If `false`, the memory pool will not allocate further after a call to `initPreheated`.31 /// If `false`, the memory pool will not allocate further after a call to `initPreheated`.
...@@ -43,17 +44,17 @@ pub fn MemoryPoolExtra(comptime Item: type, comptime pool_options: Options) type...@@ -43,17 +44,17 @@ pub fn MemoryPoolExtra(comptime Item: type, comptime pool_options: Options) type
43 pub const item_size = @max(@sizeOf(Node), @sizeOf(Item));44 pub const item_size = @max(@sizeOf(Node), @sizeOf(Item));
4445
45 // This needs to be kept in sync with Node.46 // This needs to be kept in sync with Node.
46 const node_alignment = @alignOf(*anyopaque);47 const node_alignment: Alignment = .of(*anyopaque);
4748
48 /// Alignment of the memory pool items. This is not necessarily the same49 /// Alignment of the memory pool items. This is not necessarily the same
49 /// as `@alignOf(Item)` as the pool also uses the items for internal means.50 /// as `@alignOf(Item)` as the pool also uses the items for internal means.
50 pub const item_alignment = @max(node_alignment, pool_options.alignment orelse @alignOf(Item));51 pub const item_alignment: Alignment = node_alignment.max(pool_options.alignment orelse .of(Item));
5152
52 const Node = struct {53 const Node = struct {
53 next: ?*align(item_alignment) @This(),54 next: ?*align(item_alignment.toByteUnits()) @This(),
54 };55 };
55 const NodePtr = *align(item_alignment) Node;56 const NodePtr = *align(item_alignment.toByteUnits()) Node;
56 const ItemPtr = *align(item_alignment) Item;57 const ItemPtr = *align(item_alignment.toByteUnits()) Item;
5758
58 arena: std.heap.ArenaAllocator,59 arena: std.heap.ArenaAllocator,
59 free_list: ?NodePtr = null,60 free_list: ?NodePtr = null,
...@@ -143,7 +144,7 @@ pub fn MemoryPoolExtra(comptime Item: type, comptime pool_options: Options) type...@@ -143,7 +144,7 @@ pub fn MemoryPoolExtra(comptime Item: type, comptime pool_options: Options) type
143 pool.free_list = node;144 pool.free_list = node;
144 }145 }
145146
146 fn allocNew(pool: *Pool) MemoryPoolError!*align(item_alignment) [item_size]u8 {147 fn allocNew(pool: *Pool) MemoryPoolError!*align(item_alignment.toByteUnits()) [item_size]u8 {
147 const mem = try pool.arena.allocator().alignedAlloc(u8, item_alignment, item_size);148 const mem = try pool.arena.allocator().alignedAlloc(u8, item_alignment, item_size);
148 return mem[0..item_size]; // coerce slice to array pointer149 return mem[0..item_size]; // coerce slice to array pointer
149 }150 }
...@@ -213,7 +214,7 @@ test "greater than pointer manual alignment" {...@@ -213,7 +214,7 @@ test "greater than pointer manual alignment" {
213 data: u64,214 data: u64,
214 };215 };
215216
216 var pool = MemoryPoolAligned(Foo, 16).init(std.testing.allocator);217 var pool = MemoryPoolAligned(Foo, .@"16").init(std.testing.allocator);
217 defer pool.deinit();218 defer pool.deinit();
218219
219 const foo: *align(16) Foo = try pool.create();220 const foo: *align(16) Foo = try pool.create();
lib/std/io.zig+2-2
...@@ -5,7 +5,6 @@ const c = std.c;...@@ -5,7 +5,6 @@ const c = std.c;
5const is_windows = builtin.os.tag == .windows;5const is_windows = builtin.os.tag == .windows;
6const windows = std.os.windows;6const windows = std.os.windows;
7const posix = std.posix;7const posix = std.posix;
8
9const math = std.math;8const math = std.math;
10const assert = std.debug.assert;9const assert = std.debug.assert;
11const fs = std.fs;10const fs = std.fs;
...@@ -13,6 +12,7 @@ const mem = std.mem;...@@ -13,6 +12,7 @@ const mem = std.mem;
13const meta = std.meta;12const meta = std.meta;
14const File = std.fs.File;13const File = std.fs.File;
15const Allocator = std.mem.Allocator;14const Allocator = std.mem.Allocator;
15const Alignment = std.mem.Alignment;
1616
17fn getStdOutHandle() posix.fd_t {17fn getStdOutHandle() posix.fd_t {
18 if (is_windows) {18 if (is_windows) {
...@@ -104,7 +104,7 @@ pub fn GenericReader(...@@ -104,7 +104,7 @@ pub fn GenericReader(
104104
105 pub inline fn readAllArrayListAligned(105 pub inline fn readAllArrayListAligned(
106 self: Self,106 self: Self,
107 comptime alignment: ?u29,107 comptime alignment: ?Alignment,
108 array_list: *std.ArrayListAligned(u8, alignment),108 array_list: *std.ArrayListAligned(u8, alignment),
109 max_append_size: usize,109 max_append_size: usize,
110 ) (error{StreamTooLong} || Allocator.Error || Error)!void {110 ) (error{StreamTooLong} || Allocator.Error || Error)!void {
lib/std/io/Reader.zig+2-1
...@@ -54,7 +54,7 @@ pub fn readAllArrayList(...@@ -54,7 +54,7 @@ pub fn readAllArrayList(
5454
55pub fn readAllArrayListAligned(55pub fn readAllArrayListAligned(
56 self: Self,56 self: Self,
57 comptime alignment: ?u29,57 comptime alignment: ?Alignment,
58 array_list: *std.ArrayListAligned(u8, alignment),58 array_list: *std.ArrayListAligned(u8, alignment),
59 max_append_size: usize,59 max_append_size: usize,
60) anyerror!void {60) anyerror!void {
...@@ -379,6 +379,7 @@ const assert = std.debug.assert;...@@ -379,6 +379,7 @@ const assert = std.debug.assert;
379const mem = std.mem;379const mem = std.mem;
380const testing = std.testing;380const testing = std.testing;
381const native_endian = @import("builtin").target.cpu.arch.endian();381const native_endian = @import("builtin").target.cpu.arch.endian();
382const Alignment = std.mem.Alignment;
382383
383test {384test {
384 _ = @import("Reader/test.zig");385 _ = @import("Reader/test.zig");
lib/std/math.zig+6-8
...@@ -4,6 +4,7 @@ const float = @import("math/float.zig");...@@ -4,6 +4,7 @@ const float = @import("math/float.zig");
4const assert = std.debug.assert;4const assert = std.debug.assert;
5const mem = std.mem;5const mem = std.mem;
6const testing = std.testing;6const testing = std.testing;
7const Alignment = std.mem.Alignment;
78
8/// Euler's number (e)9/// Euler's number (e)
9pub const e = 2.71828182845904523536028747135266249775724709369995;10pub const e = 2.71828182845904523536028747135266249775724709369995;
...@@ -1084,19 +1085,16 @@ test cast {...@@ -1084,19 +1085,16 @@ test cast {
10841085
1085pub const AlignCastError = error{UnalignedMemory};1086pub const AlignCastError = error{UnalignedMemory};
10861087
1087fn AlignCastResult(comptime alignment: u29, comptime Ptr: type) type {1088fn AlignCastResult(comptime alignment: Alignment, comptime Ptr: type) type {
1088 var ptr_info = @typeInfo(Ptr);1089 var ptr_info = @typeInfo(Ptr);
1089 ptr_info.pointer.alignment = alignment;1090 ptr_info.pointer.alignment = alignment.toByteUnits();
1090 return @Type(ptr_info);1091 return @Type(ptr_info);
1091}1092}
10921093
1093/// Align cast a pointer but return an error if it's the wrong alignment1094/// Align cast a pointer but return an error if it's the wrong alignment
1094pub fn alignCast(comptime alignment: u29, ptr: anytype) AlignCastError!AlignCastResult(alignment, @TypeOf(ptr)) {1095pub fn alignCast(comptime alignment: Alignment, ptr: anytype) AlignCastError!AlignCastResult(alignment, @TypeOf(ptr)) {
1095 const addr = @intFromPtr(ptr);1096 if (alignment.check(@intFromPtr(ptr))) return @alignCast(ptr);
1096 if (addr % alignment != 0) {1097 return error.UnalignedMemory;
1097 return error.UnalignedMemory;
1098 }
1099 return @alignCast(ptr);
1100}1098}
11011099
1102/// Asserts `int > 0`.1100/// Asserts `int > 0`.
lib/std/mem.zig+4-15
...@@ -38,6 +38,10 @@ pub const Alignment = enum(math.Log2Int(usize)) {...@@ -38,6 +38,10 @@ pub const Alignment = enum(math.Log2Int(usize)) {
38 return @enumFromInt(@ctz(n));38 return @enumFromInt(@ctz(n));
39 }39 }
4040
41 pub inline fn of(comptime T: type) Alignment {
42 return comptime fromByteUnits(@alignOf(T));
43 }
44
41 pub fn order(lhs: Alignment, rhs: Alignment) std.math.Order {45 pub fn order(lhs: Alignment, rhs: Alignment) std.math.Order {
42 return std.math.order(@intFromEnum(lhs), @intFromEnum(rhs));46 return std.math.order(@intFromEnum(lhs), @intFromEnum(rhs));
43 }47 }
...@@ -166,21 +170,6 @@ pub fn validationWrap(allocator: anytype) ValidationAllocator(@TypeOf(allocator)...@@ -166,21 +170,6 @@ pub fn validationWrap(allocator: anytype) ValidationAllocator(@TypeOf(allocator)
166 return ValidationAllocator(@TypeOf(allocator)).init(allocator);170 return ValidationAllocator(@TypeOf(allocator)).init(allocator);
167}171}
168172
169/// An allocator helper function. Adjusts an allocation length satisfy `len_align`.
170/// `full_len` should be the full capacity of the allocation which may be greater
171/// than the `len` that was requested. This function should only be used by allocators
172/// that are unaffected by `len_align`.
173pub fn alignAllocLen(full_len: usize, alloc_len: usize, len_align: u29) usize {
174 assert(alloc_len > 0);
175 assert(alloc_len >= len_align);
176 assert(full_len >= alloc_len);
177 if (len_align == 0)
178 return alloc_len;
179 const adjusted = alignBackwardAnyAlign(usize, full_len, len_align);
180 assert(adjusted >= alloc_len);
181 return adjusted;
182}
183
184test "Allocator basics" {173test "Allocator basics" {
185 try testing.expectError(error.OutOfMemory, testing.failing_allocator.alloc(u8, 1));174 try testing.expectError(error.OutOfMemory, testing.failing_allocator.alloc(u8, 1));
186 try testing.expectError(error.OutOfMemory, testing.failing_allocator.allocSentinel(u8, 1, 0));175 try testing.expectError(error.OutOfMemory, testing.failing_allocator.allocSentinel(u8, 1, 0));
lib/std/mem/Allocator.zig+30-19
...@@ -152,9 +152,9 @@ pub inline fn rawFree(a: Allocator, memory: []u8, alignment: Alignment, ret_addr...@@ -152,9 +152,9 @@ pub inline fn rawFree(a: Allocator, memory: []u8, alignment: Alignment, ret_addr
152pub fn create(a: Allocator, comptime T: type) Error!*T {152pub fn create(a: Allocator, comptime T: type) Error!*T {
153 if (@sizeOf(T) == 0) {153 if (@sizeOf(T) == 0) {
154 const ptr = comptime std.mem.alignBackward(usize, math.maxInt(usize), @alignOf(T));154 const ptr = comptime std.mem.alignBackward(usize, math.maxInt(usize), @alignOf(T));
155 return @as(*T, @ptrFromInt(ptr));155 return @ptrFromInt(ptr);
156 }156 }
157 const ptr: *T = @ptrCast(try a.allocBytesWithAlignment(@alignOf(T), @sizeOf(T), @returnAddress()));157 const ptr: *T = @ptrCast(try a.allocBytesWithAlignment(.of(T), @sizeOf(T), @returnAddress()));
158 return ptr;158 return ptr;
159}159}
160160
...@@ -186,7 +186,7 @@ pub fn allocWithOptions(...@@ -186,7 +186,7 @@ pub fn allocWithOptions(
186 comptime Elem: type,186 comptime Elem: type,
187 n: usize,187 n: usize,
188 /// null means naturally aligned188 /// null means naturally aligned
189 comptime optional_alignment: ?u29,189 comptime optional_alignment: ?Alignment,
190 comptime optional_sentinel: ?Elem,190 comptime optional_sentinel: ?Elem,
191) Error!AllocWithOptionsPayload(Elem, optional_alignment, optional_sentinel) {191) Error!AllocWithOptionsPayload(Elem, optional_alignment, optional_sentinel) {
192 return self.allocWithOptionsRetAddr(Elem, n, optional_alignment, optional_sentinel, @returnAddress());192 return self.allocWithOptionsRetAddr(Elem, n, optional_alignment, optional_sentinel, @returnAddress());
...@@ -197,7 +197,7 @@ pub fn allocWithOptionsRetAddr(...@@ -197,7 +197,7 @@ pub fn allocWithOptionsRetAddr(
197 comptime Elem: type,197 comptime Elem: type,
198 n: usize,198 n: usize,
199 /// null means naturally aligned199 /// null means naturally aligned
200 comptime optional_alignment: ?u29,200 comptime optional_alignment: ?Alignment,
201 comptime optional_sentinel: ?Elem,201 comptime optional_sentinel: ?Elem,
202 return_address: usize,202 return_address: usize,
203) Error!AllocWithOptionsPayload(Elem, optional_alignment, optional_sentinel) {203) Error!AllocWithOptionsPayload(Elem, optional_alignment, optional_sentinel) {
...@@ -210,11 +210,11 @@ pub fn allocWithOptionsRetAddr(...@@ -210,11 +210,11 @@ pub fn allocWithOptionsRetAddr(
210 }210 }
211}211}
212212
213fn AllocWithOptionsPayload(comptime Elem: type, comptime alignment: ?u29, comptime sentinel: ?Elem) type {213fn AllocWithOptionsPayload(comptime Elem: type, comptime alignment: ?Alignment, comptime sentinel: ?Elem) type {
214 if (sentinel) |s| {214 if (sentinel) |s| {
215 return [:s]align(alignment orelse @alignOf(Elem)) Elem;215 return [:s]align(if (alignment) |a| a.toByteUnits() else @alignOf(Elem)) Elem;
216 } else {216 } else {
217 return []align(alignment orelse @alignOf(Elem)) Elem;217 return []align(if (alignment) |a| a.toByteUnits() else @alignOf(Elem)) Elem;
218 }218 }
219}219}
220220
...@@ -239,9 +239,9 @@ pub fn alignedAlloc(...@@ -239,9 +239,9 @@ pub fn alignedAlloc(
239 self: Allocator,239 self: Allocator,
240 comptime T: type,240 comptime T: type,
241 /// null means naturally aligned241 /// null means naturally aligned
242 comptime alignment: ?u29,242 comptime alignment: ?Alignment,
243 n: usize,243 n: usize,
244) Error![]align(alignment orelse @alignOf(T)) T {244) Error![]align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T {
245 return self.allocAdvancedWithRetAddr(T, alignment, n, @returnAddress());245 return self.allocAdvancedWithRetAddr(T, alignment, n, @returnAddress());
246}246}
247247
...@@ -249,27 +249,38 @@ pub inline fn allocAdvancedWithRetAddr(...@@ -249,27 +249,38 @@ pub inline fn allocAdvancedWithRetAddr(
249 self: Allocator,249 self: Allocator,
250 comptime T: type,250 comptime T: type,
251 /// null means naturally aligned251 /// null means naturally aligned
252 comptime alignment: ?u29,252 comptime alignment: ?Alignment,
253 n: usize,253 n: usize,
254 return_address: usize,254 return_address: usize,
255) Error![]align(alignment orelse @alignOf(T)) T {255) Error![]align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T {
256 const a = alignment orelse @alignOf(T);256 const a = comptime (alignment orelse Alignment.fromByteUnits(@alignOf(T)));
257 const ptr: [*]align(a) T = @ptrCast(try self.allocWithSizeAndAlignment(@sizeOf(T), a, n, return_address));257 const ptr: [*]align(a.toByteUnits()) T = @ptrCast(try self.allocWithSizeAndAlignment(@sizeOf(T), a, n, return_address));
258 return ptr[0..n];258 return ptr[0..n];
259}259}
260260
261fn allocWithSizeAndAlignment(self: Allocator, comptime size: usize, comptime alignment: u29, n: usize, return_address: usize) Error![*]align(alignment) u8 {261fn allocWithSizeAndAlignment(
262 self: Allocator,
263 comptime size: usize,
264 comptime alignment: Alignment,
265 n: usize,
266 return_address: usize,
267) Error![*]align(alignment.toByteUnits()) u8 {
262 const byte_count = math.mul(usize, size, n) catch return Error.OutOfMemory;268 const byte_count = math.mul(usize, size, n) catch return Error.OutOfMemory;
263 return self.allocBytesWithAlignment(alignment, byte_count, return_address);269 return self.allocBytesWithAlignment(alignment, byte_count, return_address);
264}270}
265271
266fn allocBytesWithAlignment(self: Allocator, comptime alignment: u29, byte_count: usize, return_address: usize) Error![*]align(alignment) u8 {272fn allocBytesWithAlignment(
273 self: Allocator,
274 comptime alignment: Alignment,
275 byte_count: usize,
276 return_address: usize,
277) Error![*]align(alignment.toByteUnits()) u8 {
267 if (byte_count == 0) {278 if (byte_count == 0) {
268 const ptr = comptime std.mem.alignBackward(usize, math.maxInt(usize), alignment);279 const ptr = comptime alignment.backward(math.maxInt(usize));
269 return @as([*]align(alignment) u8, @ptrFromInt(ptr));280 return @as([*]align(alignment.toByteUnits()) u8, @ptrFromInt(ptr));
270 }281 }
271282
272 const byte_ptr = self.rawAlloc(byte_count, .fromByteUnits(alignment), return_address) orelse return Error.OutOfMemory;283 const byte_ptr = self.rawAlloc(byte_count, alignment, return_address) orelse return Error.OutOfMemory;
273 @memset(byte_ptr[0..byte_count], undefined);284 @memset(byte_ptr[0..byte_count], undefined);
274 return @alignCast(byte_ptr);285 return @alignCast(byte_ptr);
275}286}
...@@ -378,7 +389,7 @@ pub fn reallocAdvanced(...@@ -378,7 +389,7 @@ pub fn reallocAdvanced(
378 const Slice = @typeInfo(@TypeOf(old_mem)).pointer;389 const Slice = @typeInfo(@TypeOf(old_mem)).pointer;
379 const T = Slice.child;390 const T = Slice.child;
380 if (old_mem.len == 0) {391 if (old_mem.len == 0) {
381 return self.allocAdvancedWithRetAddr(T, Slice.alignment, new_n, return_address);392 return self.allocAdvancedWithRetAddr(T, .fromByteUnits(Slice.alignment), new_n, return_address);
382 }393 }
383 if (new_n == 0) {394 if (new_n == 0) {
384 self.free(old_mem);395 self.free(old_mem);
lib/std/meta/trailer_flags.zig+1-1
...@@ -144,7 +144,7 @@ test TrailerFlags {...@@ -144,7 +144,7 @@ test TrailerFlags {
144 .b = true,144 .b = true,
145 .c = true,145 .c = true,
146 });146 });
147 const slice = try testing.allocator.alignedAlloc(u8, 8, flags.sizeInBytes());147 const slice = try testing.allocator.alignedAlloc(u8, .@"8", flags.sizeInBytes());
148 defer testing.allocator.free(slice);148 defer testing.allocator.free(slice);
149149
150 flags.set(slice.ptr, .b, false);150 flags.set(slice.ptr, .b, false);
lib/std/multi_array_list.zig+2-10
...@@ -350,11 +350,7 @@ pub fn MultiArrayList(comptime T: type) type {...@@ -350,11 +350,7 @@ pub fn MultiArrayList(comptime T: type) type {
350 assert(new_len <= self.capacity);350 assert(new_len <= self.capacity);
351 assert(new_len <= self.len);351 assert(new_len <= self.len);
352352
353 const other_bytes = gpa.alignedAlloc(353 const other_bytes = gpa.alignedAlloc(u8, .of(Elem), capacityInBytes(new_len)) catch {
354 u8,
355 @alignOf(Elem),
356 capacityInBytes(new_len),
357 ) catch {
358 const self_slice = self.slice();354 const self_slice = self.slice();
359 inline for (fields, 0..) |field_info, i| {355 inline for (fields, 0..) |field_info, i| {
360 if (@sizeOf(field_info.type) != 0) {356 if (@sizeOf(field_info.type) != 0) {
...@@ -440,11 +436,7 @@ pub fn MultiArrayList(comptime T: type) type {...@@ -440,11 +436,7 @@ pub fn MultiArrayList(comptime T: type) type {
440 /// `new_capacity` must be greater or equal to `len`.436 /// `new_capacity` must be greater or equal to `len`.
441 pub fn setCapacity(self: *Self, gpa: Allocator, new_capacity: usize) !void {437 pub fn setCapacity(self: *Self, gpa: Allocator, new_capacity: usize) !void {
442 assert(new_capacity >= self.len);438 assert(new_capacity >= self.len);
443 const new_bytes = try gpa.alignedAlloc(439 const new_bytes = try gpa.alignedAlloc(u8, .of(Elem), capacityInBytes(new_capacity));
444 u8,
445 @alignOf(Elem),
446 capacityInBytes(new_capacity),
447 );
448 if (self.len == 0) {440 if (self.len == 0) {
449 gpa.free(self.allocatedBytes());441 gpa.free(self.allocatedBytes());
450 self.bytes = new_bytes.ptr;442 self.bytes = new_bytes.ptr;
lib/std/process.zig+1-1
...@@ -1256,7 +1256,7 @@ pub fn argsAlloc(allocator: Allocator) ![][:0]u8 {...@@ -1256,7 +1256,7 @@ pub fn argsAlloc(allocator: Allocator) ![][:0]u8 {
1256 const slice_sizes = slice_list.items;1256 const slice_sizes = slice_list.items;
1257 const slice_list_bytes = try math.mul(usize, @sizeOf([]u8), slice_sizes.len);1257 const slice_list_bytes = try math.mul(usize, @sizeOf([]u8), slice_sizes.len);
1258 const total_bytes = try math.add(usize, slice_list_bytes, contents_slice.len);1258 const total_bytes = try math.add(usize, slice_list_bytes, contents_slice.len);
1259 const buf = try allocator.alignedAlloc(u8, @alignOf([]u8), total_bytes);1259 const buf = try allocator.alignedAlloc(u8, .of([]u8), total_bytes);
1260 errdefer allocator.free(buf);1260 errdefer allocator.free(buf);
12611261
1262 const result_slice_list = mem.bytesAsSlice([:0]u8, buf[0..slice_list_bytes]);1262 const result_slice_list = mem.bytesAsSlice([:0]u8, buf[0..slice_list_bytes]);
lib/std/zig.zig+1-1
...@@ -543,7 +543,7 @@ pub fn readSourceFileToEndAlloc(gpa: Allocator, input: std.fs.File, size_hint: ?...@@ -543,7 +543,7 @@ pub fn readSourceFileToEndAlloc(gpa: Allocator, input: std.fs.File, size_hint: ?
543 gpa,543 gpa,
544 max_src_size,544 max_src_size,
545 size_hint,545 size_hint,
546 @alignOf(u8),546 .of(u8),
547 0,547 0,
548 ) catch |err| switch (err) {548 ) catch |err| switch (err) {
549 error.ConnectionResetByPeer => unreachable,549 error.ConnectionResetByPeer => unreachable,
lib/std/zon/parse.zig+1-1
...@@ -679,7 +679,7 @@ const Parser = struct {...@@ -679,7 +679,7 @@ const Parser = struct {
679 const slice = try self.gpa.allocWithOptions(679 const slice = try self.gpa.allocWithOptions(
680 pointer.child,680 pointer.child,
681 nodes.len,681 nodes.len,
682 pointer.alignment,682 .fromByteUnits(pointer.alignment),
683 pointer.sentinel(),683 pointer.sentinel(),
684 );684 );
685 errdefer self.gpa.free(slice);685 errdefer self.gpa.free(slice);
src/InternPool.zig+6-6
...@@ -255,7 +255,7 @@ pub fn trackZir(...@@ -255,7 +255,7 @@ pub fn trackZir(
255 const new_map_capacity = map_header.capacity * 2;255 const new_map_capacity = map_header.capacity * 2;
256 const new_map_buf = try arena.allocator().alignedAlloc(256 const new_map_buf = try arena.allocator().alignedAlloc(
257 u8,257 u8,
258 Map.alignment,258 .fromByteUnits(Map.alignment),
259 Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),259 Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),
260 );260 );
261 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };261 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };
...@@ -350,7 +350,7 @@ pub fn rehashTrackedInsts(...@@ -350,7 +350,7 @@ pub fn rehashTrackedInsts(
350 defer arena_state.* = arena.state;350 defer arena_state.* = arena.state;
351 const new_map_buf = try arena.allocator().alignedAlloc(351 const new_map_buf = try arena.allocator().alignedAlloc(
352 u8,352 u8,
353 Map.alignment,353 .fromByteUnits(Map.alignment),
354 Map.entries_offset + want_capacity * @sizeOf(Map.Entry),354 Map.entries_offset + want_capacity * @sizeOf(Map.Entry),
355 );355 );
356 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };356 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };
...@@ -1296,7 +1296,7 @@ const Local = struct {...@@ -1296,7 +1296,7 @@ const Local = struct {
1296 defer mutable.arena.* = arena.state;1296 defer mutable.arena.* = arena.state;
1297 const buf = try arena.allocator().alignedAlloc(1297 const buf = try arena.allocator().alignedAlloc(
1298 u8,1298 u8,
1299 alignment,1299 .fromByteUnits(alignment),
1300 bytes_offset + View.capacityInBytes(capacity),1300 bytes_offset + View.capacityInBytes(capacity),
1301 );1301 );
1302 var new_list: ListSelf = .{ .bytes = @ptrCast(buf[bytes_offset..].ptr) };1302 var new_list: ListSelf = .{ .bytes = @ptrCast(buf[bytes_offset..].ptr) };
...@@ -7547,7 +7547,7 @@ fn getOrPutKeyEnsuringAdditionalCapacity(...@@ -7547,7 +7547,7 @@ fn getOrPutKeyEnsuringAdditionalCapacity(
7547 }7547 }
7548 const new_map_buf = try arena.allocator().alignedAlloc(7548 const new_map_buf = try arena.allocator().alignedAlloc(
7549 u8,7549 u8,
7550 Map.alignment,7550 .fromByteUnits(Map.alignment),
7551 Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),7551 Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),
7552 );7552 );
7553 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };7553 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };
...@@ -11666,7 +11666,7 @@ pub fn getOrPutTrailingString(...@@ -11666,7 +11666,7 @@ pub fn getOrPutTrailingString(
11666 const new_map_capacity = map_header.capacity * 2;11666 const new_map_capacity = map_header.capacity * 2;
11667 const new_map_buf = try arena.allocator().alignedAlloc(11667 const new_map_buf = try arena.allocator().alignedAlloc(
11668 u8,11668 u8,
11669 Map.alignment,11669 .fromByteUnits(Map.alignment),
11670 Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),11670 Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),
11671 );11671 );
11672 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };11672 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };
...@@ -12586,7 +12586,7 @@ const GlobalErrorSet = struct {...@@ -12586,7 +12586,7 @@ const GlobalErrorSet = struct {
12586 const new_map_capacity = map_header.capacity * 2;12586 const new_map_capacity = map_header.capacity * 2;
12587 const new_map_buf = try arena.allocator().alignedAlloc(12587 const new_map_buf = try arena.allocator().alignedAlloc(
12588 u8,12588 u8,
12589 Map.alignment,12589 .fromByteUnits(Map.alignment),
12590 Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),12590 Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),
12591 );12591 );
12592 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };12592 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };
src/Package/Fetch.zig+1-1
...@@ -640,7 +640,7 @@ fn loadManifest(f: *Fetch, pkg_root: Cache.Path) RunError!void {...@@ -640,7 +640,7 @@ fn loadManifest(f: *Fetch, pkg_root: Cache.Path) RunError!void {
640 try fs.path.join(arena, &.{ pkg_root.sub_path, Manifest.basename }),640 try fs.path.join(arena, &.{ pkg_root.sub_path, Manifest.basename }),
641 Manifest.max_bytes,641 Manifest.max_bytes,
642 null,642 null,
643 1,643 .@"1",
644 0,644 0,
645 ) catch |err| switch (err) {645 ) catch |err| switch (err) {
646 error.FileNotFound => return,646 error.FileNotFound => return,
src/main.zig+1-1
...@@ -7510,7 +7510,7 @@ fn loadManifest(...@@ -7510,7 +7510,7 @@ fn loadManifest(
7510 Package.Manifest.basename,7510 Package.Manifest.basename,
7511 Package.Manifest.max_bytes,7511 Package.Manifest.max_bytes,
7512 null,7512 null,
7513 1,7513 .@"1",
7514 0,7514 0,
7515 ) catch |err| switch (err) {7515 ) catch |err| switch (err) {
7516 error.FileNotFound => {7516 error.FileNotFound => {
test/src/Cases.zig+1-1
...@@ -358,7 +358,7 @@ fn addFromDirInner(...@@ -358,7 +358,7 @@ fn addFromDirInner(
358 current_file.* = filename;358 current_file.* = filename;
359359
360 const max_file_size = 10 * 1024 * 1024;360 const max_file_size = 10 * 1024 * 1024;
361 const src = try iterable_dir.readFileAllocOptions(ctx.arena, filename, max_file_size, null, 1, 0);361 const src = try iterable_dir.readFileAllocOptions(ctx.arena, filename, max_file_size, null, .@"1", 0);
362362
363 // Parse the manifest363 // Parse the manifest
364 var manifest = try TestManifest.parse(ctx.arena, src);364 var manifest = try TestManifest.parse(ctx.arena, src);