authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-11-22 13:34:57-05:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-11-22 13:34:57-05:00
loge4977f3e89fcc164a4d02cd38eb066cfe1a1124f
tree7cba9d333f6ebae6208e8487080bea896086acf7
parentd5e21a4f1a2920ef7bbe3c54feab1a3b5119bf77
parenta34a51ef6eb4bd8dfab14bd8bfe1193d5573eacf
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #18067 from ziglang/use-BoundedArray-less

std: use BoundedArray less

9 files changed, 192 insertions(+), 163 deletions(-)

deps/aro/aro/Compilation.zig+18-17
......@@ -582,10 +582,9 @@ fn generateFloatMacros(w: anytype, prefix: []const u8, semantics: target_util.FP
582582 },
583583 );
584584
585 var defPrefix = std.BoundedArray(u8, 32).init(0) catch unreachable;
586 defPrefix.writer().print("__{s}_", .{prefix}) catch return error.OutOfMemory;
587
588 const prefix_slice = defPrefix.constSlice();
585 var def_prefix_buf: [32]u8 = undefined;
586 const prefix_slice = std.fmt.bufPrint(&def_prefix_buf, "__{s}_", .{prefix}) catch
587 return error.OutOfMemory;
589588
590589 try w.print("#define {s}DENORM_MIN__ {s}{s}\n", .{ prefix_slice, denormMin, ext });
591590 try w.print("#define {s}HAS_DENORM__\n", .{prefix_slice});
......@@ -770,18 +769,18 @@ fn generateExactWidthType(comp: *const Compilation, w: anytype, mapper: StrInt.T
770769 ty = if (unsigned) comp.types.int64.makeIntegerUnsigned() else comp.types.int64;
771770 }
772771
773 var prefix = std.BoundedArray(u8, 16).init(0) catch unreachable;
774 prefix.writer().print("{s}{d}", .{ if (unsigned) "__UINT" else "__INT", width }) catch return error.OutOfMemory;
772 var buffer: [16]u8 = undefined;
773 const suffix = "_TYPE__";
774 const full = std.fmt.bufPrint(&buffer, "{s}{d}{s}", .{
775 if (unsigned) "__UINT" else "__INT", width, suffix,
776 }) catch return error.OutOfMemory;
775777
776 {
777 const len = prefix.len;
778 defer prefix.resize(len) catch unreachable; // restoring previous size
779 prefix.appendSliceAssumeCapacity("_TYPE__");
780 try generateTypeMacro(w, mapper, prefix.constSlice(), ty, comp.langopts);
781 }
778 try generateTypeMacro(w, mapper, full, ty, comp.langopts);
779
780 const prefix = full[0 .. full.len - suffix.len]; // remove "_TYPE__"
782781
783 try comp.generateFmt(prefix.constSlice(), w, ty);
784 try comp.generateSuffixMacro(prefix.constSlice(), w, ty);
782 try comp.generateFmt(prefix, w, ty);
783 try comp.generateSuffixMacro(prefix, w, ty);
785784}
786785
787786pub fn hasFloat128(comp: *const Compilation) bool {
......@@ -908,10 +907,12 @@ fn generateExactWidthIntMax(comp: *const Compilation, w: anytype, specifier: Typ
908907 ty = if (unsigned) comp.types.int64.makeIntegerUnsigned() else comp.types.int64;
909908 }
910909
911 var name = std.BoundedArray(u8, 6).init(0) catch unreachable;
912 name.writer().print("{s}{d}", .{ if (unsigned) "UINT" else "INT", bit_count }) catch return error.OutOfMemory;
910 var name_buffer: [6]u8 = undefined;
911 const name = std.fmt.bufPrint(&name_buffer, "{s}{d}", .{
912 if (unsigned) "UINT" else "INT", bit_count,
913 }) catch return error.OutOfMemory;
913914
914 return comp.generateIntMax(w, name.constSlice(), ty);
915 return comp.generateIntMax(w, name, ty);
915916}
916917
917918fn generateIntWidth(comp: *Compilation, w: anytype, name: []const u8, ty: Type) !void {
deps/aro/aro/Driver/GCCDetector.zig+24-17
......@@ -29,7 +29,7 @@ pub fn appendToolPath(self: *const GCCDetector, tc: *Toolchain) !void {
2929 }, .program);
3030}
3131
32fn addDefaultGCCPrefixes(prefixes: *PathPrefixes, tc: *const Toolchain) !void {
32fn addDefaultGCCPrefixes(prefixes: *std.ArrayListUnmanaged([]const u8), tc: *const Toolchain) !void {
3333 const sysroot = tc.getSysroot();
3434 const target = tc.getTarget();
3535 if (sysroot.len == 0 and target.os.tag == .linux and tc.filesystem.exists("/opt/rh")) {
......@@ -57,14 +57,12 @@ fn addDefaultGCCPrefixes(prefixes: *PathPrefixes, tc: *const Toolchain) !void {
5757 }
5858}
5959
60const PathPrefixes = std.BoundedArray([]const u8, 16);
61
6260fn collectLibDirsAndTriples(
6361 tc: *Toolchain,
64 lib_dirs: *PathPrefixes,
65 triple_aliases: *PathPrefixes,
66 biarch_libdirs: *PathPrefixes,
67 biarch_triple_aliases: *PathPrefixes,
62 lib_dirs: *std.ArrayListUnmanaged([]const u8),
63 triple_aliases: *std.ArrayListUnmanaged([]const u8),
64 biarch_libdirs: *std.ArrayListUnmanaged([]const u8),
65 biarch_triple_aliases: *std.ArrayListUnmanaged([]const u8),
6866) !void {
6967 const AArch64LibDirs: [2][]const u8 = .{ "/lib64", "/lib" };
7068 const AArch64Triples: [4][]const u8 = .{ "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux", "aarch64-suse-linux" };
......@@ -408,10 +406,18 @@ pub fn discover(self: *GCCDetector, tc: *Toolchain) !void {
408406 else
409407 target_util.get32BitArchVariant(target);
410408
411 var candidate_lib_dirs: PathPrefixes = .{};
412 var candidate_triple_aliases: PathPrefixes = .{};
413 var candidate_biarch_lib_dirs: PathPrefixes = .{};
414 var candidate_biarch_triple_aliases: PathPrefixes = .{};
409 var candidate_lib_dirs_buffer: [16][]const u8 = undefined;
410 var candidate_lib_dirs = std.ArrayListUnmanaged([]const u8).initBuffer(&candidate_lib_dirs_buffer);
411
412 var candidate_triple_aliases_buffer: [16][]const u8 = undefined;
413 var candidate_triple_aliases = std.ArrayListUnmanaged([]const u8).initBuffer(&candidate_triple_aliases_buffer);
414
415 var candidate_biarch_lib_dirs_buffer: [16][]const u8 = undefined;
416 var candidate_biarch_lib_dirs = std.ArrayListUnmanaged([]const u8).initBuffer(&candidate_biarch_lib_dirs_buffer);
417
418 var candidate_biarch_triple_aliases_buffer: [16][]const u8 = undefined;
419 var candidate_biarch_triple_aliases = std.ArrayListUnmanaged([]const u8).initBuffer(&candidate_biarch_triple_aliases_buffer);
420
415421 try collectLibDirsAndTriples(
416422 tc,
417423 &candidate_lib_dirs,
......@@ -433,7 +439,8 @@ pub fn discover(self: *GCCDetector, tc: *Toolchain) !void {
433439 }
434440 }
435441
436 var prefixes: PathPrefixes = .{};
442 var prefixes_buf: [16][]const u8 = undefined;
443 var prefixes = std.ArrayListUnmanaged([]const u8).initBuffer(&prefixes_buf);
437444 const gcc_toolchain_dir = gccToolchainDir(tc);
438445 if (gcc_toolchain_dir.len != 0) {
439446 const adjusted = if (gcc_toolchain_dir[gcc_toolchain_dir.len - 1] == '/')
......@@ -455,10 +462,10 @@ pub fn discover(self: *GCCDetector, tc: *Toolchain) !void {
455462 }
456463
457464 const v0 = GCCVersion.parse("0.0.0");
458 for (prefixes.constSlice()) |prefix| {
465 for (prefixes.items) |prefix| {
459466 if (!tc.filesystem.exists(prefix)) continue;
460467
461 for (candidate_lib_dirs.constSlice()) |suffix| {
468 for (candidate_lib_dirs.items) |suffix| {
462469 defer fib.reset();
463470 const lib_dir = std.fs.path.join(fib.allocator(), &.{ prefix, suffix }) catch continue;
464471 if (!tc.filesystem.exists(lib_dir)) continue;
......@@ -467,17 +474,17 @@ pub fn discover(self: *GCCDetector, tc: *Toolchain) !void {
467474 const gcc_cross_dir_exists = tc.filesystem.joinedExists(&.{ lib_dir, "/gcc-cross" });
468475
469476 try self.scanLibDirForGCCTriple(tc, target, lib_dir, triple_str, false, gcc_dir_exists, gcc_cross_dir_exists);
470 for (candidate_triple_aliases.constSlice()) |candidate| {
477 for (candidate_triple_aliases.items) |candidate| {
471478 try self.scanLibDirForGCCTriple(tc, target, lib_dir, candidate, false, gcc_dir_exists, gcc_cross_dir_exists);
472479 }
473480 }
474 for (candidate_biarch_lib_dirs.constSlice()) |suffix| {
481 for (candidate_biarch_lib_dirs.items) |suffix| {
475482 const lib_dir = std.fs.path.join(fib.allocator(), &.{ prefix, suffix }) catch continue;
476483 if (!tc.filesystem.exists(lib_dir)) continue;
477484
478485 const gcc_dir_exists = tc.filesystem.joinedExists(&.{ lib_dir, "/gcc" });
479486 const gcc_cross_dir_exists = tc.filesystem.joinedExists(&.{ lib_dir, "/gcc-cross" });
480 for (candidate_biarch_triple_aliases.constSlice()) |candidate| {
487 for (candidate_biarch_triple_aliases.items) |candidate| {
481488 try self.scanLibDirForGCCTriple(tc, target, lib_dir, candidate, true, gcc_dir_exists, gcc_cross_dir_exists);
482489 }
483490 }
deps/aro/aro/Parser.zig+2-2
......@@ -7796,7 +7796,7 @@ fn stringLiteral(p: *Parser) Error!Result {
77967796 }
77977797 },
77987798 };
7799 for (char_literal_parser.errors.constSlice()) |item| {
7799 for (char_literal_parser.errors()) |item| {
78007800 try p.errExtra(item.tag, p.tok_i, item.extra);
78017801 }
78027802 }
......@@ -7911,7 +7911,7 @@ fn charLiteral(p: *Parser) Error!Result {
79117911 char_literal_parser.err(.char_lit_too_wide, .{ .none = {} });
79127912 }
79137913
7914 for (char_literal_parser.errors.constSlice()) |item| {
7914 for (char_literal_parser.errors()) |item| {
79157915 try p.errExtra(item.tag, p.tok_i, item.extra);
79167916 }
79177917 }
deps/aro/aro/text_literal.zig+18-6
......@@ -157,7 +157,8 @@ pub const Parser = struct {
157157 max_codepoint: u21,
158158 /// We only want to issue a max of 1 error per char literal
159159 errored: bool = false,
160 errors: std.BoundedArray(CharDiagnostic, 4) = .{},
160 errors_buffer: [4]CharDiagnostic,
161 errors_len: usize,
161162 comp: *const Compilation,
162163
163164 pub fn init(literal: []const u8, kind: Kind, max_codepoint: u21, comp: *const Compilation) Parser {
......@@ -166,6 +167,8 @@ pub const Parser = struct {
166167 .comp = comp,
167168 .kind = kind,
168169 .max_codepoint = max_codepoint,
170 .errors_buffer = undefined,
171 .errors_len = 0,
169172 };
170173 }
171174
......@@ -178,19 +181,28 @@ pub const Parser = struct {
178181 };
179182 }
180183
184 pub fn errors(p: *Parser) []CharDiagnostic {
185 return p.errors_buffer[0..p.errors_len];
186 }
187
181188 pub fn err(self: *Parser, tag: Diagnostics.Tag, extra: Diagnostics.Message.Extra) void {
182189 if (self.errored) return;
183190 self.errored = true;
184191 const diagnostic = .{ .tag = tag, .extra = extra };
185 self.errors.append(diagnostic) catch {
186 _ = self.errors.pop();
187 self.errors.append(diagnostic) catch unreachable;
188 };
192 if (self.errors_len == self.errors_buffer.len) {
193 self.errors_buffer[self.errors_buffer.len - 1] = diagnostic;
194 } else {
195 self.errors_buffer[self.errors_len] = diagnostic;
196 self.errors_len += 1;
197 }
189198 }
190199
191200 pub fn warn(self: *Parser, tag: Diagnostics.Tag, extra: Diagnostics.Message.Extra) void {
192201 if (self.errored) return;
193 self.errors.append(.{ .tag = tag, .extra = extra }) catch {};
202 if (self.errors_len < self.errors_buffer.len) {
203 self.errors_buffer[self.errors_len] = .{ .tag = tag, .extra = extra };
204 self.errors_len += 1;
205 }
194206 }
195207
196208 pub fn next(self: *Parser) ?Item {
lib/std/array_list.zig+11
......@@ -633,6 +633,17 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
633633 return self;
634634 }
635635
636 /// Initialize with externally-managed memory. The buffer determines the
637 /// capacity, and the length is set to zero.
638 /// When initialized this way, all methods that accept an Allocator
639 /// argument are illegal to call.
640 pub fn initBuffer(buffer: Slice) Self {
641 return .{
642 .items = buffer[0..0],
643 .capacity = buffer.len,
644 };
645 }
646
636647 /// Release all allocated memory.
637648 pub fn deinit(self: *Self, allocator: Allocator) void {
638649 allocator.free(self.allocatedSlice());
lib/std/crypto/ff.zig+86-91
......@@ -12,7 +12,6 @@ const math = std.math;
1212const mem = std.mem;
1313const meta = std.meta;
1414const testing = std.testing;
15const BoundedArray = std.BoundedArray;
1615const assert = std.debug.assert;
1716const Endian = std.builtin.Endian;
1817
......@@ -63,46 +62,54 @@ pub fn Uint(comptime max_bits: comptime_int) type {
6362
6463 return struct {
6564 const Self = @This();
66
6765 const max_limbs_count = math.divCeil(usize, max_bits, t_bits) catch unreachable;
68 const Limbs = BoundedArray(Limb, max_limbs_count);
69 limbs: Limbs,
66
67 limbs_buffer: [max_limbs_count]Limb,
68 /// The number of active limbs.
69 limbs_len: usize,
7070
7171 /// Number of bytes required to serialize an integer.
7272 pub const encoded_bytes = math.divCeil(usize, max_bits, 8) catch unreachable;
7373
74 // Returns the number of active limbs.
75 fn limbs_count(self: Self) usize {
76 return self.limbs.len;
74 /// Constant slice of active limbs.
75 fn limbsConst(self: *const Self) []const Limb {
76 return self.limbs_buffer[0..self.limbs_len];
77 }
78
79 /// Mutable slice of active limbs.
80 fn limbs(self: *Self) []Limb {
81 return self.limbs_buffer[0..self.limbs_len];
7782 }
7883
7984 // Removes limbs whose value is zero from the active limbs.
8085 fn normalize(self: Self) Self {
8186 var res = self;
82 if (self.limbs_count() < 2) {
87 if (self.limbs_len < 2) {
8388 return res;
8489 }
85 var i = self.limbs_count() - 1;
86 while (i > 0 and res.limbs.get(i) == 0) : (i -= 1) {}
87 res.limbs.resize(i + 1) catch unreachable;
90 var i = self.limbs_len - 1;
91 while (i > 0 and res.limbsConst()[i] == 0) : (i -= 1) {}
92 res.limbs_len = i + 1;
93 assert(res.limbs_len <= res.limbs_buffer.len);
8894 return res;
8995 }
9096
9197 /// The zero integer.
92 pub const zero = zero: {
93 var limbs = Limbs.init(0) catch unreachable;
94 limbs.appendNTimesAssumeCapacity(0, max_limbs_count);
95 break :zero Self{ .limbs = limbs };
98 pub const zero: Self = .{
99 .limbs_buffer = [1]Limb{0} ** max_limbs_count,
100 .limbs_len = max_limbs_count,
96101 };
97102
98103 /// Creates a new big integer from a primitive type.
99104 /// This function may not run in constant time.
100 pub fn fromPrimitive(comptime T: type, x_: T) OverflowError!Self {
101 var x = x_;
102 var out = Self.zero;
103 for (0..out.limbs.capacity()) |i| {
104 const t = if (@bitSizeOf(T) > t_bits) @as(TLimb, @truncate(x)) else x;
105 out.limbs.set(i, t);
105 pub fn fromPrimitive(comptime T: type, init_value: T) OverflowError!Self {
106 var x = init_value;
107 var out: Self = .{
108 .limbs_buffer = undefined,
109 .limbs_len = max_limbs_count,
110 };
111 for (&out.limbs_buffer) |*limb| {
112 limb.* = if (@bitSizeOf(T) > t_bits) @as(TLimb, @truncate(x)) else x;
106113 x = math.shr(T, x, t_bits);
107114 }
108115 if (x != 0) {
......@@ -115,13 +122,13 @@ pub fn Uint(comptime max_bits: comptime_int) type {
115122 /// This function may not run in constant time.
116123 pub fn toPrimitive(self: Self, comptime T: type) OverflowError!T {
117124 var x: T = 0;
118 var i = self.limbs_count() - 1;
125 var i = self.limbs_len - 1;
119126 while (true) : (i -= 1) {
120127 if (@bitSizeOf(T) >= t_bits and math.shr(T, x, @bitSizeOf(T) - t_bits) != 0) {
121128 return error.Overflow;
122129 }
123130 x = math.shl(T, x, t_bits);
124 const v = math.cast(T, self.limbs.get(i)) orelse return error.Overflow;
131 const v = math.cast(T, self.limbsConst()[i]) orelse return error.Overflow;
125132 x |= v;
126133 if (i == 0) break;
127134 }
......@@ -140,9 +147,9 @@ pub fn Uint(comptime max_bits: comptime_int) type {
140147 .big => bytes.len - 1,
141148 .little => 0,
142149 };
143 for (0..self.limbs.len) |i| {
150 for (0..self.limbs_len) |i| {
144151 var remaining_bits = t_bits;
145 var limb = self.limbs.get(i);
152 var limb = self.limbsConst()[i];
146153 while (remaining_bits >= 8) {
147154 bytes[out_i] |= math.shl(u8, @as(u8, @truncate(limb)), shift);
148155 const consumed = 8 - shift;
......@@ -152,7 +159,7 @@ pub fn Uint(comptime max_bits: comptime_int) type {
152159 switch (endian) {
153160 .big => {
154161 if (out_i == 0) {
155 if (i != self.limbs.len - 1 or limb != 0) {
162 if (i != self.limbs_len - 1 or limb != 0) {
156163 return error.Overflow;
157164 }
158165 return;
......@@ -162,7 +169,7 @@ pub fn Uint(comptime max_bits: comptime_int) type {
162169 .little => {
163170 out_i += 1;
164171 if (out_i == bytes.len) {
165 if (i != self.limbs.len - 1 or limb != 0) {
172 if (i != self.limbs_len - 1 or limb != 0) {
166173 return error.Overflow;
167174 }
168175 return;
......@@ -187,20 +194,20 @@ pub fn Uint(comptime max_bits: comptime_int) type {
187194 };
188195 while (true) {
189196 const bi = bytes[i];
190 out.limbs.set(out_i, out.limbs.get(out_i) | math.shl(Limb, bi, shift));
197 out.limbs()[out_i] |= math.shl(Limb, bi, shift);
191198 shift += 8;
192199 if (shift >= t_bits) {
193200 shift -= t_bits;
194 out.limbs.set(out_i, @as(TLimb, @truncate(out.limbs.get(out_i))));
201 out.limbs()[out_i] = @as(TLimb, @truncate(out.limbs()[out_i]));
195202 const overflow = math.shr(Limb, bi, 8 - shift);
196203 out_i += 1;
197 if (out_i >= out.limbs.len) {
204 if (out_i >= out.limbs_len) {
198205 if (overflow != 0 or i != 0) {
199206 return error.Overflow;
200207 }
201208 break;
202209 }
203 out.limbs.set(out_i, overflow);
210 out.limbs()[out_i] = overflow;
204211 }
205212 switch (endian) {
206213 .big => {
......@@ -218,32 +225,31 @@ pub fn Uint(comptime max_bits: comptime_int) type {
218225
219226 /// Returns `true` if both integers are equal.
220227 pub fn eql(x: Self, y: Self) bool {
221 return crypto.utils.timingSafeEql([max_limbs_count]Limb, x.limbs.buffer, y.limbs.buffer);
228 return crypto.utils.timingSafeEql([max_limbs_count]Limb, x.limbs_buffer, y.limbs_buffer);
222229 }
223230
224231 /// Compares two integers.
225232 pub fn compare(x: Self, y: Self) math.Order {
226233 return crypto.utils.timingSafeCompare(
227234 Limb,
228 x.limbs.constSlice(),
229 y.limbs.constSlice(),
235 x.limbsConst(),
236 y.limbsConst(),
230237 .little,
231238 );
232239 }
233240
234241 /// Returns `true` if the integer is zero.
235242 pub fn isZero(x: Self) bool {
236 const x_limbs = x.limbs.constSlice();
237243 var t: Limb = 0;
238 for (0..x.limbs_count()) |i| {
239 t |= x_limbs[i];
244 for (x.limbsConst()) |elem| {
245 t |= elem;
240246 }
241247 return ct.eql(t, 0);
242248 }
243249
244250 /// Returns `true` if the integer is odd.
245251 pub fn isOdd(x: Self) bool {
246 return @as(bool, @bitCast(@as(u1, @truncate(x.limbs.get(0)))));
252 return @as(u1, @truncate(x.limbsConst()[0])) != 0;
247253 }
248254
249255 /// Adds `y` to `x`, and returns `true` if the operation overflowed.
......@@ -258,39 +264,31 @@ pub fn Uint(comptime max_bits: comptime_int) type {
258264
259265 // Replaces the limbs of `x` with the limbs of `y` if `on` is `true`.
260266 fn cmov(x: *Self, on: bool, y: Self) void {
261 const x_limbs = x.limbs.slice();
262 const y_limbs = y.limbs.constSlice();
263 for (0..y.limbs_count()) |i| {
264 x_limbs[i] = ct.select(on, y_limbs[i], x_limbs[i]);
267 for (x.limbs(), y.limbsConst()) |*x_limb, y_limb| {
268 x_limb.* = ct.select(on, y_limb, x_limb.*);
265269 }
266270 }
267271
268 // Adds `y` to `x` if `on` is `true`, and returns `true` if the operation overflowed.
272 // Adds `y` to `x` if `on` is `true`, and returns `true` if the
273 // operation overflowed.
269274 fn conditionalAddWithOverflow(x: *Self, on: bool, y: Self) u1 {
270 assert(x.limbs_count() == y.limbs_count()); // Operands must have the same size.
271 const x_limbs = x.limbs.slice();
272 const y_limbs = y.limbs.constSlice();
273
274275 var carry: u1 = 0;
275 for (0..x.limbs_count()) |i| {
276 const res = x_limbs[i] + y_limbs[i] + carry;
277 x_limbs[i] = ct.select(on, @as(TLimb, @truncate(res)), x_limbs[i]);
278 carry = @as(u1, @truncate(res >> t_bits));
276 for (x.limbs(), y.limbsConst()) |*x_limb, y_limb| {
277 const res = x_limb.* + y_limb + carry;
278 x_limb.* = ct.select(on, @as(TLimb, @truncate(res)), x_limb.*);
279 carry = @truncate(res >> t_bits);
279280 }
280281 return carry;
281282 }
282283
283 // Subtracts `y` from `x` if `on` is `true`, and returns `true` if the operation overflowed.
284 // Subtracts `y` from `x` if `on` is `true`, and returns `true` if the
285 // operation overflowed.
284286 fn conditionalSubWithOverflow(x: *Self, on: bool, y: Self) u1 {
285 assert(x.limbs_count() == y.limbs_count()); // Operands must have the same size.
286 const x_limbs = x.limbs.slice();
287 const y_limbs = y.limbs.constSlice();
288
289287 var borrow: u1 = 0;
290 for (0..x.limbs_count()) |i| {
291 const res = x_limbs[i] -% y_limbs[i] -% borrow;
292 x_limbs[i] = ct.select(on, @as(TLimb, @truncate(res)), x_limbs[i]);
293 borrow = @as(u1, @truncate(res >> t_bits));
288 for (x.limbs(), y.limbsConst()) |*x_limb, y_limb| {
289 const res = x_limb.* -% y_limb -% borrow;
290 x_limb.* = ct.select(on, @as(TLimb, @truncate(res)), x_limb.*);
291 borrow = @truncate(res >> t_bits);
294292 }
295293 return borrow;
296294 }
......@@ -315,7 +313,7 @@ fn Fe_(comptime bits: comptime_int) type {
315313
316314 // The number of active limbs to represent the field element.
317315 fn limbs_count(self: Self) usize {
318 return self.v.limbs_count();
316 return self.v.limbs_len;
319317 }
320318
321319 /// Creates a field element from a primitive.
......@@ -398,7 +396,7 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
398396
399397 // Number of active limbs in the modulus.
400398 fn limbs_count(self: Self) usize {
401 return self.v.limbs_count();
399 return self.v.limbs_len;
402400 }
403401
404402 /// Actual size of the modulus, in bits.
......@@ -409,7 +407,7 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
409407 /// Returns the element `1`.
410408 pub fn one(self: Self) Fe {
411409 var fe = self.zero;
412 fe.v.limbs.set(0, 1);
410 fe.v.limbs()[0] = 1;
413411 return fe;
414412 }
415413
......@@ -419,10 +417,10 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
419417 if (!v_.isOdd()) return error.EvenModulus;
420418
421419 var v = v_.normalize();
422 const hi = v.limbs.get(v.limbs_count() - 1);
423 const lo = v.limbs.get(0);
420 const hi = v.limbsConst()[v.limbs_len - 1];
421 const lo = v.limbsConst()[0];
424422
425 if (v.limbs_count() < 2 and lo < 3) {
423 if (v.limbs_len < 2 and lo < 3) {
426424 return error.ModulusTooSmall;
427425 }
428426
......@@ -481,18 +479,19 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
481479 const new_len = self.limbs_count();
482480 if (fe.limbs_count() < new_len) return error.Overflow;
483481 var acc: Limb = 0;
484 for (fe.v.limbs.constSlice()[new_len..]) |limb| {
482 for (fe.v.limbsConst()[new_len..]) |limb| {
485483 acc |= limb;
486484 }
487485 if (acc != 0) return error.Overflow;
488 try fe.v.limbs.resize(new_len);
486 if (new_len > fe.v.limbs_buffer.len) return error.Overflow;
487 fe.v.limbs_len = new_len;
489488 }
490489
491490 // Computes R^2 for the Montgomery representation.
492491 fn computeRR(self: *Self) void {
493492 self.rr = self.zero;
494493 const n = self.rr.limbs_count();
495 self.rr.v.limbs.set(n - 1, 1);
494 self.rr.v.limbs()[n - 1] = 1;
496495 for ((n - 1)..(2 * n)) |_| {
497496 self.shiftIn(&self.rr, 0);
498497 }
......@@ -502,9 +501,9 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
502501 /// Computes x << t_bits + y (mod m)
503502 fn shiftIn(self: Self, x: *Fe, y: Limb) void {
504503 var d = self.zero;
505 const x_limbs = x.v.limbs.slice();
506 const d_limbs = d.v.limbs.slice();
507 const m_limbs = self.v.limbs.constSlice();
504 const x_limbs = x.v.limbs();
505 const d_limbs = d.v.limbs();
506 const m_limbs = self.v.limbsConst();
508507
509508 var need_sub = false;
510509 var i: usize = t_bits - 1;
......@@ -569,18 +568,18 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
569568 /// Reduces an arbitrary `Uint`, converting it to a field element.
570569 pub fn reduce(self: Self, x: anytype) Fe {
571570 var out = self.zero;
572 var i = x.limbs_count() - 1;
571 var i = x.limbs_len - 1;
573572 if (self.limbs_count() >= 2) {
574573 const start = @min(i, self.limbs_count() - 2);
575574 var j = start;
576575 while (true) : (j -= 1) {
577 out.v.limbs.set(j, x.limbs.get(i));
576 out.v.limbs()[j] = x.limbsConst()[i];
578577 i -= 1;
579578 if (j == 0) break;
580579 }
581580 }
582581 while (true) : (i -= 1) {
583 self.shiftIn(&out, x.limbs.get(i));
582 self.shiftIn(&out, x.limbsConst()[i]);
584583 if (i == 0) break;
585584 }
586585 return out;
......@@ -591,10 +590,10 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
591590 assert(d.limbs_count() == y.limbs_count());
592591 assert(d.limbs_count() == self.limbs_count());
593592
594 const a_limbs = x.v.limbs.constSlice();
595 const b_limbs = y.v.limbs.constSlice();
596 const d_limbs = d.v.limbs.slice();
597 const m_limbs = self.v.limbs.constSlice();
593 const a_limbs = x.v.limbsConst();
594 const b_limbs = y.v.limbsConst();
595 const d_limbs = d.v.limbs();
596 const m_limbs = self.v.limbsConst();
598597
599598 var overflow: u1 = 0;
600599 for (0..self.limbs_count()) |i| {
......@@ -685,7 +684,7 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
685684 const k: u1 = @truncate(b >> j);
686685 if (k != 0) {
687686 const t = self.montgomeryMul(out, x_m);
688 @memcpy(out.v.limbs.slice(), t.v.limbs.constSlice());
687 @memcpy(out.v.limbs(), t.v.limbsConst());
689688 }
690689 if (j == 0) break;
691690 }
......@@ -731,7 +730,7 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
731730 }
732731 const t1 = self.montgomeryMul(out, t0);
733732 if (public) {
734 @memcpy(out.v.limbs.slice(), t1.v.limbs.constSlice());
733 @memcpy(out.v.limbs(), t1.v.limbsConst());
735734 } else {
736735 out.v.cmov(!ct.eql(k, 0), t1.v);
737736 }
......@@ -790,9 +789,9 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
790789 pub fn powPublic(self: Self, x: Fe, e: Fe) NullExponentError!Fe {
791790 var e_normalized = Fe{ .v = e.v.normalize() };
792791 var buf_: [Fe.encoded_bytes]u8 = undefined;
793 var buf = buf_[0 .. math.divCeil(usize, e_normalized.v.limbs_count() * t_bits, 8) catch unreachable];
792 var buf = buf_[0 .. math.divCeil(usize, e_normalized.v.limbs_len * t_bits, 8) catch unreachable];
794793 e_normalized.toBytes(buf, .little) catch unreachable;
795 const leading = @clz(e_normalized.v.limbs.get(e_normalized.v.limbs_count() - carry_bits));
794 const leading = @clz(e_normalized.v.limbsConst()[e_normalized.v.limbs_len - carry_bits]);
796795 buf = buf[0 .. buf.len - leading / 8];
797796 return self.powWithEncodedPublicExponent(x, buf, .little);
798797 }
......@@ -835,20 +834,16 @@ const ct_protected = struct {
835834
836835 // Compares two big integers in constant time, returning true if x < y.
837836 fn limbsCmpLt(x: anytype, y: @TypeOf(x)) bool {
838 assert(x.limbs_count() == y.limbs_count());
839 const x_limbs = x.limbs.constSlice();
840 const y_limbs = y.limbs.constSlice();
841
842837 var c: u1 = 0;
843 for (0..x.limbs_count()) |i| {
844 c = @as(u1, @truncate((x_limbs[i] -% y_limbs[i] -% c) >> t_bits));
838 for (x.limbsConst(), y.limbsConst()) |x_limb, y_limb| {
839 c = @truncate((x_limb -% y_limb -% c) >> t_bits);
845840 }
846 return @as(bool, @bitCast(c));
841 return c != 0;
847842 }
848843
849844 // Compares two big integers in constant time, returning true if x >= y.
850845 fn limbsCmpGeq(x: anytype, y: @TypeOf(x)) bool {
851 return @as(bool, @bitCast(1 - @intFromBool(ct.limbsCmpLt(x, y))));
846 return !ct.limbsCmpLt(x, y);
852847 }
853848
854849 // Multiplies two limbs and returns the result as a wide limb.
lib/std/fs.zig+15-14
......@@ -2204,28 +2204,29 @@ pub const Dir = struct {
22042204 name: []const u8,
22052205 parent_dir: Dir,
22062206 iter: IterableDir.Iterator,
2207 };
22082207
2209 var stack = std.BoundedArray(StackItem, 16){};
2210 defer {
2211 for (stack.slice()) |*item| {
2212 item.iter.dir.close();
2208 fn closeAll(items: []@This()) void {
2209 for (items) |*item| item.iter.dir.close();
22132210 }
2214 }
2211 };
22152212
2216 stack.appendAssumeCapacity(StackItem{
2213 var stack_buffer: [16]StackItem = undefined;
2214 var stack = std.ArrayListUnmanaged(StackItem).initBuffer(&stack_buffer);
2215 defer StackItem.closeAll(stack.items);
2216
2217 stack.appendAssumeCapacity(.{
22172218 .name = sub_path,
22182219 .parent_dir = self,
22192220 .iter = initial_iterable_dir.iterateAssumeFirstIteration(),
22202221 });
22212222
2222 process_stack: while (stack.len != 0) {
2223 var top = &(stack.slice()[stack.len - 1]);
2223 process_stack: while (stack.items.len != 0) {
2224 var top = &stack.items[stack.items.len - 1];
22242225 while (try top.iter.next()) |entry| {
22252226 var treat_as_dir = entry.kind == .directory;
22262227 handle_entry: while (true) {
22272228 if (treat_as_dir) {
2228 if (stack.ensureUnusedCapacity(1)) {
2229 if (stack.unusedCapacitySlice().len >= 1) {
22292230 var iterable_dir = top.iter.dir.openIterableDir(entry.name, .{ .no_follow = true }) catch |err| switch (err) {
22302231 error.NotDir => {
22312232 treat_as_dir = false;
......@@ -2251,13 +2252,13 @@ pub const Dir = struct {
22512252 error.DeviceBusy,
22522253 => |e| return e,
22532254 };
2254 stack.appendAssumeCapacity(StackItem{
2255 stack.appendAssumeCapacity(.{
22552256 .name = entry.name,
22562257 .parent_dir = top.iter.dir,
22572258 .iter = iterable_dir.iterateAssumeFirstIteration(),
22582259 });
22592260 continue :process_stack;
2260 } else |_| {
2261 } else {
22612262 try top.iter.dir.deleteTreeMinStackSizeWithKindHint(entry.name, entry.kind);
22622263 break :handle_entry;
22632264 }
......@@ -2301,7 +2302,7 @@ pub const Dir = struct {
23012302 // pop the value from the stack.
23022303 const parent_dir = top.parent_dir;
23032304 const name = top.name;
2304 _ = stack.pop();
2305 stack.items.len -= 1;
23052306
23062307 var need_to_retry: bool = false;
23072308 parent_dir.deleteDir(name) catch |err| switch (err) {
......@@ -2374,7 +2375,7 @@ pub const Dir = struct {
23742375 };
23752376 // We know there is room on the stack since we are just re-adding
23762377 // the StackItem that we previously popped.
2377 stack.appendAssumeCapacity(StackItem{
2378 stack.appendAssumeCapacity(.{
23782379 .name = name,
23792380 .parent_dir = parent_dir,
23802381 .iter = iterable_dir.iterateAssumeFirstIteration(),
src/resinator/parse.zig+7-4
......@@ -1246,13 +1246,16 @@ pub const Parser = struct {
12461246 self.nextToken(.normal) catch unreachable;
12471247 switch (statement_type) {
12481248 .file_version, .product_version => {
1249 var parts = std.BoundedArray(*Node, 4){};
1249 var parts_buffer: [4]*Node = undefined;
1250 var parts = std.ArrayListUnmanaged(*Node).initBuffer(&parts_buffer);
12501251
1251 while (parts.len < 4) {
1252 while (true) {
12521253 const value = try self.parseExpression(.{ .allowed_types = .{ .number = true } });
12531254 parts.addOneAssumeCapacity().* = value;
12541255
1255 if (parts.len == 4 or !(try self.parseOptionalToken(.comma))) {
1256 if (parts.unusedCapacitySlice().len == 0 or
1257 !(try self.parseOptionalToken(.comma)))
1258 {
12561259 break;
12571260 }
12581261 }
......@@ -1260,7 +1263,7 @@ pub const Parser = struct {
12601263 const node = try self.state.arena.create(Node.VersionStatement);
12611264 node.* = .{
12621265 .type = type_token,
1263 .parts = try self.state.arena.dupe(*Node, parts.slice()),
1266 .parts = try self.state.arena.dupe(*Node, parts.items),
12641267 };
12651268 return &node.base;
12661269 },
tools/gen_spirv_spec.zig+11-12
......@@ -601,9 +601,8 @@ fn renderFieldName(writer: anytype, operands: []const g.Operand, field_index: us
601601 const operand = operands[field_index];
602602
603603 // Should be enough for all names - adjust as needed.
604 var name_buffer = std.BoundedArray(u8, 64){
605 .buffer = undefined,
606 };
604 var name_backing_buffer: [64]u8 = undefined;
605 var name_buffer = std.ArrayListUnmanaged(u8).initBuffer(&name_backing_buffer);
607606
608607 derive_from_kind: {
609608 // Operand names are often in the json encoded as "'Name'" (with two sets of quotes).
......@@ -617,33 +616,33 @@ fn renderFieldName(writer: anytype, operands: []const g.Operand, field_index: us
617616 // Use the same loop to transform to snake-case.
618617 for (name) |c| {
619618 switch (c) {
620 'a'...'z', '0'...'9' => try name_buffer.append(c),
621 'A'...'Z' => try name_buffer.append(std.ascii.toLower(c)),
622 ' ', '~' => try name_buffer.append('_'),
619 'a'...'z', '0'...'9' => name_buffer.appendAssumeCapacity(c),
620 'A'...'Z' => name_buffer.appendAssumeCapacity(std.ascii.toLower(c)),
621 ' ', '~' => name_buffer.appendAssumeCapacity('_'),
623622 else => break :derive_from_kind,
624623 }
625624 }
626625
627626 // Assume there are no duplicate 'name' fields.
628 try writer.print("{}", .{std.zig.fmtId(name_buffer.slice())});
627 try writer.print("{}", .{std.zig.fmtId(name_buffer.items)});
629628 return;
630629 }
631630
632631 // Translate to snake case.
633 name_buffer.len = 0;
632 name_buffer.items.len = 0;
634633 for (operand.kind, 0..) |c, i| {
635634 switch (c) {
636 'a'...'z', '0'...'9' => try name_buffer.append(c),
635 'a'...'z', '0'...'9' => name_buffer.appendAssumeCapacity(c),
637636 'A'...'Z' => if (i > 0 and std.ascii.isLower(operand.kind[i - 1])) {
638 try name_buffer.appendSlice(&[_]u8{ '_', std.ascii.toLower(c) });
637 name_buffer.appendSliceAssumeCapacity(&[_]u8{ '_', std.ascii.toLower(c) });
639638 } else {
640 try name_buffer.append(std.ascii.toLower(c));
639 name_buffer.appendAssumeCapacity(std.ascii.toLower(c));
641640 },
642641 else => unreachable, // Assume that the name is valid C-syntax (and contains no underscores).
643642 }
644643 }
645644
646 try writer.print("{}", .{std.zig.fmtId(name_buffer.slice())});
645 try writer.print("{}", .{std.zig.fmtId(name_buffer.items)});
647646
648647 // For fields derived from type name, there could be any amount.
649648 // Simply check against all other fields, and if another similar one exists, add a number.