Merge pull request #8554 from ziglang/stage2-whole-file-astgen

Stage2 whole file astgen
This commit is contained in:
Andrew Kelley 2021-05-18 20:20:46 -04:00 committed by GitHub
commit 6435750c99
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
359 changed files with 20082 additions and 12813 deletions

View File

@ -550,7 +550,6 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/src/codegen/llvm.zig"
"${CMAKE_SOURCE_DIR}/src/codegen/llvm/bindings.zig"
"${CMAKE_SOURCE_DIR}/src/codegen/riscv64.zig"
"${CMAKE_SOURCE_DIR}/src/codegen/spu-mk2.zig"
"${CMAKE_SOURCE_DIR}/src/codegen/wasm.zig"
"${CMAKE_SOURCE_DIR}/src/codegen/x86_64.zig"
"${CMAKE_SOURCE_DIR}/src/glibc.zig"
@ -595,7 +594,7 @@ set(ZIG_STAGE2_SOURCES
"${CMAKE_SOURCE_DIR}/src/type.zig"
"${CMAKE_SOURCE_DIR}/src/value.zig"
"${CMAKE_SOURCE_DIR}/src/windows_sdk.zig"
"${CMAKE_SOURCE_DIR}/src/zir.zig"
"${CMAKE_SOURCE_DIR}/src/Zir.zig"
"${CMAKE_SOURCE_DIR}/src/Sema.zig"
)

View File

@ -1,5 +1,5 @@
const builtin = @import("builtin");
const std = @import("std");
const builtin = std.builtin;
const Builder = std.build.Builder;
const tests = @import("test/tests.zig");
const BufMap = std.BufMap;
@ -54,6 +54,7 @@ pub fn build(b: *Builder) !void {
const skip_compile_errors = b.option(bool, "skip-compile-errors", "Main test suite skips compile error tests") orelse false;
const skip_run_translated_c = b.option(bool, "skip-run-translated-c", "Main test suite skips run-translated-c tests") orelse false;
const skip_stage2_tests = b.option(bool, "skip-stage2-tests", "Main test suite skips self-hosted compiler tests") orelse false;
const skip_install_lib_files = b.option(bool, "skip-install-lib-files", "Do not copy lib/ files to installation prefix") orelse false;
const only_install_lib_files = b.option(bool, "lib-files-only", "Only install library files") orelse false;
const is_stage1 = b.option(bool, "stage1", "Build the stage1 compiler, put stage2 behind a feature flag") orelse false;
@ -62,19 +63,23 @@ pub fn build(b: *Builder) !void {
const enable_llvm = b.option(bool, "enable-llvm", "Build self-hosted compiler with LLVM backend enabled") orelse (is_stage1 or static_llvm);
const config_h_path_option = b.option([]const u8, "config_h", "Path to the generated config.h");
b.installDirectory(InstallDirectoryOptions{
.source_dir = "lib",
.install_dir = .Lib,
.install_subdir = "zig",
.exclude_extensions = &[_][]const u8{
"test.zig",
"README.md",
".z.0",
".z.9",
".gz",
"rfc1951.txt",
},
});
if (!skip_install_lib_files) {
b.installDirectory(InstallDirectoryOptions{
.source_dir = "lib",
.install_dir = .Lib,
.install_subdir = "zig",
.exclude_extensions = &[_][]const u8{
"README.md",
".z.0",
".z.9",
".gz",
"rfc1951.txt",
},
.blank_extensions = &[_][]const u8{
"test.zig",
},
});
}
if (only_install_lib_files)
return;
@ -83,6 +88,12 @@ pub fn build(b: *Builder) !void {
const link_libc = b.option(bool, "force-link-libc", "Force self-hosted compiler to link libc") orelse enable_llvm;
const strip = b.option(bool, "strip", "Omit debug information") orelse false;
const mem_leak_frames: u32 = b.option(u32, "mem-leak-frames", "How many stack frames to print when a memory leak occurs. Tests get 2x this amount.") orelse blk: {
if (strip) break :blk @as(u32, 0);
if (mode != .Debug) break :blk 0;
break :blk 4;
};
const main_file = if (is_stage1) "src/stage1.zig" else "src/main.zig";
var exe = b.addExecutable("zig", main_file);
@ -93,6 +104,7 @@ pub fn build(b: *Builder) !void {
toolchain_step.dependOn(&exe.step);
b.default_step.dependOn(&exe.step);
exe.addBuildOption(u32, "mem_leak_frames", mem_leak_frames);
exe.addBuildOption(bool, "skip_non_native", skip_non_native);
exe.addBuildOption(bool, "have_llvm", enable_llvm);
if (enable_llvm) {
@ -228,6 +240,7 @@ pub fn build(b: *Builder) !void {
test_stage2.addBuildOption(bool, "enable_qemu", is_qemu_enabled);
test_stage2.addBuildOption(bool, "enable_wine", is_wine_enabled);
test_stage2.addBuildOption(bool, "enable_wasmtime", is_wasmtime_enabled);
test_stage2.addBuildOption(u32, "mem_leak_frames", mem_leak_frames * 2);
test_stage2.addBuildOption(bool, "enable_darling", is_darling_enabled);
test_stage2.addBuildOption(?[]const u8, "glibc_multi_install_dir", glibc_multi_dir);
test_stage2.addBuildOption([]const u8, "version", version);
@ -266,7 +279,7 @@ pub fn build(b: *Builder) !void {
toolchain_step.dependOn(tests.addPkgTests(
b,
test_filter,
"test/stage1/behavior.zig",
"test/behavior.zig",
"behavior",
"Run the behavior tests",
modes,

View File

@ -1099,7 +1099,6 @@ const nan = std.math.nan(f128);
{#code_release_fast#}
{#code_disable_cache#}
const std = @import("std");
const builtin = std.builtin;
const big = @as(f64, 1 << 40);
export fn foo_strict(x: f64) f64 {
@ -2589,7 +2588,7 @@ test "default struct initialization fields" {
exactly their bit width.
</li>
<li>{#syntax#}bool{#endsyntax#} fields use exactly 1 bit.</li>
<li>A {#link|packed enum#} field uses exactly the bit width of its integer tag type.</li>
<li>An {#link|enum#} field uses exactly the bit width of its integer tag type.</li>
<li>A {#link|packed union#} field uses exactly the bit width of the union field with
the largest bit width.</li>
<li>Non-ABI-aligned fields are packed into the smallest possible
@ -2603,7 +2602,7 @@ test "default struct initialization fields" {
</p>
{#code_begin|test#}
const std = @import("std");
const builtin = std.builtin;
const native_endian = @import("builtin").target.cpu.arch.endian();
const expect = std.testing.expect;
const Full = packed struct {
@ -2625,7 +2624,7 @@ fn doTheTest() !void {
try expect(@sizeOf(Divided) == 2);
var full = Full{ .number = 0x1234 };
var divided = @bitCast(Divided, full);
switch (builtin.endian) {
switch (native_endian) {
.Big => {
try expect(divided.half1 == 0x12);
try expect(divided.quarter3 == 0x3);
@ -3015,25 +3014,6 @@ export fn entry(foo: Foo) void { }
{#code_end#}
{#header_close#}
{#header_open|packed enum#}
<p>By default, the size of enums is not guaranteed.</p>
<p>{#syntax#}packed enum{#endsyntax#} causes the size of the enum to be the same as the size of the
integer tag type of the enum:</p>
{#code_begin|test#}
const std = @import("std");
test "packed enum" {
const Number = packed enum(u8) {
one,
two,
three,
};
try std.testing.expect(@sizeOf(Number) == @sizeOf(u8));
}
{#code_end#}
<p>This makes the enum eligible to be in a {#link|packed struct#}.</p>
{#header_close#}
{#header_open|Enum Literals#}
<p>
Enum literals allow specifying the name of an enum field without specifying the enum type:
@ -4255,7 +4235,7 @@ test "noreturn" {
<p>Another use case for {#syntax#}noreturn{#endsyntax#} is the {#syntax#}exit{#endsyntax#} function:</p>
{#code_begin|test#}
{#target_windows#}
pub extern "kernel32" fn ExitProcess(exit_code: c_uint) callconv(if (@import("builtin").arch == .i386) .Stdcall else .C) noreturn;
pub extern "kernel32" fn ExitProcess(exit_code: c_uint) callconv(if (@import("builtin").target.cpu.arch == .i386) .Stdcall else .C) noreturn;
test "foo" {
const value = bar() catch ExitProcess(1);
@ -4290,7 +4270,7 @@ export fn sub(a: i8, b: i8) i8 { return a - b; }
// at link time, when linking statically, or at runtime, when linking
// dynamically.
// The callconv specifier changes the calling convention of the function.
extern "kernel32" fn ExitProcess(exit_code: u32) callconv(if (@import("builtin").arch == .i386) .Stdcall else .C) noreturn;
extern "kernel32" fn ExitProcess(exit_code: u32) callconv(if (@import("builtin").target.cpu.arch == .i386) .Stdcall else .C) noreturn;
extern "c" fn atan2(a: f64, b: f64) f64;
// The @setCold builtin tells the optimizer that a function is rarely called.
@ -7596,7 +7576,7 @@ export fn @"A function name that is a complete sentence."() void {}
The {#syntax#}fence{#endsyntax#} function is used to introduce happens-before edges between operations.
</p>
<p>
{#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("builtin").AtomicOrder{#endsyntax#}.
{#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("std").builtin.AtomicOrder{#endsyntax#}.
</p>
{#see_also|Compile Variables#}
{#header_close#}
@ -7799,8 +7779,8 @@ test "@hasDecl" {
</p>
<ul>
<li>{#syntax#}@import("std"){#endsyntax#} - Zig Standard Library</li>
<li>{#syntax#}@import("builtin"){#endsyntax#} - Compiler-provided types and variables.
The command <code>zig builtin</code> outputs the source to stdout for reference.
<li>{#syntax#}@import("builtin"){#endsyntax#} - Target-specific information
The command <code>zig build-exe --show-builtin</code> outputs the source to stdout for reference.
</li>
</ul>
{#see_also|Compile Variables|@embedFile#}
@ -7931,11 +7911,11 @@ mem.set(u8, dest, c);{#endsyntax#}</pre>
</p>
{#code_begin|test#}
const std = @import("std");
const builtin = @import("builtin");
const native_arch = @import("builtin").target.cpu.arch;
const expect = std.testing.expect;
test "@wasmMemoryGrow" {
if (builtin.arch != .wasm32) return error.SkipZigTest;
if (native_arch != .wasm32) return error.SkipZigTest;
var prev = @wasmMemorySize(0);
try expect(prev == @wasmMemoryGrow(0, 1));
@ -8103,7 +8083,7 @@ test "foo" {
{#header_close#}
{#header_open|@setFloatMode#}
<pre>{#syntax#}@setFloatMode(mode: @import("builtin").FloatMode){#endsyntax#}</pre>
<pre>{#syntax#}@setFloatMode(mode: @import("std").builtin.FloatMode){#endsyntax#}</pre>
<p>
Sets the floating point mode of the current scope. Possible values are:
</p>
@ -8292,7 +8272,7 @@ test "vector @splat" {
{#header_close#}
{#header_open|@reduce#}
<pre>{#syntax#}@reduce(comptime op: builtin.ReduceOp, value: anytype) std.meta.Child(value){#endsyntax#}</pre>
<pre>{#syntax#}@reduce(comptime op: std.builtin.ReduceOp, value: anytype) std.meta.Child(value){#endsyntax#}</pre>
<p>
Transforms a {#link|vector|Vectors#} into a scalar value by performing a
sequential horizontal reduction of its elements using the specified operator {#syntax#}op{#endsyntax#}.
@ -8584,7 +8564,7 @@ test "integer truncation" {
{#header_close#}
{#header_open|@Type#}
<pre>{#syntax#}@Type(comptime info: @import("builtin").TypeInfo) type{#endsyntax#}</pre>
<pre>{#syntax#}@Type(comptime info: std.builtin.TypeInfo) type{#endsyntax#}</pre>
<p>
This function is the inverse of {#link|@typeInfo#}. It reifies type information
into a {#syntax#}type{#endsyntax#}.
@ -8626,7 +8606,7 @@ test "integer truncation" {
</ul>
{#header_close#}
{#header_open|@typeInfo#}
<pre>{#syntax#}@typeInfo(comptime T: type) @import("std").builtin.TypeInfo{#endsyntax#}</pre>
<pre>{#syntax#}@typeInfo(comptime T: type) std.builtin.TypeInfo{#endsyntax#}</pre>
<p>
Provides type reflection.
</p>
@ -9647,7 +9627,7 @@ test "string literal to constant slice" {
</p>
{#code_begin|syntax#}
const builtin = @import("builtin");
const separator = if (builtin.os == builtin.Os.windows) '\\' else '/';
const separator = if (builtin.os.tag == builtin.Os.windows) '\\' else '/';
{#code_end#}
<p>
Example of what is imported with {#syntax#}@import("builtin"){#endsyntax#}:
@ -9672,7 +9652,7 @@ const separator = if (builtin.os == builtin.Os.windows) '\\' else '/';
</p>
{#code_begin|test|detect_test#}
const std = @import("std");
const builtin = std.builtin;
const builtin = @import("builtin");
const expect = std.testing.expect;
test "builtin.is_test" {

View File

@ -32,7 +32,7 @@
state: usize = UNSET,
const std = @import("../std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const testing = std.testing;
const assert = std.debug.assert;
const StaticResetEvent = std.Thread.StaticResetEvent;

View File

@ -262,7 +262,7 @@ pub const AtomicEvent = struct {
while (true) {
if (waiting == WAKE) {
rc = windows.ntdll.NtWaitForKeyedEvent(handle, key, windows.FALSE, null);
assert(rc == .WAIT_0);
assert(rc == windows.NTSTATUS.WAIT_0);
break;
} else {
waiting = @cmpxchgWeak(u32, waiters, waiting, waiting - WAIT, .Acquire, .Monotonic) orelse break;
@ -271,7 +271,7 @@ pub const AtomicEvent = struct {
}
return error.TimedOut;
},
.WAIT_0 => {},
windows.NTSTATUS.WAIT_0 => {},
else => unreachable,
}
}

View File

@ -14,7 +14,7 @@ const trait = meta.trait;
const autoHash = std.hash.autoHash;
const Wyhash = std.hash.Wyhash;
const Allocator = mem.Allocator;
const builtin = @import("builtin");
const builtin = std.builtin;
const hash_map = @This();
pub fn AutoArrayHashMap(comptime K: type, comptime V: type) type {
@ -158,10 +158,20 @@ pub fn ArrayHashMap(
return self.unmanaged.getOrPutValue(self.allocator, key, value);
}
/// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`.
pub const ensureCapacity = ensureTotalCapacity;
/// Increases capacity, guaranteeing that insertions up until the
/// `expected_count` will not cause an allocation, and therefore cannot fail.
pub fn ensureCapacity(self: *Self, new_capacity: usize) !void {
return self.unmanaged.ensureCapacity(self.allocator, new_capacity);
pub fn ensureTotalCapacity(self: *Self, new_capacity: usize) !void {
return self.unmanaged.ensureTotalCapacity(self.allocator, new_capacity);
}
/// Increases capacity, guaranteeing that insertions up until
/// `additional_count` **more** items will not cause an allocation, and
/// therefore cannot fail.
pub fn ensureUnusedCapacity(self: *Self, additional_count: usize) !void {
return self.unmanaged.ensureUnusedCapacity(self.allocator, additional_count);
}
/// Returns the number of total elements which may be present before it is
@ -472,10 +482,13 @@ pub fn ArrayHashMapUnmanaged(
return res.entry;
}
/// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`.
pub const ensureCapacity = ensureTotalCapacity;
/// Increases capacity, guaranteeing that insertions up until the
/// `expected_count` will not cause an allocation, and therefore cannot fail.
pub fn ensureCapacity(self: *Self, allocator: *Allocator, new_capacity: usize) !void {
try self.entries.ensureCapacity(allocator, new_capacity);
pub fn ensureTotalCapacity(self: *Self, allocator: *Allocator, new_capacity: usize) !void {
try self.entries.ensureTotalCapacity(allocator, new_capacity);
if (new_capacity <= linear_scan_max) return;
// Ensure that the indexes will be at most 60% full if
@ -501,6 +514,17 @@ pub fn ArrayHashMapUnmanaged(
}
}
/// Increases capacity, guaranteeing that insertions up until
/// `additional_count` **more** items will not cause an allocation, and
/// therefore cannot fail.
pub fn ensureUnusedCapacity(
self: *Self,
allocator: *Allocator,
additional_capacity: usize,
) !void {
return self.ensureTotalCapacity(allocator, self.count() + additional_capacity);
}
/// Returns the number of total elements which may be present before it is
/// no longer guaranteed that no allocations will be performed.
pub fn capacity(self: Self) usize {
@ -1310,7 +1334,7 @@ test "reIndex" {
}
test "fromOwnedArrayList" {
comptime const array_hash_map_type = AutoArrayHashMap(i32, i32);
const array_hash_map_type = AutoArrayHashMap(i32, i32);
var al = std.ArrayListUnmanaged(array_hash_map_type.Entry){};
const hash = getAutoHashFn(i32);

View File

@ -131,7 +131,7 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
/// Insert `item` at index `n` by moving `list[n .. list.len]` to make room.
/// This operation is O(N).
pub fn insert(self: *Self, n: usize, item: T) !void {
try self.ensureCapacity(self.items.len + 1);
try self.ensureUnusedCapacity(1);
self.items.len += 1;
mem.copyBackwards(T, self.items[n + 1 .. self.items.len], self.items[n .. self.items.len - 1]);
@ -141,7 +141,7 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
/// Insert slice `items` at index `i` by moving `list[i .. list.len]` to make room.
/// This operation is O(N).
pub fn insertSlice(self: *Self, i: usize, items: []const T) !void {
try self.ensureCapacity(self.items.len + items.len);
try self.ensureUnusedCapacity(items.len);
self.items.len += items.len;
mem.copyBackwards(T, self.items[i + items.len .. self.items.len], self.items[i .. self.items.len - items.len]);
@ -220,7 +220,7 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
/// Append the slice of items to the list. Allocates more
/// memory as necessary.
pub fn appendSlice(self: *Self, items: []const T) !void {
try self.ensureCapacity(self.items.len + items.len);
try self.ensureUnusedCapacity(items.len);
self.appendSliceAssumeCapacity(items);
}
@ -269,7 +269,7 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
/// Adjust the list's length to `new_len`.
/// Does not initialize added items if any.
pub fn resize(self: *Self, new_len: usize) !void {
try self.ensureCapacity(new_len);
try self.ensureTotalCapacity(new_len);
self.items.len = new_len;
}
@ -294,9 +294,24 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
self.items.len = new_len;
}
/// Invalidates all element pointers.
pub fn clearRetainingCapacity(self: *Self) void {
self.items.len = 0;
}
/// Invalidates all element pointers.
pub fn clearAndFree(self: *Self) void {
self.allocator.free(self.allocatedSlice());
self.items.len = 0;
self.capacity = 0;
}
/// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`.
pub const ensureCapacity = ensureTotalCapacity;
/// Modify the array so that it can hold at least `new_capacity` items.
/// Invalidates pointers if additional memory is needed.
pub fn ensureCapacity(self: *Self, new_capacity: usize) !void {
pub fn ensureTotalCapacity(self: *Self, new_capacity: usize) !void {
var better_capacity = self.capacity;
if (better_capacity >= new_capacity) return;
@ -311,6 +326,12 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
self.capacity = new_memory.len;
}
/// Modify the array so that it can hold at least `additional_count` **more** items.
/// Invalidates pointers if additional memory is needed.
pub fn ensureUnusedCapacity(self: *Self, additional_count: usize) !void {
return self.ensureTotalCapacity(self.items.len + additional_count);
}
/// Increases the array's length to match the full capacity that is already allocated.
/// The new elements have `undefined` values. **Does not** invalidate pointers.
pub fn expandToCapacity(self: *Self) void {
@ -321,7 +342,7 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
/// The returned pointer becomes invalid when the list resized.
pub fn addOne(self: *Self) !*T {
const newlen = self.items.len + 1;
try self.ensureCapacity(newlen);
try self.ensureTotalCapacity(newlen);
return self.addOneAssumeCapacity();
}
@ -471,7 +492,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
/// to higher indices to make room.
/// This operation is O(N).
pub fn insert(self: *Self, allocator: *Allocator, n: usize, item: T) !void {
try self.ensureCapacity(allocator, self.items.len + 1);
try self.ensureUnusedCapacity(allocator, 1);
self.items.len += 1;
mem.copyBackwards(T, self.items[n + 1 .. self.items.len], self.items[n .. self.items.len - 1]);
@ -482,7 +503,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
/// higher indicices make room.
/// This operation is O(N).
pub fn insertSlice(self: *Self, allocator: *Allocator, i: usize, items: []const T) !void {
try self.ensureCapacity(allocator, self.items.len + items.len);
try self.ensureUnusedCapacity(allocator, items.len);
self.items.len += items.len;
mem.copyBackwards(T, self.items[i + items.len .. self.items.len], self.items[i .. self.items.len - items.len]);
@ -542,7 +563,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
/// Append the slice of items to the list. Allocates more
/// memory as necessary.
pub fn appendSlice(self: *Self, allocator: *Allocator, items: []const T) !void {
try self.ensureCapacity(allocator, self.items.len + items.len);
try self.ensureUnusedCapacity(allocator, items.len);
self.appendSliceAssumeCapacity(items);
}
@ -577,7 +598,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
/// Adjust the list's length to `new_len`.
/// Does not initialize added items, if any.
pub fn resize(self: *Self, allocator: *Allocator, new_len: usize) !void {
try self.ensureCapacity(allocator, new_len);
try self.ensureTotalCapacity(allocator, new_len);
self.items.len = new_len;
}
@ -602,9 +623,24 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
self.items.len = new_len;
}
/// Invalidates all element pointers.
pub fn clearRetainingCapacity(self: *Self) void {
self.items.len = 0;
}
/// Invalidates all element pointers.
pub fn clearAndFree(self: *Self, allocator: *Allocator) void {
allocator.free(self.allocatedSlice());
self.items.len = 0;
self.capacity = 0;
}
/// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`.
pub const ensureCapacity = ensureTotalCapacity;
/// Modify the array so that it can hold at least `new_capacity` items.
/// Invalidates pointers if additional memory is needed.
pub fn ensureCapacity(self: *Self, allocator: *Allocator, new_capacity: usize) !void {
pub fn ensureTotalCapacity(self: *Self, allocator: *Allocator, new_capacity: usize) !void {
var better_capacity = self.capacity;
if (better_capacity >= new_capacity) return;
@ -618,6 +654,16 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
self.capacity = new_memory.len;
}
/// Modify the array so that it can hold at least `additional_count` **more** items.
/// Invalidates pointers if additional memory is needed.
pub fn ensureUnusedCapacity(
self: *Self,
allocator: *Allocator,
additional_count: usize,
) !void {
return self.ensureTotalCapacity(allocator, self.items.len + additional_count);
}
/// Increases the array's length to match the full capacity that is already allocated.
/// The new elements have `undefined` values.
/// **Does not** invalidate pointers.
@ -629,7 +675,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ
/// The returned pointer becomes invalid when the list resized.
pub fn addOne(self: *Self, allocator: *Allocator) !*T {
const newlen = self.items.len + 1;
try self.ensureCapacity(allocator, newlen);
try self.ensureTotalCapacity(allocator, newlen);
return self.addOneAssumeCapacity();
}
@ -1188,7 +1234,7 @@ test "std.ArrayList/ArrayListUnmanaged.addManyAsArray" {
defer list.deinit();
(try list.addManyAsArray(4)).* = "aoeu".*;
try list.ensureCapacity(8);
try list.ensureTotalCapacity(8);
list.addManyAsArrayAssumeCapacity(4).* = "asdf".*;
try testing.expectEqualSlices(u8, list.items, "aoeuasdf");
@ -1198,7 +1244,7 @@ test "std.ArrayList/ArrayListUnmanaged.addManyAsArray" {
defer list.deinit(a);
(try list.addManyAsArray(a, 4)).* = "aoeu".*;
try list.ensureCapacity(a, 8);
try list.ensureTotalCapacity(a, 8);
list.addManyAsArrayAssumeCapacity(4).* = "asdf".*;
try testing.expectEqualSlices(u8, list.items, "aoeuasdf");

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const assert = std.debug.assert;
const expect = std.testing.expect;

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const assert = std.debug.assert;
const builtin = @import("builtin");
const builtin = std.builtin;
const expect = std.testing.expect;
/// Many reader, many writer, non-allocating, thread-safe

View File

@ -1019,6 +1019,23 @@ pub const Builder = struct {
};
}
pub fn truncateFile(self: *Builder, dest_path: []const u8) !void {
if (self.verbose) {
warn("truncate {s}\n", .{dest_path});
}
const cwd = fs.cwd();
var src_file = cwd.createFile(dest_path, .{}) catch |err| switch (err) {
error.FileNotFound => blk: {
if (fs.path.dirname(dest_path)) |dirname| {
try cwd.makePath(dirname);
}
break :blk try cwd.createFile(dest_path, .{});
},
else => |e| return e,
};
src_file.close();
}
pub fn pathFromRoot(self: *Builder, rel_path: []const u8) []u8 {
return fs.path.resolve(self.allocator, &[_][]const u8{ self.build_root, rel_path }) catch unreachable;
}
@ -1415,7 +1432,7 @@ pub const LibExeObjStep = struct {
red_zone: ?bool = null,
subsystem: ?builtin.SubSystem = null,
subsystem: ?std.Target.SubSystem = null,
/// Overrides the default stack size
stack_size: ?u64 = null,
@ -1967,7 +1984,7 @@ pub const LibExeObjStep = struct {
},
std.builtin.Version => {
out.print(
\\pub const {}: @import("builtin").Version = .{{
\\pub const {}: @import("std").builtin.Version = .{{
\\ .major = {d},
\\ .minor = {d},
\\ .patch = {d},
@ -2791,17 +2808,23 @@ pub const InstallDirectoryOptions = struct {
source_dir: []const u8,
install_dir: InstallDir,
install_subdir: []const u8,
exclude_extensions: ?[]const []const u8 = null,
/// File paths which end in any of these suffixes will be excluded
/// from being installed.
exclude_extensions: []const []const u8 = &.{},
/// File paths which end in any of these suffixes will result in
/// empty files being installed. This is mainly intended for large
/// test.zig files in order to prevent needless installation bloat.
/// However if the files were not present at all, then
/// `@import("test.zig")` would be a compile error.
blank_extensions: []const []const u8 = &.{},
fn dupe(self: InstallDirectoryOptions, b: *Builder) InstallDirectoryOptions {
return .{
.source_dir = b.dupe(self.source_dir),
.install_dir = self.install_dir.dupe(b),
.install_subdir = b.dupe(self.install_subdir),
.exclude_extensions = if (self.exclude_extensions) |extensions|
b.dupeStrings(extensions)
else
null,
.exclude_extensions = b.dupeStrings(self.exclude_extensions),
.blank_extensions = b.dupeStrings(self.blank_extensions),
};
}
};
@ -2829,17 +2852,29 @@ pub const InstallDirStep = struct {
const full_src_dir = self.builder.pathFromRoot(self.options.source_dir);
var it = try fs.walkPath(self.builder.allocator, full_src_dir);
next_entry: while (try it.next()) |entry| {
if (self.options.exclude_extensions) |ext_list| for (ext_list) |ext| {
for (self.options.exclude_extensions) |ext| {
if (mem.endsWith(u8, entry.path, ext)) {
continue :next_entry;
}
};
}
const rel_path = entry.path[full_src_dir.len + 1 ..];
const dest_path = try fs.path.join(self.builder.allocator, &[_][]const u8{ dest_prefix, rel_path });
const dest_path = try fs.path.join(self.builder.allocator, &[_][]const u8{
dest_prefix, rel_path,
});
switch (entry.kind) {
.Directory => try fs.cwd().makePath(dest_path),
.File => try self.builder.updateFile(entry.path, dest_path),
.File => {
for (self.options.blank_extensions) |ext| {
if (mem.endsWith(u8, entry.path, ext)) {
try self.builder.truncateFile(dest_path);
continue :next_entry;
}
}
try self.builder.updateFile(entry.path, dest_path);
},
else => continue,
}
}

View File

@ -3,39 +3,40 @@
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
pub usingnamespace @import("builtin");
const builtin = @import("builtin");
/// Deprecated: use `std.Target`.
pub const Target = std.Target;
/// Deprecated: use `std.Target.Os`.
pub const Os = std.Target.Os;
/// Deprecated: use `std.Target.Cpu.Arch`.
pub const Arch = std.Target.Cpu.Arch;
/// Deprecated: use `std.Target.Abi`.
pub const Abi = std.Target.Abi;
/// Deprecated: use `std.Target.ObjectFormat`.
pub const ObjectFormat = std.Target.ObjectFormat;
/// Deprecated: use `std.Target.SubSystem`.
pub const SubSystem = std.Target.SubSystem;
/// Deprecated: use `std.Target.Cpu`.
pub const Cpu = std.Target.Cpu;
// These are all deprecated.
pub const zig_version = builtin.zig_version;
pub const zig_is_stage2 = builtin.zig_is_stage2;
pub const output_mode = builtin.output_mode;
pub const link_mode = builtin.link_mode;
pub const is_test = builtin.is_test;
pub const single_threaded = builtin.single_threaded;
pub const abi = builtin.abi;
pub const cpu = builtin.cpu;
pub const os = builtin.os;
pub const target = builtin.target;
pub const object_format = builtin.object_format;
pub const mode = builtin.mode;
pub const link_libc = builtin.link_libc;
pub const link_libcpp = builtin.link_libcpp;
pub const have_error_return_tracing = builtin.have_error_return_tracing;
pub const valgrind_support = builtin.valgrind_support;
pub const position_independent_code = builtin.position_independent_code;
pub const position_independent_executable = builtin.position_independent_executable;
pub const strip_debug_info = builtin.strip_debug_info;
pub const code_model = builtin.code_model;
/// `explicit_subsystem` is missing when the subsystem is automatically detected,
/// so Zig standard library has the subsystem detection logic here. This should generally be
/// used rather than `explicit_subsystem`.
/// On non-Windows targets, this is `null`.
pub const subsystem: ?SubSystem = blk: {
if (@hasDecl(@This(), "explicit_subsystem")) break :blk explicit_subsystem;
pub const subsystem: ?std.Target.SubSystem = blk: {
if (@hasDecl(builtin, "explicit_subsystem")) break :blk explicit_subsystem;
switch (os.tag) {
.windows => {
if (is_test) {
break :blk SubSystem.Console;
break :blk std.Target.SubSystem.Console;
}
if (@hasDecl(root, "main") or
@hasDecl(root, "WinMain") or
@ -43,9 +44,9 @@ pub const subsystem: ?SubSystem = blk: {
@hasDecl(root, "WinMainCRTStartup") or
@hasDecl(root, "wWinMainCRTStartup"))
{
break :blk SubSystem.Windows;
break :blk std.Target.SubSystem.Windows;
} else {
break :blk SubSystem.Console;
break :blk std.Target.SubSystem.Console;
}
},
else => break :blk null,
@ -262,7 +263,7 @@ pub const TypeInfo = union(enum) {
/// This data structure is used by the Zig language code generation and
/// therefore must be kept in sync with the compiler implementation.
pub const ContainerLayout = enum {
pub const ContainerLayout = enum(u2) {
Auto,
Extern,
Packed,

View File

@ -7,6 +7,7 @@ const std = @import("../std.zig");
const assert = std.debug.assert;
const builtin = @import("builtin");
const macho = std.macho;
const native_arch = builtin.target.cpu.arch;
usingnamespace @import("../os/bits.zig");
@ -34,13 +35,13 @@ extern "c" fn fstat(fd: fd_t, buf: *libc_stat) c_int;
/// On x86_64 Darwin, fstat has to be manully linked with $INODE64 suffix to force 64bit version.
/// Note that this is fixed on aarch64 and no longer necessary.
extern "c" fn @"fstat$INODE64"(fd: fd_t, buf: *libc_stat) c_int;
pub const _fstat = if (builtin.arch == .aarch64) fstat else @"fstat$INODE64";
pub const _fstat = if (native_arch == .aarch64) fstat else @"fstat$INODE64";
extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *libc_stat, flags: u32) c_int;
/// On x86_64 Darwin, fstatat has to be manully linked with $INODE64 suffix to force 64bit version.
/// Note that this is fixed on aarch64 and no longer necessary.
extern "c" fn @"fstatat$INODE64"(dirfd: fd_t, path_name: [*:0]const u8, buf: *libc_stat, flags: u32) c_int;
pub const _fstatat = if (builtin.arch == .aarch64) fstatat else @"fstatat$INODE64";
pub const _fstatat = if (native_arch == .aarch64) fstatat else @"fstatat$INODE64";
pub extern "c" fn mach_absolute_time() u64;
pub extern "c" fn mach_timebase_info(tinfo: ?*mach_timebase_info_data) void;
@ -121,7 +122,7 @@ pub const AI_NUMERICHOST = 0x00000004;
/// prevent service name resolution
pub const AI_NUMERICSERV = 0x00001000;
pub const EAI = extern enum(c_int) {
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,

View File

@ -62,7 +62,7 @@ pub const sem_t = extern struct {
_padding: u32,
};
pub const EAI = extern enum(c_int) {
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,

View File

@ -70,7 +70,7 @@ pub const pthread_rwlock_t = extern struct {
waiters: [2]?*c_void = [_]?*c_void{ null, null },
};
pub const EAI = extern enum(c_int) {
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,

View File

@ -3,12 +3,14 @@
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const builtin = @import("builtin");
const std = @import("../std.zig");
const maxInt = std.math.maxInt;
const abi = std.Target.current.abi;
const arch = std.Target.current.cpu.arch;
const os_tag = std.Target.current.os.tag;
usingnamespace std.c;
pub const _errno = switch (builtin.abi) {
pub const _errno = switch (abi) {
.android => struct {
extern "c" var __errno: c_int;
fn getErrno() *c_int {
@ -37,7 +39,7 @@ pub const NI_NAMEREQD = 0x08;
pub const NI_DGRAM = 0x10;
pub const NI_NUMERICSCOPE = 0x100;
pub const EAI = extern enum(c_int) {
pub const EAI = enum(c_int) {
BADFLAGS = -1,
NONAME = -2,
AGAIN = -3,
@ -139,7 +141,7 @@ pub const pthread_mutex_t = extern struct {
pub const pthread_cond_t = extern struct {
size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
};
pub const pthread_rwlock_t = switch (std.builtin.abi) {
pub const pthread_rwlock_t = switch (abi) {
.android => switch (@sizeOf(usize)) {
4 => extern struct {
lock: std.c.pthread_mutex_t = std.c.PTHREAD_MUTEX_INITIALIZER,
@ -170,11 +172,11 @@ pub const sem_t = extern struct {
};
const __SIZEOF_PTHREAD_COND_T = 48;
const __SIZEOF_PTHREAD_MUTEX_T = if (builtin.os.tag == .fuchsia) 40 else switch (builtin.abi) {
const __SIZEOF_PTHREAD_MUTEX_T = if (os_tag == .fuchsia) 40 else switch (abi) {
.musl, .musleabi, .musleabihf => if (@sizeOf(usize) == 8) 40 else 24,
.gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => switch (builtin.arch) {
.gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => switch (arch) {
.aarch64 => 48,
.x86_64 => if (builtin.abi == .gnux32) 40 else 32,
.x86_64 => if (abi == .gnux32) 40 else 32,
.mips64, .powerpc64, .powerpc64le, .sparcv9 => 40,
else => if (@sizeOf(usize) == 8) 40 else 24,
},

View File

@ -15,7 +15,7 @@ const windows = os.windows;
const mem = std.mem;
const debug = std.debug;
const BufMap = std.BufMap;
const builtin = @import("builtin");
const builtin = std.builtin;
const Os = builtin.Os;
const TailQueue = std.TailQueue;
const maxInt = std.math.maxInt;

View File

@ -3,7 +3,7 @@
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const builtin = @import("builtin");
const builtin = std.builtin;
const std = @import("std.zig");
const io = std.io;
const mem = std.mem;

View File

@ -102,7 +102,7 @@ pub const Curve25519 = struct {
/// key is a low-order point.
pub fn mul(p: Curve25519, s: [32]u8) (IdentityElementError || WeakPublicKeyError)!Curve25519 {
const cofactor = [_]u8{8} ++ [_]u8{0} ** 31;
_ = ladder(p, cofactor, 4) catch |_| return error.WeakPublicKey;
_ = ladder(p, cofactor, 4) catch return error.WeakPublicKey;
return try ladder(p, s, 256);
}

View File

@ -226,12 +226,12 @@ pub const Edwards25519 = struct {
return pc;
}
const basePointPc = comptime pc: {
const basePointPc = pc: {
@setEvalBranchQuota(10000);
break :pc precompute(Edwards25519.basePoint, 15);
};
const basePointPc8 = comptime pc: {
const basePointPc8 = pc: {
@setEvalBranchQuota(10000);
break :pc precompute(Edwards25519.basePoint, 8);
};
@ -255,7 +255,7 @@ pub const Edwards25519 = struct {
return pcMul16(basePointPc, s, true);
} else {
const pc = precompute(p, 8);
pc[4].rejectIdentity() catch |_| return error.WeakPublicKey;
pc[4].rejectIdentity() catch return error.WeakPublicKey;
return pcMul(pc, s, true);
}
}
@ -306,7 +306,7 @@ pub const Edwards25519 = struct {
pcs[i] = basePointPc8;
} else {
pcs[i] = precompute(p, 8);
pcs[i][4].rejectIdentity() catch |_| return error.WeakPublicKey;
pcs[i][4].rejectIdentity() catch return error.WeakPublicKey;
}
}
var es: [count][2 * 32]i8 = undefined;

View File

@ -8,9 +8,9 @@ const std = @import("../std.zig");
const testing = std.testing;
const builtin = std.builtin;
const has_aesni = comptime std.Target.x86.featureSetHas(std.Target.current.cpu.features, .aes);
const has_avx = comptime std.Target.x86.featureSetHas(std.Target.current.cpu.features, .avx);
const has_armaes = comptime std.Target.aarch64.featureSetHas(std.Target.current.cpu.features, .aes);
const has_aesni = std.Target.x86.featureSetHas(std.Target.current.cpu.features, .aes);
const has_avx = std.Target.x86.featureSetHas(std.Target.current.cpu.features, .avx);
const has_armaes = std.Target.aarch64.featureSetHas(std.Target.current.cpu.features, .aes);
const impl = if (std.Target.current.cpu.arch == .x86_64 and has_aesni and has_avx) impl: {
break :impl @import("aes/aesni.zig");
} else if (std.Target.current.cpu.arch == .aarch64 and has_armaes)

View File

@ -106,8 +106,8 @@ fn AesOcb(comptime Aes: anytype) type {
return offset;
}
const has_aesni = comptime std.Target.x86.featureSetHas(std.Target.current.cpu.features, .aes);
const has_armaes = comptime std.Target.aarch64.featureSetHas(std.Target.current.cpu.features, .aes);
const has_aesni = std.Target.x86.featureSetHas(std.Target.current.cpu.features, .aes);
const has_armaes = std.Target.aarch64.featureSetHas(std.Target.current.cpu.features, .aes);
const wb: usize = if ((std.Target.current.cpu.arch == .x86_64 and has_aesni) or (std.Target.current.cpu.arch == .aarch64 and has_armaes)) 4 else 0;
/// c: ciphertext: output buffer should be of size m.len

View File

@ -137,9 +137,9 @@ pub const Ghash = struct {
return z0 | z1 | z2 | z3;
}
const has_pclmul = comptime std.Target.x86.featureSetHas(std.Target.current.cpu.features, .pclmul);
const has_avx = comptime std.Target.x86.featureSetHas(std.Target.current.cpu.features, .avx);
const has_armaes = comptime std.Target.aarch64.featureSetHas(std.Target.current.cpu.features, .aes);
const has_pclmul = std.Target.x86.featureSetHas(std.Target.current.cpu.features, .pclmul);
const has_avx = std.Target.x86.featureSetHas(std.Target.current.cpu.features, .avx);
const has_armaes = std.Target.aarch64.featureSetHas(std.Target.current.cpu.features, .aes);
const clmul = if (std.Target.current.cpu.arch == .x86_64 and has_pclmul and has_avx) impl: {
break :impl clmul_pclmul;
} else if (std.Target.current.cpu.arch == .aarch64 and has_armaes) impl: {

View File

@ -16,7 +16,7 @@ const debug = std.debug;
///
/// Important: the counter mode doesn't provide authenticated encryption: the ciphertext can be trivially modified without this being detected.
/// As a result, applications should generally never use it directly, but only in a construction that includes a MAC.
pub fn ctr(comptime BlockCipher: anytype, block_cipher: BlockCipher, dst: []u8, src: []const u8, iv: [BlockCipher.block_length]u8, endian: comptime builtin.Endian) void {
pub fn ctr(comptime BlockCipher: anytype, block_cipher: BlockCipher, dst: []u8, src: []const u8, iv: [BlockCipher.block_length]u8, endian: builtin.Endian) void {
debug.assert(dst.len >= src.len);
const block_length = BlockCipher.block_length;
var counter: [BlockCipher.block_length]u8 = undefined;

View File

@ -43,7 +43,7 @@ pub fn Field(comptime params: FieldParams) type {
pub const zero: Fe = Fe{ .limbs = mem.zeroes(Limbs) };
/// One.
pub const one = comptime one: {
pub const one = one: {
var fe: Fe = undefined;
fiat.setOne(&fe.limbs);
break :one fe;

View File

@ -30,8 +30,8 @@ pub const P256 = struct {
/// The P256 base point.
pub const basePoint = P256{
.x = try Fe.fromInt(48439561293906451759052585252797914202762949526041747995844080717082404635286),
.y = try Fe.fromInt(36134250956749795798585127919587881956611106672985015071877198253568414405109),
.x = Fe.fromInt(48439561293906451759052585252797914202762949526041747995844080717082404635286) catch unreachable,
.y = Fe.fromInt(36134250956749795798585127919587881956611106672985015071877198253568414405109) catch unreachable,
.z = Fe.one,
.is_base = true,
};
@ -39,7 +39,7 @@ pub const P256 = struct {
/// The P256 neutral element.
pub const identityElement = P256{ .x = Fe.zero, .y = Fe.one, .z = Fe.zero };
pub const B = try Fe.fromInt(41058363725152142129326129780047268409114441015993725554835256314039467401291);
pub const B = Fe.fromInt(41058363725152142129326129780047268409114441015993725554835256314039467401291) catch unreachable;
/// Reject the neutral element.
pub fn rejectIdentity(p: P256) IdentityElementError!void {
@ -390,12 +390,12 @@ pub const P256 = struct {
return pc;
}
const basePointPc = comptime pc: {
const basePointPc = pc: {
@setEvalBranchQuota(50000);
break :pc precompute(P256.basePoint, 15);
};
const basePointPc8 = comptime pc: {
const basePointPc8 = pc: {
@setEvalBranchQuota(50000);
break :pc precompute(P256.basePoint, 8);
};

View File

@ -111,7 +111,7 @@ fn tlsCsprngFill(_: *const std.rand.Random, buffer: []u8) void {
wipe_mem.ptr,
wipe_mem.len,
os.MADV_WIPEONFORK,
) catch |_| {
) catch {
return initAndFill(buffer);
};
}

View File

@ -20,9 +20,9 @@ pub fn timingSafeEql(comptime T: type, a: T, b: T) bool {
for (a) |x, i| {
acc |= x ^ b[i];
}
comptime const s = @typeInfo(C).Int.bits;
comptime const Cu = std.meta.Int(.unsigned, s);
comptime const Cext = std.meta.Int(.unsigned, s + 1);
const s = @typeInfo(C).Int.bits;
const Cu = std.meta.Int(.unsigned, s);
const Cext = std.meta.Int(.unsigned, s + 1);
return @bitCast(bool, @truncate(u1, (@as(Cext, @bitCast(Cu, acc)) -% 1) >> s));
},
.Vector => |info| {
@ -31,9 +31,9 @@ pub fn timingSafeEql(comptime T: type, a: T, b: T) bool {
@compileError("Elements to be compared must be integers");
}
const acc = @reduce(.Or, a ^ b);
comptime const s = @typeInfo(C).Int.bits;
comptime const Cu = std.meta.Int(.unsigned, s);
comptime const Cext = std.meta.Int(.unsigned, s + 1);
const s = @typeInfo(C).Int.bits;
const Cu = std.meta.Int(.unsigned, s);
const Cext = std.meta.Int(.unsigned, s + 1);
return @bitCast(bool, @truncate(u1, (@as(Cext, @bitCast(Cu, acc)) -% 1) >> s));
},
else => {
@ -50,7 +50,7 @@ pub fn timingSafeCompare(comptime T: type, a: []const T, b: []const T, endian: E
.Int => |cinfo| if (cinfo.signedness != .unsigned) @compileError("Elements to be compared must be unsigned") else cinfo.bits,
else => @compileError("Elements to be compared must be integers"),
};
comptime const Cext = std.meta.Int(.unsigned, bits + 1);
const Cext = std.meta.Int(.unsigned, bits + 1);
var gt: T = 0;
var eq: T = 1;
if (endian == .Little) {

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const debug = std.debug;
const mem = std.mem;
const testing = std.testing;

View File

@ -21,6 +21,9 @@ const root = @import("root");
const maxInt = std.math.maxInt;
const File = std.fs.File;
const windows = std.os.windows;
const native_arch = std.Target.current.cpu.arch;
const native_os = std.Target.current.os.tag;
const native_endian = native_arch.endian();
pub const runtime_safety = switch (builtin.mode) {
.Debug, .ReleaseSafe => true,
@ -90,7 +93,7 @@ pub fn detectTTYConfig() TTY.Config {
const stderr_file = io.getStdErr();
if (stderr_file.supportsAnsiEscapeCodes()) {
return .escape_codes;
} else if (builtin.os.tag == .windows and stderr_file.isTty()) {
} else if (native_os == .windows and stderr_file.isTty()) {
return .windows_api;
} else {
return .no_color;
@ -148,7 +151,7 @@ pub fn dumpStackTraceFromBase(bp: usize, ip: usize) void {
/// chopping off the irrelevant frames and shifting so that the returned addresses pointer
/// equals the passed in addresses pointer.
pub fn captureStackTrace(first_address: ?usize, stack_trace: *builtin.StackTrace) void {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
const addrs = stack_trace.instruction_addresses;
const u32_addrs_len = @intCast(u32, addrs.len);
const first_addr = first_address orelse {
@ -226,7 +229,7 @@ pub fn assert(ok: bool) void {
pub fn panic(comptime format: []const u8, args: anytype) noreturn {
@setCold(true);
// TODO: remove conditional once wasi / LLVM defines __builtin_return_address
const first_trace_addr = if (builtin.os.tag == .wasi) null else @returnAddress();
const first_trace_addr = if (native_os == .wasi) null else @returnAddress();
panicExtra(null, first_trace_addr, format, args);
}
@ -337,7 +340,7 @@ pub const StackIterator = struct {
fp: usize,
pub fn init(first_address: ?usize, fp: ?usize) StackIterator {
if (builtin.arch == .sparcv9) {
if (native_arch == .sparcv9) {
// Flush all the register windows on stack.
asm volatile (
\\ flushw
@ -351,25 +354,25 @@ pub const StackIterator = struct {
}
// Offset of the saved BP wrt the frame pointer.
const fp_offset = if (comptime builtin.arch.isRISCV())
const fp_offset = if (native_arch.isRISCV())
// On RISC-V the frame pointer points to the top of the saved register
// area, on pretty much every other architecture it points to the stack
// slot where the previous frame pointer is saved.
2 * @sizeOf(usize)
else if (comptime builtin.arch.isSPARC())
else if (native_arch.isSPARC())
// On SPARC the previous frame pointer is stored at 14 slots past %fp+BIAS.
14 * @sizeOf(usize)
else
0;
const fp_bias = if (comptime builtin.arch.isSPARC())
const fp_bias = if (native_arch.isSPARC())
// On SPARC frame pointers are biased by a constant.
2047
else
0;
// Positive offset of the saved PC wrt the frame pointer.
const pc_offset = if (builtin.arch == .powerpc64le)
const pc_offset = if (native_arch == .powerpc64le)
2 * @sizeOf(usize)
else
@sizeOf(usize);
@ -388,7 +391,7 @@ pub const StackIterator = struct {
}
fn next_internal(self: *StackIterator) ?usize {
const fp = if (comptime builtin.arch.isSPARC())
const fp = if (comptime native_arch.isSPARC())
// On SPARC the offset is positive. (!)
math.add(usize, self.fp, fp_offset) catch return null
else
@ -424,7 +427,7 @@ pub fn writeCurrentStackTrace(
tty_config: TTY.Config,
start_addr: ?usize,
) !void {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
return writeCurrentStackTraceWindows(out_stream, debug_info, tty_config, start_addr);
}
var it = StackIterator.init(start_addr, null);
@ -482,7 +485,7 @@ pub const TTY = struct {
.Bold => out_stream.writeAll(BOLD) catch return,
.Reset => out_stream.writeAll(RESET) catch return,
},
.windows_api => if (builtin.os.tag == .windows) {
.windows_api => if (native_os == .windows) {
const stderr_file = io.getStdErr();
const S = struct {
var attrs: windows.WORD = undefined;
@ -684,7 +687,7 @@ pub fn openSelfDebugInfo(allocator: *mem.Allocator) anyerror!DebugInfo {
if (@hasDecl(root, "os") and @hasDecl(root.os, "debug") and @hasDecl(root.os.debug, "openSelfDebugInfo")) {
return root.os.debug.openSelfDebugInfo(allocator);
}
switch (builtin.os.tag) {
switch (native_os) {
.linux,
.freebsd,
.netbsd,
@ -897,7 +900,7 @@ pub fn readElfDebugInfo(allocator: *mem.Allocator, elf_file: File) !ModuleDebugI
elf.ELFDATA2MSB => .Big,
else => return error.InvalidElfEndian,
};
assert(endian == std.builtin.endian); // this is our own debug info
assert(endian == native_endian); // this is our own debug info
const shoff = hdr.e_shoff;
const str_section_off = shoff + @as(u64, hdr.e_shentsize) * @as(u64, hdr.e_shstrndx);
@ -1132,9 +1135,9 @@ pub const DebugInfo = struct {
pub fn getModuleForAddress(self: *DebugInfo, address: usize) !*ModuleDebugInfo {
if (comptime std.Target.current.isDarwin()) {
return self.lookupModuleDyld(address);
} else if (builtin.os.tag == .windows) {
} else if (native_os == .windows) {
return self.lookupModuleWin32(address);
} else if (builtin.os.tag == .haiku) {
} else if (native_os == .haiku) {
return self.lookupModuleHaiku(address);
} else {
return self.lookupModuleDl(address);
@ -1362,7 +1365,7 @@ const SymbolInfo = struct {
}
};
pub const ModuleDebugInfo = switch (builtin.os.tag) {
pub const ModuleDebugInfo = switch (native_os) {
.macos, .ios, .watchos, .tvos => struct {
base_address: usize,
mapped_memory: []const u8,
@ -1729,7 +1732,7 @@ fn getDebugInfoAllocator() *mem.Allocator {
}
/// Whether or not the current target can print useful debug information when a segfault occurs.
pub const have_segfault_handling_support = switch (builtin.os.tag) {
pub const have_segfault_handling_support = switch (native_os) {
.linux, .netbsd => true,
.windows => true,
.freebsd, .openbsd => @hasDecl(os, "ucontext_t"),
@ -1753,7 +1756,7 @@ pub fn attachSegfaultHandler() void {
if (!have_segfault_handling_support) {
@compileError("segfault handler not supported for this target");
}
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
windows_segfault_handle = windows.kernel32.AddVectoredExceptionHandler(0, handleSegfaultWindows);
return;
}
@ -1769,7 +1772,7 @@ pub fn attachSegfaultHandler() void {
}
fn resetSegfaultHandler() void {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
if (windows_segfault_handle) |handle| {
assert(windows.kernel32.RemoveVectoredExceptionHandler(handle) != 0);
windows_segfault_handle = null;
@ -1792,7 +1795,7 @@ fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: ?*const c_v
// and the resulting segfault will crash the process rather than continually dump stack traces.
resetSegfaultHandler();
const addr = switch (builtin.os.tag) {
const addr = switch (native_os) {
.linux => @ptrToInt(info.fields.sigfault.addr),
.freebsd => @ptrToInt(info.addr),
.netbsd => @ptrToInt(info.info.reason.fault.addr),
@ -1811,7 +1814,7 @@ fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: ?*const c_v
} catch os.abort();
}
switch (builtin.arch) {
switch (native_arch) {
.i386 => {
const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr));
const ip = @intCast(usize, ctx.mcontext.gregs[os.REG_EIP]);
@ -1820,13 +1823,13 @@ fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: ?*const c_v
},
.x86_64 => {
const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr));
const ip = switch (builtin.os.tag) {
const ip = switch (native_os) {
.linux, .netbsd => @intCast(usize, ctx.mcontext.gregs[os.REG_RIP]),
.freebsd => @intCast(usize, ctx.mcontext.rip),
.openbsd => @intCast(usize, ctx.sc_rip),
else => unreachable,
};
const bp = switch (builtin.os.tag) {
const bp = switch (native_os) {
.linux, .netbsd => @intCast(usize, ctx.mcontext.gregs[os.REG_RBP]),
.openbsd => @intCast(usize, ctx.sc_rbp),
.freebsd => @intCast(usize, ctx.mcontext.rbp),

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const debug = std.debug;
const fs = std.fs;
const io = std.io;

View File

@ -3,7 +3,7 @@
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const builtin = @import("builtin");
const builtin = std.builtin;
const std = @import("std.zig");
const mem = std.mem;

View File

@ -4,13 +4,13 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std.zig");
const builtin = std.builtin;
const io = std.io;
const os = std.os;
const math = std.math;
const mem = std.mem;
const debug = std.debug;
const File = std.fs.File;
const native_endian = @import("builtin").target.cpu.arch.endian();
pub const AT_NULL = 0;
pub const AT_IGNORE = 1;
@ -311,7 +311,7 @@ pub const VER_FLG_BASE = 0x1;
pub const VER_FLG_WEAK = 0x2;
/// File types
pub const ET = extern enum(u16) {
pub const ET = enum(u16) {
/// No file type
NONE = 0,
@ -336,7 +336,7 @@ pub const ET = extern enum(u16) {
/// All integers are native endian.
pub const Header = struct {
endian: builtin.Endian,
endian: std.builtin.Endian,
machine: EM,
is_64: bool,
entry: u64,
@ -380,7 +380,7 @@ pub const Header = struct {
ELFDATA2MSB => .Big,
else => return error.InvalidElfEndian,
};
const need_bswap = endian != std.builtin.endian;
const need_bswap = endian != native_endian;
const is_64 = switch (hdr32.e_ident[EI_CLASS]) {
ELFCLASS32 => false,
@ -426,7 +426,7 @@ pub fn ProgramHeaderIterator(ParseSource: anytype) type {
try self.parse_source.reader().readNoEof(mem.asBytes(&phdr));
// ELF endianness matches native endianness.
if (self.elf_header.endian == std.builtin.endian) return phdr;
if (self.elf_header.endian == native_endian) return phdr;
// Convert fields to native endianness.
bswapAllFields(Elf64_Phdr, &phdr);
@ -439,7 +439,7 @@ pub fn ProgramHeaderIterator(ParseSource: anytype) type {
try self.parse_source.reader().readNoEof(mem.asBytes(&phdr));
// ELF endianness does NOT match native endianness.
if (self.elf_header.endian != std.builtin.endian) {
if (self.elf_header.endian != native_endian) {
// Convert fields to native endianness.
bswapAllFields(Elf32_Phdr, &phdr);
}
@ -476,7 +476,7 @@ pub fn SectionHeaderIterator(ParseSource: anytype) type {
try self.parse_source.reader().readNoEof(mem.asBytes(&shdr));
// ELF endianness matches native endianness.
if (self.elf_header.endian == std.builtin.endian) return shdr;
if (self.elf_header.endian == native_endian) return shdr;
// Convert fields to native endianness.
return Elf64_Shdr{
@ -499,7 +499,7 @@ pub fn SectionHeaderIterator(ParseSource: anytype) type {
try self.parse_source.reader().readNoEof(mem.asBytes(&shdr));
// ELF endianness does NOT match native endianness.
if (self.elf_header.endian != std.builtin.endian) {
if (self.elf_header.endian != native_endian) {
// Convert fields to native endianness.
shdr = .{
.sh_name = @byteSwap(@TypeOf(shdr.sh_name), shdr.sh_name),
@ -991,7 +991,7 @@ pub const Half = switch (@sizeOf(usize)) {
/// See current registered ELF machine architectures at:
/// http://www.uxsglobal.com/developers/gabi/latest/ch4.eheader.html
/// The underscore prefix is because many of these start with numbers.
pub const EM = extern enum(u16) {
pub const EM = enum(u16) {
/// No machine
_NONE = 0,

View File

@ -18,7 +18,7 @@ const EnumField = std.builtin.TypeInfo.EnumField;
pub fn EnumFieldStruct(comptime E: type, comptime Data: type, comptime field_default: ?Data) type {
const StructField = std.builtin.TypeInfo.StructField;
var fields: []const StructField = &[_]StructField{};
for (uniqueFields(E)) |field, i| {
for (std.meta.fields(E)) |field, i| {
fields = fields ++ &[_]StructField{.{
.name = field.name,
.field_type = Data,
@ -48,72 +48,12 @@ pub fn valuesFromFields(comptime E: type, comptime fields: []const EnumField) []
}
}
test "std.enums.valuesFromFields" {
const E = extern enum { a, b, c, d = 0 };
const fields = valuesFromFields(E, &[_]EnumField{
.{ .name = "b", .value = undefined },
.{ .name = "a", .value = undefined },
.{ .name = "a", .value = undefined },
.{ .name = "d", .value = undefined },
});
try testing.expectEqual(E.b, fields[0]);
try testing.expectEqual(E.a, fields[1]);
try testing.expectEqual(E.d, fields[2]); // a == d
try testing.expectEqual(E.d, fields[3]);
}
/// Returns the set of all named values in the given enum, in
/// declaration order.
pub fn values(comptime E: type) []const E {
return comptime valuesFromFields(E, @typeInfo(E).Enum.fields);
}
test "std.enum.values" {
const E = extern enum { a, b, c, d = 0 };
try testing.expectEqualSlices(E, &.{ .a, .b, .c, .d }, values(E));
}
/// Returns the set of all unique named values in the given enum, in
/// declaration order. For repeated values in extern enums, only the
/// first name for each value is included.
pub fn uniqueValues(comptime E: type) []const E {
return comptime valuesFromFields(E, uniqueFields(E));
}
test "std.enum.uniqueValues" {
const E = extern enum { a, b, c, d = 0, e, f = 3 };
try testing.expectEqualSlices(E, &.{ .a, .b, .c, .f }, uniqueValues(E));
const F = enum { a, b, c };
try testing.expectEqualSlices(F, &.{ .a, .b, .c }, uniqueValues(F));
}
/// Returns the set of all unique field values in the given enum, in
/// declaration order. For repeated values in extern enums, only the
/// first name for each value is included.
pub fn uniqueFields(comptime E: type) []const EnumField {
comptime {
const info = @typeInfo(E).Enum;
const raw_fields = info.fields;
// Only extern enums can contain duplicates,
// so fast path other types.
if (info.layout != .Extern) {
return raw_fields;
}
var unique_fields: []const EnumField = &[_]EnumField{};
outer: for (raw_fields) |candidate| {
for (unique_fields) |u| {
if (u.value == candidate.value)
continue :outer;
}
unique_fields = unique_fields ++ &[_]EnumField{candidate};
}
return unique_fields;
}
}
/// Determines the length of a direct-mapped enum array, indexed by
/// @intCast(usize, @enumToInt(enum_value)).
/// If the enum is non-exhaustive, the resulting length will only be enough
@ -126,7 +66,7 @@ pub fn uniqueFields(comptime E: type) []const EnumField {
fn directEnumArrayLen(comptime E: type, comptime max_unused_slots: comptime_int) comptime_int {
var max_value: comptime_int = -1;
const max_usize: comptime_int = ~@as(usize, 0);
const fields = uniqueFields(E);
const fields = std.meta.fields(E);
for (fields) |f| {
if (f.value < 0) {
@compileError("Cannot create a direct enum array for " ++ @typeName(E) ++ ", field ." ++ f.name ++ " has a negative value.");
@ -248,8 +188,8 @@ pub fn nameCast(comptime E: type, comptime value: anytype) E {
}
test "std.enums.nameCast" {
const A = enum { a = 0, b = 1 };
const B = enum { a = 1, b = 0 };
const A = enum(u1) { a = 0, b = 1 };
const B = enum(u1) { a = 1, b = 0 };
try testing.expectEqual(A.a, nameCast(A, .a));
try testing.expectEqual(A.a, nameCast(A, A.a));
try testing.expectEqual(A.a, nameCast(A, B.a));
@ -283,8 +223,8 @@ pub fn EnumSet(comptime E: type) type {
var result = Self{};
comptime var i: usize = 0;
inline while (i < Self.len) : (i += 1) {
comptime const key = Indexer.keyForIndex(i);
comptime const tag = @tagName(key);
const key = comptime Indexer.keyForIndex(i);
const tag = comptime @tagName(key);
if (@field(init_values, tag)) {
result.bits.set(i);
}
@ -311,8 +251,8 @@ pub fn EnumMap(comptime E: type, comptime V: type) type {
var result = Self{};
comptime var i: usize = 0;
inline while (i < Self.len) : (i += 1) {
comptime const key = Indexer.keyForIndex(i);
comptime const tag = @tagName(key);
const key = comptime Indexer.keyForIndex(i);
const tag = comptime @tagName(key);
if (@field(init_values, tag)) |*v| {
result.bits.set(i);
result.values[i] = v.*;
@ -344,8 +284,8 @@ pub fn EnumMap(comptime E: type, comptime V: type) type {
};
comptime var i: usize = 0;
inline while (i < Self.len) : (i += 1) {
comptime const key = Indexer.keyForIndex(i);
comptime const tag = @tagName(key);
const key = comptime Indexer.keyForIndex(i);
const tag = comptime @tagName(key);
result.values[i] = @field(init_values, tag);
}
return result;
@ -796,7 +736,7 @@ pub fn EnumIndexer(comptime E: type) type {
@compileError("Cannot create an enum indexer for a non-exhaustive enum.");
}
const const_fields = uniqueFields(E);
const const_fields = std.meta.fields(E);
var fields = const_fields[0..const_fields.len].*;
if (fields.len == 0) {
return struct {
@ -848,7 +788,7 @@ pub fn EnumIndexer(comptime E: type) type {
}
test "std.enums.EnumIndexer dense zeroed" {
const E = enum { b = 1, a = 0, c = 2 };
const E = enum(u2) { b = 1, a = 0, c = 2 };
const Indexer = EnumIndexer(E);
ensureIndexer(Indexer);
try testing.expectEqual(E, Indexer.Key);
@ -910,379 +850,3 @@ test "std.enums.EnumIndexer sparse" {
try testing.expectEqual(E.b, Indexer.keyForIndex(1));
try testing.expectEqual(E.c, Indexer.keyForIndex(2));
}
test "std.enums.EnumIndexer repeats" {
const E = extern enum { a = -2, c = 6, b = 4, b2 = 4 };
const Indexer = EnumIndexer(E);
ensureIndexer(Indexer);
try testing.expectEqual(E, Indexer.Key);
try testing.expectEqual(@as(usize, 3), Indexer.count);
try testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
try testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
try testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));
try testing.expectEqual(E.a, Indexer.keyForIndex(0));
try testing.expectEqual(E.b, Indexer.keyForIndex(1));
try testing.expectEqual(E.c, Indexer.keyForIndex(2));
}
test "std.enums.EnumSet" {
const E = extern enum { a, b, c, d, e = 0 };
const Set = EnumSet(E);
try testing.expectEqual(E, Set.Key);
try testing.expectEqual(EnumIndexer(E), Set.Indexer);
try testing.expectEqual(@as(usize, 4), Set.len);
// Empty sets
const empty = Set{};
comptime try testing.expect(empty.count() == 0);
var empty_b = Set.init(.{});
try testing.expect(empty_b.count() == 0);
const empty_c = comptime Set.init(.{});
comptime try testing.expect(empty_c.count() == 0);
const full = Set.initFull();
try testing.expect(full.count() == Set.len);
const full_b = comptime Set.initFull();
comptime try testing.expect(full_b.count() == Set.len);
try testing.expectEqual(false, empty.contains(.a));
try testing.expectEqual(false, empty.contains(.b));
try testing.expectEqual(false, empty.contains(.c));
try testing.expectEqual(false, empty.contains(.d));
try testing.expectEqual(false, empty.contains(.e));
{
var iter = empty_b.iterator();
try testing.expectEqual(@as(?E, null), iter.next());
}
var mut = Set.init(.{
.a = true,
.c = true,
});
try testing.expectEqual(@as(usize, 2), mut.count());
try testing.expectEqual(true, mut.contains(.a));
try testing.expectEqual(false, mut.contains(.b));
try testing.expectEqual(true, mut.contains(.c));
try testing.expectEqual(false, mut.contains(.d));
try testing.expectEqual(true, mut.contains(.e)); // aliases a
{
var it = mut.iterator();
try testing.expectEqual(@as(?E, .a), it.next());
try testing.expectEqual(@as(?E, .c), it.next());
try testing.expectEqual(@as(?E, null), it.next());
}
mut.toggleAll();
try testing.expectEqual(@as(usize, 2), mut.count());
try testing.expectEqual(false, mut.contains(.a));
try testing.expectEqual(true, mut.contains(.b));
try testing.expectEqual(false, mut.contains(.c));
try testing.expectEqual(true, mut.contains(.d));
try testing.expectEqual(false, mut.contains(.e)); // aliases a
{
var it = mut.iterator();
try testing.expectEqual(@as(?E, .b), it.next());
try testing.expectEqual(@as(?E, .d), it.next());
try testing.expectEqual(@as(?E, null), it.next());
}
mut.toggleSet(Set.init(.{ .a = true, .b = true }));
try testing.expectEqual(@as(usize, 2), mut.count());
try testing.expectEqual(true, mut.contains(.a));
try testing.expectEqual(false, mut.contains(.b));
try testing.expectEqual(false, mut.contains(.c));
try testing.expectEqual(true, mut.contains(.d));
try testing.expectEqual(true, mut.contains(.e)); // aliases a
mut.setUnion(Set.init(.{ .a = true, .b = true }));
try testing.expectEqual(@as(usize, 3), mut.count());
try testing.expectEqual(true, mut.contains(.a));
try testing.expectEqual(true, mut.contains(.b));
try testing.expectEqual(false, mut.contains(.c));
try testing.expectEqual(true, mut.contains(.d));
mut.remove(.c);
mut.remove(.b);
try testing.expectEqual(@as(usize, 2), mut.count());
try testing.expectEqual(true, mut.contains(.a));
try testing.expectEqual(false, mut.contains(.b));
try testing.expectEqual(false, mut.contains(.c));
try testing.expectEqual(true, mut.contains(.d));
mut.setIntersection(Set.init(.{ .a = true, .b = true }));
try testing.expectEqual(@as(usize, 1), mut.count());
try testing.expectEqual(true, mut.contains(.a));
try testing.expectEqual(false, mut.contains(.b));
try testing.expectEqual(false, mut.contains(.c));
try testing.expectEqual(false, mut.contains(.d));
mut.insert(.a);
mut.insert(.b);
try testing.expectEqual(@as(usize, 2), mut.count());
try testing.expectEqual(true, mut.contains(.a));
try testing.expectEqual(true, mut.contains(.b));
try testing.expectEqual(false, mut.contains(.c));
try testing.expectEqual(false, mut.contains(.d));
mut.setPresent(.a, false);
mut.toggle(.b);
mut.toggle(.c);
mut.setPresent(.d, true);
try testing.expectEqual(@as(usize, 2), mut.count());
try testing.expectEqual(false, mut.contains(.a));
try testing.expectEqual(false, mut.contains(.b));
try testing.expectEqual(true, mut.contains(.c));
try testing.expectEqual(true, mut.contains(.d));
}
test "std.enums.EnumArray void" {
const E = extern enum { a, b, c, d, e = 0 };
const ArrayVoid = EnumArray(E, void);
try testing.expectEqual(E, ArrayVoid.Key);
try testing.expectEqual(EnumIndexer(E), ArrayVoid.Indexer);
try testing.expectEqual(void, ArrayVoid.Value);
try testing.expectEqual(@as(usize, 4), ArrayVoid.len);
const undef = ArrayVoid.initUndefined();
var inst = ArrayVoid.initFill({});
const inst2 = ArrayVoid.init(.{ .a = {}, .b = {}, .c = {}, .d = {} });
const inst3 = ArrayVoid.initDefault({}, .{});
_ = inst.get(.a);
_ = inst.getPtr(.b);
_ = inst.getPtrConst(.c);
inst.set(.a, {});
var it = inst.iterator();
try testing.expectEqual(E.a, it.next().?.key);
try testing.expectEqual(E.b, it.next().?.key);
try testing.expectEqual(E.c, it.next().?.key);
try testing.expectEqual(E.d, it.next().?.key);
try testing.expect(it.next() == null);
}
test "std.enums.EnumArray sized" {
const E = extern enum { a, b, c, d, e = 0 };
const Array = EnumArray(E, usize);
try testing.expectEqual(E, Array.Key);
try testing.expectEqual(EnumIndexer(E), Array.Indexer);
try testing.expectEqual(usize, Array.Value);
try testing.expectEqual(@as(usize, 4), Array.len);
const undef = Array.initUndefined();
var inst = Array.initFill(5);
const inst2 = Array.init(.{ .a = 1, .b = 2, .c = 3, .d = 4 });
const inst3 = Array.initDefault(6, .{ .b = 4, .c = 2 });
try testing.expectEqual(@as(usize, 5), inst.get(.a));
try testing.expectEqual(@as(usize, 5), inst.get(.b));
try testing.expectEqual(@as(usize, 5), inst.get(.c));
try testing.expectEqual(@as(usize, 5), inst.get(.d));
try testing.expectEqual(@as(usize, 1), inst2.get(.a));
try testing.expectEqual(@as(usize, 2), inst2.get(.b));
try testing.expectEqual(@as(usize, 3), inst2.get(.c));
try testing.expectEqual(@as(usize, 4), inst2.get(.d));
try testing.expectEqual(@as(usize, 6), inst3.get(.a));
try testing.expectEqual(@as(usize, 4), inst3.get(.b));
try testing.expectEqual(@as(usize, 2), inst3.get(.c));
try testing.expectEqual(@as(usize, 6), inst3.get(.d));
try testing.expectEqual(&inst.values[0], inst.getPtr(.a));
try testing.expectEqual(&inst.values[1], inst.getPtr(.b));
try testing.expectEqual(&inst.values[2], inst.getPtr(.c));
try testing.expectEqual(&inst.values[3], inst.getPtr(.d));
try testing.expectEqual(@as(*const usize, &inst.values[0]), inst.getPtrConst(.a));
try testing.expectEqual(@as(*const usize, &inst.values[1]), inst.getPtrConst(.b));
try testing.expectEqual(@as(*const usize, &inst.values[2]), inst.getPtrConst(.c));
try testing.expectEqual(@as(*const usize, &inst.values[3]), inst.getPtrConst(.d));
inst.set(.c, 8);
try testing.expectEqual(@as(usize, 5), inst.get(.a));
try testing.expectEqual(@as(usize, 5), inst.get(.b));
try testing.expectEqual(@as(usize, 8), inst.get(.c));
try testing.expectEqual(@as(usize, 5), inst.get(.d));
var it = inst.iterator();
const Entry = Array.Entry;
try testing.expectEqual(@as(?Entry, Entry{
.key = .a,
.value = &inst.values[0],
}), it.next());
try testing.expectEqual(@as(?Entry, Entry{
.key = .b,
.value = &inst.values[1],
}), it.next());
try testing.expectEqual(@as(?Entry, Entry{
.key = .c,
.value = &inst.values[2],
}), it.next());
try testing.expectEqual(@as(?Entry, Entry{
.key = .d,
.value = &inst.values[3],
}), it.next());
try testing.expectEqual(@as(?Entry, null), it.next());
}
test "std.enums.EnumMap void" {
const E = extern enum { a, b, c, d, e = 0 };
const Map = EnumMap(E, void);
try testing.expectEqual(E, Map.Key);
try testing.expectEqual(EnumIndexer(E), Map.Indexer);
try testing.expectEqual(void, Map.Value);
try testing.expectEqual(@as(usize, 4), Map.len);
const b = Map.initFull({});
try testing.expectEqual(@as(usize, 4), b.count());
const c = Map.initFullWith(.{ .a = {}, .b = {}, .c = {}, .d = {} });
try testing.expectEqual(@as(usize, 4), c.count());
const d = Map.initFullWithDefault({}, .{ .b = {} });
try testing.expectEqual(@as(usize, 4), d.count());
var a = Map.init(.{ .b = {}, .d = {} });
try testing.expectEqual(@as(usize, 2), a.count());
try testing.expectEqual(false, a.contains(.a));
try testing.expectEqual(true, a.contains(.b));
try testing.expectEqual(false, a.contains(.c));
try testing.expectEqual(true, a.contains(.d));
try testing.expect(a.get(.a) == null);
try testing.expect(a.get(.b) != null);
try testing.expect(a.get(.c) == null);
try testing.expect(a.get(.d) != null);
try testing.expect(a.getPtr(.a) == null);
try testing.expect(a.getPtr(.b) != null);
try testing.expect(a.getPtr(.c) == null);
try testing.expect(a.getPtr(.d) != null);
try testing.expect(a.getPtrConst(.a) == null);
try testing.expect(a.getPtrConst(.b) != null);
try testing.expect(a.getPtrConst(.c) == null);
try testing.expect(a.getPtrConst(.d) != null);
_ = a.getPtrAssertContains(.b);
_ = a.getAssertContains(.d);
a.put(.a, {});
a.put(.a, {});
a.putUninitialized(.c).* = {};
a.putUninitialized(.c).* = {};
try testing.expectEqual(@as(usize, 4), a.count());
try testing.expect(a.get(.a) != null);
try testing.expect(a.get(.b) != null);
try testing.expect(a.get(.c) != null);
try testing.expect(a.get(.d) != null);
a.remove(.a);
_ = a.fetchRemove(.c);
var iter = a.iterator();
const Entry = Map.Entry;
try testing.expectEqual(E.b, iter.next().?.key);
try testing.expectEqual(E.d, iter.next().?.key);
try testing.expect(iter.next() == null);
}
test "std.enums.EnumMap sized" {
const E = extern enum { a, b, c, d, e = 0 };
const Map = EnumMap(E, usize);
try testing.expectEqual(E, Map.Key);
try testing.expectEqual(EnumIndexer(E), Map.Indexer);
try testing.expectEqual(usize, Map.Value);
try testing.expectEqual(@as(usize, 4), Map.len);
const b = Map.initFull(5);
try testing.expectEqual(@as(usize, 4), b.count());
try testing.expect(b.contains(.a));
try testing.expect(b.contains(.b));
try testing.expect(b.contains(.c));
try testing.expect(b.contains(.d));
try testing.expectEqual(@as(?usize, 5), b.get(.a));
try testing.expectEqual(@as(?usize, 5), b.get(.b));
try testing.expectEqual(@as(?usize, 5), b.get(.c));
try testing.expectEqual(@as(?usize, 5), b.get(.d));
const c = Map.initFullWith(.{ .a = 1, .b = 2, .c = 3, .d = 4 });
try testing.expectEqual(@as(usize, 4), c.count());
try testing.expect(c.contains(.a));
try testing.expect(c.contains(.b));
try testing.expect(c.contains(.c));
try testing.expect(c.contains(.d));
try testing.expectEqual(@as(?usize, 1), c.get(.a));
try testing.expectEqual(@as(?usize, 2), c.get(.b));
try testing.expectEqual(@as(?usize, 3), c.get(.c));
try testing.expectEqual(@as(?usize, 4), c.get(.d));
const d = Map.initFullWithDefault(6, .{ .b = 2, .c = 4 });
try testing.expectEqual(@as(usize, 4), d.count());
try testing.expect(d.contains(.a));
try testing.expect(d.contains(.b));
try testing.expect(d.contains(.c));
try testing.expect(d.contains(.d));
try testing.expectEqual(@as(?usize, 6), d.get(.a));
try testing.expectEqual(@as(?usize, 2), d.get(.b));
try testing.expectEqual(@as(?usize, 4), d.get(.c));
try testing.expectEqual(@as(?usize, 6), d.get(.d));
var a = Map.init(.{ .b = 2, .d = 4 });
try testing.expectEqual(@as(usize, 2), a.count());
try testing.expectEqual(false, a.contains(.a));
try testing.expectEqual(true, a.contains(.b));
try testing.expectEqual(false, a.contains(.c));
try testing.expectEqual(true, a.contains(.d));
try testing.expectEqual(@as(?usize, null), a.get(.a));
try testing.expectEqual(@as(?usize, 2), a.get(.b));
try testing.expectEqual(@as(?usize, null), a.get(.c));
try testing.expectEqual(@as(?usize, 4), a.get(.d));
try testing.expectEqual(@as(?*usize, null), a.getPtr(.a));
try testing.expectEqual(@as(?*usize, &a.values[1]), a.getPtr(.b));
try testing.expectEqual(@as(?*usize, null), a.getPtr(.c));
try testing.expectEqual(@as(?*usize, &a.values[3]), a.getPtr(.d));
try testing.expectEqual(@as(?*const usize, null), a.getPtrConst(.a));
try testing.expectEqual(@as(?*const usize, &a.values[1]), a.getPtrConst(.b));
try testing.expectEqual(@as(?*const usize, null), a.getPtrConst(.c));
try testing.expectEqual(@as(?*const usize, &a.values[3]), a.getPtrConst(.d));
try testing.expectEqual(@as(*const usize, &a.values[1]), a.getPtrAssertContains(.b));
try testing.expectEqual(@as(*const usize, &a.values[3]), a.getPtrAssertContains(.d));
try testing.expectEqual(@as(usize, 2), a.getAssertContains(.b));
try testing.expectEqual(@as(usize, 4), a.getAssertContains(.d));
a.put(.a, 3);
a.put(.a, 5);
a.putUninitialized(.c).* = 7;
a.putUninitialized(.c).* = 9;
try testing.expectEqual(@as(usize, 4), a.count());
try testing.expectEqual(@as(?usize, 5), a.get(.a));
try testing.expectEqual(@as(?usize, 2), a.get(.b));
try testing.expectEqual(@as(?usize, 9), a.get(.c));
try testing.expectEqual(@as(?usize, 4), a.get(.d));
a.remove(.a);
try testing.expectEqual(@as(?usize, null), a.fetchRemove(.a));
try testing.expectEqual(@as(?usize, 9), a.fetchRemove(.c));
a.remove(.c);
var iter = a.iterator();
const Entry = Map.Entry;
try testing.expectEqual(@as(?Entry, Entry{
.key = .b,
.value = &a.values[1],
}), iter.next());
try testing.expectEqual(@as(?Entry, Entry{
.key = .d,
.value = &a.values[3],
}), iter.next());
try testing.expectEqual(@as(?Entry, null), iter.next());
}

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const assert = std.debug.assert;
const testing = std.testing;
const Loop = std.event.Loop;

View File

@ -6,7 +6,7 @@
const std = @import("../std.zig");
const assert = std.debug.assert;
const testing = std.testing;
const builtin = @import("builtin");
const builtin = std.builtin;
const Lock = std.event.Lock;
/// This is a value that starts out unavailable, until resolve() is called

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const Lock = std.event.Lock;
const testing = std.testing;
const Allocator = std.mem.Allocator;

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const root = @import("root");
const assert = std.debug.assert;
const testing = std.testing;

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const Loop = std.event.Loop;
/// A WaitGroup keeps track and waits for a group of async tasks to finish.

View File

@ -187,7 +187,7 @@ pub fn format(
comptime var i = 0;
inline while (i < fmt.len) {
comptime const start_index = i;
const start_index = i;
inline while (i < fmt.len) : (i += 1) {
switch (fmt[i]) {
@ -226,10 +226,10 @@ pub fn format(
comptime assert(fmt[i] == '{');
i += 1;
comptime const fmt_begin = i;
const fmt_begin = i;
// Find the closing brace
inline while (i < fmt.len and fmt[i] != '}') : (i += 1) {}
comptime const fmt_end = i;
const fmt_end = i;
if (i >= fmt.len) {
@compileError("Missing closing }");
@ -246,23 +246,23 @@ pub fn format(
parser.pos = 0;
// Parse the positional argument number
comptime const opt_pos_arg = init: {
if (comptime parser.maybe('[')) {
comptime const arg_name = parser.until(']');
const opt_pos_arg = comptime init: {
if (parser.maybe('[')) {
const arg_name = parser.until(']');
if (!comptime parser.maybe(']')) {
if (!parser.maybe(']')) {
@compileError("Expected closing ]");
}
break :init comptime meta.fieldIndex(ArgsType, arg_name) orelse
break :init meta.fieldIndex(ArgsType, arg_name) orelse
@compileError("No argument with name '" ++ arg_name ++ "'");
} else {
break :init comptime parser.number();
break :init parser.number();
}
};
// Parse the format specifier
comptime const specifier_arg = comptime parser.until(':');
const specifier_arg = comptime parser.until(':');
// Skip the colon, if present
if (comptime parser.char()) |ch| {
@ -302,13 +302,13 @@ pub fn format(
// Parse the width parameter
options.width = init: {
if (comptime parser.maybe('[')) {
comptime const arg_name = parser.until(']');
const arg_name = comptime parser.until(']');
if (!comptime parser.maybe(']')) {
@compileError("Expected closing ]");
}
comptime const index = meta.fieldIndex(ArgsType, arg_name) orelse
const index = comptime meta.fieldIndex(ArgsType, arg_name) orelse
@compileError("No argument with name '" ++ arg_name ++ "'");
const arg_index = comptime arg_state.nextArg(index);
@ -328,13 +328,13 @@ pub fn format(
// Parse the precision parameter
options.precision = init: {
if (comptime parser.maybe('[')) {
comptime const arg_name = parser.until(']');
const arg_name = comptime parser.until(']');
if (!comptime parser.maybe(']')) {
@compileError("Expected closing ]");
}
comptime const arg_i = meta.fieldIndex(ArgsType, arg_name) orelse
const arg_i = comptime meta.fieldIndex(ArgsType, arg_name) orelse
@compileError("No argument with name '" ++ arg_name ++ "'");
const arg_to_use = comptime arg_state.nextArg(arg_i);
@ -905,7 +905,7 @@ pub fn formatBuf(
) !void {
if (options.width) |min_width| {
// In case of error assume the buffer content is ASCII-encoded
const width = unicode.utf8CountCodepoints(buf) catch |_| buf.len;
const width = unicode.utf8CountCodepoints(buf) catch buf.len;
const padding = if (width < min_width) min_width - width else 0;
if (padding == 0)
@ -1469,6 +1469,7 @@ pub fn Formatter(comptime format_fn: anytype) type {
/// * A prefix of "0x" implies radix=16,
/// * Otherwise radix=10 is assumed.
///
/// Ignores '_' character in `buf`.
/// See also `parseUnsigned`.
pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) ParseIntError!T {
if (buf.len == 0) return error.InvalidCharacter;
@ -1484,6 +1485,10 @@ test "parseInt" {
try std.testing.expectError(error.Overflow, parseInt(u32, "-10", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, " 10", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "10 ", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "_10_", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x_10_", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x10_", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x_10", 10));
try std.testing.expect((try parseInt(u8, "255", 10)) == 255);
try std.testing.expectError(error.Overflow, parseInt(u8, "256", 10));
@ -1505,12 +1510,18 @@ test "parseInt" {
// autodectect the radix
try std.testing.expect((try parseInt(i32, "111", 0)) == 111);
try std.testing.expect((try parseInt(i32, "1_1_1", 0)) == 111);
try std.testing.expect((try parseInt(i32, "1_1_1", 0)) == 111);
try std.testing.expect((try parseInt(i32, "+0b111", 0)) == 7);
try std.testing.expect((try parseInt(i32, "+0b1_11", 0)) == 7);
try std.testing.expect((try parseInt(i32, "+0o111", 0)) == 73);
try std.testing.expect((try parseInt(i32, "+0o11_1", 0)) == 73);
try std.testing.expect((try parseInt(i32, "+0x111", 0)) == 273);
try std.testing.expect((try parseInt(i32, "-0b111", 0)) == -7);
try std.testing.expect((try parseInt(i32, "-0b11_1", 0)) == -7);
try std.testing.expect((try parseInt(i32, "-0o111", 0)) == -73);
try std.testing.expect((try parseInt(i32, "-0x111", 0)) == -273);
try std.testing.expect((try parseInt(i32, "-0x1_11", 0)) == -273);
// bare binary/octal/decimal prefix is invalid
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0b", 0));
@ -1558,7 +1569,10 @@ fn parseWithSign(
var x: T = 0;
if (buf_start[0] == '_' or buf_start[buf_start.len - 1] == '_') return error.InvalidCharacter;
for (buf_start) |c| {
if (c == '_') continue;
const digit = try charToDigit(c, buf_radix);
if (x != 0) x = try math.mul(T, x, try math.cast(T, buf_radix));
@ -1577,6 +1591,7 @@ fn parseWithSign(
/// * A prefix of "0x" implies radix=16,
/// * Otherwise radix=10 is assumed.
///
/// Ignores '_' character in `buf`.
/// See also `parseInt`.
pub fn parseUnsigned(comptime T: type, buf: []const u8, radix: u8) ParseIntError!T {
return parseWithSign(T, buf, radix, .Pos);
@ -1585,9 +1600,11 @@ pub fn parseUnsigned(comptime T: type, buf: []const u8, radix: u8) ParseIntError
test "parseUnsigned" {
try std.testing.expect((try parseUnsigned(u16, "050124", 10)) == 50124);
try std.testing.expect((try parseUnsigned(u16, "65535", 10)) == 65535);
try std.testing.expect((try parseUnsigned(u16, "65_535", 10)) == 65535);
try std.testing.expectError(error.Overflow, parseUnsigned(u16, "65536", 10));
try std.testing.expect((try parseUnsigned(u64, "0ffffffffffffffff", 16)) == 0xffffffffffffffff);
try std.testing.expect((try parseUnsigned(u64, "0f_fff_fff_fff_fff_fff", 16)) == 0xffffffffffffffff);
try std.testing.expectError(error.Overflow, parseUnsigned(u64, "10000000000000000", 16));
try std.testing.expect((try parseUnsigned(u32, "DeadBeef", 16)) == 0xDEADBEEF);
@ -1620,8 +1637,8 @@ pub const parseFloat = @import("fmt/parse_float.zig").parseFloat;
pub const parseHexFloat = @import("fmt/parse_hex_float.zig").parseHexFloat;
test {
_ = @import("fmt/parse_float.zig");
_ = @import("fmt/parse_hex_float.zig");
_ = parseFloat;
_ = parseHexFloat;
}
pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) {
@ -2004,7 +2021,7 @@ test "float.special" {
try expectFmt("f64: nan", "f64: {}", .{math.nan_f64});
// negative nan is not defined by IEE 754,
// and ARM thus normalizes it to positive nan
if (builtin.arch != builtin.Arch.arm) {
if (builtin.target.cpu.arch != .arm) {
try expectFmt("f64: -nan", "f64: {}", .{-math.nan_f64});
}
try expectFmt("f64: inf", "f64: {}", .{math.inf_f64});
@ -2015,7 +2032,7 @@ test "float.hexadecimal.special" {
try expectFmt("f64: nan", "f64: {x}", .{math.nan_f64});
// negative nan is not defined by IEE 754,
// and ARM thus normalizes it to positive nan
if (builtin.arch != builtin.Arch.arm) {
if (builtin.target.cpu.arch != .arm) {
try expectFmt("f64: -nan", "f64: {x}", .{-math.nan_f64});
}
try expectFmt("f64: inf", "f64: {x}", .{math.inf_f64});
@ -2364,15 +2381,15 @@ test "positional/alignment/width/precision" {
}
test "vector" {
if (builtin.arch == .mipsel or builtin.arch == .mips) {
if (builtin.target.cpu.arch == .mipsel or builtin.target.cpu.arch == .mips) {
// https://github.com/ziglang/zig/issues/3317
return error.SkipZigTest;
}
if (builtin.arch == .riscv64) {
if (builtin.target.cpu.arch == .riscv64) {
// https://github.com/ziglang/zig/issues/4486
return error.SkipZigTest;
}
if (builtin.arch == .wasm32) {
if (builtin.target.cpu.arch == .wasm32) {
// https://github.com/ziglang/zig/issues/5339
return error.SkipZigTest;
}

View File

@ -3,7 +3,7 @@
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const builtin = @import("builtin");
const builtin = std.builtin;
const std = @import("std.zig");
const os = std.os;
const mem = std.mem;
@ -572,7 +572,7 @@ pub const Dir = struct {
/// Memory such as file names referenced in this returned entry becomes invalid
/// with subsequent calls to `next`, as well as when this `Dir` is deinitialized.
pub fn next(self: *Self) Error!?Entry {
start_over: while (true) {
while (true) {
const w = os.windows;
if (self.index >= self.end_index) {
var io: w.IO_STATUS_BLOCK = undefined;

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const os = std.os;
const io = std.io;
const mem = std.mem;

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const unicode = std.unicode;
const mem = std.mem;
const fs = std.fs;

View File

@ -15,22 +15,23 @@ const math = std.math;
const windows = std.os.windows;
const fs = std.fs;
const process = std.process;
const native_os = builtin.target.os.tag;
pub const sep_windows = '\\';
pub const sep_posix = '/';
pub const sep = if (builtin.os.tag == .windows) sep_windows else sep_posix;
pub const sep = if (native_os == .windows) sep_windows else sep_posix;
pub const sep_str_windows = "\\";
pub const sep_str_posix = "/";
pub const sep_str = if (builtin.os.tag == .windows) sep_str_windows else sep_str_posix;
pub const sep_str = if (native_os == .windows) sep_str_windows else sep_str_posix;
pub const delimiter_windows = ';';
pub const delimiter_posix = ':';
pub const delimiter = if (builtin.os.tag == .windows) delimiter_windows else delimiter_posix;
pub const delimiter = if (native_os == .windows) delimiter_windows else delimiter_posix;
/// Returns if the given byte is a valid path separator
pub fn isSep(byte: u8) bool {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
return byte == '/' or byte == '\\';
} else {
return byte == '/';
@ -168,7 +169,7 @@ test "join" {
pub const isAbsoluteC = @compileError("deprecated: renamed to isAbsoluteZ");
pub fn isAbsoluteZ(path_c: [*:0]const u8) bool {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
return isAbsoluteWindowsZ(path_c);
} else {
return isAbsolutePosixZ(path_c);
@ -176,7 +177,7 @@ pub fn isAbsoluteZ(path_c: [*:0]const u8) bool {
}
pub fn isAbsolute(path: []const u8) bool {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
return isAbsoluteWindows(path);
} else {
return isAbsolutePosix(path);
@ -365,7 +366,7 @@ test "windowsParsePath" {
}
pub fn diskDesignator(path: []const u8) []const u8 {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
return diskDesignatorWindows(path);
} else {
return "";
@ -430,7 +431,7 @@ fn asciiEqlIgnoreCase(s1: []const u8, s2: []const u8) bool {
/// On Windows, this calls `resolveWindows` and on POSIX it calls `resolvePosix`.
pub fn resolve(allocator: *Allocator, paths: []const []const u8) ![]u8 {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
return resolveWindows(allocator, paths);
} else {
return resolvePosix(allocator, paths);
@ -447,7 +448,7 @@ pub fn resolve(allocator: *Allocator, paths: []const []const u8) ![]u8 {
/// Without performing actual syscalls, resolving `..` could be incorrect.
pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
if (paths.len == 0) {
assert(builtin.os.tag == .windows); // resolveWindows called on non windows can't use getCwd
assert(native_os == .windows); // resolveWindows called on non windows can't use getCwd
return process.getCwdAlloc(allocator);
}
@ -542,7 +543,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
result_disk_designator = result[0..result_index];
},
WindowsPath.Kind.None => {
assert(builtin.os.tag == .windows); // resolveWindows called on non windows can't use getCwd
assert(native_os == .windows); // resolveWindows called on non windows can't use getCwd
const cwd = try process.getCwdAlloc(allocator);
defer allocator.free(cwd);
const parsed_cwd = windowsParsePath(cwd);
@ -557,7 +558,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
},
}
} else {
assert(builtin.os.tag == .windows); // resolveWindows called on non windows can't use getCwd
assert(native_os == .windows); // resolveWindows called on non windows can't use getCwd
// TODO call get cwd for the result_disk_designator instead of the global one
const cwd = try process.getCwdAlloc(allocator);
defer allocator.free(cwd);
@ -628,7 +629,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
/// Without performing actual syscalls, resolving `..` could be incorrect.
pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
if (paths.len == 0) {
assert(builtin.os.tag != .windows); // resolvePosix called on windows can't use getCwd
assert(native_os != .windows); // resolvePosix called on windows can't use getCwd
return process.getCwdAlloc(allocator);
}
@ -650,7 +651,7 @@ pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
if (have_abs) {
result = try allocator.alloc(u8, max_size);
} else {
assert(builtin.os.tag != .windows); // resolvePosix called on windows can't use getCwd
assert(native_os != .windows); // resolvePosix called on windows can't use getCwd
const cwd = try process.getCwdAlloc(allocator);
defer allocator.free(cwd);
result = try allocator.alloc(u8, max_size + cwd.len + 1);
@ -690,11 +691,11 @@ pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
}
test "resolve" {
if (builtin.os.tag == .wasi) return error.SkipZigTest;
if (native_os == .wasi) return error.SkipZigTest;
const cwd = try process.getCwdAlloc(testing.allocator);
defer testing.allocator.free(cwd);
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
if (windowsParsePath(cwd).kind == WindowsPath.Kind.Drive) {
cwd[0] = asciiUpper(cwd[0]);
}
@ -706,12 +707,12 @@ test "resolve" {
}
test "resolveWindows" {
if (builtin.arch == .aarch64) {
if (builtin.target.cpu.arch == .aarch64) {
// TODO https://github.com/ziglang/zig/issues/3288
return error.SkipZigTest;
}
if (builtin.os.tag == .wasi) return error.SkipZigTest;
if (builtin.os.tag == .windows) {
if (native_os == .wasi) return error.SkipZigTest;
if (native_os == .windows) {
const cwd = try process.getCwdAlloc(testing.allocator);
defer testing.allocator.free(cwd);
const parsed_cwd = windowsParsePath(cwd);
@ -755,7 +756,7 @@ test "resolveWindows" {
}
test "resolvePosix" {
if (builtin.os.tag == .wasi) return error.SkipZigTest;
if (native_os == .wasi) return error.SkipZigTest;
try testResolvePosix(&[_][]const u8{ "/a/b", "c" }, "/a/b/c");
try testResolvePosix(&[_][]const u8{ "/a/b", "c", "//d", "e///" }, "/d/e");
@ -788,7 +789,7 @@ fn testResolvePosix(paths: []const []const u8, expected: []const u8) !void {
///
/// If the path is the root directory, returns null.
pub fn dirname(path: []const u8) ?[]const u8 {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
return dirnameWindows(path);
} else {
return dirnamePosix(path);
@ -922,7 +923,7 @@ fn testDirnameWindows(input: []const u8, expected_output: ?[]const u8) !void {
}
pub fn basename(path: []const u8) []const u8 {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
return basenameWindows(path);
} else {
return basenamePosix(path);
@ -1038,7 +1039,7 @@ fn testBasenameWindows(input: []const u8, expected_output: []const u8) !void {
/// string is returned.
/// On Windows this canonicalizes the drive to a capital letter and paths to `\\`.
pub fn relative(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
if (builtin.os.tag == .windows) {
if (native_os == .windows) {
return relativeWindows(allocator, from, to);
} else {
return relativePosix(allocator, from, to);
@ -1164,11 +1165,11 @@ pub fn relativePosix(allocator: *Allocator, from: []const u8, to: []const u8) ![
}
test "relative" {
if (builtin.arch == .aarch64) {
if (builtin.target.cpu.arch == .aarch64) {
// TODO https://github.com/ziglang/zig/issues/3288
return error.SkipZigTest;
}
if (builtin.os.tag == .wasi) return error.SkipZigTest;
if (native_os == .wasi) return error.SkipZigTest;
try testRelativeWindows("c:/blah\\blah", "d:/games", "D:\\games");
try testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa", "..");

View File

@ -167,7 +167,7 @@ pub const PreopenList = struct {
};
test "extracting WASI preopens" {
if (@import("builtin").os.tag != .wasi) return error.SkipZigTest;
if (std.builtin.os.tag != .wasi) return error.SkipZigTest;
var preopens = PreopenList.init(std.testing.allocator);
defer preopens.deinit();

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std");
const builtin = @import("builtin");
const builtin = std.builtin;
const event = std.event;
const assert = std.debug.assert;
const testing = std.testing;

View File

@ -4,10 +4,10 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const mem = std.mem;
const meta = std.meta;
const builtin = std.builtin;
/// Describes how pointer types should be hashed.
pub const HashStrategy = enum {
@ -239,7 +239,7 @@ fn testHashDeepRecursive(key: anytype) u64 {
test "typeContainsSlice" {
comptime {
try testing.expect(!typeContainsSlice(meta.Tag(std.builtin.TypeInfo)));
try testing.expect(!typeContainsSlice(meta.Tag(builtin.TypeInfo)));
try testing.expect(typeContainsSlice([]const u8));
try testing.expect(!typeContainsSlice(u8));
@ -400,7 +400,7 @@ test "testHash union" {
test "testHash vector" {
// Disabled because of #3317
if (@import("builtin").arch == .mipsel or @import("builtin").arch == .mips) return error.SkipZigTest;
if (builtin.target.cpu.arch == .mipsel or builtin.target.cpu.arch == .mips) return error.SkipZigTest;
const a: meta.Vector(4, u32) = [_]u32{ 1, 2, 3, 4 };
const b: meta.Vector(4, u32) = [_]u32{ 1, 2, 3, 5 };

View File

@ -5,7 +5,7 @@
// and substantial portions of the software.
// zig run benchmark.zig --release-fast --override-lib-dir ..
const builtin = @import("builtin");
const builtin = std.builtin;
const std = @import("std");
const time = std.time;
const Timer = time.Timer;

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std");
const builtin = @import("builtin");
const builtin = std.builtin;
fn offsetPtr(ptr: [*]const u8, offset: usize) callconv(.Inline) [*]const u8 {
// ptr + offset doesn't work at comptime so we need this instead.

View File

@ -28,7 +28,7 @@ pub const Crc32 = Crc32WithPoly(.IEEE);
pub fn Crc32WithPoly(comptime poly: Polynomial) type {
return struct {
const Self = @This();
const lookup_tables = comptime block: {
const lookup_tables = block: {
@setEvalBranchQuota(20000);
var tables: [8][256]u32 = undefined;
@ -128,7 +128,7 @@ test "crc32 castagnoli" {
pub fn Crc32SmallWithPoly(comptime poly: Polynomial) type {
return struct {
const Self = @This();
const lookup_table = comptime block: {
const lookup_table = block: {
var table: [16]u32 = undefined;
for (table) |*e, i| {

View File

@ -6,6 +6,7 @@
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const native_endian = builtin.target.cpu.arch.endian();
const default_seed: u32 = 0xc70f6907;
@ -22,7 +23,7 @@ pub const Murmur2_32 = struct {
var h1: u32 = seed ^ len;
for (@ptrCast([*]align(1) const u32, str.ptr)[0..(len >> 2)]) |v| {
var k1: u32 = v;
if (builtin.endian == .Big)
if (native_endian == .Big)
k1 = @byteSwap(u32, k1);
k1 *%= m;
k1 ^= k1 >> 24;
@ -107,7 +108,7 @@ pub const Murmur2_64 = struct {
var h1: u64 = seed ^ (len *% m);
for (@ptrCast([*]align(1) const u64, str.ptr)[0..@intCast(usize, len >> 3)]) |v| {
var k1: u64 = v;
if (builtin.endian == .Big)
if (native_endian == .Big)
k1 = @byteSwap(u64, k1);
k1 *%= m;
k1 ^= k1 >> 47;
@ -120,7 +121,7 @@ pub const Murmur2_64 = struct {
if (rest > 0) {
var k1: u64 = 0;
@memcpy(@ptrCast([*]u8, &k1), @ptrCast([*]const u8, &str[@intCast(usize, offset)]), @intCast(usize, rest));
if (builtin.endian == .Big)
if (native_endian == .Big)
k1 = @byteSwap(u64, k1);
h1 ^= k1;
h1 *%= m;
@ -187,7 +188,7 @@ pub const Murmur3_32 = struct {
var h1: u32 = seed;
for (@ptrCast([*]align(1) const u32, str.ptr)[0..(len >> 2)]) |v| {
var k1: u32 = v;
if (builtin.endian == .Big)
if (native_endian == .Big)
k1 = @byteSwap(u32, k1);
k1 *%= c1;
k1 = rotl32(k1, 15);
@ -299,7 +300,7 @@ fn SMHasherTest(comptime hash_fn: anytype, comptime hashbits: u32) u32 {
key[i] = @truncate(u8, i);
var h = hash_fn(key[0..i], 256 - i);
if (builtin.endian == .Big)
if (native_endian == .Big)
h = @byteSwap(@TypeOf(h), h);
@memcpy(@ptrCast([*]u8, &hashes[i * hashbytes]), @ptrCast([*]u8, &h), hashbytes);
}
@ -313,7 +314,7 @@ test "murmur2_32" {
var v1: u64 = 0x1234567812345678;
var v0le: u32 = v0;
var v1le: u64 = v1;
if (builtin.endian == .Big) {
if (native_endian == .Big) {
v0le = @byteSwap(u32, v0le);
v1le = @byteSwap(u64, v1le);
}
@ -327,7 +328,7 @@ test "murmur2_64" {
var v1: u64 = 0x1234567812345678;
var v0le: u32 = v0;
var v1le: u64 = v1;
if (builtin.endian == .Big) {
if (native_endian == .Big) {
v0le = @byteSwap(u32, v0le);
v1le = @byteSwap(u64, v1le);
}
@ -341,7 +342,7 @@ test "murmur3_32" {
var v1: u64 = 0x1234567812345678;
var v0le: u32 = v0;
var v1le: u64 = v1;
if (builtin.endian == .Big) {
if (native_endian == .Big) {
v0le = @byteSwap(u32, v0le);
v1le = @byteSwap(u64, v1le);
}

View File

@ -4,7 +4,6 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std.zig");
const builtin = @import("builtin");
const assert = debug.assert;
const autoHash = std.hash.autoHash;
const debug = std.debug;

View File

@ -10,7 +10,7 @@ const assert = debug.assert;
const testing = std.testing;
const mem = std.mem;
const os = std.os;
const builtin = @import("builtin");
const builtin = std.builtin;
const c = std.c;
const maxInt = std.math.maxInt;
@ -28,17 +28,17 @@ const CAllocator = struct {
}
}
usingnamespace if (comptime @hasDecl(c, "malloc_size"))
usingnamespace if (@hasDecl(c, "malloc_size"))
struct {
pub const supports_malloc_size = true;
pub const malloc_size = c.malloc_size;
}
else if (comptime @hasDecl(c, "malloc_usable_size"))
else if (@hasDecl(c, "malloc_usable_size"))
struct {
pub const supports_malloc_size = true;
pub const malloc_size = c.malloc_usable_size;
}
else if (comptime @hasDecl(c, "_msize"))
else if (@hasDecl(c, "_msize"))
struct {
pub const supports_malloc_size = true;
pub const malloc_size = c._msize;

View File

@ -317,7 +317,10 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
if (is_used) {
const slot_index = @intCast(SlotIndex, used_bits_byte * 8 + bit_index);
const stack_trace = bucketStackTrace(bucket, size_class, slot_index, .alloc);
log.err("Memory leak detected: {s}", .{stack_trace});
const addr = bucket.page + slot_index * size_class;
log.err("memory address 0x{x} leaked: {s}", .{
@ptrToInt(addr), stack_trace,
});
leaks = true;
}
if (bit_index == math.maxInt(u3))
@ -345,7 +348,9 @@ pub fn GeneralPurposeAllocator(comptime config: Config) type {
}
var it = self.large_allocations.iterator();
while (it.next()) |large_alloc| {
log.err("Memory leak detected: {s}", .{large_alloc.value.getStackTrace()});
log.err("memory address 0x{x} leaked: {s}", .{
@ptrToInt(large_alloc.value.bytes.ptr), large_alloc.value.getStackTrace(),
});
leaks = true;
}
return leaks;

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const root = @import("root");
const c = std.c;

View File

@ -23,9 +23,9 @@ pub fn BitReader(endian: builtin.Endian, comptime ReaderType: type) type {
pub const Reader = io.Reader(*Self, Error, read);
const Self = @This();
const u8_bit_count = comptime meta.bitCount(u8);
const u7_bit_count = comptime meta.bitCount(u7);
const u4_bit_count = comptime meta.bitCount(u4);
const u8_bit_count = meta.bitCount(u8);
const u7_bit_count = meta.bitCount(u7);
const u4_bit_count = meta.bitCount(u4);
pub fn init(forward_reader: ReaderType) Self {
return Self{

View File

@ -23,8 +23,8 @@ pub fn BitWriter(endian: builtin.Endian, comptime WriterType: type) type {
pub const Writer = io.Writer(*Self, Error, write);
const Self = @This();
const u8_bit_count = comptime meta.bitCount(u8);
const u4_bit_count = comptime meta.bitCount(u4);
const u8_bit_count = meta.bitCount(u8);
const u4_bit_count = meta.bitCount(u4);
pub fn init(forward_writer: WriterType) Self {
return Self{

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std");
const builtin = std.builtin;
const builtin = @import("builtin");
const io = std.io;
const meta = std.meta;
const trait = std.trait;
@ -15,6 +15,7 @@ const expectError = std.testing.expectError;
const mem = std.mem;
const fs = std.fs;
const File = std.fs.File;
const native_endian = builtin.target.cpu.arch.endian();
const tmpDir = std.testing.tmpDir;
@ -72,7 +73,7 @@ test "BitStreams with File Stream" {
var file = try tmp.dir.createFile(tmp_file_name, .{});
defer file.close();
var bit_stream = io.bitWriter(builtin.endian, file.writer());
var bit_stream = io.bitWriter(native_endian, file.writer());
try bit_stream.writeBits(@as(u2, 1), 1);
try bit_stream.writeBits(@as(u5, 2), 2);
@ -86,7 +87,7 @@ test "BitStreams with File Stream" {
var file = try tmp.dir.openFile(tmp_file_name, .{});
defer file.close();
var bit_stream = io.bitReader(builtin.endian, file.reader());
var bit_stream = io.bitReader(native_endian, file.reader());
var out_bits: usize = undefined;

View File

@ -195,7 +195,7 @@ pub const StreamingParser = struct {
p.number_is_integer = undefined;
}
pub const State = enum {
pub const State = enum(u8) {
// These must be first with these explicit values as we rely on them for indexing the
// bit-stack directly and avoiding a branch.
ObjectSeparator = 0,
@ -1781,7 +1781,7 @@ test "parse" {
}
test "parse into enum" {
const T = extern enum {
const T = enum(u32) {
Foo = 42,
Bar,
@"with\\escape",

View File

@ -1365,7 +1365,7 @@ pub const BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: u8 = 0xa0;
pub const BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: u8 = 0xb0;
pub const BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: u8 = 0xc0;
pub const reloc_type_x86_64 = packed enum(u4) {
pub const reloc_type_x86_64 = enum(u4) {
/// for absolute addresses
X86_64_RELOC_UNSIGNED = 0,
@ -1397,9 +1397,9 @@ pub const reloc_type_x86_64 = packed enum(u4) {
X86_64_RELOC_TLV,
};
pub const reloc_type_arm64 = packed enum(u4) {
pub const reloc_type_arm64 = enum(u4) {
/// For pointers.
ARM64_RELOC_UNSIGNED = 0,
ARM64_RELOC_UNSIGNED,
/// Must be followed by a ARM64_RELOC_UNSIGNED.
ARM64_RELOC_SUBTRACTOR,

View File

@ -986,9 +986,9 @@ pub fn ceilPowerOfTwoPromote(comptime T: type, value: T) std.meta.Int(@typeInfo(
comptime assert(@typeInfo(T) == .Int);
comptime assert(@typeInfo(T).Int.signedness == .unsigned);
assert(value != 0);
comptime const PromotedType = std.meta.Int(@typeInfo(T).Int.signedness, @typeInfo(T).Int.bits + 1);
comptime const shiftType = std.math.Log2Int(PromotedType);
return @as(PromotedType, 1) << @intCast(shiftType, @typeInfo(T).Int.bits - @clz(T, value - 1));
const PromotedType = std.meta.Int(@typeInfo(T).Int.signedness, @typeInfo(T).Int.bits + 1);
const ShiftType = std.math.Log2Int(PromotedType);
return @as(PromotedType, 1) << @intCast(ShiftType, @typeInfo(T).Int.bits - @clz(T, value - 1));
}
/// Returns the next power of two (if the value is not already a power of two).
@ -998,8 +998,8 @@ pub fn ceilPowerOfTwo(comptime T: type, value: T) (error{Overflow}!T) {
comptime assert(@typeInfo(T) == .Int);
const info = @typeInfo(T).Int;
comptime assert(info.signedness == .unsigned);
comptime const PromotedType = std.meta.Int(info.signedness, info.bits + 1);
comptime const overflowBit = @as(PromotedType, 1) << info.bits;
const PromotedType = std.meta.Int(info.signedness, info.bits + 1);
const overflowBit = @as(PromotedType, 1) << info.bits;
var x = ceilPowerOfTwoPromote(T, value);
if (overflowBit & x != 0) {
return error.Overflow;
@ -1327,7 +1327,7 @@ test "order.compare" {
}
test "math.comptime" {
comptime const v = sin(@as(f32, 1)) + ln(@as(f32, 5));
const v = comptime (sin(@as(f32, 1)) + ln(@as(f32, 5)));
try testing.expect(v == sin(@as(f32, 1)) + ln(@as(f32, 5)));
}

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/math/acoshf.c
// https://git.musl-libc.org/cgit/musl/tree/src/math/acosh.c
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
// https://git.musl-libc.org/cgit/musl/tree/src/math/ceil.c
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;

View File

@ -10,7 +10,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/complex/catan.c
const std = @import("../../std.zig");
const builtin = @import("builtin");
const testing = std.testing;
const math = std.math;
const cmath = math.complex;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/complex/ccoshf.c
// https://git.musl-libc.org/cgit/musl/tree/src/complex/ccosh.c
const builtin = @import("builtin");
const std = @import("../../std.zig");
const testing = std.testing;
const math = std.math;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/complex/cexpf.c
// https://git.musl-libc.org/cgit/musl/tree/src/complex/cexp.c
const builtin = @import("builtin");
const std = @import("../../std.zig");
const testing = std.testing;
const math = std.math;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/complex/csinhf.c
// https://git.musl-libc.org/cgit/musl/tree/src/complex/csinh.c
const builtin = @import("builtin");
const std = @import("../../std.zig");
const testing = std.testing;
const math = std.math;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/complex/ctanhf.c
// https://git.musl-libc.org/cgit/musl/tree/src/complex/ctanh.c
const builtin = @import("builtin");
const std = @import("../../std.zig");
const testing = std.testing;
const math = std.math;

View File

@ -8,7 +8,6 @@
//
// https://golang.org/src/math/sin.go
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/math/coshf.c
// https://git.musl-libc.org/cgit/musl/tree/src/math/cosh.c
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expo2 = @import("expo2.zig").expo2;

View File

@ -11,7 +11,6 @@
// TODO: Updated recently.
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/math/floorf.c
// https://git.musl-libc.org/cgit/musl/tree/src/math/floor.c
const builtin = @import("builtin");
const expect = std.testing.expect;
const std = @import("../std.zig");
const math = std.math;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/math/log1pf.c
// https://git.musl-libc.org/cgit/musl/tree/src/math/log1p.c
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;

View File

@ -8,7 +8,6 @@
//
// https://golang.org/src/math/pow.go
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;

View File

@ -8,7 +8,6 @@
//
// https://github.com/rust-lang/rust/blob/360432f1e8794de58cd94f34c9c17ad65871e5b5/src/libcore/num/mod.rs#L3423
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const assert = std.debug.assert;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/math/roundf.c
// https://git.musl-libc.org/cgit/musl/tree/src/math/round.c
const builtin = @import("builtin");
const expect = std.testing.expect;
const std = @import("../std.zig");
const math = std.math;

View File

@ -8,7 +8,6 @@
//
// https://golang.org/src/math/sin.go
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/math/sinhf.c
// https://git.musl-libc.org/cgit/musl/tree/src/math/sinh.c
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;

View File

@ -6,8 +6,7 @@
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
const builtin = @import("builtin");
const TypeId = builtin.TypeId;
const TypeId = std.builtin.TypeId;
const maxInt = std.math.maxInt;
/// Returns the square root of x.

View File

@ -8,7 +8,6 @@
//
// https://golang.org/src/math/tan.go
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;

View File

@ -9,7 +9,6 @@
// https://git.musl-libc.org/cgit/musl/tree/src/math/tanhf.c
// https://git.musl-libc.org/cgit/musl/tree/src/math/tanh.c
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;

View File

@ -7,17 +7,18 @@ const std = @import("std.zig");
const debug = std.debug;
const assert = debug.assert;
const math = std.math;
const builtin = std.builtin;
const mem = @This();
const meta = std.meta;
const trait = meta.trait;
const testing = std.testing;
const Endian = std.builtin.Endian;
const native_endian = std.Target.current.cpu.arch.endian();
/// Compile time known minimum page size.
/// https://github.com/ziglang/zig/issues/4082
pub const page_size = switch (builtin.arch) {
pub const page_size = switch (std.Target.current.cpu.arch) {
.wasm32, .wasm64 => 64 * 1024,
.aarch64 => switch (builtin.os.tag) {
.aarch64 => switch (std.Target.current.os.tag) {
.macos, .ios, .watchos, .tvos => 16 * 1024,
else => 4 * 1024,
},
@ -355,7 +356,7 @@ test "mem.zeroes" {
/// If the field is present in the provided initial values, it will have that value instead.
/// Structs are initialized recursively.
pub fn zeroInit(comptime T: type, init: anytype) T {
comptime const Init = @TypeOf(init);
const Init = @TypeOf(init);
switch (@typeInfo(T)) {
.Struct => |struct_info| {
@ -1230,7 +1231,7 @@ test "mem.containsAtLeast" {
/// Reads an integer from memory with size equal to bytes.len.
/// T specifies the return type, which must be large enough to store
/// the result.
pub fn readVarInt(comptime ReturnType: type, bytes: []const u8, endian: builtin.Endian) ReturnType {
pub fn readVarInt(comptime ReturnType: type, bytes: []const u8, endian: Endian) ReturnType {
var result: ReturnType = 0;
switch (endian) {
.Big => {
@ -1265,12 +1266,12 @@ pub fn readIntForeign(comptime T: type, bytes: *const [@divExact(@typeInfo(T).In
return @byteSwap(T, readIntNative(T, bytes));
}
pub const readIntLittle = switch (builtin.endian) {
pub const readIntLittle = switch (native_endian) {
.Little => readIntNative,
.Big => readIntForeign,
};
pub const readIntBig = switch (builtin.endian) {
pub const readIntBig = switch (native_endian) {
.Little => readIntForeign,
.Big => readIntNative,
};
@ -1294,12 +1295,12 @@ pub fn readIntSliceForeign(comptime T: type, bytes: []const u8) T {
return @byteSwap(T, readIntSliceNative(T, bytes));
}
pub const readIntSliceLittle = switch (builtin.endian) {
pub const readIntSliceLittle = switch (native_endian) {
.Little => readIntSliceNative,
.Big => readIntSliceForeign,
};
pub const readIntSliceBig = switch (builtin.endian) {
pub const readIntSliceBig = switch (native_endian) {
.Little => readIntSliceForeign,
.Big => readIntSliceNative,
};
@ -1307,8 +1308,8 @@ pub const readIntSliceBig = switch (builtin.endian) {
/// Reads an integer from memory with bit count specified by T.
/// The bit count of T must be evenly divisible by 8.
/// This function cannot fail and cannot cause undefined behavior.
pub fn readInt(comptime T: type, bytes: *const [@divExact(@typeInfo(T).Int.bits, 8)]u8, endian: builtin.Endian) T {
if (endian == builtin.endian) {
pub fn readInt(comptime T: type, bytes: *const [@divExact(@typeInfo(T).Int.bits, 8)]u8, endian: Endian) T {
if (endian == native_endian) {
return readIntNative(T, bytes);
} else {
return readIntForeign(T, bytes);
@ -1318,7 +1319,7 @@ pub fn readInt(comptime T: type, bytes: *const [@divExact(@typeInfo(T).Int.bits,
/// Asserts that bytes.len >= @typeInfo(T).Int.bits / 8. Reads the integer starting from index 0
/// and ignores extra bytes.
/// The bit count of T must be evenly divisible by 8.
pub fn readIntSlice(comptime T: type, bytes: []const u8, endian: builtin.Endian) T {
pub fn readIntSlice(comptime T: type, bytes: []const u8, endian: Endian) T {
const n = @divExact(@typeInfo(T).Int.bits, 8);
assert(bytes.len >= n);
return readInt(T, bytes[0..n], endian);
@ -1376,12 +1377,12 @@ pub fn writeIntForeign(comptime T: type, buf: *[@divExact(@typeInfo(T).Int.bits,
writeIntNative(T, buf, @byteSwap(T, value));
}
pub const writeIntLittle = switch (builtin.endian) {
pub const writeIntLittle = switch (native_endian) {
.Little => writeIntNative,
.Big => writeIntForeign,
};
pub const writeIntBig = switch (builtin.endian) {
pub const writeIntBig = switch (native_endian) {
.Little => writeIntForeign,
.Big => writeIntNative,
};
@ -1389,8 +1390,8 @@ pub const writeIntBig = switch (builtin.endian) {
/// Writes an integer to memory, storing it in twos-complement.
/// This function always succeeds, has defined behavior for all inputs, but
/// the integer bit width must be divisible by 8.
pub fn writeInt(comptime T: type, buffer: *[@divExact(@typeInfo(T).Int.bits, 8)]u8, value: T, endian: builtin.Endian) void {
if (endian == builtin.endian) {
pub fn writeInt(comptime T: type, buffer: *[@divExact(@typeInfo(T).Int.bits, 8)]u8, value: T, endian: Endian) void {
if (endian == native_endian) {
return writeIntNative(T, buffer, value);
} else {
return writeIntForeign(T, buffer, value);
@ -1440,12 +1441,12 @@ pub fn writeIntSliceBig(comptime T: type, buffer: []u8, value: T) void {
}
}
pub const writeIntSliceNative = switch (builtin.endian) {
pub const writeIntSliceNative = switch (native_endian) {
.Little => writeIntSliceLittle,
.Big => writeIntSliceBig,
};
pub const writeIntSliceForeign = switch (builtin.endian) {
pub const writeIntSliceForeign = switch (native_endian) {
.Little => writeIntSliceBig,
.Big => writeIntSliceLittle,
};
@ -1456,7 +1457,7 @@ pub const writeIntSliceForeign = switch (builtin.endian) {
/// Any extra bytes in buffer not part of the integer are set to zero, with
/// respect to endianness. To avoid the branch to check for extra buffer bytes,
/// use writeInt instead.
pub fn writeIntSlice(comptime T: type, buffer: []u8, value: T, endian: builtin.Endian) void {
pub fn writeIntSlice(comptime T: type, buffer: []u8, value: T, endian: Endian) void {
comptime assert(@typeInfo(T).Int.bits % 8 == 0);
return switch (endian) {
.Little => writeIntSliceLittle(T, buffer, value),
@ -1866,10 +1867,10 @@ fn testReadIntImpl() !void {
0x56,
0x78,
};
try testing.expect(readInt(u32, &bytes, builtin.Endian.Big) == 0x12345678);
try testing.expect(readInt(u32, &bytes, Endian.Big) == 0x12345678);
try testing.expect(readIntBig(u32, &bytes) == 0x12345678);
try testing.expect(readIntBig(i32, &bytes) == 0x12345678);
try testing.expect(readInt(u32, &bytes, builtin.Endian.Little) == 0x78563412);
try testing.expect(readInt(u32, &bytes, Endian.Little) == 0x78563412);
try testing.expect(readIntLittle(u32, &bytes) == 0x78563412);
try testing.expect(readIntLittle(i32, &bytes) == 0x78563412);
}
@ -1880,7 +1881,7 @@ fn testReadIntImpl() !void {
0x12,
0x34,
};
const answer = readInt(u32, &buf, builtin.Endian.Big);
const answer = readInt(u32, &buf, Endian.Big);
try testing.expect(answer == 0x00001234);
}
{
@ -1890,7 +1891,7 @@ fn testReadIntImpl() !void {
0x00,
0x00,
};
const answer = readInt(u32, &buf, builtin.Endian.Little);
const answer = readInt(u32, &buf, Endian.Little);
try testing.expect(answer == 0x00003412);
}
{
@ -1912,19 +1913,19 @@ test "writeIntSlice" {
fn testWriteIntImpl() !void {
var bytes: [8]u8 = undefined;
writeIntSlice(u0, bytes[0..], 0, builtin.Endian.Big);
writeIntSlice(u0, bytes[0..], 0, Endian.Big);
try testing.expect(eql(u8, &bytes, &[_]u8{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
}));
writeIntSlice(u0, bytes[0..], 0, builtin.Endian.Little);
writeIntSlice(u0, bytes[0..], 0, Endian.Little);
try testing.expect(eql(u8, &bytes, &[_]u8{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
}));
writeIntSlice(u64, bytes[0..], 0x12345678CAFEBABE, builtin.Endian.Big);
writeIntSlice(u64, bytes[0..], 0x12345678CAFEBABE, Endian.Big);
try testing.expect(eql(u8, &bytes, &[_]u8{
0x12,
0x34,
@ -1936,7 +1937,7 @@ fn testWriteIntImpl() !void {
0xBE,
}));
writeIntSlice(u64, bytes[0..], 0xBEBAFECA78563412, builtin.Endian.Little);
writeIntSlice(u64, bytes[0..], 0xBEBAFECA78563412, Endian.Little);
try testing.expect(eql(u8, &bytes, &[_]u8{
0x12,
0x34,
@ -1948,7 +1949,7 @@ fn testWriteIntImpl() !void {
0xBE,
}));
writeIntSlice(u32, bytes[0..], 0x12345678, builtin.Endian.Big);
writeIntSlice(u32, bytes[0..], 0x12345678, Endian.Big);
try testing.expect(eql(u8, &bytes, &[_]u8{
0x00,
0x00,
@ -1960,7 +1961,7 @@ fn testWriteIntImpl() !void {
0x78,
}));
writeIntSlice(u32, bytes[0..], 0x78563412, builtin.Endian.Little);
writeIntSlice(u32, bytes[0..], 0x78563412, Endian.Little);
try testing.expect(eql(u8, &bytes, &[_]u8{
0x12,
0x34,
@ -1972,7 +1973,7 @@ fn testWriteIntImpl() !void {
0x00,
}));
writeIntSlice(u16, bytes[0..], 0x1234, builtin.Endian.Big);
writeIntSlice(u16, bytes[0..], 0x1234, Endian.Big);
try testing.expect(eql(u8, &bytes, &[_]u8{
0x00,
0x00,
@ -1984,7 +1985,7 @@ fn testWriteIntImpl() !void {
0x34,
}));
writeIntSlice(u16, bytes[0..], 0x1234, builtin.Endian.Little);
writeIntSlice(u16, bytes[0..], 0x1234, Endian.Little);
try testing.expect(eql(u8, &bytes, &[_]u8{
0x34,
0x12,
@ -2173,7 +2174,7 @@ test "replaceOwned" {
/// Converts a little-endian integer to host endianness.
pub fn littleToNative(comptime T: type, x: T) T {
return switch (builtin.endian) {
return switch (native_endian) {
.Little => x,
.Big => @byteSwap(T, x),
};
@ -2181,14 +2182,14 @@ pub fn littleToNative(comptime T: type, x: T) T {
/// Converts a big-endian integer to host endianness.
pub fn bigToNative(comptime T: type, x: T) T {
return switch (builtin.endian) {
return switch (native_endian) {
.Little => @byteSwap(T, x),
.Big => x,
};
}
/// Converts an integer from specified endianness to host endianness.
pub fn toNative(comptime T: type, x: T, endianness_of_x: builtin.Endian) T {
pub fn toNative(comptime T: type, x: T, endianness_of_x: Endian) T {
return switch (endianness_of_x) {
.Little => littleToNative(T, x),
.Big => bigToNative(T, x),
@ -2196,7 +2197,7 @@ pub fn toNative(comptime T: type, x: T, endianness_of_x: builtin.Endian) T {
}
/// Converts an integer which has host endianness to the desired endianness.
pub fn nativeTo(comptime T: type, x: T, desired_endianness: builtin.Endian) T {
pub fn nativeTo(comptime T: type, x: T, desired_endianness: Endian) T {
return switch (desired_endianness) {
.Little => nativeToLittle(T, x),
.Big => nativeToBig(T, x),
@ -2205,7 +2206,7 @@ pub fn nativeTo(comptime T: type, x: T, desired_endianness: builtin.Endian) T {
/// Converts an integer which has host endianness to little endian.
pub fn nativeToLittle(comptime T: type, x: T) T {
return switch (builtin.endian) {
return switch (native_endian) {
.Little => x,
.Big => @byteSwap(T, x),
};
@ -2213,13 +2214,13 @@ pub fn nativeToLittle(comptime T: type, x: T) T {
/// Converts an integer which has host endianness to big endian.
pub fn nativeToBig(comptime T: type, x: T) T {
return switch (builtin.endian) {
return switch (native_endian) {
.Little => @byteSwap(T, x),
.Big => x,
};
}
fn CopyPtrAttrs(comptime source: type, comptime size: builtin.TypeInfo.Pointer.Size, comptime child: type) type {
fn CopyPtrAttrs(comptime source: type, comptime size: std.builtin.TypeInfo.Pointer.Size, comptime child: type) type {
const info = @typeInfo(source).Pointer;
return @Type(.{
.Pointer = .{
@ -2251,7 +2252,7 @@ pub fn asBytes(ptr: anytype) AsBytesReturnType(@TypeOf(ptr)) {
test "asBytes" {
const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (builtin.endian) {
const deadbeef_bytes = switch (native_endian) {
.Big => "\xDE\xAD\xBE\xEF",
.Little => "\xEF\xBE\xAD\xDE",
};
@ -2304,13 +2305,13 @@ pub fn toBytes(value: anytype) [@sizeOf(@TypeOf(value))]u8 {
test "toBytes" {
var my_bytes = toBytes(@as(u32, 0x12345678));
switch (builtin.endian) {
switch (native_endian) {
.Big => try testing.expect(eql(u8, &my_bytes, "\x12\x34\x56\x78")),
.Little => try testing.expect(eql(u8, &my_bytes, "\x78\x56\x34\x12")),
}
my_bytes[0] = '\x99';
switch (builtin.endian) {
switch (native_endian) {
.Big => try testing.expect(eql(u8, &my_bytes, "\x99\x34\x56\x78")),
.Little => try testing.expect(eql(u8, &my_bytes, "\x99\x56\x34\x12")),
}
@ -2337,14 +2338,14 @@ pub fn bytesAsValue(comptime T: type, bytes: anytype) BytesAsValueReturnType(T,
test "bytesAsValue" {
const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (builtin.endian) {
const deadbeef_bytes = switch (native_endian) {
.Big => "\xDE\xAD\xBE\xEF",
.Little => "\xEF\xBE\xAD\xDE",
};
try testing.expect(deadbeef == bytesAsValue(u32, deadbeef_bytes).*);
var codeface_bytes: [4]u8 = switch (builtin.endian) {
var codeface_bytes: [4]u8 = switch (native_endian) {
.Big => "\xC0\xDE\xFA\xCE",
.Little => "\xCE\xFA\xDE\xC0",
}.*;
@ -2392,7 +2393,7 @@ pub fn bytesToValue(comptime T: type, bytes: anytype) T {
return bytesAsValue(T, bytes).*;
}
test "bytesToValue" {
const deadbeef_bytes = switch (builtin.endian) {
const deadbeef_bytes = switch (native_endian) {
.Big => "\xDE\xAD\xBE\xEF",
.Little => "\xEF\xBE\xAD\xDE",
};
@ -2521,7 +2522,7 @@ test "sliceAsBytes" {
const bytes = [_]u16{ 0xDEAD, 0xBEEF };
const slice = sliceAsBytes(bytes[0..]);
try testing.expect(slice.len == 4);
try testing.expect(eql(u8, slice, switch (builtin.endian) {
try testing.expect(eql(u8, slice, switch (native_endian) {
.Big => "\xDE\xAD\xBE\xEF",
.Little => "\xAD\xDE\xEF\xBE",
}));
@ -2543,7 +2544,7 @@ test "sliceAsBytes packed struct at runtime and comptime" {
var foo: Foo = undefined;
var slice = sliceAsBytes(@as(*[1]Foo, &foo)[0..1]);
slice[0] = 0x13;
switch (builtin.endian) {
switch (native_endian) {
.Big => {
try testing.expect(foo.a == 0x1);
try testing.expect(foo.b == 0x3);

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const debug = std.debug;
const mem = std.mem;
const math = std.math;
@ -342,12 +342,6 @@ test "std.meta.containerLayout" {
const E1 = enum {
A,
};
const E2 = packed enum {
A,
};
const E3 = extern enum {
A,
};
const S1 = struct {};
const S2 = packed struct {};
const S3 = extern struct {};
@ -362,8 +356,6 @@ test "std.meta.containerLayout" {
};
try testing.expect(containerLayout(E1) == .Auto);
try testing.expect(containerLayout(E2) == .Packed);
try testing.expect(containerLayout(E3) == .Extern);
try testing.expect(containerLayout(S1) == .Auto);
try testing.expect(containerLayout(S2) == .Packed);
try testing.expect(containerLayout(S3) == .Extern);
@ -1024,7 +1016,7 @@ test "std.meta.cast" {
try testing.expectEqual(@intToPtr(?*c_void, 2), cast(?*c_void, @intToPtr(*u8, 2)));
const C_ENUM = extern enum(c_int) {
const C_ENUM = enum(c_int) {
A = 0,
B,
C,
@ -1107,7 +1099,7 @@ pub fn sizeof(target: anytype) usize {
}
test "sizeof" {
const E = extern enum(c_int) { One, _ };
const E = enum(c_int) { One, _ };
const S = extern struct { a: u32 };
const ptr_size = @sizeOf(*c_void);

View File

@ -483,8 +483,8 @@ pub fn hasDecls(comptime T: type, comptime names: anytype) bool {
test "std.meta.trait.hasDecls" {
const TestStruct1 = struct {};
const TestStruct2 = struct {
pub var a: u32;
pub var b: u32;
pub var a: u32 = undefined;
pub var b: u32 = undefined;
c: bool,
pub fn useless() void {}
};

View File

@ -147,7 +147,7 @@ pub fn MultiArrayList(comptime S: type) type {
/// Extend the list by 1 element. Allocates more memory as necessary.
pub fn append(self: *Self, gpa: *Allocator, elem: S) !void {
try self.ensureCapacity(gpa, self.len + 1);
try self.ensureUnusedCapacity(gpa, 1);
self.appendAssumeCapacity(elem);
}
@ -162,7 +162,7 @@ pub fn MultiArrayList(comptime S: type) type {
/// Adjust the list's length to `new_len`.
/// Does not initialize added items, if any.
pub fn resize(self: *Self, gpa: *Allocator, new_len: usize) !void {
try self.ensureCapacity(gpa, new_len);
try self.ensureTotalCapacity(gpa, new_len);
self.len = new_len;
}
@ -224,10 +224,13 @@ pub fn MultiArrayList(comptime S: type) type {
self.len = new_len;
}
/// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`.
pub const ensureCapacity = ensureTotalCapacity;
/// Modify the array so that it can hold at least `new_capacity` items.
/// Implements super-linear growth to achieve amortized O(1) append operations.
/// Invalidates pointers if additional memory is needed.
pub fn ensureCapacity(self: *Self, gpa: *Allocator, new_capacity: usize) !void {
pub fn ensureTotalCapacity(self: *Self, gpa: *Allocator, new_capacity: usize) !void {
var better_capacity = self.capacity;
if (better_capacity >= new_capacity) return;
@ -239,6 +242,12 @@ pub fn MultiArrayList(comptime S: type) type {
return self.setCapacity(gpa, better_capacity);
}
/// Modify the array so that it can hold at least `additional_count` **more** items.
/// Invalidates pointers if additional memory is needed.
pub fn ensureUnusedCapacity(self: *Self, gpa: *Allocator, additional_count: usize) !void {
return self.ensureTotalCapacity(gpa, self.len + additional_count);
}
/// Modify the array so that it can hold exactly `new_capacity` items.
/// Invalidates pointers if additional memory is needed.
/// `new_capacity` must be greater or equal to `len`.
@ -305,7 +314,7 @@ test "basic usage" {
try testing.expectEqual(@as(usize, 0), list.items(.a).len);
try list.ensureCapacity(ally, 2);
try list.ensureTotalCapacity(ally, 2);
list.appendAssumeCapacity(.{
.a = 1,
@ -382,7 +391,7 @@ test "regression test for @reduce bug" {
}){};
defer list.deinit(ally);
try list.ensureCapacity(ally, 20);
try list.ensureTotalCapacity(ally, 20);
try list.append(ally, .{ .tag = .keyword_const, .start = 0 });
try list.append(ally, .{ .tag = .identifier, .start = 6 });
@ -462,7 +471,7 @@ test "ensure capacity on empty list" {
var list = MultiArrayList(Foo){};
defer list.deinit(ally);
try list.ensureCapacity(ally, 2);
try list.ensureTotalCapacity(ally, 2);
list.appendAssumeCapacity(.{ .a = 1, .b = 2 });
list.appendAssumeCapacity(.{ .a = 3, .b = 4 });
@ -477,7 +486,7 @@ test "ensure capacity on empty list" {
try testing.expectEqualSlices(u8, &[_]u8{ 6, 8 }, list.items(.b));
list.len = 0;
try list.ensureCapacity(ally, 16);
try list.ensureTotalCapacity(ally, 16);
list.appendAssumeCapacity(.{ .a = 9, .b = 10 });
list.appendAssumeCapacity(.{ .a = 11, .b = 12 });

View File

@ -11,11 +11,12 @@ const mem = std.mem;
const os = std.os;
const fs = std.fs;
const io = std.io;
const native_endian = builtin.target.cpu.arch.endian();
// Windows 10 added support for unix sockets in build 17063, redstone 4 is the
// first release to support them.
pub const has_unix_sockets = @hasDecl(os, "sockaddr_un") and
(builtin.os.tag != .windows or
(builtin.target.os.tag != .windows or
std.Target.current.os.version_range.windows.isAtLeast(.win10_rs4) orelse false);
pub const Address = extern union {
@ -567,7 +568,7 @@ pub const Ip6Address = extern struct {
return;
}
const big_endian_parts = @ptrCast(*align(1) const [8]u16, &self.sa.addr);
const native_endian_parts = switch (builtin.endian) {
const native_endian_parts = switch (native_endian) {
.Big => big_endian_parts.*,
.Little => blk: {
var buf: [8]u16 = undefined;
@ -673,7 +674,7 @@ pub fn tcpConnectToHost(allocator: *mem.Allocator, name: []const u8, port: u16)
pub fn tcpConnectToAddress(address: Address) !Stream {
const nonblock = if (std.io.is_async) os.SOCK_NONBLOCK else 0;
const sock_flags = os.SOCK_STREAM | nonblock |
(if (builtin.os.tag == .windows) 0 else os.SOCK_CLOEXEC);
(if (builtin.target.os.tag == .windows) 0 else os.SOCK_CLOEXEC);
const sockfd = try os.socket(address.any.family, sock_flags, os.IPPROTO_TCP);
errdefer os.closeSocket(sockfd);
@ -704,14 +705,14 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
const arena = &result.arena.allocator;
errdefer result.arena.deinit();
if (builtin.os.tag == .windows or builtin.link_libc) {
if (builtin.target.os.tag == .windows or builtin.link_libc) {
const name_c = try std.cstr.addNullByte(allocator, name);
defer allocator.free(name_c);
const port_c = try std.fmt.allocPrint(allocator, "{}\x00", .{port});
defer allocator.free(port_c);
const sys = if (builtin.os.tag == .windows) os.windows.ws2_32 else os.system;
const sys = if (builtin.target.os.tag == .windows) os.windows.ws2_32 else os.system;
const hints = os.addrinfo{
.flags = sys.AI_NUMERICSERV,
.family = os.AF_UNSPEC,
@ -724,7 +725,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
};
var res: *os.addrinfo = undefined;
const rc = sys.getaddrinfo(name_c.ptr, std.meta.assumeSentinel(port_c.ptr, 0), &hints, &res);
if (builtin.os.tag == .windows) switch (@intToEnum(os.windows.ws2_32.WinsockError, @intCast(u16, rc))) {
if (builtin.target.os.tag == .windows) switch (@intToEnum(os.windows.ws2_32.WinsockError, @intCast(u16, rc))) {
@intToEnum(os.windows.ws2_32.WinsockError, 0) => {},
.WSATRY_AGAIN => return error.TemporaryNameServerFailure,
.WSANO_RECOVERY => return error.NameServerFailure,
@ -782,7 +783,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
return result;
}
if (builtin.os.tag == .linux) {
if (builtin.target.os.tag == .linux) {
const flags = std.c.AI_NUMERICSERV;
const family = os.AF_UNSPEC;
var lookup_addrs = std.ArrayList(LookupAddr).init(allocator);

View File

@ -21,7 +21,7 @@
const root = @import("root");
const std = @import("std.zig");
const builtin = @import("builtin");
const builtin = std.builtin;
const assert = std.debug.assert;
const math = std.math;
const mem = std.mem;

View File

@ -1535,19 +1535,19 @@ pub const rusage = extern struct {
nivcsw: isize,
};
pub const rlimit_resource = extern enum(c_int) {
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
AS = 5,
RSS = 5,
MEMLOCK = 6,
NPROC = 7,
NOFILE = 8,
_,
pub const AS: rlimit_resource = .RSS;
};
pub const rlim_t = u64;
@ -1683,7 +1683,7 @@ pub const TCSANOW = 0; // make change immediate
pub const TCSADRAIN = 1; // drain output, then change
pub const TCSAFLUSH = 2; // drain output, flush input
pub const TCSASOFT = 0x10; // flag - don't alter h.w. state
pub const TCSA = extern enum(c_uint) {
pub const TCSA = enum(c_uint) {
NOW,
DRAIN,
FLUSH,

View File

@ -735,7 +735,7 @@ pub const Flock = extern struct {
l_whence: c_short,
};
pub const rlimit_resource = extern enum(c_int) {
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
@ -746,11 +746,11 @@ pub const rlimit_resource = extern enum(c_int) {
NPROC = 7,
NOFILE = 8,
SBSIZE = 9,
AS = 10,
VMEM = 10,
POSIXLOCKS = 11,
_,
pub const AS: rlimit_resource = .VMEM;
};
pub const rlim_t = i64;

View File

@ -4,7 +4,7 @@
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../../std.zig");
const builtin = std.builtin;
const builtin = @import("builtin");
const maxInt = std.math.maxInt;
pub const blksize_t = i32;
@ -842,7 +842,7 @@ pub const sigset_t = extern struct {
pub const empty_sigset = sigset_t{ .__bits = [_]u32{0} ** _SIG_WORDS };
pub usingnamespace switch (builtin.arch) {
pub usingnamespace switch (builtin.target.cpu.arch) {
.x86_64 => struct {
pub const ucontext_t = extern struct {
sigmask: sigset_t,
@ -1011,7 +1011,7 @@ pub const EOWNERDEAD = 96; // Previous owner died
pub const ELAST = 96; // Must be equal largest errno
pub const MINSIGSTKSZ = switch (builtin.arch) {
pub const MINSIGSTKSZ = switch (builtin.target.cpu.arch) {
.i386, .x86_64 => 2048,
.arm, .aarch64 => 4096,
else => @compileError("MINSIGSTKSZ not defined for this architecture"),
@ -1467,7 +1467,7 @@ pub const IPPROTO_RESERVED_253 = 253;
/// Reserved
pub const IPPROTO_RESERVED_254 = 254;
pub const rlimit_resource = extern enum(c_int) {
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
@ -1479,13 +1479,13 @@ pub const rlimit_resource = extern enum(c_int) {
NOFILE = 8,
SBSIZE = 9,
VMEM = 10,
AS = 10,
NPTS = 11,
SWAP = 12,
KQUEUES = 13,
UMTXP = 14,
_,
pub const AS: rlimit_resource = .VMEM;
};
pub const rlim_t = i64;

View File

@ -1314,7 +1314,7 @@ pub const IPPROTO_RESERVED_253 = 253;
/// Reserved
pub const IPPROTO_RESERVED_254 = 254;
pub const rlimit_resource = extern enum(c_int) {
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
@ -1326,13 +1326,13 @@ pub const rlimit_resource = extern enum(c_int) {
NOFILE = 8,
SBSIZE = 9,
VMEM = 10,
AS = 10,
NPTS = 11,
SWAP = 12,
KQUEUES = 13,
UMTXP = 14,
_,
pub const AS: rlimit_resource = .VMEM;
};
pub const rlim_t = i64;
@ -1355,7 +1355,7 @@ pub const SHUT_WR = 1;
pub const SHUT_RDWR = 2;
// TODO fill out if needed
pub const directory_which = extern enum(c_int) {
pub const directory_which = enum(c_int) {
B_USER_SETTINGS_DIRECTORY = 0xbbe,
_,

View File

@ -3,18 +3,18 @@
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const builtin = @import("builtin");
const std = @import("../../std.zig");
const maxInt = std.math.maxInt;
const arch = @import("builtin").target.cpu.arch;
usingnamespace @import("../bits.zig");
pub usingnamespace switch (builtin.arch) {
pub usingnamespace switch (arch) {
.mips, .mipsel => @import("linux/errno-mips.zig"),
.sparc, .sparcel, .sparcv9 => @import("linux/errno-sparc.zig"),
else => @import("linux/errno-generic.zig"),
};
pub usingnamespace switch (builtin.arch) {
pub usingnamespace switch (arch) {
.i386 => @import("linux/i386.zig"),
.x86_64 => @import("linux/x86_64.zig"),
.aarch64 => @import("linux/arm64.zig"),
@ -31,10 +31,10 @@ pub usingnamespace @import("linux/netlink.zig");
pub usingnamespace @import("linux/prctl.zig");
pub usingnamespace @import("linux/securebits.zig");
const is_mips = builtin.arch.isMIPS();
const is_ppc = builtin.arch.isPPC();
const is_ppc64 = builtin.arch.isPPC64();
const is_sparc = builtin.arch.isSPARC();
const is_mips = arch.isMIPS();
const is_ppc = arch.isPPC();
const is_ppc64 = arch.isPPC64();
const is_sparc = arch.isSPARC();
pub const pid_t = i32;
pub const fd_t = i32;
@ -136,7 +136,7 @@ pub const PROT_WRITE = 0x2;
pub const PROT_EXEC = 0x4;
/// page may be used for atomic ops
pub const PROT_SEM = switch (builtin.arch) {
pub const PROT_SEM = switch (arch) {
// TODO: also xtensa
.mips, .mipsel, .mips64, .mips64el => 0x10,
else => 0x8,
@ -1074,7 +1074,7 @@ pub const sigset_t = [1024 / 32]u32;
pub const all_mask: sigset_t = [_]u32{0xffffffff} ** sigset_t.len;
pub const app_mask: sigset_t = [2]u32{ 0xfffffffc, 0x7fffffff } ++ [_]u32{0xffffffff} ** 30;
pub const k_sigaction = switch (builtin.arch) {
pub const k_sigaction = switch (arch) {
.mips, .mipsel => extern struct {
flags: c_uint,
handler: ?fn (c_int) callconv(.C) void,
@ -1198,7 +1198,7 @@ pub const epoll_data = extern union {
// On x86_64 the structure is packed so that it matches the definition of its
// 32bit counterpart
pub const epoll_event = switch (builtin.arch) {
pub const epoll_event = switch (arch) {
.x86_64 => packed struct {
events: u32,
data: epoll_data,
@ -1365,12 +1365,12 @@ pub fn CPU_COUNT(set: cpu_set_t) cpu_count_t {
//#define CPU_ZERO(set) CPU_ZERO_S(sizeof(cpu_set_t),set)
//#define CPU_EQUAL(s1,s2) CPU_EQUAL_S(sizeof(cpu_set_t),s1,s2)
pub const MINSIGSTKSZ = switch (builtin.arch) {
pub const MINSIGSTKSZ = switch (arch) {
.i386, .x86_64, .arm, .mipsel => 2048,
.aarch64 => 5120,
else => @compileError("MINSIGSTKSZ not defined for this architecture"),
};
pub const SIGSTKSZ = switch (builtin.arch) {
pub const SIGSTKSZ = switch (arch) {
.i386, .x86_64, .arm, .mipsel => 8192,
.aarch64 => 16384,
else => @compileError("SIGSTKSZ not defined for this architecture"),
@ -1564,7 +1564,7 @@ pub const io_uring_sqe = extern struct {
__pad2: [2]u64,
};
pub const IOSQE_BIT = extern enum(u8) {
pub const IOSQE_BIT = enum(u8) {
FIXED_FILE,
IO_DRAIN,
IO_LINK,
@ -1595,7 +1595,7 @@ pub const IOSQE_ASYNC = 1 << @enumToInt(IOSQE_BIT.ASYNC);
/// select buffer from buf_group
pub const IOSQE_BUFFER_SELECT = 1 << @enumToInt(IOSQE_BIT.BUFFER_SELECT);
pub const IORING_OP = extern enum(u8) {
pub const IORING_OP = enum(u8) {
NOP,
READV,
WRITEV,
@ -1664,7 +1664,7 @@ pub const IORING_ENTER_GETEVENTS = 1 << 0;
pub const IORING_ENTER_SQ_WAKEUP = 1 << 1;
// io_uring_register opcodes and arguments
pub const IORING_REGISTER = extern enum(u8) {
pub const IORING_REGISTER = enum(u8) {
REGISTER_BUFFERS,
UNREGISTER_BUFFERS,
REGISTER_FILES,
@ -1731,7 +1731,7 @@ pub const io_uring_restriction = extern struct {
};
/// io_uring_restriction->opcode values
pub const IORING_RESTRICTION = extern enum(u8) {
pub const IORING_RESTRICTION = enum(u8) {
/// Allow an io_uring_register(2) opcode
REGISTER_OP = 0,
@ -1986,7 +1986,7 @@ pub const tcp_repair_window = extern struct {
rcv_wup: u32,
};
pub const TcpRepairOption = extern enum {
pub const TcpRepairOption = enum {
TCP_NO_QUEUE,
TCP_RECV_QUEUE,
TCP_SEND_QUEUE,
@ -1994,7 +1994,7 @@ pub const TcpRepairOption = extern enum {
};
/// why fastopen failed from client perspective
pub const tcp_fastopen_client_fail = extern enum {
pub const tcp_fastopen_client_fail = enum {
/// catch-all
TFO_STATUS_UNSPEC,
/// if not in TFO_CLIENT_NO_COOKIE mode
@ -2130,7 +2130,7 @@ pub const B3000000 = 0o0010015;
pub const B3500000 = 0o0010016;
pub const B4000000 = 0o0010017;
pub usingnamespace switch (builtin.arch) {
pub usingnamespace switch (arch) {
.powerpc, .powerpc64, .powerpc64le => struct {
pub const VINTR = 0;
pub const VQUIT = 1;
@ -2261,7 +2261,7 @@ pub const NOFLSH = 128;
pub const TOSTOP = 256;
pub const IEXTEN = 32768;
pub const TCSA = extern enum(c_uint) {
pub const TCSA = enum(c_uint) {
NOW,
DRAIN,
FLUSH,
@ -2312,7 +2312,7 @@ pub const ifreq = extern struct {
};
// doc comments copied from musl
pub const rlimit_resource = extern enum(c_int) {
pub const rlimit_resource = enum(c_int) {
/// Per-process CPU limit, in seconds.
CPU,

View File

@ -15,7 +15,7 @@ const uid_t = linux.uid_t;
const gid_t = linux.gid_t;
const pid_t = linux.pid_t;
pub const SYS = extern enum(usize) {
pub const SYS = enum(usize) {
restart_syscall = 0,
exit = 1,
fork = 2,
@ -242,7 +242,6 @@ pub const SYS = extern enum(usize) {
tgkill = 268,
utimes = 269,
fadvise64_64 = 270,
arm_fadvise64_64 = 270,
pciconfig_iobase = 271,
pciconfig_read = 272,
pciconfig_write = 273,
@ -313,8 +312,7 @@ pub const SYS = extern enum(usize) {
set_robust_list = 338,
get_robust_list = 339,
splice = 340,
sync_file_range2 = 341,
arm_sync_file_range = 341,
sync_file_range = 341,
tee = 342,
vmsplice = 343,
move_pages = 344,

View File

@ -17,7 +17,7 @@ const gid_t = linux.gid_t;
const pid_t = linux.pid_t;
const stack_t = linux.stack_t;
const sigset_t = linux.sigset_t;
pub const SYS = extern enum(usize) {
pub const SYS = enum(usize) {
io_setup = 0,
io_destroy = 1,
io_submit = 2,
@ -102,7 +102,6 @@ pub const SYS = extern enum(usize) {
sync = 81,
fsync = 82,
fdatasync = 83,
sync_file_range2 = 84,
sync_file_range = 84,
timerfd_create = 85,
timerfd_settime = 86,

View File

@ -17,7 +17,7 @@ const pid_t = linux.pid_t;
const stack_t = linux.stack_t;
const sigset_t = linux.sigset_t;
pub const SYS = extern enum(usize) {
pub const SYS = enum(usize) {
restart_syscall = 0,
exit = 1,
fork = 2,

View File

@ -12,7 +12,7 @@ const uid_t = linux.uid_t;
const gid_t = linux.gid_t;
const pid_t = linux.pid_t;
pub const SYS = extern enum(usize) {
pub const SYS = enum(usize) {
pub const Linux = 4000;
syscall = Linux + 0,

View File

@ -126,7 +126,7 @@ pub const NLM_F_CAPPED = 0x100;
/// extended ACK TVLs were included
pub const NLM_F_ACK_TLVS = 0x200;
pub const NetlinkMessageType = extern enum(u16) {
pub const NetlinkMessageType = enum(u16) {
/// < 0x10: reserved control messages
pub const MIN_TYPE = 0x10;
@ -287,7 +287,7 @@ pub const rtattr = extern struct {
pub const ALIGNTO = 4;
};
pub const IFLA = extern enum(c_ushort) {
pub const IFLA = enum(c_ushort) {
UNSPEC,
ADDRESS,
BROADCAST,
@ -351,8 +351,7 @@ pub const IFLA = extern enum(c_ushort) {
EVENT,
NEW_NETNSID,
IF_NETNSID = 46,
TARGET_NETNSID = 46, // new alias
IF_NETNSID,
CARRIER_UP_COUNT,
CARRIER_DOWN_COUNT,
@ -361,6 +360,8 @@ pub const IFLA = extern enum(c_ushort) {
MAX_MTU,
_,
pub const TARGET_NETNSID: IFLA = .IF_NETNSID;
};
pub const rtnl_link_ifmap = extern struct {

View File

@ -14,7 +14,7 @@ const gid_t = linux.gid_t;
const pid_t = linux.pid_t;
const stack_t = linux.stack_t;
const sigset_t = linux.sigset_t;
pub const SYS = extern enum(usize) {
pub const SYS = enum(usize) {
restart_syscall = 0,
exit = 1,
fork = 2,
@ -321,7 +321,7 @@ pub const SYS = extern enum(usize) {
signalfd = 305,
timerfd_create = 306,
eventfd = 307,
sync_file_range2 = 308,
sync_file_range = 308,
fallocate = 309,
subpage_prot = 310,
timerfd_settime = 311,

View File

@ -14,7 +14,7 @@ const gid_t = linux.gid_t;
const pid_t = linux.pid_t;
const stack_t = linux.stack_t;
const sigset_t = linux.sigset_t;
pub const SYS = extern enum(usize) {
pub const SYS = enum(usize) {
restart_syscall = 0,
exit = 1,
fork = 2,
@ -295,7 +295,7 @@ pub const SYS = extern enum(usize) {
mknodat = 288,
fchownat = 289,
futimesat = 290,
newfstatat = 291,
fstatat = 291,
unlinkat = 292,
renameat = 293,
linkat = 294,
@ -312,7 +312,7 @@ pub const SYS = extern enum(usize) {
signalfd = 305,
timerfd_create = 306,
eventfd = 307,
sync_file_range2 = 308,
sync_file_range = 308,
fallocate = 309,
subpage_prot = 310,
timerfd_settime = 311,

Some files were not shown because too many files have changed in this diff Show More