aboutsummaryrefslogtreecommitdiff
path: root/lib/std
diff options
context:
space:
mode:
authorVexu <15308111+Vexu@users.noreply.github.com>2019-11-23 19:13:48 +0200
committerVexu <15308111+Vexu@users.noreply.github.com>2019-11-23 19:13:48 +0200
commit03cc81665bb28eb35c8c6d4be17b5a56fa66261f (patch)
treee686671775e606c3cf1129b535f2c2487e4e6e3c /lib/std
parent86d9563d1539cd7581dc120023bb830fae77ba0f (diff)
parentad0871ea4bf2dfbed07282ffe14738b5347d5d32 (diff)
downloadzig-03cc81665bb28eb35c8c6d4be17b5a56fa66261f.tar.gz
zig-03cc81665bb28eb35c8c6d4be17b5a56fa66261f.zip
Merge branch 'master' into modernize-stage2
Diffstat (limited to 'lib/std')
-rw-r--r--lib/std/array_list.zig16
-rw-r--r--lib/std/ascii.zig22
-rw-r--r--lib/std/atomic/queue.zig6
-rw-r--r--lib/std/atomic/stack.zig8
-rw-r--r--lib/std/bloom_filter.zig22
-rw-r--r--lib/std/build.zig83
-rw-r--r--lib/std/builtin.zig33
-rw-r--r--lib/std/c.zig24
-rw-r--r--lib/std/c/darwin.zig18
-rw-r--r--lib/std/c/dragonfly.zig13
-rw-r--r--lib/std/c/emscripten.zig8
-rw-r--r--lib/std/c/freebsd.zig12
-rw-r--r--lib/std/c/fuchsia.zig8
-rw-r--r--lib/std/c/haiku.zig14
-rw-r--r--lib/std/c/hermit.zig6
-rw-r--r--lib/std/c/linux.zig23
-rw-r--r--lib/std/c/minix.zig18
-rw-r--r--lib/std/c/netbsd.zig29
-rw-r--r--lib/std/c/openbsd.zig6
-rw-r--r--lib/std/c/solaris.zig15
-rw-r--r--lib/std/child_process.zig97
-rw-r--r--lib/std/coff.zig2
-rw-r--r--lib/std/crypto/aes.zig20
-rw-r--r--lib/std/crypto/benchmark.zig4
-rw-r--r--lib/std/crypto/blake2.zig16
-rw-r--r--lib/std/crypto/chacha20.zig8
-rw-r--r--lib/std/crypto/gimli.zig8
-rw-r--r--lib/std/crypto/md5.zig8
-rw-r--r--lib/std/crypto/poly1305.zig12
-rw-r--r--lib/std/crypto/sha1.zig30
-rw-r--r--lib/std/crypto/sha2.zig38
-rw-r--r--lib/std/crypto/sha3.zig2
-rw-r--r--lib/std/crypto/x25519.zig66
-rw-r--r--lib/std/debug.zig49
-rw-r--r--lib/std/debug/leb128.zig6
-rw-r--r--lib/std/dynamic_library.zig4
-rw-r--r--lib/std/elf.zig24
-rw-r--r--lib/std/event/channel.zig4
-rw-r--r--lib/std/event/fs.zig13
-rw-r--r--lib/std/event/future.zig25
-rw-r--r--lib/std/event/group.zig41
-rw-r--r--lib/std/event/lock.zig10
-rw-r--r--lib/std/event/loop.zig52
-rw-r--r--lib/std/event/rwlock.zig44
-rw-r--r--lib/std/fifo.zig26
-rw-r--r--lib/std/fmt.zig130
-rw-r--r--lib/std/fmt/errol.zig4
-rw-r--r--lib/std/fmt/parse_float.zig20
-rw-r--r--lib/std/fs.zig115
-rw-r--r--lib/std/fs/file.zig56
-rw-r--r--lib/std/fs/path.zig2
-rw-r--r--lib/std/hash/auto_hash.zig14
-rw-r--r--lib/std/hash/cityhash.zig8
-rw-r--r--lib/std/hash/crc.zig8
-rw-r--r--lib/std/hash/murmur.zig2
-rw-r--r--lib/std/hash/siphash.zig14
-rw-r--r--lib/std/hash_map.zig2
-rw-r--r--lib/std/heap.zig12
-rw-r--r--lib/std/http/headers.zig10
-rw-r--r--lib/std/io.zig74
-rw-r--r--lib/std/io/out_stream.zig4
-rw-r--r--lib/std/io/test.zig64
-rw-r--r--lib/std/json.zig130
-rw-r--r--lib/std/json/write_stream.zig6
-rw-r--r--lib/std/lazy_init.zig26
-rw-r--r--lib/std/math.zig163
-rw-r--r--lib/std/math/acos.zig4
-rw-r--r--lib/std/math/acosh.zig4
-rw-r--r--lib/std/math/asin.zig4
-rw-r--r--lib/std/math/asinh.zig4
-rw-r--r--lib/std/math/atan.zig4
-rw-r--r--lib/std/math/atanh.zig4
-rw-r--r--lib/std/math/big/int.zig22
-rw-r--r--lib/std/math/cbrt.zig10
-rw-r--r--lib/std/math/ceil.zig6
-rw-r--r--lib/std/math/complex.zig8
-rw-r--r--lib/std/math/complex/acos.zig2
-rw-r--r--lib/std/math/complex/ldexp.zig4
-rw-r--r--lib/std/math/complex/sqrt.zig4
-rw-r--r--lib/std/math/complex/tanh.zig2
-rw-r--r--lib/std/math/copysign.zig6
-rw-r--r--lib/std/math/cos.zig4
-rw-r--r--lib/std/math/cosh.zig4
-rw-r--r--lib/std/math/exp.zig6
-rw-r--r--lib/std/math/exp2.zig6
-rw-r--r--lib/std/math/expm1.zig4
-rw-r--r--lib/std/math/expo2.zig2
-rw-r--r--lib/std/math/fabs.zig8
-rw-r--r--lib/std/math/floor.zig10
-rw-r--r--lib/std/math/fma.zig2
-rw-r--r--lib/std/math/frexp.zig4
-rw-r--r--lib/std/math/hypot.zig2
-rw-r--r--lib/std/math/ilogb.zig6
-rw-r--r--lib/std/math/isfinite.zig12
-rw-r--r--lib/std/math/isinf.zig48
-rw-r--r--lib/std/math/isnan.zig8
-rw-r--r--lib/std/math/isnormal.zig12
-rw-r--r--lib/std/math/ln.zig10
-rw-r--r--lib/std/math/log.zig14
-rw-r--r--lib/std/math/log10.zig10
-rw-r--r--lib/std/math/log1p.zig6
-rw-r--r--lib/std/math/log2.zig8
-rw-r--r--lib/std/math/modf.zig8
-rw-r--r--lib/std/math/round.zig4
-rw-r--r--lib/std/math/scalbn.zig4
-rw-r--r--lib/std/math/signbit.zig6
-rw-r--r--lib/std/math/sin.zig6
-rw-r--r--lib/std/math/sinh.zig4
-rw-r--r--lib/std/math/sqrt.zig10
-rw-r--r--lib/std/math/tan.zig4
-rw-r--r--lib/std/math/tanh.zig4
-rw-r--r--lib/std/math/trunc.zig8
-rw-r--r--lib/std/mem.zig26
-rw-r--r--lib/std/meta.zig4
-rw-r--r--lib/std/meta/trait.zig4
-rw-r--r--lib/std/mutex.zig133
-rw-r--r--lib/std/net.zig186
-rw-r--r--lib/std/net/test.zig38
-rw-r--r--lib/std/os.zig33
-rw-r--r--lib/std/os/bits.zig3
-rw-r--r--lib/std/os/bits/darwin.zig6
-rw-r--r--lib/std/os/bits/dragonfly.zig14
-rw-r--r--lib/std/os/bits/freebsd.zig6
-rw-r--r--lib/std/os/bits/linux.zig15
-rw-r--r--lib/std/os/bits/netbsd.zig7
-rw-r--r--lib/std/os/bits/windows.zig19
-rw-r--r--lib/std/os/linux.zig194
-rw-r--r--lib/std/os/linux/arm-eabi.zig4
-rw-r--r--lib/std/os/linux/arm64.zig2
-rw-r--r--lib/std/os/linux/mipsel.zig6
-rw-r--r--lib/std/os/linux/riscv64.zig2
-rw-r--r--lib/std/os/linux/test.zig6
-rw-r--r--lib/std/os/linux/vdso.zig4
-rw-r--r--lib/std/os/linux/x86_64.zig2
-rw-r--r--lib/std/os/test.zig2
-rw-r--r--lib/std/os/uefi/protocols.zig44
-rw-r--r--lib/std/os/uefi/protocols/device_path_protocol.zig17
-rw-r--r--lib/std/os/uefi/protocols/ip6_config_protocol.zig45
-rw-r--r--lib/std/os/uefi/protocols/ip6_protocol.zig143
-rw-r--r--lib/std/os/uefi/protocols/ip6_service_binding_protocol.zig25
-rw-r--r--lib/std/os/uefi/protocols/loaded_image_protocol.zig36
-rw-r--r--lib/std/os/uefi/protocols/managed_network_protocol.zig126
-rw-r--r--lib/std/os/uefi/protocols/managed_network_service_binding_protocol.zig25
-rw-r--r--lib/std/os/uefi/protocols/simple_network_protocol.zig172
-rw-r--r--lib/std/os/uefi/protocols/udp6_protocol.zig112
-rw-r--r--lib/std/os/uefi/protocols/udp6_service_binding_protocol.zig25
-rw-r--r--lib/std/os/uefi/tables.zig3
-rw-r--r--lib/std/os/uefi/tables/boot_services.zig86
-rw-r--r--lib/std/os/uefi/tables/runtime_services.zig8
-rw-r--r--lib/std/os/uefi/tables/system_table.zig1
-rw-r--r--lib/std/os/windows.zig132
-rw-r--r--lib/std/os/windows/bits.zig131
-rw-r--r--lib/std/os/windows/kernel32.zig13
-rw-r--r--lib/std/os/windows/ntdll.zig30
-rw-r--r--lib/std/os/windows/status.zig1654
-rw-r--r--lib/std/os/windows/ws2_32.zig257
-rw-r--r--lib/std/os/zen.zig4
-rw-r--r--lib/std/packed_int_array.zig36
-rw-r--r--lib/std/parker.zig180
-rw-r--r--lib/std/pdb.zig2
-rw-r--r--lib/std/priority_queue.zig60
-rw-r--r--lib/std/progress.zig7
-rw-r--r--lib/std/rand.zig16
-rw-r--r--lib/std/rand/ziggurat.zig2
-rw-r--r--lib/std/segmented_list.zig10
-rw-r--r--lib/std/sort.zig8
-rw-r--r--lib/std/special/build_runner.zig35
-rw-r--r--lib/std/special/c.zig6
-rw-r--r--lib/std/special/compiler_rt.zig34
-rw-r--r--lib/std/special/compiler_rt/addXf3.zig26
-rw-r--r--lib/std/special/compiler_rt/addXf3_test.zig8
-rw-r--r--lib/std/special/compiler_rt/comparedf2.zig20
-rw-r--r--lib/std/special/compiler_rt/comparesf2.zig20
-rw-r--r--lib/std/special/compiler_rt/comparetf2.zig20
-rw-r--r--lib/std/special/compiler_rt/divdf3.zig66
-rw-r--r--lib/std/special/compiler_rt/divsf3.zig22
-rw-r--r--lib/std/special/compiler_rt/divti3_test.zig8
-rw-r--r--lib/std/special/compiler_rt/extendXfYf2.zig14
-rw-r--r--lib/std/special/compiler_rt/extendXfYf2_test.zig8
-rw-r--r--lib/std/special/compiler_rt/fixdfdi_test.zig2
-rw-r--r--lib/std/special/compiler_rt/fixdfsi_test.zig2
-rw-r--r--lib/std/special/compiler_rt/fixdfti_test.zig2
-rw-r--r--lib/std/special/compiler_rt/fixint.zig6
-rw-r--r--lib/std/special/compiler_rt/fixint_test.zig26
-rw-r--r--lib/std/special/compiler_rt/fixsfdi_test.zig2
-rw-r--r--lib/std/special/compiler_rt/fixsfsi_test.zig2
-rw-r--r--lib/std/special/compiler_rt/fixsfti_test.zig2
-rw-r--r--lib/std/special/compiler_rt/fixtfdi_test.zig2
-rw-r--r--lib/std/special/compiler_rt/fixtfsi_test.zig2
-rw-r--r--lib/std/special/compiler_rt/fixtfti_test.zig2
-rw-r--r--lib/std/special/compiler_rt/fixuint.zig8
-rw-r--r--lib/std/special/compiler_rt/fixunstfsi_test.zig2
-rw-r--r--lib/std/special/compiler_rt/fixunstfti_test.zig2
-rw-r--r--lib/std/special/compiler_rt/floatsiXf.zig10
-rw-r--r--lib/std/special/compiler_rt/floattidf.zig2
-rw-r--r--lib/std/special/compiler_rt/floattisf.zig2
-rw-r--r--lib/std/special/compiler_rt/floattitf.zig2
-rw-r--r--lib/std/special/compiler_rt/floatunsidf.zig6
-rw-r--r--lib/std/special/compiler_rt/floatuntidf.zig4
-rw-r--r--lib/std/special/compiler_rt/floatuntisf.zig4
-rw-r--r--lib/std/special/compiler_rt/floatuntitf.zig4
-rw-r--r--lib/std/special/compiler_rt/mulXf3.zig50
-rw-r--r--lib/std/special/compiler_rt/mulXf3_test.zig18
-rw-r--r--lib/std/special/compiler_rt/muldi3.zig2
-rw-r--r--lib/std/special/compiler_rt/mulodi4.zig2
-rw-r--r--lib/std/special/compiler_rt/mulodi4_test.zig48
-rw-r--r--lib/std/special/compiler_rt/muloti4.zig2
-rw-r--r--lib/std/special/compiler_rt/muloti4_test.zig62
-rw-r--r--lib/std/special/compiler_rt/multi3.zig2
-rw-r--r--lib/std/special/compiler_rt/negXf2.zig2
-rw-r--r--lib/std/special/compiler_rt/popcountdi2_test.zig6
-rw-r--r--lib/std/special/compiler_rt/truncXfYf2.zig2
-rw-r--r--lib/std/special/compiler_rt/truncXfYf2_test.zig20
-rw-r--r--lib/std/special/compiler_rt/udivmod.zig6
-rw-r--r--lib/std/special/docs/index.html2
-rw-r--r--lib/std/special/docs/main.js31
-rw-r--r--lib/std/special/start.zig2
-rw-r--r--lib/std/spinlock.zig45
-rw-r--r--lib/std/statically_initialized_mutex.zig105
-rw-r--r--lib/std/std.zig2
-rw-r--r--lib/std/target.zig38
-rw-r--r--lib/std/testing.zig2
-rw-r--r--lib/std/thread.zig2
-rw-r--r--lib/std/time.zig8
-rw-r--r--lib/std/unicode.zig26
-rw-r--r--lib/std/unicode/throughput_test.zig4
-rw-r--r--lib/std/valgrind.zig80
-rw-r--r--lib/std/valgrind/callgrind.zig14
-rw-r--r--lib/std/valgrind/memcheck.zig81
-rw-r--r--lib/std/zig/ast.zig23
-rw-r--r--lib/std/zig/parse.zig93
-rw-r--r--lib/std/zig/parse_string_literal.zig2
-rw-r--r--lib/std/zig/parser_test.zig98
-rw-r--r--lib/std/zig/render.zig78
-rw-r--r--lib/std/zig/tokenizer.zig56
235 files changed, 5726 insertions, 1986 deletions
diff --git a/lib/std/array_list.zig b/lib/std/array_list.zig
index a57839ec3b..59fd2a10e5 100644
--- a/lib/std/array_list.zig
+++ b/lib/std/array_list.zig
@@ -344,18 +344,18 @@ test "std.ArrayList.orderedRemove" {
try list.append(7);
//remove from middle
- testing.expectEqual(i32(4), list.orderedRemove(3));
- testing.expectEqual(i32(5), list.at(3));
- testing.expectEqual(usize(6), list.len);
+ testing.expectEqual(@as(i32, 4), list.orderedRemove(3));
+ testing.expectEqual(@as(i32, 5), list.at(3));
+ testing.expectEqual(@as(usize, 6), list.len);
//remove from end
- testing.expectEqual(i32(7), list.orderedRemove(5));
- testing.expectEqual(usize(5), list.len);
+ testing.expectEqual(@as(i32, 7), list.orderedRemove(5));
+ testing.expectEqual(@as(usize, 5), list.len);
//remove from front
- testing.expectEqual(i32(1), list.orderedRemove(0));
- testing.expectEqual(i32(2), list.at(0));
- testing.expectEqual(usize(4), list.len);
+ testing.expectEqual(@as(i32, 1), list.orderedRemove(0));
+ testing.expectEqual(@as(i32, 2), list.at(0));
+ testing.expectEqual(@as(usize, 4), list.len);
}
test "std.ArrayList.swapRemove" {
diff --git a/lib/std/ascii.zig b/lib/std/ascii.zig
index 2bc11ba3f2..71f52bfd17 100644
--- a/lib/std/ascii.zig
+++ b/lib/std/ascii.zig
@@ -129,26 +129,26 @@ const combinedTable = init: {
comptime var i = 0;
inline while (i < 128) : (i += 1) {
table[i] =
- u8(alpha[i]) << @enumToInt(tIndex.Alpha) |
- u8(hex[i]) << @enumToInt(tIndex.Hex) |
- u8(space[i]) << @enumToInt(tIndex.Space) |
- u8(digit[i]) << @enumToInt(tIndex.Digit) |
- u8(lower[i]) << @enumToInt(tIndex.Lower) |
- u8(upper[i]) << @enumToInt(tIndex.Upper) |
- u8(punct[i]) << @enumToInt(tIndex.Punct) |
- u8(graph[i]) << @enumToInt(tIndex.Graph);
+ @as(u8, alpha[i]) << @enumToInt(tIndex.Alpha) |
+ @as(u8, hex[i]) << @enumToInt(tIndex.Hex) |
+ @as(u8, space[i]) << @enumToInt(tIndex.Space) |
+ @as(u8, digit[i]) << @enumToInt(tIndex.Digit) |
+ @as(u8, lower[i]) << @enumToInt(tIndex.Lower) |
+ @as(u8, upper[i]) << @enumToInt(tIndex.Upper) |
+ @as(u8, punct[i]) << @enumToInt(tIndex.Punct) |
+ @as(u8, graph[i]) << @enumToInt(tIndex.Graph);
}
mem.set(u8, table[128..256], 0);
break :init table;
};
fn inTable(c: u8, t: tIndex) bool {
- return (combinedTable[c] & (u8(1) << @enumToInt(t))) != 0;
+ return (combinedTable[c] & (@as(u8, 1) << @enumToInt(t))) != 0;
}
pub fn isAlNum(c: u8) bool {
- return (combinedTable[c] & ((u8(1) << @enumToInt(tIndex.Alpha)) |
- u8(1) << @enumToInt(tIndex.Digit))) != 0;
+ return (combinedTable[c] & ((@as(u8, 1) << @enumToInt(tIndex.Alpha)) |
+ @as(u8, 1) << @enumToInt(tIndex.Digit))) != 0;
}
pub fn isAlpha(c: u8) bool {
diff --git a/lib/std/atomic/queue.zig b/lib/std/atomic/queue.zig
index dbc011bed3..9d6b15ff4a 100644
--- a/lib/std/atomic/queue.zig
+++ b/lib/std/atomic/queue.zig
@@ -199,7 +199,7 @@ test "std.atomic.Queue" {
for (putters) |t|
t.wait();
- _ = @atomicRmw(u8, &context.puts_done, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst);
+ @atomicStore(u8, &context.puts_done, 1, AtomicOrder.SeqCst);
for (getters) |t|
t.wait();
@@ -214,8 +214,8 @@ test "std.atomic.Queue" {
std.debug.panic(
"failure\nget_count:{} != puts_per_thread:{} * put_thread_count:{}",
context.get_count,
- u32(puts_per_thread),
- u32(put_thread_count),
+ @as(u32, puts_per_thread),
+ @as(u32, put_thread_count),
);
}
}
diff --git a/lib/std/atomic/stack.zig b/lib/std/atomic/stack.zig
index dd288adbf1..4246e15985 100644
--- a/lib/std/atomic/stack.zig
+++ b/lib/std/atomic/stack.zig
@@ -11,7 +11,7 @@ pub fn Stack(comptime T: type) type {
root: ?*Node,
lock: @typeOf(lock_init),
- const lock_init = if (builtin.single_threaded) {} else u8(0);
+ const lock_init = if (builtin.single_threaded) {} else @as(u8, 0);
pub const Self = @This();
@@ -128,7 +128,7 @@ test "std.atomic.stack" {
for (putters) |t|
t.wait();
- _ = @atomicRmw(u8, &context.puts_done, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst);
+ @atomicStore(u8, &context.puts_done, 1, AtomicOrder.SeqCst);
for (getters) |t|
t.wait();
}
@@ -141,8 +141,8 @@ test "std.atomic.stack" {
std.debug.panic(
"failure\nget_count:{} != puts_per_thread:{} * put_thread_count:{}",
context.get_count,
- u32(puts_per_thread),
- u32(put_thread_count),
+ @as(u32, puts_per_thread),
+ @as(u32, put_thread_count),
);
}
}
diff --git a/lib/std/bloom_filter.zig b/lib/std/bloom_filter.zig
index c36c5e9dfa..6c4d713076 100644
--- a/lib/std/bloom_filter.zig
+++ b/lib/std/bloom_filter.zig
@@ -28,7 +28,7 @@ pub fn BloomFilter(
assert(n_items > 0);
assert(math.isPowerOfTwo(n_items));
assert(K > 0);
- const cellEmpty = if (Cell == bool) false else Cell(0);
+ const cellEmpty = if (Cell == bool) false else @as(Cell, 0);
const cellMax = if (Cell == bool) true else math.maxInt(Cell);
const n_bytes = (n_items * comptime std.meta.bitCount(Cell)) / 8;
assert(n_bytes > 0);
@@ -137,7 +137,7 @@ pub fn BloomFilter(
var i: usize = 0;
while (i < n_items) : (i += 1) {
const cell = self.getCell(@intCast(Index, i));
- n += if (if (Cell == bool) cell else cell > 0) Index(1) else Index(0);
+ n += if (if (Cell == bool) cell else cell > 0) @as(Index, 1) else @as(Index, 0);
}
}
return n;
@@ -161,7 +161,7 @@ fn hashFunc(out: []u8, Ki: usize, in: []const u8) void {
test "std.BloomFilter" {
inline for ([_]type{ bool, u1, u2, u3, u4 }) |Cell| {
- const emptyCell = if (Cell == bool) false else Cell(0);
+ const emptyCell = if (Cell == bool) false else @as(Cell, 0);
const BF = BloomFilter(128 * 8, 8, Cell, builtin.endian, hashFunc);
var bf = BF{};
var i: usize = undefined;
@@ -170,8 +170,8 @@ test "std.BloomFilter" {
while (i < BF.items) : (i += 1) {
testing.expectEqual(emptyCell, bf.getCell(@intCast(BF.Index, i)));
}
- testing.expectEqual(BF.Index(0), bf.popCount());
- testing.expectEqual(f64(0), bf.estimateItems());
+ testing.expectEqual(@as(BF.Index, 0), bf.popCount());
+ testing.expectEqual(@as(f64, 0), bf.estimateItems());
// fill in a few items
bf.incrementCell(42);
bf.incrementCell(255);
@@ -196,8 +196,8 @@ test "std.BloomFilter" {
while (i < BF.items) : (i += 1) {
testing.expectEqual(emptyCell, bf.getCell(@intCast(BF.Index, i)));
}
- testing.expectEqual(BF.Index(0), bf.popCount());
- testing.expectEqual(f64(0), bf.estimateItems());
+ testing.expectEqual(@as(BF.Index, 0), bf.popCount());
+ testing.expectEqual(@as(f64, 0), bf.estimateItems());
// Lets add a string
bf.add("foo");
@@ -218,8 +218,8 @@ test "std.BloomFilter" {
while (i < BF.items) : (i += 1) {
testing.expectEqual(emptyCell, bf.getCell(@intCast(BF.Index, i)));
}
- testing.expectEqual(BF.Index(0), bf.popCount());
- testing.expectEqual(f64(0), bf.estimateItems());
+ testing.expectEqual(@as(BF.Index, 0), bf.popCount());
+ testing.expectEqual(@as(f64, 0), bf.estimateItems());
comptime var teststrings = [_][]const u8{
"foo",
@@ -246,12 +246,12 @@ test "std.BloomFilter" {
inline for (teststrings) |str| {
testing.expectEqual(true, larger_bf.contains(str));
}
- testing.expectEqual(u12(bf.popCount()) * (4096 / 1024), larger_bf.popCount());
+ testing.expectEqual(@as(u12, bf.popCount()) * (4096 / 1024), larger_bf.popCount());
const smaller_bf = bf.resize(64);
inline for (teststrings) |str| {
testing.expectEqual(true, smaller_bf.contains(str));
}
- testing.expect(bf.popCount() <= u10(smaller_bf.popCount()) * (1024 / 64));
+ testing.expect(bf.popCount() <= @as(u10, smaller_bf.popCount()) * (1024 / 64));
}
}
diff --git a/lib/std/build.zig b/lib/std/build.zig
index 899e74105b..b124b12fef 100644
--- a/lib/std/build.zig
+++ b/lib/std/build.zig
@@ -53,7 +53,7 @@ pub const Builder = struct {
release_mode: ?builtin.Mode,
is_release: bool,
override_lib_dir: ?[]const u8,
-
+ vcpkg_root: VcpkgRoot,
pkg_config_pkg_list: ?(PkgConfigError![]const PkgConfigPkg) = null,
const PkgConfigError = error{
@@ -159,6 +159,7 @@ pub const Builder = struct {
.is_release = false,
.override_lib_dir = null,
.install_path = undefined,
+ .vcpkg_root = VcpkgRoot{ .Unattempted = {} },
};
try self.top_level_steps.append(&self.install_tls);
try self.top_level_steps.append(&self.uninstall_tls);
@@ -957,6 +958,7 @@ pub const Builder = struct {
error.ProcessTerminated => error.PkgConfigCrashed,
error.ExitCodeFailure => error.PkgConfigFailed,
error.FileNotFound => error.PkgConfigNotInstalled,
+ error.InvalidName => error.PkgConfigNotInstalled,
error.PkgConfigInvalidOutput => error.PkgConfigInvalidOutput,
else => return err,
};
@@ -1046,6 +1048,7 @@ pub const LibExeObjStep = struct {
output_dir: ?[]const u8,
need_system_paths: bool,
is_linking_libc: bool = false,
+ vcpkg_bin_path: ?[]const u8 = null,
installed_path: ?[]const u8,
install_step: ?*InstallArtifactStep,
@@ -1264,6 +1267,11 @@ pub const LibExeObjStep = struct {
// option is supplied.
const run_step = RunStep.create(exe.builder, exe.builder.fmt("run {}", exe.step.name));
run_step.addArtifactArg(exe);
+
+ if (exe.vcpkg_bin_path) |path| {
+ run_step.addPathDir(path);
+ }
+
return run_step;
}
@@ -1569,6 +1577,43 @@ pub const LibExeObjStep = struct {
}) catch unreachable;
}
+ /// If Vcpkg was found on the system, it will be added to include and lib
+ /// paths for the specified target.
+ pub fn addVcpkgPaths(self: *LibExeObjStep, linkage: VcpkgLinkage) !void {
+ // Ideally in the Unattempted case we would call the function recursively
+ // after findVcpkgRoot and have only one switch statement, but the compiler
+ // cannot resolve the error set.
+ switch (self.builder.vcpkg_root) {
+ .Unattempted => {
+ self.builder.vcpkg_root = if (try findVcpkgRoot(self.builder.allocator)) |root|
+ VcpkgRoot{ .Found = root }
+ else
+ .NotFound;
+ },
+ .NotFound => return error.VcpkgNotFound,
+ .Found => {},
+ }
+
+ switch (self.builder.vcpkg_root) {
+ .Unattempted => unreachable,
+ .NotFound => return error.VcpkgNotFound,
+ .Found => |root| {
+ const allocator = self.builder.allocator;
+ const triplet = try Target.vcpkgTriplet(allocator, self.target, linkage);
+ defer self.builder.allocator.free(triplet);
+
+ const include_path = try fs.path.join(allocator, [_][]const u8{ root, "installed", triplet, "include" });
+ errdefer allocator.free(include_path);
+ try self.include_dirs.append(IncludeDir{ .RawPath = include_path });
+
+ const lib_path = try fs.path.join(allocator, [_][]const u8{ root, "installed", triplet, "lib" });
+ try self.lib_paths.append(lib_path);
+
+ self.vcpkg_bin_path = try fs.path.join(allocator, [_][]const u8{ root, "installed", triplet, "bin" });
+ },
+ }
+ }
+
pub fn setExecCmd(self: *LibExeObjStep, args: []const ?[]const u8) void {
assert(self.kind == Kind.Test);
self.exec_cmd_args = args;
@@ -2341,6 +2386,42 @@ fn doAtomicSymLinks(allocator: *Allocator, output_path: []const u8, filename_maj
};
}
+/// Returned slice must be freed by the caller.
+fn findVcpkgRoot(allocator: *Allocator) !?[]const u8 {
+ const appdata_path = try fs.getAppDataDir(allocator, "vcpkg");
+ defer allocator.free(appdata_path);
+
+ const path_file = try fs.path.join(allocator, [_][]const u8{ appdata_path, "vcpkg.path.txt" });
+ defer allocator.free(path_file);
+
+ const file = fs.File.openRead(path_file) catch return null;
+ defer file.close();
+
+ const size = @intCast(usize, try file.getEndPos());
+ const vcpkg_path = try allocator.alloc(u8, size);
+ const size_read = try file.read(vcpkg_path);
+ std.debug.assert(size == size_read);
+
+ return vcpkg_path;
+}
+
+const VcpkgRoot = union(VcpkgRootStatus) {
+ Unattempted: void,
+ NotFound: void,
+ Found: []const u8,
+};
+
+const VcpkgRootStatus = enum {
+ Unattempted,
+ NotFound,
+ Found,
+};
+
+pub const VcpkgLinkage = enum {
+ Static,
+ Dynamic,
+};
+
pub const InstallDir = enum {
Prefix,
Lib,
diff --git a/lib/std/builtin.zig b/lib/std/builtin.zig
index 8315cd84cf..8052f0b31a 100644
--- a/lib/std/builtin.zig
+++ b/lib/std/builtin.zig
@@ -90,40 +90,11 @@ pub const Mode = enum {
ReleaseSmall,
};
-/// This data structure is used by the Zig language code generation and
-/// therefore must be kept in sync with the compiler implementation.
-pub const TypeId = enum {
- Type,
- Void,
- Bool,
- NoReturn,
- Int,
- Float,
- Pointer,
- Array,
- Struct,
- ComptimeFloat,
- ComptimeInt,
- Undefined,
- Null,
- Optional,
- ErrorUnion,
- ErrorSet,
- Enum,
- Union,
- Fn,
- BoundFn,
- ArgTuple,
- Opaque,
- Frame,
- AnyFrame,
- Vector,
- EnumLiteral,
-};
+pub const TypeId = @TagType(TypeInfo);
/// This data structure is used by the Zig language code generation and
/// therefore must be kept in sync with the compiler implementation.
-pub const TypeInfo = union(TypeId) {
+pub const TypeInfo = union(enum) {
Type: void,
Void: void,
Bool: void,
diff --git a/lib/std/c.zig b/lib/std/c.zig
index 853712abd4..3fd39b26f5 100644
--- a/lib/std/c.zig
+++ b/lib/std/c.zig
@@ -8,9 +8,16 @@ pub usingnamespace switch (builtin.os) {
.linux => @import("c/linux.zig"),
.windows => @import("c/windows.zig"),
.macosx, .ios, .tvos, .watchos => @import("c/darwin.zig"),
- .freebsd => @import("c/freebsd.zig"),
+ .freebsd, .kfreebsd => @import("c/freebsd.zig"),
.netbsd => @import("c/netbsd.zig"),
.dragonfly => @import("c/dragonfly.zig"),
+ .openbsd => @import("c/openbsd.zig"),
+ .haiku => @import("c/haiku.zig"),
+ .hermit => @import("c/hermit.zig"),
+ .solaris => @import("c/solaris.zig"),
+ .fuchsia => @import("c/fuchsia.zig"),
+ .minix => @import("c/minix.zig"),
+ .emscripten => @import("c/emscripten.zig"),
else => struct {},
};
@@ -203,3 +210,18 @@ pub extern "c" fn dn_expand(
exp_dn: [*]u8,
length: c_int,
) c_int;
+
+pub extern "c" fn sched_yield() c_int;
+
+pub const PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{};
+pub extern "c" fn pthread_mutex_lock(mutex: *pthread_mutex_t) c_int;
+pub extern "c" fn pthread_mutex_unlock(mutex: *pthread_mutex_t) c_int;
+pub extern "c" fn pthread_mutex_destroy(mutex: *pthread_mutex_t) c_int;
+
+pub const PTHREAD_COND_INITIALIZER = pthread_cond_t{};
+pub extern "c" fn pthread_cond_wait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t) c_int;
+pub extern "c" fn pthread_cond_signal(cond: *pthread_cond_t) c_int;
+pub extern "c" fn pthread_cond_destroy(cond: *pthread_cond_t) c_int;
+
+pub const pthread_t = *@OpaqueType();
+pub const FILE = @OpaqueType();
diff --git a/lib/std/c/darwin.zig b/lib/std/c/darwin.zig
index f3cd77ec6f..4d40e8aee5 100644
--- a/lib/std/c/darwin.zig
+++ b/lib/std/c/darwin.zig
@@ -53,7 +53,7 @@ pub extern "c" fn host_get_clock_service(host: host_t, clock_id: clock_id_t, clo
pub extern "c" fn mach_port_deallocate(task: ipc_space_t, name: mach_port_name_t) kern_return_t;
pub fn sigaddset(set: *sigset_t, signo: u5) void {
- set.* |= u32(1) << (signo - 1);
+ set.* |= @as(u32, 1) << (signo - 1);
}
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
@@ -112,3 +112,19 @@ pub const EAI_PROTOCOL = 13;
/// argument buffer overflow
pub const EAI_OVERFLOW = 14;
pub const EAI_MAX = 15;
+
+pub const pthread_mutex_t = extern struct {
+ __sig: c_long = 0x32AAABA7,
+ __opaque: [__PTHREAD_MUTEX_SIZE__]u8 = [_]u8{0} ** __PTHREAD_MUTEX_SIZE__,
+};
+pub const pthread_cond_t = extern struct {
+ __sig: c_long = 0x3CB0B1BB,
+ __opaque: [__PTHREAD_COND_SIZE__]u8 = [_]u8{0} ** __PTHREAD_COND_SIZE__,
+};
+const __PTHREAD_MUTEX_SIZE__ = if (@sizeOf(usize) == 8) 56 else 40;
+const __PTHREAD_COND_SIZE__ = if (@sizeOf(usize) == 8) 40 else 24;
+
+pub const pthread_attr_t = extern struct {
+ __sig: c_long,
+ __opaque: [56]u8,
+};
diff --git a/lib/std/c/dragonfly.zig b/lib/std/c/dragonfly.zig
index bd44a25514..a271b2e869 100644
--- a/lib/std/c/dragonfly.zig
+++ b/lib/std/c/dragonfly.zig
@@ -1,6 +1,5 @@
const std = @import("../std.zig");
usingnamespace std.c;
-
extern "c" threadlocal var errno: c_int;
pub fn _errno() *c_int {
return &errno;
@@ -12,3 +11,15 @@ pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) isize
pub const dl_iterate_phdr_callback = extern fn (info: *dl_phdr_info, size: usize, data: ?*c_void) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int;
+
+pub const pthread_mutex_t = extern struct {
+ inner: ?*c_void = null,
+};
+pub const pthread_cond_t = extern struct {
+ inner: ?*c_void = null,
+};
+
+pub const pthread_attr_t = extern struct { // copied from freebsd
+ __size: [56]u8,
+ __align: c_long,
+};
diff --git a/lib/std/c/emscripten.zig b/lib/std/c/emscripten.zig
new file mode 100644
index 0000000000..e91e1421c7
--- /dev/null
+++ b/lib/std/c/emscripten.zig
@@ -0,0 +1,8 @@
+pub const pthread_mutex_t = extern struct {
+ size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(4) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
+};
+pub const pthread_cond_t = extern struct {
+ size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
+};
+const __SIZEOF_PTHREAD_COND_T = 48;
+const __SIZEOF_PTHREAD_MUTEX_T = 28;
diff --git a/lib/std/c/freebsd.zig b/lib/std/c/freebsd.zig
index 550b5a59b1..4f18df15fd 100644
--- a/lib/std/c/freebsd.zig
+++ b/lib/std/c/freebsd.zig
@@ -10,3 +10,15 @@ pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) isize
pub const dl_iterate_phdr_callback = extern fn (info: *dl_phdr_info, size: usize, data: ?*c_void) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int;
+
+pub const pthread_mutex_t = extern struct {
+ inner: ?*c_void = null,
+};
+pub const pthread_cond_t = extern struct {
+ inner: ?*c_void = null,
+};
+
+pub const pthread_attr_t = extern struct {
+ __size: [56]u8,
+ __align: c_long,
+};
diff --git a/lib/std/c/fuchsia.zig b/lib/std/c/fuchsia.zig
new file mode 100644
index 0000000000..4f52b8900d
--- /dev/null
+++ b/lib/std/c/fuchsia.zig
@@ -0,0 +1,8 @@
+pub const pthread_mutex_t = extern struct {
+ size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
+};
+pub const pthread_cond_t = extern struct {
+ size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
+};
+const __SIZEOF_PTHREAD_COND_T = 48;
+const __SIZEOF_PTHREAD_MUTEX_T = 40;
diff --git a/lib/std/c/haiku.zig b/lib/std/c/haiku.zig
new file mode 100644
index 0000000000..eb1e52a618
--- /dev/null
+++ b/lib/std/c/haiku.zig
@@ -0,0 +1,14 @@
+pub const pthread_mutex_t = extern struct {
+ flags: u32 = 0,
+ lock: i32 = 0,
+ unused: i32 = -42,
+ owner: i32 = -1,
+ owner_count: i32 = 0,
+};
+pub const pthread_cond_t = extern struct {
+ flags: u32 = 0,
+ unused: i32 = -42,
+ mutex: ?*c_void = null,
+ waiter_count: i32 = 0,
+ lock: i32 = 0,
+};
diff --git a/lib/std/c/hermit.zig b/lib/std/c/hermit.zig
new file mode 100644
index 0000000000..b9be76c3ba
--- /dev/null
+++ b/lib/std/c/hermit.zig
@@ -0,0 +1,6 @@
+pub const pthread_mutex_t = extern struct {
+ inner: usize = ~usize(0),
+};
+pub const pthread_cond_t = extern struct {
+ inner: usize = ~usize(0),
+};
diff --git a/lib/std/c/linux.zig b/lib/std/c/linux.zig
index a1db162e20..07fdceec9a 100644
--- a/lib/std/c/linux.zig
+++ b/lib/std/c/linux.zig
@@ -75,3 +75,26 @@ pub const dl_iterate_phdr_callback = extern fn (info: *dl_phdr_info, size: usize
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int;
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
+
+pub const pthread_attr_t = extern struct {
+ __size: [56]u8,
+ __align: c_long,
+};
+
+pub const pthread_mutex_t = extern struct {
+ size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
+};
+pub const pthread_cond_t = extern struct {
+ size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
+};
+const __SIZEOF_PTHREAD_COND_T = 48;
+const __SIZEOF_PTHREAD_MUTEX_T = if (builtin.os == .fuchsia) 40 else switch (builtin.abi) {
+ .musl, .musleabi, .musleabihf => if (@sizeOf(usize) == 8) 40 else 24,
+ .gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => switch (builtin.arch) {
+ .aarch64 => 48,
+ .x86_64 => if (builtin.abi == .gnux32) 40 else 32,
+ .mips64, .powerpc64, .powerpc64le, .sparcv9 => 40,
+ else => if (@sizeOf(usize) == 8) 40 else 24,
+ },
+ else => unreachable,
+};
diff --git a/lib/std/c/minix.zig b/lib/std/c/minix.zig
new file mode 100644
index 0000000000..98ec087a93
--- /dev/null
+++ b/lib/std/c/minix.zig
@@ -0,0 +1,18 @@
+const builtin = @import("builtin");
+pub const pthread_mutex_t = extern struct {
+ size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
+};
+pub const pthread_cond_t = extern struct {
+ size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
+};
+const __SIZEOF_PTHREAD_COND_T = 48;
+const __SIZEOF_PTHREAD_MUTEX_T = switch (builtin.abi) {
+ .musl, .musleabi, .musleabihf => if (@sizeOf(usize) == 8) 40 else 24,
+ .gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => switch (builtin.arch) {
+ .aarch64 => 48,
+ .x86_64 => if (builtin.abi == .gnux32) 40 else 32,
+ .mips64, .powerpc64, .powerpc64le, .sparcv9 => 40,
+ else => if (@sizeOf(usize) == 8) 40 else 24,
+ },
+ else => unreachable,
+};
diff --git a/lib/std/c/netbsd.zig b/lib/std/c/netbsd.zig
index 417c78db69..c253362ac1 100644
--- a/lib/std/c/netbsd.zig
+++ b/lib/std/c/netbsd.zig
@@ -6,3 +6,32 @@ pub const _errno = __errno;
pub extern "c" fn getdents(fd: c_int, buf_ptr: [*]u8, nbytes: usize) usize;
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
+
+pub const pthread_mutex_t = extern struct {
+ ptm_magic: c_uint = 0x33330003,
+ ptm_errorcheck: padded_spin_t = 0,
+ ptm_unused: padded_spin_t = 0,
+ ptm_owner: usize = 0,
+ ptm_waiters: ?*u8 = null,
+ ptm_recursed: c_uint = 0,
+ ptm_spare2: ?*c_void = null,
+};
+pub const pthread_cond_t = extern struct {
+ ptc_magic: c_uint = 0x55550005,
+ ptc_lock: pthread_spin_t = 0,
+ ptc_waiters_first: ?*u8 = null,
+ ptc_waiters_last: ?*u8 = null,
+ ptc_mutex: ?*pthread_mutex_t = null,
+ ptc_private: ?*c_void = null,
+};
+const pthread_spin_t = if (builtin.arch == .arm or .arch == .powerpc) c_int else u8;
+const padded_spin_t = switch (builtin.arch) {
+ .sparc, .sparcel, .sparcv9, .i386, .x86_64, .le64 => u32,
+ else => spin_t,
+};
+
+pub const pthread_attr_t = extern struct {
+ pta_magic: u32,
+ pta_flags: c_int,
+ pta_private: *c_void,
+};
diff --git a/lib/std/c/openbsd.zig b/lib/std/c/openbsd.zig
new file mode 100644
index 0000000000..22963b08c3
--- /dev/null
+++ b/lib/std/c/openbsd.zig
@@ -0,0 +1,6 @@
+pub const pthread_mutex_t = extern struct {
+ inner: ?*c_void = null,
+};
+pub const pthread_cond_t = extern struct {
+ inner: ?*c_void = null,
+};
diff --git a/lib/std/c/solaris.zig b/lib/std/c/solaris.zig
new file mode 100644
index 0000000000..7c70a01fc4
--- /dev/null
+++ b/lib/std/c/solaris.zig
@@ -0,0 +1,15 @@
+pub const pthread_mutex_t = extern struct {
+ __pthread_mutex_flag1: u16 = 0,
+ __pthread_mutex_flag2: u8 = 0,
+ __pthread_mutex_ceiling: u8 = 0,
+ __pthread_mutex_type: u16 = 0,
+ __pthread_mutex_magic: u16 = 0x4d58,
+ __pthread_mutex_lock: u64 = 0,
+ __pthread_mutex_data: u64 = 0,
+};
+pub const pthread_cond_t = extern struct {
+ __pthread_cond_flag: u32 = 0,
+ __pthread_cond_type: u16 = 0,
+ __pthread_cond_magic: u16 = 0x4356,
+ __pthread_cond_data: u64 = 0,
+};
diff --git a/lib/std/child_process.zig b/lib/std/child_process.zig
index 5fae9447a9..680c378c0d 100644
--- a/lib/std/child_process.zig
+++ b/lib/std/child_process.zig
@@ -50,8 +50,20 @@ pub const ChildProcess = struct {
err_pipe: if (builtin.os == .windows) void else [2]os.fd_t,
llnode: if (builtin.os == .windows) void else TailQueue(*ChildProcess).Node,
- pub const SpawnError = error{OutOfMemory} || os.ExecveError || os.SetIdError ||
- os.ChangeCurDirError || windows.CreateProcessError;
+ pub const SpawnError = error{
+ OutOfMemory,
+
+ /// POSIX-only. `StdIo.Ignore` was selected and opening `/dev/null` returned ENODEV.
+ NoDevice,
+
+ /// Windows-only. One of:
+ /// * `cwd` was provided and it could not be re-encoded into UTF16LE, or
+ /// * The `PATH` or `PATHEXT` environment variable contained invalid UTF-8.
+ InvalidUtf8,
+
+ /// Windows-only. `cwd` was provided, but the path did not exist when spawning the child process.
+ CurrentWorkingDirectoryUnlinked,
+ } || os.ExecveError || os.SetIdError || os.ChangeCurDirError || windows.CreateProcessError || windows.WaitForSingleObjectError;
pub const Term = union(enum) {
Exited: u32,
@@ -102,7 +114,7 @@ pub const ChildProcess = struct {
}
/// On success must call `kill` or `wait`.
- pub fn spawn(self: *ChildProcess) !void {
+ pub fn spawn(self: *ChildProcess) SpawnError!void {
if (builtin.os == .windows) {
return self.spawnWindows();
} else {
@@ -110,7 +122,7 @@ pub const ChildProcess = struct {
}
}
- pub fn spawnAndWait(self: *ChildProcess) !Term {
+ pub fn spawnAndWait(self: *ChildProcess) SpawnError!Term {
try self.spawn();
return self.wait();
}
@@ -162,7 +174,13 @@ pub const ChildProcess = struct {
/// Spawns a child process, waits for it, collecting stdout and stderr, and then returns.
/// If it succeeds, the caller owns result.stdout and result.stderr memory.
- pub fn exec(allocator: *mem.Allocator, argv: []const []const u8, cwd: ?[]const u8, env_map: ?*const BufMap, max_output_size: usize) !ExecResult {
+ pub fn exec(
+ allocator: *mem.Allocator,
+ argv: []const []const u8,
+ cwd: ?[]const u8,
+ env_map: ?*const BufMap,
+ max_output_size: usize,
+ ) !ExecResult {
const child = try ChildProcess.init(argv, allocator);
defer child.deinit();
@@ -219,7 +237,7 @@ pub const ChildProcess = struct {
fn waitUnwrappedWindows(self: *ChildProcess) !void {
const result = windows.WaitForSingleObject(self.handle, windows.INFINITE);
- self.term = (SpawnError!Term)(x: {
+ self.term = @as(SpawnError!Term, x: {
var exit_code: windows.DWORD = undefined;
if (windows.kernel32.GetExitCodeProcess(self.handle, &exit_code) == 0) {
break :x Term{ .Unknown = 0 };
@@ -292,7 +310,7 @@ pub const ChildProcess = struct {
Term{ .Unknown = status };
}
- fn spawnPosix(self: *ChildProcess) !void {
+ fn spawnPosix(self: *ChildProcess) SpawnError!void {
const stdin_pipe = if (self.stdin_behavior == StdIo.Pipe) try os.pipe() else undefined;
errdefer if (self.stdin_behavior == StdIo.Pipe) {
destroyPipe(stdin_pipe);
@@ -309,7 +327,16 @@ pub const ChildProcess = struct {
};
const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore);
- const dev_null_fd = if (any_ignore) try os.openC(c"/dev/null", os.O_RDWR, 0) else undefined;
+ const dev_null_fd = if (any_ignore)
+ os.openC(c"/dev/null", os.O_RDWR, 0) catch |err| switch (err) {
+ error.PathAlreadyExists => unreachable,
+ error.NoSpaceLeft => unreachable,
+ error.FileTooBig => unreachable,
+ error.DeviceBusy => unreachable,
+ else => |e| return e,
+ }
+ else
+ undefined;
defer {
if (any_ignore) os.close(dev_null_fd);
}
@@ -403,7 +430,7 @@ pub const ChildProcess = struct {
}
}
- fn spawnWindows(self: *ChildProcess) !void {
+ fn spawnWindows(self: *ChildProcess) SpawnError!void {
const saAttr = windows.SECURITY_ATTRIBUTES{
.nLength = @sizeOf(windows.SECURITY_ATTRIBUTES),
.bInheritHandle = windows.TRUE,
@@ -412,11 +439,28 @@ pub const ChildProcess = struct {
const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore);
- const nul_handle = if (any_ignore) blk: {
- break :blk try windows.CreateFile("NUL", windows.GENERIC_READ, windows.FILE_SHARE_READ, null, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, null);
- } else blk: {
- break :blk undefined;
- };
+ const nul_handle = if (any_ignore)
+ windows.CreateFile(
+ "NUL",
+ windows.GENERIC_READ,
+ windows.FILE_SHARE_READ,
+ null,
+ windows.OPEN_EXISTING,
+ windows.FILE_ATTRIBUTE_NORMAL,
+ null,
+ ) catch |err| switch (err) {
+ error.SharingViolation => unreachable, // not possible for "NUL"
+ error.PathAlreadyExists => unreachable, // not possible for "NUL"
+ error.PipeBusy => unreachable, // not possible for "NUL"
+ error.InvalidUtf8 => unreachable, // not possible for "NUL"
+ error.BadPathName => unreachable, // not possible for "NUL"
+ error.FileNotFound => unreachable, // not possible for "NUL"
+ error.AccessDenied => unreachable, // not possible for "NUL"
+ error.NameTooLong => unreachable, // not possible for "NUL"
+ else => |e| return e,
+ }
+ else
+ undefined;
defer {
if (any_ignore) os.close(nul_handle);
}
@@ -542,10 +586,25 @@ pub const ChildProcess = struct {
windowsCreateProcess(app_name_w.ptr, cmd_line_w.ptr, envp_ptr, cwd_w_ptr, &siStartInfo, &piProcInfo) catch |no_path_err| {
if (no_path_err != error.FileNotFound) return no_path_err;
- const PATH = try process.getEnvVarOwned(self.allocator, "PATH");
- defer self.allocator.free(PATH);
- const PATHEXT = try process.getEnvVarOwned(self.allocator, "PATHEXT");
- defer self.allocator.free(PATHEXT);
+ var free_path = true;
+ const PATH = process.getEnvVarOwned(self.allocator, "PATH") catch |err| switch (err) {
+ error.EnvironmentVariableNotFound => blk: {
+ free_path = false;
+ break :blk "";
+ },
+ else => |e| return e,
+ };
+ defer if (free_path) self.allocator.free(PATH);
+
+ var free_path_ext = true;
+ const PATHEXT = process.getEnvVarOwned(self.allocator, "PATHEXT") catch |err| switch (err) {
+ error.EnvironmentVariableNotFound => blk: {
+ free_path_ext = false;
+ break :blk "";
+ },
+ else => |e| return e,
+ };
+ defer if (free_path_ext) self.allocator.free(PATHEXT);
var it = mem.tokenize(PATH, ";");
retry: while (it.next()) |search_path| {
@@ -717,7 +776,7 @@ fn destroyPipe(pipe: [2]os.fd_t) void {
// Child of fork calls this to report an error to the fork parent.
// Then the child exits.
fn forkChildErrReport(fd: i32, err: ChildProcess.SpawnError) noreturn {
- writeIntFd(fd, ErrInt(@errorToInt(err))) catch {};
+ writeIntFd(fd, @as(ErrInt, @errorToInt(err))) catch {};
os.exit(1);
}
diff --git a/lib/std/coff.zig b/lib/std/coff.zig
index 3890151d09..c6d7660f8b 100644
--- a/lib/std/coff.zig
+++ b/lib/std/coff.zig
@@ -179,7 +179,7 @@ pub const Coff = struct {
if (byte != 0 and i == buffer.len)
return error.NameTooLong;
- return i;
+ return @as(usize, i);
}
pub fn loadSections(self: *Coff) !void {
diff --git a/lib/std/crypto/aes.zig b/lib/std/crypto/aes.zig
index 4e7a4f2e13..ddccd0b1b3 100644
--- a/lib/std/crypto/aes.zig
+++ b/lib/std/crypto/aes.zig
@@ -6,7 +6,7 @@ const testing = std.testing;
// Apply sbox0 to each byte in w.
fn subw(w: u32) u32 {
- return u32(sbox0[w >> 24]) << 24 | u32(sbox0[w >> 16 & 0xff]) << 16 | u32(sbox0[w >> 8 & 0xff]) << 8 | u32(sbox0[w & 0xff]);
+ return @as(u32, sbox0[w >> 24]) << 24 | @as(u32, sbox0[w >> 16 & 0xff]) << 16 | @as(u32, sbox0[w >> 8 & 0xff]) << 8 | @as(u32, sbox0[w & 0xff]);
}
fn rotw(w: u32) u32 {
@@ -48,10 +48,10 @@ fn encryptBlock(xk: []const u32, dst: []u8, src: []const u8) void {
}
// Last round uses s-box directly and XORs to produce output.
- s0 = u32(sbox0[t0 >> 24]) << 24 | u32(sbox0[t1 >> 16 & 0xff]) << 16 | u32(sbox0[t2 >> 8 & 0xff]) << 8 | u32(sbox0[t3 & 0xff]);
- s1 = u32(sbox0[t1 >> 24]) << 24 | u32(sbox0[t2 >> 16 & 0xff]) << 16 | u32(sbox0[t3 >> 8 & 0xff]) << 8 | u32(sbox0[t0 & 0xff]);
- s2 = u32(sbox0[t2 >> 24]) << 24 | u32(sbox0[t3 >> 16 & 0xff]) << 16 | u32(sbox0[t0 >> 8 & 0xff]) << 8 | u32(sbox0[t1 & 0xff]);
- s3 = u32(sbox0[t3 >> 24]) << 24 | u32(sbox0[t0 >> 16 & 0xff]) << 16 | u32(sbox0[t1 >> 8 & 0xff]) << 8 | u32(sbox0[t2 & 0xff]);
+ s0 = @as(u32, sbox0[t0 >> 24]) << 24 | @as(u32, sbox0[t1 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t2 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t3 & 0xff]);
+ s1 = @as(u32, sbox0[t1 >> 24]) << 24 | @as(u32, sbox0[t2 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t3 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t0 & 0xff]);
+ s2 = @as(u32, sbox0[t2 >> 24]) << 24 | @as(u32, sbox0[t3 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t0 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t1 & 0xff]);
+ s3 = @as(u32, sbox0[t3 >> 24]) << 24 | @as(u32, sbox0[t0 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t1 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t2 & 0xff]);
s0 ^= xk[k + 0];
s1 ^= xk[k + 1];
@@ -99,10 +99,10 @@ pub fn decryptBlock(xk: []const u32, dst: []u8, src: []const u8) void {
}
// Last round uses s-box directly and XORs to produce output.
- s0 = u32(sbox1[t0 >> 24]) << 24 | u32(sbox1[t3 >> 16 & 0xff]) << 16 | u32(sbox1[t2 >> 8 & 0xff]) << 8 | u32(sbox1[t1 & 0xff]);
- s1 = u32(sbox1[t1 >> 24]) << 24 | u32(sbox1[t0 >> 16 & 0xff]) << 16 | u32(sbox1[t3 >> 8 & 0xff]) << 8 | u32(sbox1[t2 & 0xff]);
- s2 = u32(sbox1[t2 >> 24]) << 24 | u32(sbox1[t1 >> 16 & 0xff]) << 16 | u32(sbox1[t0 >> 8 & 0xff]) << 8 | u32(sbox1[t3 & 0xff]);
- s3 = u32(sbox1[t3 >> 24]) << 24 | u32(sbox1[t2 >> 16 & 0xff]) << 16 | u32(sbox1[t1 >> 8 & 0xff]) << 8 | u32(sbox1[t0 & 0xff]);
+ s0 = @as(u32, sbox1[t0 >> 24]) << 24 | @as(u32, sbox1[t3 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t2 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t1 & 0xff]);
+ s1 = @as(u32, sbox1[t1 >> 24]) << 24 | @as(u32, sbox1[t0 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t3 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t2 & 0xff]);
+ s2 = @as(u32, sbox1[t2 >> 24]) << 24 | @as(u32, sbox1[t1 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t0 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t3 & 0xff]);
+ s3 = @as(u32, sbox1[t3 >> 24]) << 24 | @as(u32, sbox1[t2 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t1 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t0 & 0xff]);
s0 ^= xk[k + 0];
s1 ^= xk[k + 1];
@@ -256,7 +256,7 @@ fn expandKey(key: []const u8, enc: []u32, dec: []u32) void {
while (i < enc.len) : (i += 1) {
var t = enc[i - 1];
if (i % nk == 0) {
- t = subw(rotw(t)) ^ (u32(powx[i / nk - 1]) << 24);
+ t = subw(rotw(t)) ^ (@as(u32, powx[i / nk - 1]) << 24);
} else if (nk > 6 and i % nk == 4) {
t = subw(t);
}
diff --git a/lib/std/crypto/benchmark.zig b/lib/std/crypto/benchmark.zig
index 7b0747da7b..05edae0b9b 100644
--- a/lib/std/crypto/benchmark.zig
+++ b/lib/std/crypto/benchmark.zig
@@ -131,9 +131,7 @@ fn printPad(stdout: var, s: []const u8) !void {
}
pub fn main() !void {
- var stdout_file = try std.io.getStdOut();
- var stdout_out_stream = stdout_file.outStream();
- const stdout = &stdout_out_stream.stream;
+ const stdout = &std.io.getStdOut().outStream().stream;
var buffer: [1024]u8 = undefined;
var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);
diff --git a/lib/std/crypto/blake2.zig b/lib/std/crypto/blake2.zig
index 6bb2764b92..d6b1e49724 100644
--- a/lib/std/crypto/blake2.zig
+++ b/lib/std/crypto/blake2.zig
@@ -164,13 +164,13 @@ fn Blake2s(comptime out_len: usize) type {
inline while (j < 10) : (j += 1) {
inline for (rounds) |r| {
v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]];
- v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], usize(16));
+ v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], @as(usize, 16));
v[r.c] = v[r.c] +% v[r.d];
- v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], usize(12));
+ v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], @as(usize, 12));
v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]];
- v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], usize(8));
+ v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], @as(usize, 8));
v[r.c] = v[r.c] +% v[r.d];
- v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], usize(7));
+ v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], @as(usize, 7));
}
}
@@ -398,13 +398,13 @@ fn Blake2b(comptime out_len: usize) type {
inline while (j < 12) : (j += 1) {
inline for (rounds) |r| {
v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]];
- v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], usize(32));
+ v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], @as(usize, 32));
v[r.c] = v[r.c] +% v[r.d];
- v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], usize(24));
+ v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], @as(usize, 24));
v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]];
- v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], usize(16));
+ v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], @as(usize, 16));
v[r.c] = v[r.c] +% v[r.d];
- v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], usize(63));
+ v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], @as(usize, 63));
}
}
diff --git a/lib/std/crypto/chacha20.zig b/lib/std/crypto/chacha20.zig
index 0d997e0d14..d5d03f2bfa 100644
--- a/lib/std/crypto/chacha20.zig
+++ b/lib/std/crypto/chacha20.zig
@@ -49,13 +49,13 @@ fn salsa20_wordtobyte(out: []u8, input: [16]u32) void {
// two-round cycles
inline for (rounds) |r| {
x[r.a] +%= x[r.b];
- x[r.d] = std.math.rotl(u32, x[r.d] ^ x[r.a], u32(16));
+ x[r.d] = std.math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 16));
x[r.c] +%= x[r.d];
- x[r.b] = std.math.rotl(u32, x[r.b] ^ x[r.c], u32(12));
+ x[r.b] = std.math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 12));
x[r.a] +%= x[r.b];
- x[r.d] = std.math.rotl(u32, x[r.d] ^ x[r.a], u32(8));
+ x[r.d] = std.math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 8));
x[r.c] +%= x[r.d];
- x[r.b] = std.math.rotl(u32, x[r.b] ^ x[r.c], u32(7));
+ x[r.b] = std.math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 7));
}
}
diff --git a/lib/std/crypto/gimli.zig b/lib/std/crypto/gimli.zig
index 0a0a5056c6..0d18afd705 100644
--- a/lib/std/crypto/gimli.zig
+++ b/lib/std/crypto/gimli.zig
@@ -34,9 +34,9 @@ pub const State = struct {
pub fn permute(self: *Self) void {
const state = &self.data;
- var round = u32(24);
+ var round = @as(u32, 24);
while (round > 0) : (round -= 1) {
- var column = usize(0);
+ var column = @as(usize, 0);
while (column < 4) : (column += 1) {
const x = math.rotl(u32, state[column], 24);
const y = math.rotl(u32, state[4 + column], 9);
@@ -61,7 +61,7 @@ pub const State = struct {
}
pub fn squeeze(self: *Self, out: []u8) void {
- var i = usize(0);
+ var i = @as(usize, 0);
while (i + RATE <= out.len) : (i += RATE) {
self.permute();
mem.copy(u8, out[i..], self.toSliceConst()[0..RATE]);
@@ -79,7 +79,7 @@ test "permute" {
var state = State{
.data = blk: {
var input: [12]u32 = undefined;
- var i = u32(0);
+ var i = @as(u32, 0);
while (i < 12) : (i += 1) {
input[i] = i * i * i + i *% 0x9e3779b9;
}
diff --git a/lib/std/crypto/md5.zig b/lib/std/crypto/md5.zig
index ddbb39a9df..db6150699d 100644
--- a/lib/std/crypto/md5.zig
+++ b/lib/std/crypto/md5.zig
@@ -126,10 +126,10 @@ pub const Md5 = struct {
while (i < 16) : (i += 1) {
// NOTE: Performing or's separately improves perf by ~10%
s[i] = 0;
- s[i] |= u32(b[i * 4 + 0]);
- s[i] |= u32(b[i * 4 + 1]) << 8;
- s[i] |= u32(b[i * 4 + 2]) << 16;
- s[i] |= u32(b[i * 4 + 3]) << 24;
+ s[i] |= @as(u32, b[i * 4 + 0]);
+ s[i] |= @as(u32, b[i * 4 + 1]) << 8;
+ s[i] |= @as(u32, b[i * 4 + 2]) << 16;
+ s[i] |= @as(u32, b[i * 4 + 3]) << 24;
}
var v: [4]u32 = [_]u32{
diff --git a/lib/std/crypto/poly1305.zig b/lib/std/crypto/poly1305.zig
index bd0b33e586..78881ba049 100644
--- a/lib/std/crypto/poly1305.zig
+++ b/lib/std/crypto/poly1305.zig
@@ -87,11 +87,11 @@ pub const Poly1305 = struct {
// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff
fn polyBlock(ctx: *Self) void {
// s = h + c, without carry propagation
- const s0 = u64(ctx.h[0]) + ctx.c[0]; // s0 <= 1_fffffffe
- const s1 = u64(ctx.h[1]) + ctx.c[1]; // s1 <= 1_fffffffe
- const s2 = u64(ctx.h[2]) + ctx.c[2]; // s2 <= 1_fffffffe
- const s3 = u64(ctx.h[3]) + ctx.c[3]; // s3 <= 1_fffffffe
- const s4 = u64(ctx.h[4]) + ctx.c[4]; // s4 <= 5
+ const s0 = @as(u64, ctx.h[0]) + ctx.c[0]; // s0 <= 1_fffffffe
+ const s1 = @as(u64, ctx.h[1]) + ctx.c[1]; // s1 <= 1_fffffffe
+ const s2 = @as(u64, ctx.h[2]) + ctx.c[2]; // s2 <= 1_fffffffe
+ const s3 = @as(u64, ctx.h[3]) + ctx.c[3]; // s3 <= 1_fffffffe
+ const s4 = @as(u64, ctx.h[4]) + ctx.c[4]; // s4 <= 5
// Local all the things!
const r0 = ctx.r[0]; // r0 <= 0fffffff
@@ -197,7 +197,7 @@ pub const Poly1305 = struct {
// check if we should subtract 2^130-5 by performing the
// corresponding carry propagation.
- const _u0 = u64(5) + ctx.h[0]; // <= 1_00000004
+ const _u0 = @as(u64, 5) + ctx.h[0]; // <= 1_00000004
const _u1 = (_u0 >> 32) + ctx.h[1]; // <= 1_00000000
const _u2 = (_u1 >> 32) + ctx.h[2]; // <= 1_00000000
const _u3 = (_u2 >> 32) + ctx.h[3]; // <= 1_00000000
diff --git a/lib/std/crypto/sha1.zig b/lib/std/crypto/sha1.zig
index c5160a1f37..c17ef2daf7 100644
--- a/lib/std/crypto/sha1.zig
+++ b/lib/std/crypto/sha1.zig
@@ -146,10 +146,10 @@ pub const Sha1 = struct {
Rp(0, 1, 2, 3, 4, 15),
};
inline for (round0a) |r| {
- s[r.i] = (u32(b[r.i * 4 + 0]) << 24) | (u32(b[r.i * 4 + 1]) << 16) | (u32(b[r.i * 4 + 2]) << 8) | (u32(b[r.i * 4 + 3]) << 0);
+ s[r.i] = (@as(u32, b[r.i * 4 + 0]) << 24) | (@as(u32, b[r.i * 4 + 1]) << 16) | (@as(u32, b[r.i * 4 + 2]) << 8) | (@as(u32, b[r.i * 4 + 3]) << 0);
- v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x5A827999 +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d]));
- v[r.b] = math.rotl(u32, v[r.b], u32(30));
+ v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x5A827999 +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d]));
+ v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round0b = comptime [_]RoundParam{
@@ -160,10 +160,10 @@ pub const Sha1 = struct {
};
inline for (round0b) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
- s[r.i & 0xf] = math.rotl(u32, t, u32(1));
+ s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
- v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x5A827999 +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d]));
- v[r.b] = math.rotl(u32, v[r.b], u32(30));
+ v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x5A827999 +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) | (~v[r.b] & v[r.d]));
+ v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round1 = comptime [_]RoundParam{
@@ -190,10 +190,10 @@ pub const Sha1 = struct {
};
inline for (round1) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
- s[r.i & 0xf] = math.rotl(u32, t, u32(1));
+ s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
- v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x6ED9EBA1 +% s[r.i & 0xf] +% (v[r.b] ^ v[r.c] ^ v[r.d]);
- v[r.b] = math.rotl(u32, v[r.b], u32(30));
+ v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x6ED9EBA1 +% s[r.i & 0xf] +% (v[r.b] ^ v[r.c] ^ v[r.d]);
+ v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round2 = comptime [_]RoundParam{
@@ -220,10 +220,10 @@ pub const Sha1 = struct {
};
inline for (round2) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
- s[r.i & 0xf] = math.rotl(u32, t, u32(1));
+ s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
- v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0x8F1BBCDC +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) ^ (v[r.b] & v[r.d]) ^ (v[r.c] & v[r.d]));
- v[r.b] = math.rotl(u32, v[r.b], u32(30));
+ v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0x8F1BBCDC +% s[r.i & 0xf] +% ((v[r.b] & v[r.c]) ^ (v[r.b] & v[r.d]) ^ (v[r.c] & v[r.d]));
+ v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
const round3 = comptime [_]RoundParam{
@@ -250,10 +250,10 @@ pub const Sha1 = struct {
};
inline for (round3) |r| {
const t = s[(r.i - 3) & 0xf] ^ s[(r.i - 8) & 0xf] ^ s[(r.i - 14) & 0xf] ^ s[(r.i - 16) & 0xf];
- s[r.i & 0xf] = math.rotl(u32, t, u32(1));
+ s[r.i & 0xf] = math.rotl(u32, t, @as(u32, 1));
- v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], u32(5)) +% 0xCA62C1D6 +% s[r.i & 0xf] +% (v[r.b] ^ v[r.c] ^ v[r.d]);
- v[r.b] = math.rotl(u32, v[r.b], u32(30));
+ v[r.e] = v[r.e] +% math.rotl(u32, v[r.a], @as(u32, 5)) +% 0xCA62C1D6 +% s[r.i & 0xf] +% (v[r.b] ^ v[r.c] ^ v[r.d]);
+ v[r.b] = math.rotl(u32, v[r.b], @as(u32, 30));
}
d.s[0] +%= v[0];
diff --git a/lib/std/crypto/sha2.zig b/lib/std/crypto/sha2.zig
index b40a39d579..77698176bd 100644
--- a/lib/std/crypto/sha2.zig
+++ b/lib/std/crypto/sha2.zig
@@ -180,13 +180,13 @@ fn Sha2_32(comptime params: Sha2Params32) type {
var i: usize = 0;
while (i < 16) : (i += 1) {
s[i] = 0;
- s[i] |= u32(b[i * 4 + 0]) << 24;
- s[i] |= u32(b[i * 4 + 1]) << 16;
- s[i] |= u32(b[i * 4 + 2]) << 8;
- s[i] |= u32(b[i * 4 + 3]) << 0;
+ s[i] |= @as(u32, b[i * 4 + 0]) << 24;
+ s[i] |= @as(u32, b[i * 4 + 1]) << 16;
+ s[i] |= @as(u32, b[i * 4 + 2]) << 8;
+ s[i] |= @as(u32, b[i * 4 + 3]) << 0;
}
while (i < 64) : (i += 1) {
- s[i] = s[i - 16] +% s[i - 7] +% (math.rotr(u32, s[i - 15], u32(7)) ^ math.rotr(u32, s[i - 15], u32(18)) ^ (s[i - 15] >> 3)) +% (math.rotr(u32, s[i - 2], u32(17)) ^ math.rotr(u32, s[i - 2], u32(19)) ^ (s[i - 2] >> 10));
+ s[i] = s[i - 16] +% s[i - 7] +% (math.rotr(u32, s[i - 15], @as(u32, 7)) ^ math.rotr(u32, s[i - 15], @as(u32, 18)) ^ (s[i - 15] >> 3)) +% (math.rotr(u32, s[i - 2], @as(u32, 17)) ^ math.rotr(u32, s[i - 2], @as(u32, 19)) ^ (s[i - 2] >> 10));
}
var v: [8]u32 = [_]u32{
@@ -267,11 +267,11 @@ fn Sha2_32(comptime params: Sha2Params32) type {
Rp256(1, 2, 3, 4, 5, 6, 7, 0, 63, 0xC67178F2),
};
inline for (round0) |r| {
- v[r.h] = v[r.h] +% (math.rotr(u32, v[r.e], u32(6)) ^ math.rotr(u32, v[r.e], u32(11)) ^ math.rotr(u32, v[r.e], u32(25))) +% (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% r.k +% s[r.i];
+ v[r.h] = v[r.h] +% (math.rotr(u32, v[r.e], @as(u32, 6)) ^ math.rotr(u32, v[r.e], @as(u32, 11)) ^ math.rotr(u32, v[r.e], @as(u32, 25))) +% (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% r.k +% s[r.i];
v[r.d] = v[r.d] +% v[r.h];
- v[r.h] = v[r.h] +% (math.rotr(u32, v[r.a], u32(2)) ^ math.rotr(u32, v[r.a], u32(13)) ^ math.rotr(u32, v[r.a], u32(22))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c]));
+ v[r.h] = v[r.h] +% (math.rotr(u32, v[r.a], @as(u32, 2)) ^ math.rotr(u32, v[r.a], @as(u32, 13)) ^ math.rotr(u32, v[r.a], @as(u32, 22))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c]));
}
d.s[0] +%= v[0];
@@ -522,17 +522,19 @@ fn Sha2_64(comptime params: Sha2Params64) type {
var i: usize = 0;
while (i < 16) : (i += 1) {
s[i] = 0;
- s[i] |= u64(b[i * 8 + 0]) << 56;
- s[i] |= u64(b[i * 8 + 1]) << 48;
- s[i] |= u64(b[i * 8 + 2]) << 40;
- s[i] |= u64(b[i * 8 + 3]) << 32;
- s[i] |= u64(b[i * 8 + 4]) << 24;
- s[i] |= u64(b[i * 8 + 5]) << 16;
- s[i] |= u64(b[i * 8 + 6]) << 8;
- s[i] |= u64(b[i * 8 + 7]) << 0;
+ s[i] |= @as(u64, b[i * 8 + 0]) << 56;
+ s[i] |= @as(u64, b[i * 8 + 1]) << 48;
+ s[i] |= @as(u64, b[i * 8 + 2]) << 40;
+ s[i] |= @as(u64, b[i * 8 + 3]) << 32;
+ s[i] |= @as(u64, b[i * 8 + 4]) << 24;
+ s[i] |= @as(u64, b[i * 8 + 5]) << 16;
+ s[i] |= @as(u64, b[i * 8 + 6]) << 8;
+ s[i] |= @as(u64, b[i * 8 + 7]) << 0;
}
while (i < 80) : (i += 1) {
- s[i] = s[i - 16] +% s[i - 7] +% (math.rotr(u64, s[i - 15], u64(1)) ^ math.rotr(u64, s[i - 15], u64(8)) ^ (s[i - 15] >> 7)) +% (math.rotr(u64, s[i - 2], u64(19)) ^ math.rotr(u64, s[i - 2], u64(61)) ^ (s[i - 2] >> 6));
+ s[i] = s[i - 16] +% s[i - 7] +%
+ (math.rotr(u64, s[i - 15], @as(u64, 1)) ^ math.rotr(u64, s[i - 15], @as(u64, 8)) ^ (s[i - 15] >> 7)) +%
+ (math.rotr(u64, s[i - 2], @as(u64, 19)) ^ math.rotr(u64, s[i - 2], @as(u64, 61)) ^ (s[i - 2] >> 6));
}
var v: [8]u64 = [_]u64{
@@ -629,11 +631,11 @@ fn Sha2_64(comptime params: Sha2Params64) type {
Rp512(1, 2, 3, 4, 5, 6, 7, 0, 79, 0x6C44198C4A475817),
};
inline for (round0) |r| {
- v[r.h] = v[r.h] +% (math.rotr(u64, v[r.e], u64(14)) ^ math.rotr(u64, v[r.e], u64(18)) ^ math.rotr(u64, v[r.e], u64(41))) +% (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% r.k +% s[r.i];
+ v[r.h] = v[r.h] +% (math.rotr(u64, v[r.e], @as(u64, 14)) ^ math.rotr(u64, v[r.e], @as(u64, 18)) ^ math.rotr(u64, v[r.e], @as(u64, 41))) +% (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% r.k +% s[r.i];
v[r.d] = v[r.d] +% v[r.h];
- v[r.h] = v[r.h] +% (math.rotr(u64, v[r.a], u64(28)) ^ math.rotr(u64, v[r.a], u64(34)) ^ math.rotr(u64, v[r.a], u64(39))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c]));
+ v[r.h] = v[r.h] +% (math.rotr(u64, v[r.a], @as(u64, 28)) ^ math.rotr(u64, v[r.a], @as(u64, 34)) ^ math.rotr(u64, v[r.a], @as(u64, 39))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c]));
}
d.s[0] +%= v[0];
diff --git a/lib/std/crypto/sha3.zig b/lib/std/crypto/sha3.zig
index 659e7a254f..d417ef07e2 100644
--- a/lib/std/crypto/sha3.zig
+++ b/lib/std/crypto/sha3.zig
@@ -133,7 +133,7 @@ fn keccak_f(comptime F: usize, d: []u8) void {
}
x = 0;
inline while (x < 5) : (x += 1) {
- t[0] = c[M5[x + 4]] ^ math.rotl(u64, c[M5[x + 1]], usize(1));
+ t[0] = c[M5[x + 4]] ^ math.rotl(u64, c[M5[x + 1]], @as(usize, 1));
y = 0;
inline while (y < 5) : (y += 1) {
s[x + y * 5] ^= t[0];
diff --git a/lib/std/crypto/x25519.zig b/lib/std/crypto/x25519.zig
index 7f9220c3f4..cd908b0868 100644
--- a/lib/std/crypto/x25519.zig
+++ b/lib/std/crypto/x25519.zig
@@ -199,9 +199,9 @@ const Fe = struct {
inline fn carryRound(c: []i64, t: []i64, comptime i: comptime_int, comptime shift: comptime_int, comptime mult: comptime_int) void {
const j = (i + 1) % 10;
- c[i] = (t[i] + (i64(1) << shift)) >> (shift + 1);
+ c[i] = (t[i] + (@as(i64, 1) << shift)) >> (shift + 1);
t[j] += c[i] * mult;
- t[i] -= c[i] * (i64(1) << (shift + 1));
+ t[i] -= c[i] * (@as(i64, 1) << (shift + 1));
}
fn carry1(h: *Fe, t: []i64) void {
@@ -256,15 +256,15 @@ const Fe = struct {
var t: [10]i64 = undefined;
t[0] = readIntSliceLittle(u32, s[0..4]);
- t[1] = u32(readIntSliceLittle(u24, s[4..7])) << 6;
- t[2] = u32(readIntSliceLittle(u24, s[7..10])) << 5;
- t[3] = u32(readIntSliceLittle(u24, s[10..13])) << 3;
- t[4] = u32(readIntSliceLittle(u24, s[13..16])) << 2;
+ t[1] = @as(u32, readIntSliceLittle(u24, s[4..7])) << 6;
+ t[2] = @as(u32, readIntSliceLittle(u24, s[7..10])) << 5;
+ t[3] = @as(u32, readIntSliceLittle(u24, s[10..13])) << 3;
+ t[4] = @as(u32, readIntSliceLittle(u24, s[13..16])) << 2;
t[5] = readIntSliceLittle(u32, s[16..20]);
- t[6] = u32(readIntSliceLittle(u24, s[20..23])) << 7;
- t[7] = u32(readIntSliceLittle(u24, s[23..26])) << 5;
- t[8] = u32(readIntSliceLittle(u24, s[26..29])) << 4;
- t[9] = (u32(readIntSliceLittle(u24, s[29..32])) & 0x7fffff) << 2;
+ t[6] = @as(u32, readIntSliceLittle(u24, s[20..23])) << 7;
+ t[7] = @as(u32, readIntSliceLittle(u24, s[23..26])) << 5;
+ t[8] = @as(u32, readIntSliceLittle(u24, s[26..29])) << 4;
+ t[9] = (@as(u32, readIntSliceLittle(u24, s[29..32])) & 0x7fffff) << 2;
carry1(h, t[0..]);
}
@@ -273,7 +273,7 @@ const Fe = struct {
var t: [10]i64 = undefined;
for (t[0..]) |_, i| {
- t[i] = i64(f.b[i]) * g;
+ t[i] = @as(i64, f.b[i]) * g;
}
carry1(h, t[0..]);
@@ -305,16 +305,16 @@ const Fe = struct {
// t's become h
var t: [10]i64 = undefined;
- t[0] = f[0] * i64(g[0]) + F[1] * i64(G[9]) + f[2] * i64(G[8]) + F[3] * i64(G[7]) + f[4] * i64(G[6]) + F[5] * i64(G[5]) + f[6] * i64(G[4]) + F[7] * i64(G[3]) + f[8] * i64(G[2]) + F[9] * i64(G[1]);
- t[1] = f[0] * i64(g[1]) + f[1] * i64(g[0]) + f[2] * i64(G[9]) + f[3] * i64(G[8]) + f[4] * i64(G[7]) + f[5] * i64(G[6]) + f[6] * i64(G[5]) + f[7] * i64(G[4]) + f[8] * i64(G[3]) + f[9] * i64(G[2]);
- t[2] = f[0] * i64(g[2]) + F[1] * i64(g[1]) + f[2] * i64(g[0]) + F[3] * i64(G[9]) + f[4] * i64(G[8]) + F[5] * i64(G[7]) + f[6] * i64(G[6]) + F[7] * i64(G[5]) + f[8] * i64(G[4]) + F[9] * i64(G[3]);
- t[3] = f[0] * i64(g[3]) + f[1] * i64(g[2]) + f[2] * i64(g[1]) + f[3] * i64(g[0]) + f[4] * i64(G[9]) + f[5] * i64(G[8]) + f[6] * i64(G[7]) + f[7] * i64(G[6]) + f[8] * i64(G[5]) + f[9] * i64(G[4]);
- t[4] = f[0] * i64(g[4]) + F[1] * i64(g[3]) + f[2] * i64(g[2]) + F[3] * i64(g[1]) + f[4] * i64(g[0]) + F[5] * i64(G[9]) + f[6] * i64(G[8]) + F[7] * i64(G[7]) + f[8] * i64(G[6]) + F[9] * i64(G[5]);
- t[5] = f[0] * i64(g[5]) + f[1] * i64(g[4]) + f[2] * i64(g[3]) + f[3] * i64(g[2]) + f[4] * i64(g[1]) + f[5] * i64(g[0]) + f[6] * i64(G[9]) + f[7] * i64(G[8]) + f[8] * i64(G[7]) + f[9] * i64(G[6]);
- t[6] = f[0] * i64(g[6]) + F[1] * i64(g[5]) + f[2] * i64(g[4]) + F[3] * i64(g[3]) + f[4] * i64(g[2]) + F[5] * i64(g[1]) + f[6] * i64(g[0]) + F[7] * i64(G[9]) + f[8] * i64(G[8]) + F[9] * i64(G[7]);
- t[7] = f[0] * i64(g[7]) + f[1] * i64(g[6]) + f[2] * i64(g[5]) + f[3] * i64(g[4]) + f[4] * i64(g[3]) + f[5] * i64(g[2]) + f[6] * i64(g[1]) + f[7] * i64(g[0]) + f[8] * i64(G[9]) + f[9] * i64(G[8]);
- t[8] = f[0] * i64(g[8]) + F[1] * i64(g[7]) + f[2] * i64(g[6]) + F[3] * i64(g[5]) + f[4] * i64(g[4]) + F[5] * i64(g[3]) + f[6] * i64(g[2]) + F[7] * i64(g[1]) + f[8] * i64(g[0]) + F[9] * i64(G[9]);
- t[9] = f[0] * i64(g[9]) + f[1] * i64(g[8]) + f[2] * i64(g[7]) + f[3] * i64(g[6]) + f[4] * i64(g[5]) + f[5] * i64(g[4]) + f[6] * i64(g[3]) + f[7] * i64(g[2]) + f[8] * i64(g[1]) + f[9] * i64(g[0]);
+ t[0] = f[0] * @as(i64, g[0]) + F[1] * @as(i64, G[9]) + f[2] * @as(i64, G[8]) + F[3] * @as(i64, G[7]) + f[4] * @as(i64, G[6]) + F[5] * @as(i64, G[5]) + f[6] * @as(i64, G[4]) + F[7] * @as(i64, G[3]) + f[8] * @as(i64, G[2]) + F[9] * @as(i64, G[1]);
+ t[1] = f[0] * @as(i64, g[1]) + f[1] * @as(i64, g[0]) + f[2] * @as(i64, G[9]) + f[3] * @as(i64, G[8]) + f[4] * @as(i64, G[7]) + f[5] * @as(i64, G[6]) + f[6] * @as(i64, G[5]) + f[7] * @as(i64, G[4]) + f[8] * @as(i64, G[3]) + f[9] * @as(i64, G[2]);
+ t[2] = f[0] * @as(i64, g[2]) + F[1] * @as(i64, g[1]) + f[2] * @as(i64, g[0]) + F[3] * @as(i64, G[9]) + f[4] * @as(i64, G[8]) + F[5] * @as(i64, G[7]) + f[6] * @as(i64, G[6]) + F[7] * @as(i64, G[5]) + f[8] * @as(i64, G[4]) + F[9] * @as(i64, G[3]);
+ t[3] = f[0] * @as(i64, g[3]) + f[1] * @as(i64, g[2]) + f[2] * @as(i64, g[1]) + f[3] * @as(i64, g[0]) + f[4] * @as(i64, G[9]) + f[5] * @as(i64, G[8]) + f[6] * @as(i64, G[7]) + f[7] * @as(i64, G[6]) + f[8] * @as(i64, G[5]) + f[9] * @as(i64, G[4]);
+ t[4] = f[0] * @as(i64, g[4]) + F[1] * @as(i64, g[3]) + f[2] * @as(i64, g[2]) + F[3] * @as(i64, g[1]) + f[4] * @as(i64, g[0]) + F[5] * @as(i64, G[9]) + f[6] * @as(i64, G[8]) + F[7] * @as(i64, G[7]) + f[8] * @as(i64, G[6]) + F[9] * @as(i64, G[5]);
+ t[5] = f[0] * @as(i64, g[5]) + f[1] * @as(i64, g[4]) + f[2] * @as(i64, g[3]) + f[3] * @as(i64, g[2]) + f[4] * @as(i64, g[1]) + f[5] * @as(i64, g[0]) + f[6] * @as(i64, G[9]) + f[7] * @as(i64, G[8]) + f[8] * @as(i64, G[7]) + f[9] * @as(i64, G[6]);
+ t[6] = f[0] * @as(i64, g[6]) + F[1] * @as(i64, g[5]) + f[2] * @as(i64, g[4]) + F[3] * @as(i64, g[3]) + f[4] * @as(i64, g[2]) + F[5] * @as(i64, g[1]) + f[6] * @as(i64, g[0]) + F[7] * @as(i64, G[9]) + f[8] * @as(i64, G[8]) + F[9] * @as(i64, G[7]);
+ t[7] = f[0] * @as(i64, g[7]) + f[1] * @as(i64, g[6]) + f[2] * @as(i64, g[5]) + f[3] * @as(i64, g[4]) + f[4] * @as(i64, g[3]) + f[5] * @as(i64, g[2]) + f[6] * @as(i64, g[1]) + f[7] * @as(i64, g[0]) + f[8] * @as(i64, G[9]) + f[9] * @as(i64, G[8]);
+ t[8] = f[0] * @as(i64, g[8]) + F[1] * @as(i64, g[7]) + f[2] * @as(i64, g[6]) + F[3] * @as(i64, g[5]) + f[4] * @as(i64, g[4]) + F[5] * @as(i64, g[3]) + f[6] * @as(i64, g[2]) + F[7] * @as(i64, g[1]) + f[8] * @as(i64, g[0]) + F[9] * @as(i64, G[9]);
+ t[9] = f[0] * @as(i64, g[9]) + f[1] * @as(i64, g[8]) + f[2] * @as(i64, g[7]) + f[3] * @as(i64, g[6]) + f[4] * @as(i64, g[5]) + f[5] * @as(i64, g[4]) + f[6] * @as(i64, g[3]) + f[7] * @as(i64, g[2]) + f[8] * @as(i64, g[1]) + f[9] * @as(i64, g[0]);
carry2(h, t[0..]);
}
@@ -348,16 +348,16 @@ const Fe = struct {
var t: [10]i64 = undefined;
- t[0] = f0 * i64(f0) + f1_2 * i64(f9_38) + f2_2 * i64(f8_19) + f3_2 * i64(f7_38) + f4_2 * i64(f6_19) + f5 * i64(f5_38);
- t[1] = f0_2 * i64(f1) + f2 * i64(f9_38) + f3_2 * i64(f8_19) + f4 * i64(f7_38) + f5_2 * i64(f6_19);
- t[2] = f0_2 * i64(f2) + f1_2 * i64(f1) + f3_2 * i64(f9_38) + f4_2 * i64(f8_19) + f5_2 * i64(f7_38) + f6 * i64(f6_19);
- t[3] = f0_2 * i64(f3) + f1_2 * i64(f2) + f4 * i64(f9_38) + f5_2 * i64(f8_19) + f6 * i64(f7_38);
- t[4] = f0_2 * i64(f4) + f1_2 * i64(f3_2) + f2 * i64(f2) + f5_2 * i64(f9_38) + f6_2 * i64(f8_19) + f7 * i64(f7_38);
- t[5] = f0_2 * i64(f5) + f1_2 * i64(f4) + f2_2 * i64(f3) + f6 * i64(f9_38) + f7_2 * i64(f8_19);
- t[6] = f0_2 * i64(f6) + f1_2 * i64(f5_2) + f2_2 * i64(f4) + f3_2 * i64(f3) + f7_2 * i64(f9_38) + f8 * i64(f8_19);
- t[7] = f0_2 * i64(f7) + f1_2 * i64(f6) + f2_2 * i64(f5) + f3_2 * i64(f4) + f8 * i64(f9_38);
- t[8] = f0_2 * i64(f8) + f1_2 * i64(f7_2) + f2_2 * i64(f6) + f3_2 * i64(f5_2) + f4 * i64(f4) + f9 * i64(f9_38);
- t[9] = f0_2 * i64(f9) + f1_2 * i64(f8) + f2_2 * i64(f7) + f3_2 * i64(f6) + f4 * i64(f5_2);
+ t[0] = f0 * @as(i64, f0) + f1_2 * @as(i64, f9_38) + f2_2 * @as(i64, f8_19) + f3_2 * @as(i64, f7_38) + f4_2 * @as(i64, f6_19) + f5 * @as(i64, f5_38);
+ t[1] = f0_2 * @as(i64, f1) + f2 * @as(i64, f9_38) + f3_2 * @as(i64, f8_19) + f4 * @as(i64, f7_38) + f5_2 * @as(i64, f6_19);
+ t[2] = f0_2 * @as(i64, f2) + f1_2 * @as(i64, f1) + f3_2 * @as(i64, f9_38) + f4_2 * @as(i64, f8_19) + f5_2 * @as(i64, f7_38) + f6 * @as(i64, f6_19);
+ t[3] = f0_2 * @as(i64, f3) + f1_2 * @as(i64, f2) + f4 * @as(i64, f9_38) + f5_2 * @as(i64, f8_19) + f6 * @as(i64, f7_38);
+ t[4] = f0_2 * @as(i64, f4) + f1_2 * @as(i64, f3_2) + f2 * @as(i64, f2) + f5_2 * @as(i64, f9_38) + f6_2 * @as(i64, f8_19) + f7 * @as(i64, f7_38);
+ t[5] = f0_2 * @as(i64, f5) + f1_2 * @as(i64, f4) + f2_2 * @as(i64, f3) + f6 * @as(i64, f9_38) + f7_2 * @as(i64, f8_19);
+ t[6] = f0_2 * @as(i64, f6) + f1_2 * @as(i64, f5_2) + f2_2 * @as(i64, f4) + f3_2 * @as(i64, f3) + f7_2 * @as(i64, f9_38) + f8 * @as(i64, f8_19);
+ t[7] = f0_2 * @as(i64, f7) + f1_2 * @as(i64, f6) + f2_2 * @as(i64, f5) + f3_2 * @as(i64, f4) + f8 * @as(i64, f9_38);
+ t[8] = f0_2 * @as(i64, f8) + f1_2 * @as(i64, f7_2) + f2_2 * @as(i64, f6) + f3_2 * @as(i64, f5_2) + f4 * @as(i64, f4) + f9 * @as(i64, f9_38);
+ t[9] = f0_2 * @as(i64, f9) + f1_2 * @as(i64, f8) + f2_2 * @as(i64, f7) + f3_2 * @as(i64, f6) + f4 * @as(i64, f5_2);
carry2(h, t[0..]);
}
@@ -500,7 +500,7 @@ const Fe = struct {
if (i + 1 < 10) {
t[i + 1] += c[i];
}
- t[i] -= c[i] * (i32(1) << shift);
+ t[i] -= c[i] * (@as(i32, 1) << shift);
}
fn toBytes(s: []u8, h: *const Fe) void {
@@ -511,7 +511,7 @@ const Fe = struct {
t[i] = h.b[i];
}
- var q = (19 * t[9] + ((i32(1) << 24))) >> 25;
+ var q = (19 * t[9] + ((@as(i32, 1) << 24))) >> 25;
{
var i: usize = 0;
while (i < 5) : (i += 1) {
diff --git a/lib/std/debug.zig b/lib/std/debug.zig
index 61b492c20d..7698443ce8 100644
--- a/lib/std/debug.zig
+++ b/lib/std/debug.zig
@@ -45,18 +45,19 @@ var stderr_file_out_stream: File.OutStream = undefined;
var stderr_stream: ?*io.OutStream(File.WriteError) = null;
var stderr_mutex = std.Mutex.init();
+
pub fn warn(comptime fmt: []const u8, args: ...) void {
const held = stderr_mutex.acquire();
defer held.release();
- const stderr = getStderrStream() catch return;
+ const stderr = getStderrStream();
stderr.print(fmt, args) catch return;
}
-pub fn getStderrStream() !*io.OutStream(File.WriteError) {
+pub fn getStderrStream() *io.OutStream(File.WriteError) {
if (stderr_stream) |st| {
return st;
} else {
- stderr_file = try io.getStdErr();
+ stderr_file = io.getStdErr();
stderr_file_out_stream = stderr_file.outStream();
const st = &stderr_file_out_stream.stream;
stderr_stream = st;
@@ -64,6 +65,10 @@ pub fn getStderrStream() !*io.OutStream(File.WriteError) {
}
}
+pub fn getStderrMutex() *std.Mutex {
+ return &stderr_mutex;
+}
+
/// TODO multithreaded awareness
var self_debug_info: ?DebugInfo = null;
@@ -85,7 +90,7 @@ fn wantTtyColor() bool {
/// Tries to print the current stack trace to stderr, unbuffered, and ignores any error returned.
/// TODO multithreaded awareness
pub fn dumpCurrentStackTrace(start_addr: ?usize) void {
- const stderr = getStderrStream() catch return;
+ const stderr = getStderrStream();
if (builtin.strip_debug_info) {
stderr.print("Unable to dump stack trace: debug info stripped\n") catch return;
return;
@@ -104,7 +109,7 @@ pub fn dumpCurrentStackTrace(start_addr: ?usize) void {
/// unbuffered, and ignores any error returned.
/// TODO multithreaded awareness
pub fn dumpStackTraceFromBase(bp: usize, ip: usize) void {
- const stderr = getStderrStream() catch return;
+ const stderr = getStderrStream();
if (builtin.strip_debug_info) {
stderr.print("Unable to dump stack trace: debug info stripped\n") catch return;
return;
@@ -177,7 +182,7 @@ pub fn captureStackTrace(first_address: ?usize, stack_trace: *builtin.StackTrace
/// Tries to print a stack trace to stderr, unbuffered, and ignores any error returned.
/// TODO multithreaded awareness
pub fn dumpStackTrace(stack_trace: builtin.StackTrace) void {
- const stderr = getStderrStream() catch return;
+ const stderr = getStderrStream();
if (builtin.strip_debug_info) {
stderr.print("Unable to dump stack trace: debug info stripped\n") catch return;
return;
@@ -232,7 +237,7 @@ pub fn panicExtra(trace: ?*const builtin.StackTrace, first_trace_addr: ?usize, c
// which first called panic can finish printing a stack trace.
os.abort();
}
- const stderr = getStderrStream() catch os.abort();
+ const stderr = getStderrStream();
stderr.print(format ++ "\n", args) catch os.abort();
if (trace) |t| {
dumpStackTrace(t.*);
@@ -1003,7 +1008,7 @@ fn readSparseBitVector(stream: var, allocator: *mem.Allocator) ![]usize {
const word = try stream.readIntLittle(u32);
var bit_i: u5 = 0;
while (true) : (bit_i += 1) {
- if (word & (u32(1) << bit_i) != 0) {
+ if (word & (@as(u32, 1) << bit_i) != 0) {
try list.append(word_i * 32 + bit_i);
}
if (bit_i == maxInt(u5)) break;
@@ -1551,13 +1556,14 @@ fn parseFormValueConstant(allocator: *mem.Allocator, in_stream: var, signed: boo
// TODO the noasyncs here are workarounds
fn parseFormValueDwarfOffsetSize(in_stream: var, is_64: bool) !u64 {
- return if (is_64) try noasync in_stream.readIntLittle(u64) else u64(try noasync in_stream.readIntLittle(u32));
+ return if (is_64) try noasync in_stream.readIntLittle(u64) else @as(u64, try noasync in_stream.readIntLittle(u32));
}
// TODO the noasyncs here are workarounds
fn parseFormValueTargetAddrSize(in_stream: var) !u64 {
if (@sizeOf(usize) == 4) {
- return u64(try noasync in_stream.readIntLittle(u32));
+ // TODO this cast should not be needed
+ return @as(u64, try noasync in_stream.readIntLittle(u32));
} else if (@sizeOf(usize) == 8) {
return noasync in_stream.readIntLittle(u64);
} else {
@@ -1705,7 +1711,12 @@ fn getLineNumberInfoMacOs(di: *DebugInfo, symbol: MachoSymbol, target_address: u
const ofile_path = mem.toSliceConst(u8, di.strings.ptr + ofile.n_strx);
gop.kv.value = MachOFile{
- .bytes = try std.io.readFileAllocAligned(di.ofiles.allocator, ofile_path, @alignOf(macho.mach_header_64)),
+ .bytes = try std.fs.Dir.cwd().readFileAllocAligned(
+ di.ofiles.allocator,
+ ofile_path,
+ maxInt(usize),
+ @alignOf(macho.mach_header_64),
+ ),
.sect_debug_info = null,
.sect_debug_line = null,
};
@@ -1841,7 +1852,7 @@ fn getLineNumberInfoMacOs(di: *DebugInfo, symbol: MachoSymbol, target_address: u
// special opcodes
const adjusted_opcode = opcode - opcode_base;
const inc_addr = minimum_instruction_length * (adjusted_opcode / line_range);
- const inc_line = i32(line_base) + i32(adjusted_opcode % line_range);
+ const inc_line = @as(i32, line_base) + @as(i32, adjusted_opcode % line_range);
prog.line += inc_line;
prog.address += inc_addr;
if (try prog.checkLineMatch()) |info| return info;
@@ -1908,7 +1919,7 @@ fn getLineNumberInfoDwarf(di: *DwarfInfo, compile_unit: CompileUnit, target_addr
if (unit_length == 0) {
return error.MissingDebugInfo;
}
- const next_offset = unit_length + (if (is_64) usize(12) else usize(4));
+ const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));
const version = try di.dwarf_in_stream.readInt(u16, di.endian);
// TODO support 3 and 5
@@ -2007,7 +2018,7 @@ fn getLineNumberInfoDwarf(di: *DwarfInfo, compile_unit: CompileUnit, target_addr
// special opcodes
const adjusted_opcode = opcode - opcode_base;
const inc_addr = minimum_instruction_length * (adjusted_opcode / line_range);
- const inc_line = i32(line_base) + i32(adjusted_opcode % line_range);
+ const inc_line = @as(i32, line_base) + @as(i32, adjusted_opcode % line_range);
prog.line += inc_line;
prog.address += inc_addr;
if (try prog.checkLineMatch()) |info| return info;
@@ -2088,7 +2099,7 @@ fn scanAllFunctions(di: *DwarfInfo) !void {
var is_64: bool = undefined;
const unit_length = try readInitialLength(@typeOf(di.dwarf_in_stream.readFn).ReturnType.ErrorSet, di.dwarf_in_stream, &is_64);
if (unit_length == 0) return;
- const next_offset = unit_length + (if (is_64) usize(12) else usize(4));
+ const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));
const version = try di.dwarf_in_stream.readInt(u16, di.endian);
if (version < 2 or version > 5) return error.InvalidDebugInfo;
@@ -2190,7 +2201,7 @@ fn scanAllCompileUnits(di: *DwarfInfo) !void {
var is_64: bool = undefined;
const unit_length = try readInitialLength(@typeOf(di.dwarf_in_stream.readFn).ReturnType.ErrorSet, di.dwarf_in_stream, &is_64);
if (unit_length == 0) return;
- const next_offset = unit_length + (if (is_64) usize(12) else usize(4));
+ const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));
const version = try di.dwarf_in_stream.readInt(u16, di.endian);
if (version < 2 or version > 5) return error.InvalidDebugInfo;
@@ -2307,7 +2318,8 @@ fn readInitialLengthMem(ptr: *[*]const u8, is_64: *bool) !u64 {
} else {
if (first_32_bits >= 0xfffffff0) return error.InvalidDebugInfo;
ptr.* += 4;
- return u64(first_32_bits);
+ // TODO this cast should not be needed
+ return @as(u64, first_32_bits);
}
}
@@ -2324,7 +2336,8 @@ fn readInitialLength(comptime E: type, in_stream: *io.InStream(E), is_64: *bool)
return in_stream.readIntLittle(u64);
} else {
if (first_32_bits >= 0xfffffff0) return error.InvalidDebugInfo;
- return u64(first_32_bits);
+ // TODO this cast should not be needed
+ return @as(u64, first_32_bits);
}
}
diff --git a/lib/std/debug/leb128.zig b/lib/std/debug/leb128.zig
index cb59c5b0d2..dba57e1f97 100644
--- a/lib/std/debug/leb128.zig
+++ b/lib/std/debug/leb128.zig
@@ -62,13 +62,13 @@ pub fn readILEB128(comptime T: type, in_stream: var) !T {
var shift: usize = 0;
while (true) {
- const byte = u8(try in_stream.readByte());
+ const byte: u8 = try in_stream.readByte();
if (shift > T.bit_count)
return error.Overflow;
var operand: UT = undefined;
- if (@shlWithOverflow(UT, UT(byte & 0x7f), @intCast(ShiftT, shift), &operand)) {
+ if (@shlWithOverflow(UT, @as(UT, byte & 0x7f), @intCast(ShiftT, shift), &operand)) {
if (byte != 0x7f)
return error.Overflow;
}
@@ -101,7 +101,7 @@ pub fn readILEB128Mem(comptime T: type, ptr: *[*]const u8) !T {
return error.Overflow;
var operand: UT = undefined;
- if (@shlWithOverflow(UT, UT(byte & 0x7f), @intCast(ShiftT, shift), &operand)) {
+ if (@shlWithOverflow(UT, @as(UT, byte & 0x7f), @intCast(ShiftT, shift), &operand)) {
if (byte != 0x7f)
return error.Overflow;
}
diff --git a/lib/std/dynamic_library.zig b/lib/std/dynamic_library.zig
index 3413788019..0e8792ca90 100644
--- a/lib/std/dynamic_library.zig
+++ b/lib/std/dynamic_library.zig
@@ -215,8 +215,8 @@ pub const ElfLib = struct {
var i: usize = 0;
while (i < self.hashtab[1]) : (i += 1) {
- if (0 == (u32(1) << @intCast(u5, self.syms[i].st_info & 0xf) & OK_TYPES)) continue;
- if (0 == (u32(1) << @intCast(u5, self.syms[i].st_info >> 4) & OK_BINDS)) continue;
+ if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info & 0xf) & OK_TYPES)) continue;
+ if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info >> 4) & OK_BINDS)) continue;
if (0 == self.syms[i].st_shndx) continue;
if (!mem.eql(u8, name, mem.toSliceConst(u8, self.strings + self.syms[i].st_name))) continue;
if (maybe_versym) |versym| {
diff --git a/lib/std/elf.zig b/lib/std/elf.zig
index b3aea3e5c6..3bb4054bfe 100644
--- a/lib/std/elf.zig
+++ b/lib/std/elf.zig
@@ -441,9 +441,9 @@ pub const Elf = struct {
elf.program_header_offset = try in.readInt(u64, elf.endian);
elf.section_header_offset = try in.readInt(u64, elf.endian);
} else {
- elf.entry_addr = u64(try in.readInt(u32, elf.endian));
- elf.program_header_offset = u64(try in.readInt(u32, elf.endian));
- elf.section_header_offset = u64(try in.readInt(u32, elf.endian));
+ elf.entry_addr = @as(u64, try in.readInt(u32, elf.endian));
+ elf.program_header_offset = @as(u64, try in.readInt(u32, elf.endian));
+ elf.section_header_offset = @as(u64, try in.readInt(u32, elf.endian));
}
// skip over flags
@@ -458,13 +458,13 @@ pub const Elf = struct {
const ph_entry_count = try in.readInt(u16, elf.endian);
const sh_entry_size = try in.readInt(u16, elf.endian);
const sh_entry_count = try in.readInt(u16, elf.endian);
- elf.string_section_index = usize(try in.readInt(u16, elf.endian));
+ elf.string_section_index = @as(usize, try in.readInt(u16, elf.endian));
if (elf.string_section_index >= sh_entry_count) return error.InvalidFormat;
- const sh_byte_count = u64(sh_entry_size) * u64(sh_entry_count);
+ const sh_byte_count = @as(u64, sh_entry_size) * @as(u64, sh_entry_count);
const end_sh = try math.add(u64, elf.section_header_offset, sh_byte_count);
- const ph_byte_count = u64(ph_entry_size) * u64(ph_entry_count);
+ const ph_byte_count = @as(u64, ph_entry_size) * @as(u64, ph_entry_count);
const end_ph = try math.add(u64, elf.program_header_offset, ph_byte_count);
const stream_end = try seekable_stream.getEndPos();
@@ -499,14 +499,14 @@ pub const Elf = struct {
// TODO (multiple occurrences) allow implicit cast from %u32 -> %u64 ?
elf_section.name = try in.readInt(u32, elf.endian);
elf_section.sh_type = try in.readInt(u32, elf.endian);
- elf_section.flags = u64(try in.readInt(u32, elf.endian));
- elf_section.addr = u64(try in.readInt(u32, elf.endian));
- elf_section.offset = u64(try in.readInt(u32, elf.endian));
- elf_section.size = u64(try in.readInt(u32, elf.endian));
+ elf_section.flags = @as(u64, try in.readInt(u32, elf.endian));
+ elf_section.addr = @as(u64, try in.readInt(u32, elf.endian));
+ elf_section.offset = @as(u64, try in.readInt(u32, elf.endian));
+ elf_section.size = @as(u64, try in.readInt(u32, elf.endian));
elf_section.link = try in.readInt(u32, elf.endian);
elf_section.info = try in.readInt(u32, elf.endian);
- elf_section.addr_align = u64(try in.readInt(u32, elf.endian));
- elf_section.ent_size = u64(try in.readInt(u32, elf.endian));
+ elf_section.addr_align = @as(u64, try in.readInt(u32, elf.endian));
+ elf_section.ent_size = @as(u64, try in.readInt(u32, elf.endian));
}
}
diff --git a/lib/std/event/channel.zig b/lib/std/event/channel.zig
index 2ea99d234d..ac5a65e1b0 100644
--- a/lib/std/event/channel.zig
+++ b/lib/std/event/channel.zig
@@ -161,7 +161,7 @@ pub fn Channel(comptime T: type) type {
fn dispatch(self: *SelfChannel) void {
// set the "need dispatch" flag
- _ = @atomicRmw(u8, &self.need_dispatch, .Xchg, 1, .SeqCst);
+ @atomicStore(u8, &self.need_dispatch, 1, .SeqCst);
lock: while (true) {
// set the lock flag
@@ -169,7 +169,7 @@ pub fn Channel(comptime T: type) type {
if (prev_lock != 0) return;
// clear the need_dispatch flag since we're about to do it
- _ = @atomicRmw(u8, &self.need_dispatch, .Xchg, 0, .SeqCst);
+ @atomicStore(u8, &self.need_dispatch, 0, .SeqCst);
while (true) {
one_dispatch: {
diff --git a/lib/std/event/fs.zig b/lib/std/event/fs.zig
index d86bcbaed5..eef5cfae7d 100644
--- a/lib/std/event/fs.zig
+++ b/lib/std/event/fs.zig
@@ -328,11 +328,11 @@ pub fn preadWindows(loop: *Loop, fd: fd_t, data: []u8, offset: u64) !usize {
windows.ERROR.IO_PENDING => unreachable,
windows.ERROR.OPERATION_ABORTED => return error.OperationAborted,
windows.ERROR.BROKEN_PIPE => return error.BrokenPipe,
- windows.ERROR.HANDLE_EOF => return usize(bytes_transferred),
+ windows.ERROR.HANDLE_EOF => return @as(usize, bytes_transferred),
else => |err| return windows.unexpectedError(err),
}
}
- return usize(bytes_transferred);
+ return @as(usize, bytes_transferred);
}
/// iovecs must live until preadv frame completes
@@ -415,7 +415,8 @@ pub fn openPosix(
pub fn openRead(loop: *Loop, path: []const u8) File.OpenError!fd_t {
switch (builtin.os) {
.macosx, .linux, .freebsd, .netbsd, .dragonfly => {
- const flags = os.O_LARGEFILE | os.O_RDONLY | os.O_CLOEXEC;
+ const O_LARGEFILE = if (@hasDecl(os, "O_LARGEFILE")) os.O_LARGEFILE else 0;
+ const flags = O_LARGEFILE | os.O_RDONLY | os.O_CLOEXEC;
return openPosix(loop, path, flags, File.default_mode);
},
@@ -448,7 +449,8 @@ pub fn openWriteMode(loop: *Loop, path: []const u8, mode: File.Mode) File.OpenEr
.netbsd,
.dragonfly,
=> {
- const flags = os.O_LARGEFILE | os.O_WRONLY | os.O_CREAT | os.O_CLOEXEC | os.O_TRUNC;
+ const O_LARGEFILE = if (@hasDecl(os, "O_LARGEFILE")) os.O_LARGEFILE else 0;
+ const flags = O_LARGEFILE | os.O_WRONLY | os.O_CREAT | os.O_CLOEXEC | os.O_TRUNC;
return openPosix(loop, path, flags, File.default_mode);
},
.windows => return windows.CreateFile(
@@ -472,7 +474,8 @@ pub fn openReadWrite(
) File.OpenError!fd_t {
switch (builtin.os) {
.macosx, .linux, .freebsd, .netbsd, .dragonfly => {
- const flags = os.O_LARGEFILE | os.O_RDWR | os.O_CREAT | os.O_CLOEXEC;
+ const O_LARGEFILE = if (@hasDecl(os, "O_LARGEFILE")) os.O_LARGEFILE else 0;
+ const flags = O_LARGEFILE | os.O_RDWR | os.O_CREAT | os.O_CLOEXEC;
return openPosix(loop, path, flags, mode);
},
diff --git a/lib/std/event/future.zig b/lib/std/event/future.zig
index 356d9cac79..5261db990c 100644
--- a/lib/std/event/future.zig
+++ b/lib/std/event/future.zig
@@ -12,12 +12,13 @@ pub fn Future(comptime T: type) type {
return struct {
lock: Lock,
data: T,
+ available: Available,
- /// TODO make this an enum
- /// 0 - not started
- /// 1 - started
- /// 2 - finished
- available: u8,
+ const Available = enum(u8) {
+ NotStarted,
+ Started,
+ Finished,
+ };
const Self = @This();
const Queue = std.atomic.Queue(anyframe);
@@ -34,7 +35,7 @@ pub fn Future(comptime T: type) type {
/// available.
/// Thread-safe.
pub async fn get(self: *Self) *T {
- if (@atomicLoad(u8, &self.available, .SeqCst) == 2) {
+ if (@atomicLoad(Available, &self.available, .SeqCst) == .Finished) {
return &self.data;
}
const held = self.lock.acquire();
@@ -46,7 +47,7 @@ pub fn Future(comptime T: type) type {
/// Gets the data without waiting for it. If it's available, a pointer is
/// returned. Otherwise, null is returned.
pub fn getOrNull(self: *Self) ?*T {
- if (@atomicLoad(u8, &self.available, .SeqCst) == 2) {
+ if (@atomicLoad(Available, &self.available, .SeqCst) == .Finished) {
return &self.data;
} else {
return null;
@@ -59,14 +60,14 @@ pub fn Future(comptime T: type) type {
/// It's not required to call start() before resolve() but it can be useful since
/// this method is thread-safe.
pub async fn start(self: *Self) ?*T {
- const state = @cmpxchgStrong(u8, &self.available, 0, 1, .SeqCst, .SeqCst) orelse return null;
+ const state = @cmpxchgStrong(Available, &self.available, .NotStarted, .Started, .SeqCst, .SeqCst) orelse return null;
switch (state) {
- 1 => {
+ .Started => {
const held = self.lock.acquire();
held.release();
return &self.data;
},
- 2 => return &self.data,
+ .Finished => return &self.data,
else => unreachable,
}
}
@@ -74,8 +75,8 @@ pub fn Future(comptime T: type) type {
/// Make the data become available. May be called only once.
/// Before calling this, modify the `data` property.
pub fn resolve(self: *Self) void {
- const prev = @atomicRmw(u8, &self.available, .Xchg, 2, .SeqCst);
- assert(prev == 0 or prev == 1); // resolve() called twice
+ const prev = @atomicRmw(Available, &self.available, .Xchg, .Finished, .SeqCst);
+ assert(prev != .Finished); // resolve() called twice
Lock.Held.release(Lock.Held{ .lock = &self.lock });
}
};
diff --git a/lib/std/event/group.zig b/lib/std/event/group.zig
index f073bb3df2..77dd2cd1aa 100644
--- a/lib/std/event/group.zig
+++ b/lib/std/event/group.zig
@@ -8,7 +8,7 @@ const Allocator = std.mem.Allocator;
pub fn Group(comptime ReturnType: type) type {
return struct {
frame_stack: Stack,
- alloc_stack: Stack,
+ alloc_stack: AllocStack,
lock: Lock,
allocator: *Allocator,
@@ -19,11 +19,17 @@ pub fn Group(comptime ReturnType: type) type {
else => void,
};
const Stack = std.atomic.Stack(anyframe->ReturnType);
+ const AllocStack = std.atomic.Stack(Node);
+
+ pub const Node = struct {
+ bytes: []const u8 = [0]u8{},
+ handle: anyframe->ReturnType,
+ };
pub fn init(allocator: *Allocator) Self {
return Self{
.frame_stack = Stack.init(),
- .alloc_stack = Stack.init(),
+ .alloc_stack = AllocStack.init(),
.lock = Lock.init(),
.allocator = allocator,
};
@@ -31,10 +37,12 @@ pub fn Group(comptime ReturnType: type) type {
/// Add a frame to the group. Thread-safe.
pub fn add(self: *Self, handle: anyframe->ReturnType) (error{OutOfMemory}!void) {
- const node = try self.allocator.create(Stack.Node);
- node.* = Stack.Node{
+ const node = try self.allocator.create(AllocStack.Node);
+ node.* = AllocStack.Node{
.next = undefined,
- .data = handle,
+ .data = Node{
+ .handle = handle,
+ },
};
self.alloc_stack.push(node);
}
@@ -48,6 +56,24 @@ pub fn Group(comptime ReturnType: type) type {
self.frame_stack.push(node);
}
+ /// This is equivalent to adding a frame to the group but the memory of its frame is
+ /// allocated by the group and freed by `wait`.
+ /// `func` must be async and have return type `ReturnType`.
+ /// Thread-safe.
+ pub fn call(self: *Self, comptime func: var, args: ...) error{OutOfMemory}!void {
+ var frame = try self.allocator.create(@Frame(func));
+ const node = try self.allocator.create(AllocStack.Node);
+ node.* = AllocStack.Node{
+ .next = undefined,
+ .data = Node{
+ .handle = frame,
+ .bytes = @sliceToBytes((*[1]@Frame(func))(frame)[0..]),
+ },
+ };
+ frame.* = async func(args);
+ self.alloc_stack.push(node);
+ }
+
/// Wait for all the calls and promises of the group to complete.
/// Thread-safe.
/// Safe to call any number of times.
@@ -67,8 +93,7 @@ pub fn Group(comptime ReturnType: type) type {
}
}
while (self.alloc_stack.pop()) |node| {
- const handle = node.data;
- self.allocator.destroy(node);
+ const handle = node.data.handle;
if (Error == void) {
await handle;
} else {
@@ -76,6 +101,8 @@ pub fn Group(comptime ReturnType: type) type {
result = err;
};
}
+ self.allocator.free(node.data.bytes);
+ self.allocator.destroy(node);
}
return result;
}
diff --git a/lib/std/event/lock.zig b/lib/std/event/lock.zig
index 576a09064f..a95c5bf7e2 100644
--- a/lib/std/event/lock.zig
+++ b/lib/std/event/lock.zig
@@ -31,8 +31,8 @@ pub const Lock = struct {
}
// We need to release the lock.
- _ = @atomicRmw(u8, &self.lock.queue_empty_bit, .Xchg, 1, .SeqCst);
- _ = @atomicRmw(u8, &self.lock.shared_bit, .Xchg, 0, .SeqCst);
+ @atomicStore(u8, &self.lock.queue_empty_bit, 1, .SeqCst);
+ @atomicStore(u8, &self.lock.shared_bit, 0, .SeqCst);
// There might be a queue item. If we know the queue is empty, we can be done,
// because the other actor will try to obtain the lock.
@@ -56,8 +56,8 @@ pub const Lock = struct {
}
// Release the lock again.
- _ = @atomicRmw(u8, &self.lock.queue_empty_bit, .Xchg, 1, .SeqCst);
- _ = @atomicRmw(u8, &self.lock.shared_bit, .Xchg, 0, .SeqCst);
+ @atomicStore(u8, &self.lock.queue_empty_bit, 1, .SeqCst);
+ @atomicStore(u8, &self.lock.shared_bit, 0, .SeqCst);
// Find out if we can be done.
if (@atomicLoad(u8, &self.lock.queue_empty_bit, .SeqCst) == 1) {
@@ -101,7 +101,7 @@ pub const Lock = struct {
// We set this bit so that later we can rely on the fact, that if queue_empty_bit is 1, some actor
// will attempt to grab the lock.
- _ = @atomicRmw(u8, &self.queue_empty_bit, .Xchg, 0, .SeqCst);
+ @atomicStore(u8, &self.queue_empty_bit, 0, .SeqCst);
const old_bit = @atomicRmw(u8, &self.shared_bit, .Xchg, 1, .SeqCst);
if (old_bit == 0) {
diff --git a/lib/std/event/loop.zig b/lib/std/event/loop.zig
index d5d73dabbc..44174c862c 100644
--- a/lib/std/event/loop.zig
+++ b/lib/std/event/loop.zig
@@ -266,7 +266,7 @@ pub const Loop = struct {
},
};
- const empty_kevs = ([*]os.Kevent)(undefined)[0..0];
+ const empty_kevs = &[0]os.Kevent{};
for (self.eventfd_resume_nodes) |*eventfd_node, i| {
eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{
@@ -289,7 +289,7 @@ pub const Loop = struct {
.next = undefined,
};
self.available_eventfd_resume_nodes.push(eventfd_node);
- const kevent_array = (*const [1]os.Kevent)(&eventfd_node.data.kevent);
+ const kevent_array = @as(*const [1]os.Kevent, &eventfd_node.data.kevent);
_ = try os.kevent(self.os_data.kqfd, kevent_array, empty_kevs, null);
eventfd_node.data.kevent.flags = os.EV_CLEAR | os.EV_ENABLE;
eventfd_node.data.kevent.fflags = os.NOTE_TRIGGER;
@@ -305,7 +305,7 @@ pub const Loop = struct {
.data = 0,
.udata = @ptrToInt(&self.final_resume_node),
};
- const final_kev_arr = (*const [1]os.Kevent)(&self.os_data.final_kevent);
+ const final_kev_arr = @as(*const [1]os.Kevent, &self.os_data.final_kevent);
_ = try os.kevent(self.os_data.kqfd, final_kev_arr, empty_kevs, null);
self.os_data.final_kevent.flags = os.EV_ENABLE;
self.os_data.final_kevent.fflags = os.NOTE_TRIGGER;
@@ -572,8 +572,8 @@ pub const Loop = struct {
eventfd_node.base.handle = next_tick_node.data;
switch (builtin.os) {
.macosx, .freebsd, .netbsd, .dragonfly => {
- const kevent_array = (*const [1]os.Kevent)(&eventfd_node.kevent);
- const empty_kevs = ([*]os.Kevent)(undefined)[0..0];
+ const kevent_array = @as(*const [1]os.Kevent, &eventfd_node.kevent);
+ const empty_kevs = &[0]os.Kevent{};
_ = os.kevent(self.os_data.kqfd, kevent_array, empty_kevs, null) catch {
self.next_tick_queue.unget(next_tick_node);
self.available_eventfd_resume_nodes.push(resume_stack_node);
@@ -645,12 +645,6 @@ pub const Loop = struct {
}
}
- /// This is equivalent to function call, except it calls `startCpuBoundOperation` first.
- pub fn call(comptime func: var, args: ...) @typeOf(func).ReturnType {
- startCpuBoundOperation();
- return func(args);
- }
-
/// Yielding lets the event loop run, starting any unstarted async operations.
/// Note that async operations automatically start when a function yields for any other reason,
/// for example, when async I/O is performed. This function is intended to be used only when
@@ -695,8 +689,8 @@ pub const Loop = struct {
},
.macosx, .freebsd, .netbsd, .dragonfly => {
self.posixFsRequest(&self.os_data.fs_end_request);
- const final_kevent = (*const [1]os.Kevent)(&self.os_data.final_kevent);
- const empty_kevs = ([*]os.Kevent)(undefined)[0..0];
+ const final_kevent = @as(*const [1]os.Kevent, &self.os_data.final_kevent);
+ const empty_kevs = &[0]os.Kevent{};
// cannot fail because we already added it and this just enables it
_ = os.kevent(self.os_data.kqfd, final_kevent, empty_kevs, null) catch unreachable;
return;
@@ -753,7 +747,7 @@ pub const Loop = struct {
},
.macosx, .freebsd, .netbsd, .dragonfly => {
var eventlist: [1]os.Kevent = undefined;
- const empty_kevs = ([*]os.Kevent)(undefined)[0..0];
+ const empty_kevs = &[0]os.Kevent{};
const count = os.kevent(self.os_data.kqfd, empty_kevs, eventlist[0..], null) catch unreachable;
for (eventlist[0..count]) |ev| {
const resume_node = @intToPtr(*ResumeNode, ev.udata);
@@ -815,12 +809,12 @@ pub const Loop = struct {
self.os_data.fs_queue.put(request_node);
switch (builtin.os) {
.macosx, .freebsd, .netbsd, .dragonfly => {
- const fs_kevs = (*const [1]os.Kevent)(&self.os_data.fs_kevent_wake);
- const empty_kevs = ([*]os.Kevent)(undefined)[0..0];
+ const fs_kevs = @as(*const [1]os.Kevent, &self.os_data.fs_kevent_wake);
+ const empty_kevs = &[0]os.Kevent{};
_ = os.kevent(self.os_data.fs_kqfd, fs_kevs, empty_kevs, null) catch unreachable;
},
.linux => {
- _ = @atomicRmw(i32, &self.os_data.fs_queue_item, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst);
+ @atomicStore(i32, &self.os_data.fs_queue_item, 1, AtomicOrder.SeqCst);
const rc = os.linux.futex_wake(&self.os_data.fs_queue_item, os.linux.FUTEX_WAKE, 1);
switch (os.linux.getErrno(rc)) {
0 => {},
@@ -843,7 +837,7 @@ pub const Loop = struct {
fn posixFsRun(self: *Loop) void {
while (true) {
if (builtin.os == .linux) {
- _ = @atomicRmw(i32, &self.os_data.fs_queue_item, .Xchg, 0, .SeqCst);
+ @atomicStore(i32, &self.os_data.fs_queue_item, 0, .SeqCst);
}
while (self.os_data.fs_queue.get()) |node| {
switch (node.data.msg) {
@@ -862,7 +856,8 @@ pub const Loop = struct {
},
.Close => |*msg| noasync os.close(msg.fd),
.WriteFile => |*msg| blk: {
- const flags = os.O_LARGEFILE | os.O_WRONLY | os.O_CREAT |
+ const O_LARGEFILE = if (@hasDecl(os, "O_LARGEFILE")) os.O_LARGEFILE else 0;
+ const flags = O_LARGEFILE | os.O_WRONLY | os.O_CREAT |
os.O_CLOEXEC | os.O_TRUNC;
const fd = noasync os.openC(msg.path.ptr, flags, msg.mode) catch |err| {
msg.result = err;
@@ -890,7 +885,7 @@ pub const Loop = struct {
}
},
.macosx, .freebsd, .netbsd, .dragonfly => {
- const fs_kevs = (*const [1]os.Kevent)(&self.os_data.fs_kevent_wait);
+ const fs_kevs = @as(*const [1]os.Kevent, &self.os_data.fs_kevent_wait);
var out_kevs: [1]os.Kevent = undefined;
_ = os.kevent(self.os_data.fs_kqfd, fs_kevs, out_kevs[0..], null) catch unreachable;
},
@@ -942,23 +937,6 @@ test "std.event.Loop - basic" {
loop.run();
}
-test "std.event.Loop - call" {
- // https://github.com/ziglang/zig/issues/1908
- if (builtin.single_threaded) return error.SkipZigTest;
-
- var loop: Loop = undefined;
- try loop.initMultiThreaded();
- defer loop.deinit();
-
- var did_it = false;
- var handle = async Loop.call(testEventLoop);
- var handle2 = async Loop.call(testEventLoop2, &handle, &did_it);
-
- loop.run();
-
- testing.expect(did_it);
-}
-
async fn testEventLoop() i32 {
return 1234;
}
diff --git a/lib/std/event/rwlock.zig b/lib/std/event/rwlock.zig
index c05e740b09..ec4ab8f6d0 100644
--- a/lib/std/event/rwlock.zig
+++ b/lib/std/event/rwlock.zig
@@ -13,17 +13,17 @@ const Loop = std.event.Loop;
/// When a write lock is held, it will not be released until the writer queue is empty.
/// TODO: make this API also work in blocking I/O mode
pub const RwLock = struct {
- shared_state: u8, // TODO make this an enum
+ shared_state: State,
writer_queue: Queue,
reader_queue: Queue,
writer_queue_empty_bit: u8, // TODO make this a bool
reader_queue_empty_bit: u8, // TODO make this a bool
reader_lock_count: usize,
- const State = struct {
- const Unlocked = 0;
- const WriteLock = 1;
- const ReadLock = 2;
+ const State = enum(u8) {
+ Unlocked,
+ WriteLock,
+ ReadLock,
};
const Queue = std.atomic.Queue(anyframe);
@@ -40,8 +40,8 @@ pub const RwLock = struct {
return;
}
- _ = @atomicRmw(u8, &self.lock.reader_queue_empty_bit, .Xchg, 1, .SeqCst);
- if (@cmpxchgStrong(u8, &self.lock.shared_state, State.ReadLock, State.Unlocked, .SeqCst, .SeqCst) != null) {
+ @atomicStore(u8, &self.lock.reader_queue_empty_bit, 1, .SeqCst);
+ if (@cmpxchgStrong(State, &self.lock.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {
// Didn't unlock. Someone else's problem.
return;
}
@@ -64,15 +64,15 @@ pub const RwLock = struct {
// We need to release the write lock. Check if any readers are waiting to grab the lock.
if (@atomicLoad(u8, &self.lock.reader_queue_empty_bit, .SeqCst) == 0) {
// Switch to a read lock.
- _ = @atomicRmw(u8, &self.lock.shared_state, .Xchg, State.ReadLock, .SeqCst);
+ @atomicStore(State, &self.lock.shared_state, .ReadLock, .SeqCst);
while (self.lock.reader_queue.get()) |node| {
global_event_loop.onNextTick(node);
}
return;
}
- _ = @atomicRmw(u8, &self.lock.writer_queue_empty_bit, .Xchg, 1, .SeqCst);
- _ = @atomicRmw(u8, &self.lock.shared_state, .Xchg, State.Unlocked, .SeqCst);
+ @atomicStore(u8, &self.lock.writer_queue_empty_bit, 1, .SeqCst);
+ @atomicStore(State, &self.lock.shared_state, .Unlocked, .SeqCst);
self.lock.commonPostUnlock();
}
@@ -80,7 +80,7 @@ pub const RwLock = struct {
pub fn init() RwLock {
return RwLock{
- .shared_state = State.Unlocked,
+ .shared_state = .Unlocked,
.writer_queue = Queue.init(),
.writer_queue_empty_bit = 1,
.reader_queue = Queue.init(),
@@ -92,7 +92,7 @@ pub const RwLock = struct {
/// Must be called when not locked. Not thread safe.
/// All calls to acquire() and release() must complete before calling deinit().
pub fn deinit(self: *RwLock) void {
- assert(self.shared_state == State.Unlocked);
+ assert(self.shared_state == .Unlocked);
while (self.writer_queue.get()) |node| resume node.data;
while (self.reader_queue.get()) |node| resume node.data;
}
@@ -113,10 +113,10 @@ pub const RwLock = struct {
// We set this bit so that later we can rely on the fact, that if reader_queue_empty_bit is 1,
// some actor will attempt to grab the lock.
- _ = @atomicRmw(u8, &self.reader_queue_empty_bit, .Xchg, 0, .SeqCst);
+ @atomicStore(u8, &self.reader_queue_empty_bit, 0, .SeqCst);
// Here we don't care if we are the one to do the locking or if it was already locked for reading.
- const have_read_lock = if (@cmpxchgStrong(u8, &self.shared_state, State.Unlocked, State.ReadLock, .SeqCst, .SeqCst)) |old_state| old_state == State.ReadLock else true;
+ const have_read_lock = if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst)) |old_state| old_state == .ReadLock else true;
if (have_read_lock) {
// Give out all the read locks.
if (self.reader_queue.get()) |first_node| {
@@ -144,10 +144,10 @@ pub const RwLock = struct {
// We set this bit so that later we can rely on the fact, that if writer_queue_empty_bit is 1,
// some actor will attempt to grab the lock.
- _ = @atomicRmw(u8, &self.writer_queue_empty_bit, .Xchg, 0, .SeqCst);
+ @atomicStore(u8, &self.writer_queue_empty_bit, 0, .SeqCst);
// Here we must be the one to acquire the write lock. It cannot already be locked.
- if (@cmpxchgStrong(u8, &self.shared_state, State.Unlocked, State.WriteLock, .SeqCst, .SeqCst) == null) {
+ if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) == null) {
// We now have a write lock.
if (self.writer_queue.get()) |node| {
// Whether this node is us or someone else, we tail resume it.
@@ -166,7 +166,7 @@ pub const RwLock = struct {
// But if there's a writer_queue item or a reader_queue item,
// we are the actor which must loop and attempt to grab the lock again.
if (@atomicLoad(u8, &self.writer_queue_empty_bit, .SeqCst) == 0) {
- if (@cmpxchgStrong(u8, &self.shared_state, State.Unlocked, State.WriteLock, .SeqCst, .SeqCst) != null) {
+ if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) != null) {
// We did not obtain the lock. Great, the queues are someone else's problem.
return;
}
@@ -176,13 +176,13 @@ pub const RwLock = struct {
return;
}
// Release the lock again.
- _ = @atomicRmw(u8, &self.writer_queue_empty_bit, .Xchg, 1, .SeqCst);
- _ = @atomicRmw(u8, &self.shared_state, .Xchg, State.Unlocked, .SeqCst);
+ @atomicStore(u8, &self.writer_queue_empty_bit, 1, .SeqCst);
+ @atomicStore(State, &self.shared_state, .Unlocked, .SeqCst);
continue;
}
if (@atomicLoad(u8, &self.reader_queue_empty_bit, .SeqCst) == 0) {
- if (@cmpxchgStrong(u8, &self.shared_state, State.Unlocked, State.ReadLock, .SeqCst, .SeqCst) != null) {
+ if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst) != null) {
// We did not obtain the lock. Great, the queues are someone else's problem.
return;
}
@@ -195,8 +195,8 @@ pub const RwLock = struct {
return;
}
// Release the lock again.
- _ = @atomicRmw(u8, &self.reader_queue_empty_bit, .Xchg, 1, .SeqCst);
- if (@cmpxchgStrong(u8, &self.shared_state, State.ReadLock, State.Unlocked, .SeqCst, .SeqCst) != null) {
+ @atomicStore(u8, &self.reader_queue_empty_bit, 1, .SeqCst);
+ if (@cmpxchgStrong(State, &self.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {
// Didn't unlock. Someone else's problem.
return;
}
diff --git a/lib/std/fifo.zig b/lib/std/fifo.zig
index b47dda34de..73f9b2dee7 100644
--- a/lib/std/fifo.zig
+++ b/lib/std/fifo.zig
@@ -257,7 +257,7 @@ test "ByteFifo" {
defer fifo.deinit();
try fifo.write("HELLO");
- testing.expectEqual(usize(5), fifo.readableLength());
+ testing.expectEqual(@as(usize, 5), fifo.readableLength());
testing.expectEqualSlices(u8, "HELLO", fifo.readableSlice(0));
{
@@ -265,34 +265,34 @@ test "ByteFifo" {
while (i < 5) : (i += 1) {
try fifo.write([_]u8{try fifo.peekItem(i)});
}
- testing.expectEqual(usize(10), fifo.readableLength());
+ testing.expectEqual(@as(usize, 10), fifo.readableLength());
testing.expectEqualSlices(u8, "HELLOHELLO", fifo.readableSlice(0));
}
{
- testing.expectEqual(u8('H'), try fifo.readItem());
- testing.expectEqual(u8('E'), try fifo.readItem());
- testing.expectEqual(u8('L'), try fifo.readItem());
- testing.expectEqual(u8('L'), try fifo.readItem());
- testing.expectEqual(u8('O'), try fifo.readItem());
+ testing.expectEqual(@as(u8, 'H'), try fifo.readItem());
+ testing.expectEqual(@as(u8, 'E'), try fifo.readItem());
+ testing.expectEqual(@as(u8, 'L'), try fifo.readItem());
+ testing.expectEqual(@as(u8, 'L'), try fifo.readItem());
+ testing.expectEqual(@as(u8, 'O'), try fifo.readItem());
}
- testing.expectEqual(usize(5), fifo.readableLength());
+ testing.expectEqual(@as(usize, 5), fifo.readableLength());
{ // Writes that wrap around
- testing.expectEqual(usize(11), fifo.writableLength());
- testing.expectEqual(usize(6), fifo.writableSlice(0).len);
+ testing.expectEqual(@as(usize, 11), fifo.writableLength());
+ testing.expectEqual(@as(usize, 6), fifo.writableSlice(0).len);
fifo.writeAssumeCapacity("6<chars<11");
testing.expectEqualSlices(u8, "HELLO6<char", fifo.readableSlice(0));
testing.expectEqualSlices(u8, "s<11", fifo.readableSlice(11));
fifo.discard(11);
testing.expectEqualSlices(u8, "s<11", fifo.readableSlice(0));
fifo.discard(4);
- testing.expectEqual(usize(0), fifo.readableLength());
+ testing.expectEqual(@as(usize, 0), fifo.readableLength());
}
{
const buf = try fifo.writeableWithSize(12);
- testing.expectEqual(usize(12), buf.len);
+ testing.expectEqual(@as(usize, 12), buf.len);
var i: u8 = 0;
while (i < 10) : (i += 1) {
buf[i] = i + 'a';
@@ -313,6 +313,6 @@ test "ByteFifo" {
try fifo.print("{}, {}!", "Hello", "World");
var result: [30]u8 = undefined;
testing.expectEqualSlices(u8, "Hello, World!", fifo.read(&result));
- testing.expectEqual(usize(0), fifo.readableLength());
+ testing.expectEqual(@as(usize, 0), fifo.readableLength());
}
}
diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig
index d3d795bf9d..743ca4d920 100644
--- a/lib/std/fmt.zig
+++ b/lib/std/fmt.zig
@@ -167,6 +167,10 @@ pub fn format(
'}' => {
const arg_to_print = comptime nextArg(&used_pos_args, maybe_pos_arg, &next_arg);
+ if (arg_to_print >= args.len) {
+ @compileError("Too few arguments");
+ }
+
try formatType(
args[arg_to_print],
fmt[0..0],
@@ -378,10 +382,10 @@ pub fn formatType(
const info = @typeInfo(T).Union;
if (info.tag_type) |UnionTagType| {
try output(context, "{ .");
- try output(context, @tagName(UnionTagType(value)));
+ try output(context, @tagName(@as(UnionTagType, value)));
try output(context, " = ");
inline for (info.fields) |u_field| {
- if (@enumToInt(UnionTagType(value)) == u_field.enum_field.?.value) {
+ if (@enumToInt(@as(UnionTagType, value)) == u_field.enum_field.?.value) {
try formatType(@field(value, u_field.name), "", options, context, Errors, output, max_depth - 1);
}
}
@@ -499,7 +503,7 @@ pub fn formatIntValue(
const int_value = if (@typeOf(value) == comptime_int) blk: {
const Int = math.IntFittingRange(value, value);
- break :blk Int(value);
+ break :blk @as(Int, value);
} else
value;
@@ -508,7 +512,7 @@ pub fn formatIntValue(
uppercase = false;
} else if (comptime std.mem.eql(u8, fmt, "c")) {
if (@typeOf(int_value).bit_count <= 8) {
- return formatAsciiChar(u8(int_value), options, context, Errors, output);
+ return formatAsciiChar(@as(u8, int_value), options, context, Errors, output);
} else {
@compileError("Cannot print integer that is larger than 8 bits as a ascii");
}
@@ -574,7 +578,7 @@ pub fn formatAsciiChar(
comptime Errors: type,
output: fn (@typeOf(context), []const u8) Errors!void,
) Errors!void {
- return output(context, (*const [1]u8)(&c)[0..]);
+ return output(context, @as(*const [1]u8, &c)[0..]);
}
pub fn formatBuf(
@@ -590,7 +594,7 @@ pub fn formatBuf(
var leftover_padding = if (width > buf.len) (width - buf.len) else return;
const pad_byte: u8 = options.fill;
while (leftover_padding > 0) : (leftover_padding -= 1) {
- try output(context, (*const [1]u8)(&pad_byte)[0..1]);
+ try output(context, @as(*const [1]u8, &pad_byte)[0..1]);
}
}
@@ -664,7 +668,7 @@ pub fn formatFloatScientific(
try output(context, float_decimal.digits[0..1]);
try output(context, ".");
if (float_decimal.digits.len > 1) {
- const num_digits = if (@typeOf(value) == f32) math.min(usize(9), float_decimal.digits.len) else float_decimal.digits.len;
+ const num_digits = if (@typeOf(value) == f32) math.min(@as(usize, 9), float_decimal.digits.len) else float_decimal.digits.len;
try output(context, float_decimal.digits[1..num_digits]);
} else {
@@ -699,7 +703,7 @@ pub fn formatFloatDecimal(
comptime Errors: type,
output: fn (@typeOf(context), []const u8) Errors!void,
) Errors!void {
- var x = f64(value);
+ var x = @as(f64, value);
// Errol doesn't handle these special cases.
if (math.signbit(x)) {
@@ -888,7 +892,7 @@ pub fn formatInt(
) Errors!void {
const int_value = if (@typeOf(value) == comptime_int) blk: {
const Int = math.IntFittingRange(value, value);
- break :blk Int(value);
+ break :blk @as(Int, value);
} else
value;
@@ -917,14 +921,14 @@ fn formatIntSigned(
const uint = @IntType(false, @typeOf(value).bit_count);
if (value < 0) {
const minus_sign: u8 = '-';
- try output(context, (*const [1]u8)(&minus_sign)[0..]);
+ try output(context, @as(*const [1]u8, &minus_sign)[0..]);
const new_value = @intCast(uint, -(value + 1)) + 1;
return formatIntUnsigned(new_value, base, uppercase, new_options, context, Errors, output);
} else if (options.width == null or options.width.? == 0) {
return formatIntUnsigned(@intCast(uint, value), base, uppercase, options, context, Errors, output);
} else {
const plus_sign: u8 = '+';
- try output(context, (*const [1]u8)(&plus_sign)[0..]);
+ try output(context, @as(*const [1]u8, &plus_sign)[0..]);
const new_value = @intCast(uint, value);
return formatIntUnsigned(new_value, base, uppercase, new_options, context, Errors, output);
}
@@ -962,7 +966,7 @@ fn formatIntUnsigned(
const zero_byte: u8 = options.fill;
var leftover_padding = padding - index;
while (true) {
- try output(context, (*const [1]u8)(&zero_byte)[0..]);
+ try output(context, @as(*const [1]u8, &zero_byte)[0..]);
leftover_padding -= 1;
if (leftover_padding == 0) break;
}
@@ -994,7 +998,7 @@ fn formatIntCallback(context: *FormatIntBuf, bytes: []const u8) (error{}!void) {
pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) !T {
if (!T.is_signed) return parseUnsigned(T, buf, radix);
- if (buf.len == 0) return T(0);
+ if (buf.len == 0) return @as(T, 0);
if (buf[0] == '-') {
return math.negate(try parseUnsigned(T, buf[1..], radix));
} else if (buf[0] == '+') {
@@ -1084,7 +1088,7 @@ pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) {
fn digitToChar(digit: u8, uppercase: bool) u8 {
return switch (digit) {
0...9 => digit + '0',
- 10...35 => digit + ((if (uppercase) u8('A') else u8('a')) - 10),
+ 10...35 => digit + ((if (uppercase) @as(u8, 'A') else @as(u8, 'a')) - 10),
else => unreachable,
};
}
@@ -1130,19 +1134,19 @@ fn countSize(size: *usize, bytes: []const u8) (error{}!void) {
test "bufPrintInt" {
var buffer: [100]u8 = undefined;
const buf = buffer[0..];
- testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, i32(-12345678), 2, false, FormatOptions{}), "-101111000110000101001110"));
- testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, i32(-12345678), 10, false, FormatOptions{}), "-12345678"));
- testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, i32(-12345678), 16, false, FormatOptions{}), "-bc614e"));
- testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, i32(-12345678), 16, true, FormatOptions{}), "-BC614E"));
+ testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, @as(i32, -12345678), 2, false, FormatOptions{}), "-101111000110000101001110"));
+ testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, @as(i32, -12345678), 10, false, FormatOptions{}), "-12345678"));
+ testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, @as(i32, -12345678), 16, false, FormatOptions{}), "-bc614e"));
+ testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, @as(i32, -12345678), 16, true, FormatOptions{}), "-BC614E"));
- testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, u32(12345678), 10, true, FormatOptions{}), "12345678"));
+ testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, @as(u32, 12345678), 10, true, FormatOptions{}), "12345678"));
- testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, u32(666), 10, false, FormatOptions{ .width = 6 }), " 666"));
- testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, u32(0x1234), 16, false, FormatOptions{ .width = 6 }), " 1234"));
- testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, u32(0x1234), 16, false, FormatOptions{ .width = 1 }), "1234"));
+ testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, @as(u32, 666), 10, false, FormatOptions{ .width = 6 }), " 666"));
+ testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, @as(u32, 0x1234), 16, false, FormatOptions{ .width = 6 }), " 1234"));
+ testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, @as(u32, 0x1234), 16, false, FormatOptions{ .width = 1 }), "1234"));
- testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, i32(42), 10, false, FormatOptions{ .width = 3 }), "+42"));
- testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, i32(-42), 10, false, FormatOptions{ .width = 3 }), "-42"));
+ testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, @as(i32, 42), 10, false, FormatOptions{ .width = 3 }), "+42"));
+ testing.expect(mem.eql(u8, bufPrintIntToSlice(buf, @as(i32, -42), 10, false, FormatOptions{ .width = 3 }), "-42"));
}
fn bufPrintIntToSlice(buf: []u8, value: var, base: u8, uppercase: bool, options: FormatOptions) []u8 {
@@ -1204,8 +1208,8 @@ test "int.specifier" {
}
test "int.padded" {
- try testFmt("u8: ' 1'", "u8: '{:4}'", u8(1));
- try testFmt("u8: 'xxx1'", "u8: '{:x<4}'", u8(1));
+ try testFmt("u8: ' 1'", "u8: '{:4}'", @as(u8, 1));
+ try testFmt("u8: 'xxx1'", "u8: '{:x<4}'", @as(u8, 1));
}
test "buffer" {
@@ -1283,8 +1287,8 @@ test "filesize" {
// TODO https://github.com/ziglang/zig/issues/3289
return error.SkipZigTest;
}
- try testFmt("file size: 63MiB\n", "file size: {Bi}\n", usize(63 * 1024 * 1024));
- try testFmt("file size: 66.06MB\n", "file size: {B:.2}\n", usize(63 * 1024 * 1024));
+ try testFmt("file size: 63MiB\n", "file size: {Bi}\n", @as(usize, 63 * 1024 * 1024));
+ try testFmt("file size: 66.06MB\n", "file size: {B:.2}\n", @as(usize, 63 * 1024 * 1024));
}
test "struct" {
@@ -1321,10 +1325,10 @@ test "float.scientific" {
// TODO https://github.com/ziglang/zig/issues/3289
return error.SkipZigTest;
}
- try testFmt("f32: 1.34000003e+00", "f32: {e}", f32(1.34));
- try testFmt("f32: 1.23400001e+01", "f32: {e}", f32(12.34));
- try testFmt("f64: -1.234e+11", "f64: {e}", f64(-12.34e10));
- try testFmt("f64: 9.99996e-40", "f64: {e}", f64(9.999960e-40));
+ try testFmt("f32: 1.34000003e+00", "f32: {e}", @as(f32, 1.34));
+ try testFmt("f32: 1.23400001e+01", "f32: {e}", @as(f32, 12.34));
+ try testFmt("f64: -1.234e+11", "f64: {e}", @as(f64, -12.34e10));
+ try testFmt("f64: 9.99996e-40", "f64: {e}", @as(f64, 9.999960e-40));
}
test "float.scientific.precision" {
@@ -1332,12 +1336,12 @@ test "float.scientific.precision" {
// TODO https://github.com/ziglang/zig/issues/3289
return error.SkipZigTest;
}
- try testFmt("f64: 1.40971e-42", "f64: {e:.5}", f64(1.409706e-42));
- try testFmt("f64: 1.00000e-09", "f64: {e:.5}", f64(@bitCast(f32, u32(814313563))));
- try testFmt("f64: 7.81250e-03", "f64: {e:.5}", f64(@bitCast(f32, u32(1006632960))));
+ try testFmt("f64: 1.40971e-42", "f64: {e:.5}", @as(f64, 1.409706e-42));
+ try testFmt("f64: 1.00000e-09", "f64: {e:.5}", @as(f64, @bitCast(f32, @as(u32, 814313563))));
+ try testFmt("f64: 7.81250e-03", "f64: {e:.5}", @as(f64, @bitCast(f32, @as(u32, 1006632960))));
// libc rounds 1.000005e+05 to 1.00000e+05 but zig does 1.00001e+05.
// In fact, libc doesn't round a lot of 5 cases up when one past the precision point.
- try testFmt("f64: 1.00001e+05", "f64: {e:.5}", f64(@bitCast(f32, u32(1203982400))));
+ try testFmt("f64: 1.00001e+05", "f64: {e:.5}", @as(f64, @bitCast(f32, @as(u32, 1203982400))));
}
test "float.special" {
@@ -1360,21 +1364,21 @@ test "float.decimal" {
// TODO https://github.com/ziglang/zig/issues/3289
return error.SkipZigTest;
}
- try testFmt("f64: 152314000000000000000000000000", "f64: {d}", f64(1.52314e+29));
- try testFmt("f32: 1.1", "f32: {d:.1}", f32(1.1234));
- try testFmt("f32: 1234.57", "f32: {d:.2}", f32(1234.567));
+ try testFmt("f64: 152314000000000000000000000000", "f64: {d}", @as(f64, 1.52314e+29));
+ try testFmt("f32: 1.1", "f32: {d:.1}", @as(f32, 1.1234));
+ try testFmt("f32: 1234.57", "f32: {d:.2}", @as(f32, 1234.567));
// -11.1234 is converted to f64 -11.12339... internally (errol3() function takes f64).
// -11.12339... is rounded back up to -11.1234
- try testFmt("f32: -11.1234", "f32: {d:.4}", f32(-11.1234));
- try testFmt("f32: 91.12345", "f32: {d:.5}", f32(91.12345));
- try testFmt("f64: 91.1234567890", "f64: {d:.10}", f64(91.12345678901235));
- try testFmt("f64: 0.00000", "f64: {d:.5}", f64(0.0));
- try testFmt("f64: 6", "f64: {d:.0}", f64(5.700));
- try testFmt("f64: 10.0", "f64: {d:.1}", f64(9.999));
- try testFmt("f64: 1.000", "f64: {d:.3}", f64(1.0));
- try testFmt("f64: 0.00030000", "f64: {d:.8}", f64(0.0003));
- try testFmt("f64: 0.00000", "f64: {d:.5}", f64(1.40130e-45));
- try testFmt("f64: 0.00000", "f64: {d:.5}", f64(9.999960e-40));
+ try testFmt("f32: -11.1234", "f32: {d:.4}", @as(f32, -11.1234));
+ try testFmt("f32: 91.12345", "f32: {d:.5}", @as(f32, 91.12345));
+ try testFmt("f64: 91.1234567890", "f64: {d:.10}", @as(f64, 91.12345678901235));
+ try testFmt("f64: 0.00000", "f64: {d:.5}", @as(f64, 0.0));
+ try testFmt("f64: 6", "f64: {d:.0}", @as(f64, 5.700));
+ try testFmt("f64: 10.0", "f64: {d:.1}", @as(f64, 9.999));
+ try testFmt("f64: 1.000", "f64: {d:.3}", @as(f64, 1.0));
+ try testFmt("f64: 0.00030000", "f64: {d:.8}", @as(f64, 0.0003));
+ try testFmt("f64: 0.00000", "f64: {d:.5}", @as(f64, 1.40130e-45));
+ try testFmt("f64: 0.00000", "f64: {d:.5}", @as(f64, 9.999960e-40));
}
test "float.libc.sanity" {
@@ -1382,22 +1386,22 @@ test "float.libc.sanity" {
// TODO https://github.com/ziglang/zig/issues/3289
return error.SkipZigTest;
}
- try testFmt("f64: 0.00001", "f64: {d:.5}", f64(@bitCast(f32, u32(916964781))));
- try testFmt("f64: 0.00001", "f64: {d:.5}", f64(@bitCast(f32, u32(925353389))));
- try testFmt("f64: 0.10000", "f64: {d:.5}", f64(@bitCast(f32, u32(1036831278))));
- try testFmt("f64: 1.00000", "f64: {d:.5}", f64(@bitCast(f32, u32(1065353133))));
- try testFmt("f64: 10.00000", "f64: {d:.5}", f64(@bitCast(f32, u32(1092616192))));
+ try testFmt("f64: 0.00001", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 916964781))));
+ try testFmt("f64: 0.00001", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 925353389))));
+ try testFmt("f64: 0.10000", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 1036831278))));
+ try testFmt("f64: 1.00000", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 1065353133))));
+ try testFmt("f64: 10.00000", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 1092616192))));
// libc differences
//
// This is 0.015625 exactly according to gdb. We thus round down,
// however glibc rounds up for some reason. This occurs for all
// floats of the form x.yyyy25 on a precision point.
- try testFmt("f64: 0.01563", "f64: {d:.5}", f64(@bitCast(f32, u32(1015021568))));
+ try testFmt("f64: 0.01563", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 1015021568))));
// errol3 rounds to ... 630 but libc rounds to ...632. Grisu3
// also rounds to 630 so I'm inclined to believe libc is not
// optimal here.
- try testFmt("f64: 18014400656965630.00000", "f64: {d:.5}", f64(@bitCast(f32, u32(1518338049))));
+ try testFmt("f64: 18014400656965630.00000", "f64: {d:.5}", @as(f64, @bitCast(f32, @as(u32, 1518338049))));
}
test "custom" {
@@ -1673,17 +1677,17 @@ test "formatType max_depth" {
}
test "positional" {
- try testFmt("2 1 0", "{2} {1} {0}", usize(0), usize(1), usize(2));
- try testFmt("2 1 0", "{2} {1} {}", usize(0), usize(1), usize(2));
- try testFmt("0 0", "{0} {0}", usize(0));
- try testFmt("0 1", "{} {1}", usize(0), usize(1));
- try testFmt("1 0 0 1", "{1} {} {0} {}", usize(0), usize(1));
+ try testFmt("2 1 0", "{2} {1} {0}", @as(usize, 0), @as(usize, 1), @as(usize, 2));
+ try testFmt("2 1 0", "{2} {1} {}", @as(usize, 0), @as(usize, 1), @as(usize, 2));
+ try testFmt("0 0", "{0} {0}", @as(usize, 0));
+ try testFmt("0 1", "{} {1}", @as(usize, 0), @as(usize, 1));
+ try testFmt("1 0 0 1", "{1} {} {0} {}", @as(usize, 0), @as(usize, 1));
}
test "positional with specifier" {
- try testFmt("10.0", "{0d:.1}", f64(9.999));
+ try testFmt("10.0", "{0d:.1}", @as(f64, 9.999));
}
test "positional/alignment/width/precision" {
- try testFmt("10.0", "{0d: >3.1}", f64(9.999));
+ try testFmt("10.0", "{0d: >3.1}", @as(f64, 9.999));
}
diff --git a/lib/std/fmt/errol.zig b/lib/std/fmt/errol.zig
index a835195fc7..e697b7d42f 100644
--- a/lib/std/fmt/errol.zig
+++ b/lib/std/fmt/errol.zig
@@ -296,7 +296,7 @@ fn hpMul10(hp: *HP) void {
/// @buf: The output buffer.
/// &return: The exponent.
fn errolInt(val: f64, buffer: []u8) FloatDecimal {
- const pow19 = u128(1e19);
+ const pow19 = @as(u128, 1e19);
assert((val > 9.007199254740992e15) and val < (3.40282366920938e38));
@@ -670,7 +670,7 @@ fn fpeint(from: f64) u128 {
const bits = @bitCast(u64, from);
assert((bits & ((1 << 52) - 1)) == 0);
- return u128(1) << @truncate(u7, (bits >> 52) -% 1023);
+ return @as(u128, 1) << @truncate(u7, (bits >> 52) -% 1023);
}
/// Given two different integers with the same length in terms of the number
diff --git a/lib/std/fmt/parse_float.zig b/lib/std/fmt/parse_float.zig
index 9a35e27c21..78ce0b7d0a 100644
--- a/lib/std/fmt/parse_float.zig
+++ b/lib/std/fmt/parse_float.zig
@@ -59,29 +59,29 @@ const Z96 = struct {
// d += s
inline fn add(d: *Z96, s: Z96) void {
- var w = u64(d.d0) + u64(s.d0);
+ var w = @as(u64, d.d0) + @as(u64, s.d0);
d.d0 = @truncate(u32, w);
w >>= 32;
- w += u64(d.d1) + u64(s.d1);
+ w += @as(u64, d.d1) + @as(u64, s.d1);
d.d1 = @truncate(u32, w);
w >>= 32;
- w += u64(d.d2) + u64(s.d2);
+ w += @as(u64, d.d2) + @as(u64, s.d2);
d.d2 = @truncate(u32, w);
}
// d -= s
inline fn sub(d: *Z96, s: Z96) void {
- var w = u64(d.d0) -% u64(s.d0);
+ var w = @as(u64, d.d0) -% @as(u64, s.d0);
d.d0 = @truncate(u32, w);
w >>= 32;
- w += u64(d.d1) -% u64(s.d1);
+ w += @as(u64, d.d1) -% @as(u64, s.d1);
d.d1 = @truncate(u32, w);
w >>= 32;
- w += u64(d.d2) -% u64(s.d2);
+ w += @as(u64, d.d2) -% @as(u64, s.d2);
d.d2 = @truncate(u32, w);
}
};
@@ -160,7 +160,7 @@ fn convertRepr(comptime T: type, n: FloatRepr) T {
break :blk if (n.negative) f64_minus_zero else f64_plus_zero;
} else if (s.d2 != 0) {
const binexs2 = @intCast(u64, binary_exponent) << 52;
- const rr = (u64(s.d2 & ~mask28) << 24) | ((u64(s.d1) + 128) >> 8) | binexs2;
+ const rr = (@as(u64, s.d2 & ~mask28) << 24) | ((@as(u64, s.d1) + 128) >> 8) | binexs2;
break :blk if (n.negative) rr | (1 << 63) else rr;
} else {
break :blk 0;
@@ -375,7 +375,7 @@ pub fn parseFloat(comptime T: type, s: []const u8) !T {
return switch (try parseRepr(s, &r)) {
ParseResult.Ok => convertRepr(T, r),
ParseResult.PlusZero => 0.0,
- ParseResult.MinusZero => -T(0.0),
+ ParseResult.MinusZero => -@as(T, 0.0),
ParseResult.PlusInf => std.math.inf(T),
ParseResult.MinusInf => -std.math.inf(T),
};
@@ -426,8 +426,8 @@ test "fmt.parseFloat" {
expect(approxEq(T, try parseFloat(T, "1234e-2"), 12.34, epsilon));
expect(approxEq(T, try parseFloat(T, "123142.1"), 123142.1, epsilon));
- expect(approxEq(T, try parseFloat(T, "-123142.1124"), T(-123142.1124), epsilon));
- expect(approxEq(T, try parseFloat(T, "0.7062146892655368"), T(0.7062146892655368), epsilon));
+ expect(approxEq(T, try parseFloat(T, "-123142.1124"), @as(T, -123142.1124), epsilon));
+ expect(approxEq(T, try parseFloat(T, "0.7062146892655368"), @as(T, 0.7062146892655368), epsilon));
}
}
}
diff --git a/lib/std/fs.zig b/lib/std/fs.zig
index 2a96fd3fbc..bc2c921d1e 100644
--- a/lib/std/fs.zig
+++ b/lib/std/fs.zig
@@ -6,6 +6,7 @@ const base64 = std.base64;
const crypto = std.crypto;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
+const math = std.math;
pub const path = @import("fs/path.zig");
pub const File = @import("fs/file.zig").File;
@@ -584,7 +585,7 @@ pub const Dir = struct {
.FileBothDirectoryInformation,
w.FALSE,
null,
- if (self.first) w.BOOLEAN(w.TRUE) else w.BOOLEAN(w.FALSE),
+ if (self.first) @as(w.BOOLEAN, w.TRUE) else @as(w.BOOLEAN, w.FALSE),
);
self.first = false;
if (io.Information == 0) return null;
@@ -698,17 +699,81 @@ pub const Dir = struct {
/// Call `File.close` on the result when done.
pub fn openRead(self: Dir, sub_path: []const u8) File.OpenError!File {
+ if (builtin.os == .windows) {
+ const path_w = try os.windows.sliceToPrefixedFileW(sub_path);
+ return self.openReadW(&path_w);
+ }
const path_c = try os.toPosixPath(sub_path);
return self.openReadC(&path_c);
}
/// Call `File.close` on the result when done.
pub fn openReadC(self: Dir, sub_path: [*]const u8) File.OpenError!File {
- const flags = os.O_LARGEFILE | os.O_RDONLY | os.O_CLOEXEC;
+ if (builtin.os == .windows) {
+ const path_w = try os.windows.cStrToPrefixedFileW(sub_path);
+ return self.openReadW(&path_w);
+ }
+ const O_LARGEFILE = if (@hasDecl(os, "O_LARGEFILE")) os.O_LARGEFILE else 0;
+ const flags = O_LARGEFILE | os.O_RDONLY | os.O_CLOEXEC;
const fd = try os.openatC(self.fd, sub_path, flags, 0);
return File.openHandle(fd);
}
+ pub fn openReadW(self: Dir, sub_path_w: [*]const u16) File.OpenError!File {
+ const w = os.windows;
+
+ var result = File{ .handle = undefined };
+
+ const path_len_bytes = math.cast(u16, mem.toSliceConst(u16, sub_path_w).len * 2) catch |err| switch (err) {
+ error.Overflow => return error.NameTooLong,
+ };
+ var nt_name = w.UNICODE_STRING{
+ .Length = path_len_bytes,
+ .MaximumLength = path_len_bytes,
+ .Buffer = @intToPtr([*]u16, @ptrToInt(sub_path_w)),
+ };
+ var attr = w.OBJECT_ATTRIBUTES{
+ .Length = @sizeOf(w.OBJECT_ATTRIBUTES),
+ .RootDirectory = if (path.isAbsoluteW(sub_path_w)) null else self.fd,
+ .Attributes = 0, // Note we do not use OBJ_CASE_INSENSITIVE here.
+ .ObjectName = &nt_name,
+ .SecurityDescriptor = null,
+ .SecurityQualityOfService = null,
+ };
+ if (sub_path_w[0] == '.' and sub_path_w[1] == 0) {
+ return error.IsDir;
+ }
+ if (sub_path_w[0] == '.' and sub_path_w[1] == '.' and sub_path_w[2] == 0) {
+ return error.IsDir;
+ }
+ var io: w.IO_STATUS_BLOCK = undefined;
+ const rc = w.ntdll.NtCreateFile(
+ &result.handle,
+ w.GENERIC_READ | w.SYNCHRONIZE,
+ &attr,
+ &io,
+ null,
+ w.FILE_ATTRIBUTE_NORMAL,
+ w.FILE_SHARE_READ,
+ w.FILE_OPEN,
+ w.FILE_NON_DIRECTORY_FILE | w.FILE_SYNCHRONOUS_IO_NONALERT,
+ null,
+ 0,
+ );
+ switch (rc) {
+ w.STATUS.SUCCESS => return result,
+ w.STATUS.OBJECT_NAME_INVALID => unreachable,
+ w.STATUS.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
+ w.STATUS.OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
+ w.STATUS.INVALID_PARAMETER => unreachable,
+ w.STATUS.SHARING_VIOLATION => return error.SharingViolation,
+ w.STATUS.ACCESS_DENIED => return error.AccessDenied,
+ w.STATUS.PIPE_BUSY => return error.PipeBusy,
+ w.STATUS.OBJECT_PATH_SYNTAX_BAD => unreachable,
+ else => return w.unexpectedStatus(rc),
+ }
+ }
+
/// Call `close` on the result when done.
pub fn openDir(self: Dir, sub_path: []const u8) OpenError!Dir {
if (builtin.os == .windows) {
@@ -866,6 +931,34 @@ pub const Dir = struct {
return os.readlinkatC(self.fd, sub_path_c, buffer);
}
+ /// On success, caller owns returned buffer.
+ /// If the file is larger than `max_bytes`, returns `error.FileTooBig`.
+ pub fn readFileAlloc(self: Dir, allocator: *mem.Allocator, file_path: []const u8, max_bytes: usize) ![]u8 {
+ return self.readFileAllocAligned(allocator, file_path, max_bytes, @alignOf(u8));
+ }
+
+ /// On success, caller owns returned buffer.
+ /// If the file is larger than `max_bytes`, returns `error.FileTooBig`.
+ pub fn readFileAllocAligned(
+ self: Dir,
+ allocator: *mem.Allocator,
+ file_path: []const u8,
+ max_bytes: usize,
+ comptime A: u29,
+ ) ![]align(A) u8 {
+ var file = try self.openRead(file_path);
+ defer file.close();
+
+ const size = math.cast(usize, try file.getEndPos()) catch math.maxInt(usize);
+ if (size > max_bytes) return error.FileTooBig;
+
+ const buf = try allocator.alignedAlloc(u8, A, size);
+ errdefer allocator.free(buf);
+
+ try file.inStream().stream.readNoEof(buf);
+ return buf;
+ }
+
pub const DeleteTreeError = error{
AccessDenied,
FileTooBig,
@@ -1100,7 +1193,7 @@ pub const Walker = struct {
}
pub fn deinit(self: *Walker) void {
- while (self.stack.popOrNull()) |*item| item.dir_it.close();
+ while (self.stack.popOrNull()) |*item| item.dir_it.dir.close();
self.stack.deinit();
self.name_buffer.deinit();
}
@@ -1150,9 +1243,9 @@ pub fn openSelfExe() OpenSelfExeError!File {
return File.openReadC(c"/proc/self/exe");
}
if (builtin.os == .windows) {
- var buf: [os.windows.PATH_MAX_WIDE]u16 = undefined;
- const wide_slice = try selfExePathW(&buf);
- return File.openReadW(wide_slice.ptr);
+ const wide_slice = selfExePathW();
+ const prefixed_path_w = try os.windows.wToPrefixedFileW(wide_slice);
+ return Dir.cwd().openReadW(&prefixed_path_w);
}
var buf: [MAX_PATH_BYTES]u8 = undefined;
const self_exe_path = try selfExePath(&buf);
@@ -1203,8 +1296,7 @@ pub fn selfExePath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]u8 {
return mem.toSlice(u8, out_buffer);
},
.windows => {
- var utf16le_buf: [os.windows.PATH_MAX_WIDE]u16 = undefined;
- const utf16le_slice = try selfExePathW(&utf16le_buf);
+ const utf16le_slice = selfExePathW();
// Trust that Windows gives us valid UTF-16LE.
const end_index = std.unicode.utf16leToUtf8(out_buffer, utf16le_slice) catch unreachable;
return out_buffer[0..end_index];
@@ -1213,9 +1305,10 @@ pub fn selfExePath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]u8 {
}
}
-/// Same as `selfExePath` except the result is UTF16LE-encoded.
-pub fn selfExePathW(out_buffer: *[os.windows.PATH_MAX_WIDE]u16) SelfExePathError![]u16 {
- return os.windows.GetModuleFileNameW(null, out_buffer, out_buffer.len);
+/// The result is UTF16LE-encoded.
+pub fn selfExePathW() []const u16 {
+ const image_path_name = &os.windows.peb().ProcessParameters.ImagePathName;
+ return mem.toSliceConst(u16, image_path_name.Buffer);
}
/// `selfExeDirPath` except allocates the result on the heap.
diff --git a/lib/std/fs/file.zig b/lib/std/fs/file.zig
index 431b89bebf..b25403fa02 100644
--- a/lib/std/fs/file.zig
+++ b/lib/std/fs/file.zig
@@ -25,42 +25,23 @@ pub const File = struct {
pub const OpenError = windows.CreateFileError || os.OpenError;
- /// Call close to clean up.
+ /// Deprecated; call `std.fs.Dir.openRead` directly.
pub fn openRead(path: []const u8) OpenError!File {
- if (builtin.os == .windows) {
- const path_w = try windows.sliceToPrefixedFileW(path);
- return openReadW(&path_w);
- }
- const path_c = try os.toPosixPath(path);
- return openReadC(&path_c);
+ return std.fs.Dir.cwd().openRead(path);
}
- /// `openRead` except with a null terminated path
- pub fn openReadC(path: [*]const u8) OpenError!File {
- if (builtin.os == .windows) {
- const path_w = try windows.cStrToPrefixedFileW(path);
- return openReadW(&path_w);
- }
- const flags = os.O_LARGEFILE | os.O_RDONLY | os.O_CLOEXEC;
- const fd = try os.openC(path, flags, 0);
- return openHandle(fd);
+ /// Deprecated; call `std.fs.Dir.openReadC` directly.
+ pub fn openReadC(path_c: [*]const u8) OpenError!File {
+ return std.fs.Dir.cwd().openReadC(path_c);
}
- /// `openRead` except with a null terminated UTF16LE encoded path
+ /// Deprecated; call `std.fs.Dir.openReadW` directly.
pub fn openReadW(path_w: [*]const u16) OpenError!File {
- const handle = try windows.CreateFileW(
- path_w,
- windows.GENERIC_READ,
- windows.FILE_SHARE_READ,
- null,
- windows.OPEN_EXISTING,
- windows.FILE_ATTRIBUTE_NORMAL,
- null,
- );
- return openHandle(handle);
+ return std.fs.Dir.cwd().openReadW(path_w);
}
/// Calls `openWriteMode` with `default_mode` for the mode.
+ /// TODO: deprecate this and move it to `std.fs.Dir`.
pub fn openWrite(path: []const u8) OpenError!File {
return openWriteMode(path, default_mode);
}
@@ -68,6 +49,7 @@ pub const File = struct {
/// If the path does not exist it will be created.
/// If a file already exists in the destination it will be truncated.
/// Call close to clean up.
+ /// TODO: deprecate this and move it to `std.fs.Dir`.
pub fn openWriteMode(path: []const u8, file_mode: Mode) OpenError!File {
if (builtin.os == .windows) {
const path_w = try windows.sliceToPrefixedFileW(path);
@@ -78,17 +60,20 @@ pub const File = struct {
}
/// Same as `openWriteMode` except `path` is null-terminated.
+ /// TODO: deprecate this and move it to `std.fs.Dir`.
pub fn openWriteModeC(path: [*]const u8, file_mode: Mode) OpenError!File {
if (builtin.os == .windows) {
const path_w = try windows.cStrToPrefixedFileW(path);
return openWriteModeW(&path_w, file_mode);
}
- const flags = os.O_LARGEFILE | os.O_WRONLY | os.O_CREAT | os.O_CLOEXEC | os.O_TRUNC;
+ const O_LARGEFILE = if (@hasDecl(os, "O_LARGEFILE")) os.O_LARGEFILE else 0;
+ const flags = O_LARGEFILE | os.O_WRONLY | os.O_CREAT | os.O_CLOEXEC | os.O_TRUNC;
const fd = try os.openC(path, flags, file_mode);
return openHandle(fd);
}
/// Same as `openWriteMode` except `path` is null-terminated and UTF16LE encoded
+ /// TODO: deprecate this and move it to `std.fs.Dir`.
pub fn openWriteModeW(path_w: [*]const u16, file_mode: Mode) OpenError!File {
const handle = try windows.CreateFileW(
path_w,
@@ -105,6 +90,7 @@ pub const File = struct {
/// If the path does not exist it will be created.
/// If a file already exists in the destination this returns OpenError.PathAlreadyExists
/// Call close to clean up.
+ /// TODO: deprecate this and move it to `std.fs.Dir`.
pub fn openWriteNoClobber(path: []const u8, file_mode: Mode) OpenError!File {
if (builtin.os == .windows) {
const path_w = try windows.sliceToPrefixedFileW(path);
@@ -114,16 +100,19 @@ pub const File = struct {
return openWriteNoClobberC(&path_c, file_mode);
}
+ /// TODO: deprecate this and move it to `std.fs.Dir`.
pub fn openWriteNoClobberC(path: [*]const u8, file_mode: Mode) OpenError!File {
if (builtin.os == .windows) {
const path_w = try windows.cStrToPrefixedFileW(path);
return openWriteNoClobberW(&path_w, file_mode);
}
- const flags = os.O_LARGEFILE | os.O_WRONLY | os.O_CREAT | os.O_CLOEXEC | os.O_EXCL;
+ const O_LARGEFILE = if (@hasDecl(os, "O_LARGEFILE")) os.O_LARGEFILE else 0;
+ const flags = O_LARGEFILE | os.O_WRONLY | os.O_CREAT | os.O_CLOEXEC | os.O_EXCL;
const fd = try os.openC(path, flags, file_mode);
return openHandle(fd);
}
+ /// TODO: deprecate this and move it to `std.fs.Dir`.
pub fn openWriteNoClobberW(path_w: [*]const u16, file_mode: Mode) OpenError!File {
const handle = try windows.CreateFileW(
path_w,
@@ -146,16 +135,19 @@ pub const File = struct {
/// In general it is recommended to avoid this function. For example,
/// instead of testing if a file exists and then opening it, just
/// open it and handle the error for file not found.
+ /// TODO: deprecate this and move it to `std.fs.Dir`.
pub fn access(path: []const u8) !void {
return os.access(path, os.F_OK);
}
/// Same as `access` except the parameter is null-terminated.
+ /// TODO: deprecate this and move it to `std.fs.Dir`.
pub fn accessC(path: [*]const u8) !void {
return os.accessC(path, os.F_OK);
}
/// Same as `access` except the parameter is null-terminated UTF16LE-encoded.
+ /// TODO: deprecate this and move it to `std.fs.Dir`.
pub fn accessW(path: [*]const u16) !void {
return os.accessW(path, os.F_OK);
}
@@ -272,9 +264,9 @@ pub const File = struct {
return Stat{
.size = @bitCast(u64, st.size),
.mode = st.mode,
- .atime = i64(atime.tv_sec) * std.time.ns_per_s + atime.tv_nsec,
- .mtime = i64(mtime.tv_sec) * std.time.ns_per_s + mtime.tv_nsec,
- .ctime = i64(ctime.tv_sec) * std.time.ns_per_s + ctime.tv_nsec,
+ .atime = @as(i64, atime.tv_sec) * std.time.ns_per_s + atime.tv_nsec,
+ .mtime = @as(i64, mtime.tv_sec) * std.time.ns_per_s + mtime.tv_nsec,
+ .ctime = @as(i64, ctime.tv_sec) * std.time.ns_per_s + ctime.tv_nsec,
};
}
diff --git a/lib/std/fs/path.zig b/lib/std/fs/path.zig
index 1c9e3e100b..6a24055667 100644
--- a/lib/std/fs/path.zig
+++ b/lib/std/fs/path.zig
@@ -32,7 +32,7 @@ pub fn isSep(byte: u8) bool {
/// This is different from mem.join in that the separator will not be repeated if
/// it is found at the end or beginning of a pair of consecutive paths.
fn joinSep(allocator: *Allocator, separator: u8, paths: []const []const u8) ![]u8 {
- if (paths.len == 0) return (([*]u8)(undefined))[0..0];
+ if (paths.len == 0) return &[0]u8{};
const total_len = blk: {
var sum: usize = paths[0].len;
diff --git a/lib/std/hash/auto_hash.zig b/lib/std/hash/auto_hash.zig
index 3a4abcbcd9..1df434116c 100644
--- a/lib/std/hash/auto_hash.zig
+++ b/lib/std/hash/auto_hash.zig
@@ -306,7 +306,7 @@ test "hash struct deep" {
test "testHash optional" {
const a: ?u32 = 123;
const b: ?u32 = null;
- testing.expectEqual(testHash(a), testHash(u32(123)));
+ testing.expectEqual(testHash(a), testHash(@as(u32, 123)));
testing.expect(testHash(a) != testHash(b));
testing.expectEqual(testHash(b), 0);
}
@@ -315,9 +315,9 @@ test "testHash array" {
const a = [_]u32{ 1, 2, 3 };
const h = testHash(a);
var hasher = Wyhash.init(0);
- autoHash(&hasher, u32(1));
- autoHash(&hasher, u32(2));
- autoHash(&hasher, u32(3));
+ autoHash(&hasher, @as(u32, 1));
+ autoHash(&hasher, @as(u32, 2));
+ autoHash(&hasher, @as(u32, 3));
testing.expectEqual(h, hasher.final());
}
@@ -330,9 +330,9 @@ test "testHash struct" {
const f = Foo{};
const h = testHash(f);
var hasher = Wyhash.init(0);
- autoHash(&hasher, u32(1));
- autoHash(&hasher, u32(2));
- autoHash(&hasher, u32(3));
+ autoHash(&hasher, @as(u32, 1));
+ autoHash(&hasher, @as(u32, 2));
+ autoHash(&hasher, @as(u32, 3));
testing.expectEqual(h, hasher.final());
}
diff --git a/lib/std/hash/cityhash.zig b/lib/std/hash/cityhash.zig
index 43e5b7a385..d31ee17105 100644
--- a/lib/std/hash/cityhash.zig
+++ b/lib/std/hash/cityhash.zig
@@ -214,7 +214,7 @@ pub const CityHash64 = struct {
}
fn hashLen0To16(str: []const u8) u64 {
- const len: u64 = u64(str.len);
+ const len: u64 = @as(u64, str.len);
if (len >= 8) {
const mul: u64 = k2 +% len *% 2;
const a: u64 = fetch64(str.ptr) +% k2;
@@ -240,7 +240,7 @@ pub const CityHash64 = struct {
}
fn hashLen17To32(str: []const u8) u64 {
- const len: u64 = u64(str.len);
+ const len: u64 = @as(u64, str.len);
const mul: u64 = k2 +% len *% 2;
const a: u64 = fetch64(str.ptr) *% k1;
const b: u64 = fetch64(str.ptr + 8);
@@ -251,7 +251,7 @@ pub const CityHash64 = struct {
}
fn hashLen33To64(str: []const u8) u64 {
- const len: u64 = u64(str.len);
+ const len: u64 = @as(u64, str.len);
const mul: u64 = k2 +% len *% 2;
const a: u64 = fetch64(str.ptr) *% k2;
const b: u64 = fetch64(str.ptr + 8);
@@ -305,7 +305,7 @@ pub const CityHash64 = struct {
return hashLen33To64(str);
}
- var len: u64 = u64(str.len);
+ var len: u64 = @as(u64, str.len);
var x: u64 = fetch64(str.ptr + str.len - 40);
var y: u64 = fetch64(str.ptr + str.len - 16) +% fetch64(str.ptr + str.len - 56);
diff --git a/lib/std/hash/crc.zig b/lib/std/hash/crc.zig
index cdcaf55610..6176ded81d 100644
--- a/lib/std/hash/crc.zig
+++ b/lib/std/hash/crc.zig
@@ -65,10 +65,10 @@ pub fn Crc32WithPoly(comptime poly: u32) type {
const p = input[i .. i + 8];
// Unrolling this way gives ~50Mb/s increase
- self.crc ^= (u32(p[0]) << 0);
- self.crc ^= (u32(p[1]) << 8);
- self.crc ^= (u32(p[2]) << 16);
- self.crc ^= (u32(p[3]) << 24);
+ self.crc ^= (@as(u32, p[0]) << 0);
+ self.crc ^= (@as(u32, p[1]) << 8);
+ self.crc ^= (@as(u32, p[2]) << 16);
+ self.crc ^= (@as(u32, p[3]) << 24);
self.crc =
lookup_tables[0][p[7]] ^
diff --git a/lib/std/hash/murmur.zig b/lib/std/hash/murmur.zig
index a0c8f91338..f70190d311 100644
--- a/lib/std/hash/murmur.zig
+++ b/lib/std/hash/murmur.zig
@@ -98,7 +98,7 @@ pub const Murmur2_64 = struct {
pub fn hashWithSeed(str: []const u8, seed: u64) u64 {
const m: u64 = 0xc6a4a7935bd1e995;
- const len = u64(str.len);
+ const len = @as(u64, str.len);
var h1: u64 = seed ^ (len *% m);
for (@ptrCast([*]allowzero align(1) const u64, str.ptr)[0..@intCast(usize, len >> 3)]) |v| {
var k1: u64 = v;
diff --git a/lib/std/hash/siphash.zig b/lib/std/hash/siphash.zig
index 3d67ba685b..c3a9184fa4 100644
--- a/lib/std/hash/siphash.zig
+++ b/lib/std/hash/siphash.zig
@@ -102,7 +102,7 @@ fn SipHashStateless(comptime T: type, comptime c_rounds: usize, comptime d_round
}
const b2 = self.v0 ^ self.v1 ^ self.v2 ^ self.v3;
- return (u128(b2) << 64) | b1;
+ return (@as(u128, b2) << 64) | b1;
}
fn round(self: *Self, b: []const u8) void {
@@ -121,19 +121,19 @@ fn SipHashStateless(comptime T: type, comptime c_rounds: usize, comptime d_round
fn sipRound(d: *Self) void {
d.v0 +%= d.v1;
- d.v1 = math.rotl(u64, d.v1, u64(13));
+ d.v1 = math.rotl(u64, d.v1, @as(u64, 13));
d.v1 ^= d.v0;
- d.v0 = math.rotl(u64, d.v0, u64(32));
+ d.v0 = math.rotl(u64, d.v0, @as(u64, 32));
d.v2 +%= d.v3;
- d.v3 = math.rotl(u64, d.v3, u64(16));
+ d.v3 = math.rotl(u64, d.v3, @as(u64, 16));
d.v3 ^= d.v2;
d.v0 +%= d.v3;
- d.v3 = math.rotl(u64, d.v3, u64(21));
+ d.v3 = math.rotl(u64, d.v3, @as(u64, 21));
d.v3 ^= d.v0;
d.v2 +%= d.v1;
- d.v1 = math.rotl(u64, d.v1, u64(17));
+ d.v1 = math.rotl(u64, d.v1, @as(u64, 17));
d.v1 ^= d.v2;
- d.v2 = math.rotl(u64, d.v2, u64(32));
+ d.v2 = math.rotl(u64, d.v2, @as(u64, 32));
}
pub fn hash(key: []const u8, input: []const u8) T {
diff --git a/lib/std/hash_map.zig b/lib/std/hash_map.zig
index 7c872de5ca..aae3b60831 100644
--- a/lib/std/hash_map.zig
+++ b/lib/std/hash_map.zig
@@ -402,7 +402,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3
}
fn keyToIndex(hm: Self, key: K) usize {
- return hm.constrainIndex(usize(hash(key)));
+ return hm.constrainIndex(@as(usize, hash(key)));
}
fn constrainIndex(hm: Self, i: usize) usize {
diff --git a/lib/std/heap.zig b/lib/std/heap.zig
index 8723c7eab6..24ab395734 100644
--- a/lib/std/heap.zig
+++ b/lib/std/heap.zig
@@ -41,8 +41,7 @@ var direct_allocator_state = Allocator{
const DirectAllocator = struct {
fn alloc(allocator: *Allocator, n: usize, alignment: u29) error{OutOfMemory}![]u8 {
- if (n == 0)
- return (([*]u8)(undefined))[0..0];
+ if (n == 0) return &[0]u8{};
if (builtin.os == .windows) {
const w = os.windows;
@@ -261,8 +260,7 @@ pub const HeapAllocator = switch (builtin.os) {
fn alloc(allocator: *Allocator, n: usize, alignment: u29) error{OutOfMemory}![]u8 {
const self = @fieldParentPtr(HeapAllocator, "allocator", allocator);
- if (n == 0)
- return (([*]u8)(undefined))[0..0];
+ if (n == 0) return &[0]u8{};
const amt = n + alignment + @sizeOf(usize);
const optional_heap_handle = @atomicLoad(?HeapHandle, &self.heap_handle, builtin.AtomicOrder.SeqCst);
@@ -677,7 +675,7 @@ pub fn StackFallbackAllocator(comptime size: usize) type {
) catch {
const result = try self.fallback_allocator.reallocFn(
self.fallback_allocator,
- ([*]u8)(undefined)[0..0],
+ &[0]u8{},
undefined,
new_size,
new_align,
@@ -895,10 +893,10 @@ fn testAllocatorLargeAlignment(allocator: *mem.Allocator) mem.Allocator.Error!vo
if (mem.page_size << 2 > maxInt(usize)) return;
const USizeShift = @IntType(false, std.math.log2(usize.bit_count));
- const large_align = u29(mem.page_size << 2);
+ const large_align = @as(u29, mem.page_size << 2);
var align_mask: usize = undefined;
- _ = @shlWithOverflow(usize, ~usize(0), USizeShift(@ctz(u29, large_align)), &align_mask);
+ _ = @shlWithOverflow(usize, ~@as(usize, 0), @as(USizeShift, @ctz(u29, large_align)), &align_mask);
var slice = try allocator.alignedAlloc(u8, large_align, 500);
testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
diff --git a/lib/std/http/headers.zig b/lib/std/http/headers.zig
index 7ee035ce80..a860186e47 100644
--- a/lib/std/http/headers.zig
+++ b/lib/std/http/headers.zig
@@ -399,7 +399,7 @@ test "Headers.iterator" {
}
count += 1;
}
- testing.expectEqual(i32(2), count);
+ testing.expectEqual(@as(i32, 2), count);
}
test "Headers.contains" {
@@ -420,10 +420,10 @@ test "Headers.delete" {
try h.append("cookie", "somevalue", null);
testing.expectEqual(false, h.delete("not-present"));
- testing.expectEqual(usize(3), h.count());
+ testing.expectEqual(@as(usize, 3), h.count());
testing.expectEqual(true, h.delete("foo"));
- testing.expectEqual(usize(2), h.count());
+ testing.expectEqual(@as(usize, 2), h.count());
{
const e = h.at(0);
testing.expectEqualSlices(u8, "baz", e.name);
@@ -448,7 +448,7 @@ test "Headers.orderedRemove" {
try h.append("cookie", "somevalue", null);
h.orderedRemove(0);
- testing.expectEqual(usize(2), h.count());
+ testing.expectEqual(@as(usize, 2), h.count());
{
const e = h.at(0);
testing.expectEqualSlices(u8, "baz", e.name);
@@ -471,7 +471,7 @@ test "Headers.swapRemove" {
try h.append("cookie", "somevalue", null);
h.swapRemove(0);
- testing.expectEqual(usize(2), h.count());
+ testing.expectEqual(@as(usize, 2), h.count());
{
const e = h.at(0);
testing.expectEqualSlices(u8, "cookie", e.name);
diff --git a/lib/std/io.zig b/lib/std/io.zig
index 95280b888f..124d3cf253 100644
--- a/lib/std/io.zig
+++ b/lib/std/io.zig
@@ -34,28 +34,23 @@ else
Mode.blocking;
pub const is_async = mode != .blocking;
-pub const GetStdIoError = os.windows.GetStdHandleError;
-
-pub fn getStdOut() GetStdIoError!File {
+pub fn getStdOut() File {
if (builtin.os == .windows) {
- const handle = try os.windows.GetStdHandle(os.windows.STD_OUTPUT_HANDLE);
- return File.openHandle(handle);
+ return File.openHandle(os.windows.peb().ProcessParameters.hStdOutput);
}
return File.openHandle(os.STDOUT_FILENO);
}
-pub fn getStdErr() GetStdIoError!File {
+pub fn getStdErr() File {
if (builtin.os == .windows) {
- const handle = try os.windows.GetStdHandle(os.windows.STD_ERROR_HANDLE);
- return File.openHandle(handle);
+ return File.openHandle(os.windows.peb().ProcessParameters.hStdError);
}
return File.openHandle(os.STDERR_FILENO);
}
-pub fn getStdIn() GetStdIoError!File {
+pub fn getStdIn() File {
if (builtin.os == .windows) {
- const handle = try os.windows.GetStdHandle(os.windows.STD_INPUT_HANDLE);
- return File.openHandle(handle);
+ return File.openHandle(os.windows.peb().ProcessParameters.hStdInput);
}
return File.openHandle(os.STDIN_FILENO);
}
@@ -74,24 +69,9 @@ pub fn writeFile(path: []const u8, data: []const u8) !void {
}
/// On success, caller owns returned buffer.
-/// TODO move this to `std.fs` and add a version to `std.fs.Dir`.
+/// This function is deprecated; use `std.fs.Dir.readFileAlloc`.
pub fn readFileAlloc(allocator: *mem.Allocator, path: []const u8) ![]u8 {
- return readFileAllocAligned(allocator, path, @alignOf(u8));
-}
-
-/// On success, caller owns returned buffer.
-/// TODO move this to `std.fs` and add a version to `std.fs.Dir`.
-pub fn readFileAllocAligned(allocator: *mem.Allocator, path: []const u8, comptime A: u29) ![]align(A) u8 {
- var file = try File.openRead(path);
- defer file.close();
-
- const size = try math.cast(usize, try file.getEndPos());
- const buf = try allocator.alignedAlloc(u8, A, size);
- errdefer allocator.free(buf);
-
- var adapter = file.inStream();
- try adapter.stream.readNoEof(buf[0..size]);
- return buf;
+ return fs.Dir.cwd().readFileAlloc(allocator, path, math.maxInt(usize));
}
pub fn BufferedInStream(comptime Error: type) type {
@@ -353,21 +333,21 @@ pub fn BitInStream(endian: builtin.Endian, comptime Error: type) type {
const Buf = @IntType(false, buf_bit_count);
const BufShift = math.Log2Int(Buf);
- out_bits.* = usize(0);
+ out_bits.* = @as(usize, 0);
if (U == u0 or bits == 0) return 0;
- var out_buffer = Buf(0);
+ var out_buffer = @as(Buf, 0);
if (self.bit_count > 0) {
const n = if (self.bit_count >= bits) @intCast(u3, bits) else self.bit_count;
const shift = u7_bit_count - n;
switch (endian) {
builtin.Endian.Big => {
- out_buffer = Buf(self.bit_buffer >> shift);
+ out_buffer = @as(Buf, self.bit_buffer >> shift);
self.bit_buffer <<= n;
},
builtin.Endian.Little => {
const value = (self.bit_buffer << shift) >> shift;
- out_buffer = Buf(value);
+ out_buffer = @as(Buf, value);
self.bit_buffer >>= n;
},
}
@@ -393,28 +373,28 @@ pub fn BitInStream(endian: builtin.Endian, comptime Error: type) type {
if (n >= u8_bit_count) {
out_buffer <<= @intCast(u3, u8_bit_count - 1);
out_buffer <<= 1;
- out_buffer |= Buf(next_byte);
+ out_buffer |= @as(Buf, next_byte);
out_bits.* += u8_bit_count;
continue;
}
const shift = @intCast(u3, u8_bit_count - n);
out_buffer <<= @intCast(BufShift, n);
- out_buffer |= Buf(next_byte >> shift);
+ out_buffer |= @as(Buf, next_byte >> shift);
out_bits.* += n;
self.bit_buffer = @truncate(u7, next_byte << @intCast(u3, n - 1));
self.bit_count = shift;
},
builtin.Endian.Little => {
if (n >= u8_bit_count) {
- out_buffer |= Buf(next_byte) << @intCast(BufShift, out_bits.*);
+ out_buffer |= @as(Buf, next_byte) << @intCast(BufShift, out_bits.*);
out_bits.* += u8_bit_count;
continue;
}
const shift = @intCast(u3, u8_bit_count - n);
const value = (next_byte << shift) >> shift;
- out_buffer |= Buf(value) << @intCast(BufShift, out_bits.*);
+ out_buffer |= @as(Buf, value) << @intCast(BufShift, out_bits.*);
out_bits.* += n;
self.bit_buffer = @truncate(u7, next_byte >> @intCast(u3, n));
self.bit_count = shift;
@@ -434,7 +414,7 @@ pub fn BitInStream(endian: builtin.Endian, comptime Error: type) type {
var self = @fieldParentPtr(Self, "stream", self_stream);
var out_bits: usize = undefined;
- var out_bits_total = usize(0);
+ var out_bits_total = @as(usize, 0);
//@NOTE: I'm not sure this is a good idea, maybe alignToByte should be forced
if (self.bit_count > 0) {
for (buffer) |*b, i| {
@@ -598,7 +578,7 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr
self.index = 0;
}
- fn writeFn(out_stream: *Stream, bytes: []const u8) !void {
+ fn writeFn(out_stream: *Stream, bytes: []const u8) Error!void {
const self = @fieldParentPtr(Self, "stream", out_stream);
if (bytes.len >= self.buffer.len) {
@@ -814,8 +794,7 @@ pub const BufferedAtomicFile = struct {
};
pub fn readLine(buf: *std.Buffer) ![]u8 {
- var stdin = try getStdIn();
- var stdin_stream = stdin.inStream();
+ var stdin_stream = getStdIn().inStream();
return readLineFrom(&stdin_stream.stream, buf);
}
@@ -856,8 +835,7 @@ test "io.readLineFrom" {
}
pub fn readLineSlice(slice: []u8) ![]u8 {
- var stdin = try getStdIn();
- var stdin_stream = stdin.inStream();
+ var stdin_stream = getStdIn().inStream();
return readLineSliceFrom(&stdin_stream.stream, slice);
}
@@ -949,14 +927,14 @@ pub fn Deserializer(comptime endian: builtin.Endian, comptime packing: Packing,
return @truncate(T, @bitCast(PossiblySignedByte, buffer[0]));
}
- var result = U(0);
+ var result = @as(U, 0);
for (buffer) |byte, i| {
switch (endian) {
builtin.Endian.Big => {
result = (result << u8_bit_count) | byte;
},
builtin.Endian.Little => {
- result |= U(byte) << @intCast(Log2U, u8_bit_count * i);
+ result |= @as(U, byte) << @intCast(Log2U, u8_bit_count * i);
},
}
}
@@ -1050,7 +1028,7 @@ pub fn Deserializer(comptime endian: builtin.Endian, comptime packing: Packing,
return;
}
- ptr.* = OC(undefined); //make it non-null so the following .? is guaranteed safe
+ ptr.* = @as(OC, undefined); //make it non-null so the following .? is guaranteed safe
const val_ptr = &ptr.*.?;
try self.deserializeInto(val_ptr);
},
@@ -1154,7 +1132,7 @@ pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, co
switch (@typeId(T)) {
builtin.TypeId.Void => return,
- builtin.TypeId.Bool => try self.serializeInt(u1(@boolToInt(value))),
+ builtin.TypeId.Bool => try self.serializeInt(@as(u1, @boolToInt(value))),
builtin.TypeId.Float, builtin.TypeId.Int => try self.serializeInt(value),
builtin.TypeId.Struct => {
const info = @typeInfo(T);
@@ -1197,10 +1175,10 @@ pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, co
},
builtin.TypeId.Optional => {
if (value == null) {
- try self.serializeInt(u1(@boolToInt(false)));
+ try self.serializeInt(@as(u1, @boolToInt(false)));
return;
}
- try self.serializeInt(u1(@boolToInt(true)));
+ try self.serializeInt(@as(u1, @boolToInt(true)));
const OC = comptime meta.Child(T);
const val_ptr = &value.?;
diff --git a/lib/std/io/out_stream.zig b/lib/std/io/out_stream.zig
index 42c40337a8..c0cd6e48a1 100644
--- a/lib/std/io/out_stream.zig
+++ b/lib/std/io/out_stream.zig
@@ -40,12 +40,12 @@ pub fn OutStream(comptime WriteError: type) type {
}
pub fn writeByte(self: *Self, byte: u8) Error!void {
- const slice = (*const [1]u8)(&byte)[0..];
+ const slice = @as(*const [1]u8, &byte)[0..];
return self.writeFn(self, slice);
}
pub fn writeByteNTimes(self: *Self, byte: u8, n: usize) Error!void {
- const slice = (*const [1]u8)(&byte)[0..];
+ const slice = @as(*const [1]u8, &byte)[0..];
var i: usize = 0;
while (i < n) : (i += 1) {
try self.writeFn(self, slice);
diff --git a/lib/std/io/test.zig b/lib/std/io/test.zig
index e93b74169b..28b8371d9d 100644
--- a/lib/std/io/test.zig
+++ b/lib/std/io/test.zig
@@ -226,49 +226,49 @@ test "BitOutStream" {
const OutError = io.SliceOutStream.Error;
var bit_stream_be = io.BitOutStream(builtin.Endian.Big, OutError).init(&mem_out_be.stream);
- try bit_stream_be.writeBits(u2(1), 1);
- try bit_stream_be.writeBits(u5(2), 2);
- try bit_stream_be.writeBits(u128(3), 3);
- try bit_stream_be.writeBits(u8(4), 4);
- try bit_stream_be.writeBits(u9(5), 5);
- try bit_stream_be.writeBits(u1(1), 1);
+ try bit_stream_be.writeBits(@as(u2, 1), 1);
+ try bit_stream_be.writeBits(@as(u5, 2), 2);
+ try bit_stream_be.writeBits(@as(u128, 3), 3);
+ try bit_stream_be.writeBits(@as(u8, 4), 4);
+ try bit_stream_be.writeBits(@as(u9, 5), 5);
+ try bit_stream_be.writeBits(@as(u1, 1), 1);
expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001011);
mem_out_be.pos = 0;
- try bit_stream_be.writeBits(u15(0b110011010000101), 15);
+ try bit_stream_be.writeBits(@as(u15, 0b110011010000101), 15);
try bit_stream_be.flushBits();
expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001010);
mem_out_be.pos = 0;
- try bit_stream_be.writeBits(u32(0b110011010000101), 16);
+ try bit_stream_be.writeBits(@as(u32, 0b110011010000101), 16);
expect(mem_be[0] == 0b01100110 and mem_be[1] == 0b10000101);
- try bit_stream_be.writeBits(u0(0), 0);
+ try bit_stream_be.writeBits(@as(u0, 0), 0);
var mem_out_le = io.SliceOutStream.init(mem_le[0..]);
var bit_stream_le = io.BitOutStream(builtin.Endian.Little, OutError).init(&mem_out_le.stream);
- try bit_stream_le.writeBits(u2(1), 1);
- try bit_stream_le.writeBits(u5(2), 2);
- try bit_stream_le.writeBits(u128(3), 3);
- try bit_stream_le.writeBits(u8(4), 4);
- try bit_stream_le.writeBits(u9(5), 5);
- try bit_stream_le.writeBits(u1(1), 1);
+ try bit_stream_le.writeBits(@as(u2, 1), 1);
+ try bit_stream_le.writeBits(@as(u5, 2), 2);
+ try bit_stream_le.writeBits(@as(u128, 3), 3);
+ try bit_stream_le.writeBits(@as(u8, 4), 4);
+ try bit_stream_le.writeBits(@as(u9, 5), 5);
+ try bit_stream_le.writeBits(@as(u1, 1), 1);
expect(mem_le[0] == 0b00011101 and mem_le[1] == 0b10010101);
mem_out_le.pos = 0;
- try bit_stream_le.writeBits(u15(0b110011010000101), 15);
+ try bit_stream_le.writeBits(@as(u15, 0b110011010000101), 15);
try bit_stream_le.flushBits();
expect(mem_le[0] == 0b10000101 and mem_le[1] == 0b01100110);
mem_out_le.pos = 0;
- try bit_stream_le.writeBits(u32(0b1100110100001011), 16);
+ try bit_stream_le.writeBits(@as(u32, 0b1100110100001011), 16);
expect(mem_le[0] == 0b00001011 and mem_le[1] == 0b11001101);
- try bit_stream_le.writeBits(u0(0), 0);
+ try bit_stream_le.writeBits(@as(u0, 0), 0);
}
test "BitStreams with File Stream" {
@@ -282,12 +282,12 @@ test "BitStreams with File Stream" {
const OutError = File.WriteError;
var bit_stream = io.BitOutStream(builtin.endian, OutError).init(file_out_stream);
- try bit_stream.writeBits(u2(1), 1);
- try bit_stream.writeBits(u5(2), 2);
- try bit_stream.writeBits(u128(3), 3);
- try bit_stream.writeBits(u8(4), 4);
- try bit_stream.writeBits(u9(5), 5);
- try bit_stream.writeBits(u1(1), 1);
+ try bit_stream.writeBits(@as(u2, 1), 1);
+ try bit_stream.writeBits(@as(u5, 2), 2);
+ try bit_stream.writeBits(@as(u128, 3), 3);
+ try bit_stream.writeBits(@as(u8, 4), 4);
+ try bit_stream.writeBits(@as(u9, 5), 5);
+ try bit_stream.writeBits(@as(u1, 1), 1);
try bit_stream.flushBits();
}
{
@@ -345,8 +345,8 @@ fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packi
inline while (i <= max_test_bitsize) : (i += 1) {
const U = @IntType(false, i);
const S = @IntType(true, i);
- try serializer.serializeInt(U(i));
- if (i != 0) try serializer.serializeInt(S(-1)) else try serializer.serialize(S(0));
+ try serializer.serializeInt(@as(U, i));
+ if (i != 0) try serializer.serializeInt(@as(S, -1)) else try serializer.serialize(@as(S, 0));
}
try serializer.flush();
@@ -356,8 +356,8 @@ fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packi
const S = @IntType(true, i);
const x = try deserializer.deserializeInt(U);
const y = try deserializer.deserializeInt(S);
- expect(x == U(i));
- if (i != 0) expect(y == S(-1)) else expect(y == 0);
+ expect(x == @as(U, i));
+ if (i != 0) expect(y == @as(S, -1)) else expect(y == 0);
}
const u8_bit_count = comptime meta.bitCount(u8);
@@ -577,11 +577,11 @@ fn testBadData(comptime endian: builtin.Endian, comptime packing: io.Packing) !v
var in_stream = &in.stream;
var deserializer = io.Deserializer(endian, packing, InError).init(in_stream);
- try serializer.serialize(u14(3));
+ try serializer.serialize(@as(u14, 3));
expectError(error.InvalidEnumTag, deserializer.deserialize(A));
out.pos = 0;
- try serializer.serialize(u14(3));
- try serializer.serialize(u14(88));
+ try serializer.serialize(@as(u14, 3));
+ try serializer.serialize(@as(u14, 88));
expectError(error.InvalidEnumTag, deserializer.deserialize(C));
}
@@ -603,7 +603,7 @@ test "c out stream" {
}
const out_stream = &io.COutStream.init(out_file).stream;
- try out_stream.print("hi: {}\n", i32(123));
+ try out_stream.print("hi: {}\n", @as(i32, 123));
}
test "File seek ops" {
diff --git a/lib/std/json.zig b/lib/std/json.zig
index e126f103ae..6946ba0170 100644
--- a/lib/std/json.zig
+++ b/lib/std/json.zig
@@ -1012,119 +1012,39 @@ pub const Value = union(enum) {
Object: ObjectMap,
pub fn dump(self: Value) void {
- switch (self) {
- Value.Null => {
- debug.warn("null");
- },
- Value.Bool => |inner| {
- debug.warn("{}", inner);
- },
- Value.Integer => |inner| {
- debug.warn("{}", inner);
- },
- Value.Float => |inner| {
- debug.warn("{:.5}", inner);
- },
- Value.String => |inner| {
- debug.warn("\"{}\"", inner);
- },
- Value.Array => |inner| {
- var not_first = false;
- debug.warn("[");
- for (inner.toSliceConst()) |value| {
- if (not_first) {
- debug.warn(",");
- }
- not_first = true;
- value.dump();
- }
- debug.warn("]");
- },
- Value.Object => |inner| {
- var not_first = false;
- debug.warn("{{");
- var it = inner.iterator();
-
- while (it.next()) |entry| {
- if (not_first) {
- debug.warn(",");
- }
- not_first = true;
- debug.warn("\"{}\":", entry.key);
- entry.value.dump();
- }
- debug.warn("}}");
- },
- }
+ var held = std.debug.getStderrMutex().acquire();
+ defer held.release();
+
+ const stderr = std.debug.getStderrStream();
+ self.dumpStream(stderr, 1024) catch return;
}
- pub fn dumpIndent(self: Value, indent: usize) void {
+ pub fn dumpIndent(self: Value, comptime indent: usize) void {
if (indent == 0) {
self.dump();
} else {
- self.dumpIndentLevel(indent, 0);
+ var held = std.debug.getStderrMutex().acquire();
+ defer held.release();
+
+ const stderr = std.debug.getStderrStream();
+ self.dumpStreamIndent(indent, stderr, 1024) catch return;
}
}
- fn dumpIndentLevel(self: Value, indent: usize, level: usize) void {
- switch (self) {
- Value.Null => {
- debug.warn("null");
- },
- Value.Bool => |inner| {
- debug.warn("{}", inner);
- },
- Value.Integer => |inner| {
- debug.warn("{}", inner);
- },
- Value.Float => |inner| {
- debug.warn("{:.5}", inner);
- },
- Value.String => |inner| {
- debug.warn("\"{}\"", inner);
- },
- Value.Array => |inner| {
- var not_first = false;
- debug.warn("[\n");
-
- for (inner.toSliceConst()) |value| {
- if (not_first) {
- debug.warn(",\n");
- }
- not_first = true;
- padSpace(level + indent);
- value.dumpIndentLevel(indent, level + indent);
- }
- debug.warn("\n");
- padSpace(level);
- debug.warn("]");
- },
- Value.Object => |inner| {
- var not_first = false;
- debug.warn("{{\n");
- var it = inner.iterator();
-
- while (it.next()) |entry| {
- if (not_first) {
- debug.warn(",\n");
- }
- not_first = true;
- padSpace(level + indent);
- debug.warn("\"{}\": ", entry.key);
- entry.value.dumpIndentLevel(indent, level + indent);
- }
- debug.warn("\n");
- padSpace(level);
- debug.warn("}}");
- },
- }
+ pub fn dumpStream(self: @This(), stream: var, comptime max_depth: usize) !void {
+ var w = std.json.WriteStream(@typeOf(stream).Child, max_depth).init(stream);
+ w.newline = "";
+ w.one_indent = "";
+ w.space = "";
+ try w.emitJson(self);
}
- fn padSpace(indent: usize) void {
- var i: usize = 0;
- while (i < indent) : (i += 1) {
- debug.warn(" ");
- }
+ pub fn dumpStreamIndent(self: @This(), comptime indent: usize, stream: var, comptime max_depth: usize) !void {
+ var one_indent = " " ** indent;
+
+ var w = std.json.WriteStream(@typeOf(stream).Child, max_depth).init(stream);
+ w.one_indent = one_indent;
+ try w.emitJson(self);
}
};
@@ -1423,7 +1343,7 @@ test "write json then parse it" {
try jw.emitBool(true);
try jw.objectField("int");
- try jw.emitNumber(i32(1234));
+ try jw.emitNumber(@as(i32, 1234));
try jw.objectField("array");
try jw.beginArray();
@@ -1432,7 +1352,7 @@ test "write json then parse it" {
try jw.emitNull();
try jw.arrayElem();
- try jw.emitNumber(f64(12.34));
+ try jw.emitNumber(@as(f64, 12.34));
try jw.endArray();
diff --git a/lib/std/json/write_stream.zig b/lib/std/json/write_stream.zig
index 0702a3e9f5..fbf860965f 100644
--- a/lib/std/json/write_stream.zig
+++ b/lib/std/json/write_stream.zig
@@ -27,6 +27,9 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
/// The string used as a newline character.
newline: []const u8 = "\n",
+ /// The string used as spacing.
+ space: []const u8 = " ",
+
stream: *OutStream,
state_index: usize,
state: [max_depth]State,
@@ -87,7 +90,8 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
self.pushState(.Value);
try self.indent();
try self.writeEscapedString(name);
- try self.stream.write(": ");
+ try self.stream.write(":");
+ try self.stream.write(self.space);
},
}
}
diff --git a/lib/std/lazy_init.zig b/lib/std/lazy_init.zig
index 7beabb9cde..dc792b398c 100644
--- a/lib/std/lazy_init.zig
+++ b/lib/std/lazy_init.zig
@@ -1,24 +1,26 @@
const std = @import("std.zig");
-const builtin = @import("builtin");
const assert = std.debug.assert;
const testing = std.testing;
-const AtomicRmwOp = builtin.AtomicRmwOp;
-const AtomicOrder = builtin.AtomicOrder;
/// Thread-safe initialization of global data.
/// TODO use a mutex instead of a spinlock
pub fn lazyInit(comptime T: type) LazyInit(T) {
return LazyInit(T){
.data = undefined,
- .state = 0,
};
}
fn LazyInit(comptime T: type) type {
return struct {
- state: u8, // TODO make this an enum
+ state: State = .NotResolved,
data: Data,
+ const State = enum(u8) {
+ NotResolved,
+ Resolving,
+ Resolved,
+ };
+
const Self = @This();
// TODO this isn't working for void, investigate and then remove this special case
@@ -30,16 +32,16 @@ fn LazyInit(comptime T: type) type {
/// perform the initialization and then call resolve().
pub fn get(self: *Self) ?Ptr {
while (true) {
- var state = @cmpxchgWeak(u8, &self.state, 0, 1, AtomicOrder.SeqCst, AtomicOrder.SeqCst) orelse return null;
+ var state = @cmpxchgWeak(State, &self.state, .NotResolved, .Resolving, .SeqCst, .SeqCst) orelse return null;
switch (state) {
- 0 => continue,
- 1 => {
+ .NotResolved => continue,
+ .Resolving => {
// TODO mutex instead of a spinlock
continue;
},
- 2 => {
+ .Resolved => {
if (@sizeOf(T) == 0) {
- return T(undefined);
+ return @as(T, undefined);
} else {
return &self.data;
}
@@ -50,8 +52,8 @@ fn LazyInit(comptime T: type) type {
}
pub fn resolve(self: *Self) void {
- const prev = @atomicRmw(u8, &self.state, AtomicRmwOp.Xchg, 2, AtomicOrder.SeqCst);
- assert(prev == 1); // resolve() called twice
+ const prev = @atomicRmw(State, &self.state, .Xchg, .Resolved, .SeqCst);
+ assert(prev != .Resolved); // resolve() called twice
}
};
}
diff --git a/lib/std/math.zig b/lib/std/math.zig
index 9b56d0b8ce..714521357c 100644
--- a/lib/std/math.zig
+++ b/lib/std/math.zig
@@ -10,6 +10,9 @@ pub const e = 2.71828182845904523536028747135266249775724709369995;
/// Archimedes' constant (Ï€)
pub const pi = 3.14159265358979323846264338327950288419716939937510;
+/// Circle constant (Ï„)
+pub const tau = 2 * pi;
+
/// log2(e)
pub const log2e = 1.442695040888963407359924681001892137;
@@ -44,10 +47,10 @@ pub const sqrt2 = 1.414213562373095048801688724209698079;
pub const sqrt1_2 = 0.707106781186547524400844362104849039;
// From a small c++ [program using boost float128](https://github.com/winksaville/cpp_boost_float128)
-pub const f128_true_min = @bitCast(f128, u128(0x00000000000000000000000000000001));
-pub const f128_min = @bitCast(f128, u128(0x00010000000000000000000000000000));
-pub const f128_max = @bitCast(f128, u128(0x7FFEFFFFFFFFFFFFFFFFFFFFFFFFFFFF));
-pub const f128_epsilon = @bitCast(f128, u128(0x3F8F0000000000000000000000000000));
+pub const f128_true_min = @bitCast(f128, @as(u128, 0x00000000000000000000000000000001));
+pub const f128_min = @bitCast(f128, @as(u128, 0x00010000000000000000000000000000));
+pub const f128_max = @bitCast(f128, @as(u128, 0x7FFEFFFFFFFFFFFFFFFFFFFFFFFFFFFF));
+pub const f128_epsilon = @bitCast(f128, @as(u128, 0x3F8F0000000000000000000000000000));
pub const f128_toint = 1.0 / f128_epsilon;
// float.h details
@@ -69,28 +72,28 @@ pub const f16_max = 65504;
pub const f16_epsilon = 0.0009765625; // 2**-10
pub const f16_toint = 1.0 / f16_epsilon;
-pub const nan_u16 = u16(0x7C01);
+pub const nan_u16 = @as(u16, 0x7C01);
pub const nan_f16 = @bitCast(f16, nan_u16);
-pub const inf_u16 = u16(0x7C00);
+pub const inf_u16 = @as(u16, 0x7C00);
pub const inf_f16 = @bitCast(f16, inf_u16);
-pub const nan_u32 = u32(0x7F800001);
+pub const nan_u32 = @as(u32, 0x7F800001);
pub const nan_f32 = @bitCast(f32, nan_u32);
-pub const inf_u32 = u32(0x7F800000);
+pub const inf_u32 = @as(u32, 0x7F800000);
pub const inf_f32 = @bitCast(f32, inf_u32);
-pub const nan_u64 = u64(0x7FF << 52) | 1;
+pub const nan_u64 = @as(u64, 0x7FF << 52) | 1;
pub const nan_f64 = @bitCast(f64, nan_u64);
-pub const inf_u64 = u64(0x7FF << 52);
+pub const inf_u64 = @as(u64, 0x7FF << 52);
pub const inf_f64 = @bitCast(f64, inf_u64);
-pub const nan_u128 = u128(0x7fff0000000000000000000000000001);
+pub const nan_u128 = @as(u128, 0x7fff0000000000000000000000000001);
pub const nan_f128 = @bitCast(f128, nan_u128);
-pub const inf_u128 = u128(0x7fff0000000000000000000000000000);
+pub const inf_u128 = @as(u128, 0x7fff0000000000000000000000000000);
pub const inf_f128 = @bitCast(f128, inf_u128);
pub const nan = @import("math/nan.zig").nan;
@@ -248,7 +251,7 @@ pub fn Min(comptime A: type, comptime B: type) type {
},
else => {},
}
- return @typeOf(A(0) + B(0));
+ return @typeOf(@as(A, 0) + @as(B, 0));
}
/// Returns the smaller number. When one of the parameter's type's full range fits in the other,
@@ -273,7 +276,7 @@ pub fn min(x: var, y: var) Min(@typeOf(x), @typeOf(y)) {
}
test "math.min" {
- testing.expect(min(i32(-1), i32(2)) == -1);
+ testing.expect(min(@as(i32, -1), @as(i32, 2)) == -1);
{
var a: u16 = 999;
var b: u32 = 10;
@@ -309,7 +312,7 @@ pub fn max(x: var, y: var) @typeOf(x + y) {
}
test "math.max" {
- testing.expect(max(i32(-1), i32(2)) == 2);
+ testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2);
}
pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) {
@@ -352,10 +355,10 @@ pub fn shl(comptime T: type, a: T, shift_amt: var) T {
}
test "math.shl" {
- testing.expect(shl(u8, 0b11111111, usize(3)) == 0b11111000);
- testing.expect(shl(u8, 0b11111111, usize(8)) == 0);
- testing.expect(shl(u8, 0b11111111, usize(9)) == 0);
- testing.expect(shl(u8, 0b11111111, isize(-2)) == 0b00111111);
+ testing.expect(shl(u8, 0b11111111, @as(usize, 3)) == 0b11111000);
+ testing.expect(shl(u8, 0b11111111, @as(usize, 8)) == 0);
+ testing.expect(shl(u8, 0b11111111, @as(usize, 9)) == 0);
+ testing.expect(shl(u8, 0b11111111, @as(isize, -2)) == 0b00111111);
testing.expect(shl(u8, 0b11111111, 3) == 0b11111000);
testing.expect(shl(u8, 0b11111111, 8) == 0);
testing.expect(shl(u8, 0b11111111, 9) == 0);
@@ -380,10 +383,10 @@ pub fn shr(comptime T: type, a: T, shift_amt: var) T {
}
test "math.shr" {
- testing.expect(shr(u8, 0b11111111, usize(3)) == 0b00011111);
- testing.expect(shr(u8, 0b11111111, usize(8)) == 0);
- testing.expect(shr(u8, 0b11111111, usize(9)) == 0);
- testing.expect(shr(u8, 0b11111111, isize(-2)) == 0b11111100);
+ testing.expect(shr(u8, 0b11111111, @as(usize, 3)) == 0b00011111);
+ testing.expect(shr(u8, 0b11111111, @as(usize, 8)) == 0);
+ testing.expect(shr(u8, 0b11111111, @as(usize, 9)) == 0);
+ testing.expect(shr(u8, 0b11111111, @as(isize, -2)) == 0b11111100);
testing.expect(shr(u8, 0b11111111, 3) == 0b00011111);
testing.expect(shr(u8, 0b11111111, 8) == 0);
testing.expect(shr(u8, 0b11111111, 9) == 0);
@@ -402,11 +405,11 @@ pub fn rotr(comptime T: type, x: T, r: var) T {
}
test "math.rotr" {
- testing.expect(rotr(u8, 0b00000001, usize(0)) == 0b00000001);
- testing.expect(rotr(u8, 0b00000001, usize(9)) == 0b10000000);
- testing.expect(rotr(u8, 0b00000001, usize(8)) == 0b00000001);
- testing.expect(rotr(u8, 0b00000001, usize(4)) == 0b00010000);
- testing.expect(rotr(u8, 0b00000001, isize(-1)) == 0b00000010);
+ testing.expect(rotr(u8, 0b00000001, @as(usize, 0)) == 0b00000001);
+ testing.expect(rotr(u8, 0b00000001, @as(usize, 9)) == 0b10000000);
+ testing.expect(rotr(u8, 0b00000001, @as(usize, 8)) == 0b00000001);
+ testing.expect(rotr(u8, 0b00000001, @as(usize, 4)) == 0b00010000);
+ testing.expect(rotr(u8, 0b00000001, @as(isize, -1)) == 0b00000010);
}
/// Rotates left. Only unsigned values can be rotated.
@@ -421,11 +424,11 @@ pub fn rotl(comptime T: type, x: T, r: var) T {
}
test "math.rotl" {
- testing.expect(rotl(u8, 0b00000001, usize(0)) == 0b00000001);
- testing.expect(rotl(u8, 0b00000001, usize(9)) == 0b00000010);
- testing.expect(rotl(u8, 0b00000001, usize(8)) == 0b00000001);
- testing.expect(rotl(u8, 0b00000001, usize(4)) == 0b00010000);
- testing.expect(rotl(u8, 0b00000001, isize(-1)) == 0b10000000);
+ testing.expect(rotl(u8, 0b00000001, @as(usize, 0)) == 0b00000001);
+ testing.expect(rotl(u8, 0b00000001, @as(usize, 9)) == 0b00000010);
+ testing.expect(rotl(u8, 0b00000001, @as(usize, 8)) == 0b00000001);
+ testing.expect(rotl(u8, 0b00000001, @as(usize, 4)) == 0b00010000);
+ testing.expect(rotl(u8, 0b00000001, @as(isize, -1)) == 0b10000000);
}
pub fn Log2Int(comptime T: type) type {
@@ -532,8 +535,8 @@ test "math.absInt" {
comptime testAbsInt();
}
fn testAbsInt() void {
- testing.expect((absInt(i32(-10)) catch unreachable) == 10);
- testing.expect((absInt(i32(10)) catch unreachable) == 10);
+ testing.expect((absInt(@as(i32, -10)) catch unreachable) == 10);
+ testing.expect((absInt(@as(i32, 10)) catch unreachable) == 10);
}
pub const absFloat = fabs;
@@ -543,8 +546,8 @@ test "math.absFloat" {
comptime testAbsFloat();
}
fn testAbsFloat() void {
- testing.expect(absFloat(f32(-10.05)) == 10.05);
- testing.expect(absFloat(f32(10.05)) == 10.05);
+ testing.expect(absFloat(@as(f32, -10.05)) == 10.05);
+ testing.expect(absFloat(@as(f32, 10.05)) == 10.05);
}
pub fn divTrunc(comptime T: type, numerator: T, denominator: T) !T {
@@ -679,14 +682,14 @@ pub fn absCast(x: var) t: {
}
test "math.absCast" {
- testing.expect(absCast(i32(-999)) == 999);
- testing.expect(@typeOf(absCast(i32(-999))) == u32);
+ testing.expect(absCast(@as(i32, -999)) == 999);
+ testing.expect(@typeOf(absCast(@as(i32, -999))) == u32);
- testing.expect(absCast(i32(999)) == 999);
- testing.expect(@typeOf(absCast(i32(999))) == u32);
+ testing.expect(absCast(@as(i32, 999)) == 999);
+ testing.expect(@typeOf(absCast(@as(i32, 999))) == u32);
- testing.expect(absCast(i32(minInt(i32))) == -minInt(i32));
- testing.expect(@typeOf(absCast(i32(minInt(i32)))) == u32);
+ testing.expect(absCast(@as(i32, minInt(i32))) == -minInt(i32));
+ testing.expect(@typeOf(absCast(@as(i32, minInt(i32)))) == u32);
testing.expect(absCast(-999) == 999);
}
@@ -705,13 +708,13 @@ pub fn negateCast(x: var) !@IntType(true, @typeOf(x).bit_count) {
}
test "math.negateCast" {
- testing.expect((negateCast(u32(999)) catch unreachable) == -999);
- testing.expect(@typeOf(negateCast(u32(999)) catch unreachable) == i32);
+ testing.expect((negateCast(@as(u32, 999)) catch unreachable) == -999);
+ testing.expect(@typeOf(negateCast(@as(u32, 999)) catch unreachable) == i32);
- testing.expect((negateCast(u32(-minInt(i32))) catch unreachable) == minInt(i32));
- testing.expect(@typeOf(negateCast(u32(-minInt(i32))) catch unreachable) == i32);
+ testing.expect((negateCast(@as(u32, -minInt(i32))) catch unreachable) == minInt(i32));
+ testing.expect(@typeOf(negateCast(@as(u32, -minInt(i32))) catch unreachable) == i32);
- testing.expectError(error.Overflow, negateCast(u32(maxInt(i32) + 10)));
+ testing.expectError(error.Overflow, negateCast(@as(u32, maxInt(i32) + 10)));
}
/// Cast an integer to a different integer type. If the value doesn't fit,
@@ -729,13 +732,13 @@ pub fn cast(comptime T: type, x: var) (error{Overflow}!T) {
}
test "math.cast" {
- testing.expectError(error.Overflow, cast(u8, u32(300)));
- testing.expectError(error.Overflow, cast(i8, i32(-200)));
- testing.expectError(error.Overflow, cast(u8, i8(-1)));
- testing.expectError(error.Overflow, cast(u64, i8(-1)));
+ testing.expectError(error.Overflow, cast(u8, @as(u32, 300)));
+ testing.expectError(error.Overflow, cast(i8, @as(i32, -200)));
+ testing.expectError(error.Overflow, cast(u8, @as(i8, -1)));
+ testing.expectError(error.Overflow, cast(u64, @as(i8, -1)));
- testing.expect((try cast(u8, u32(255))) == u8(255));
- testing.expect(@typeOf(try cast(u8, u32(255))) == u8);
+ testing.expect((try cast(u8, @as(u32, 255))) == @as(u8, 255));
+ testing.expect(@typeOf(try cast(u8, @as(u32, 255))) == u8);
}
pub const AlignCastError = error{UnalignedMemory};
@@ -786,9 +789,9 @@ pub fn ceilPowerOfTwoPromote(comptime T: type, value: T) @IntType(T.is_signed, T
comptime assert(@typeId(T) == builtin.TypeId.Int);
comptime assert(!T.is_signed);
assert(value != 0);
- comptime const promotedType = @IntType(T.is_signed, T.bit_count + 1);
- comptime const shiftType = std.math.Log2Int(promotedType);
- return promotedType(1) << @intCast(shiftType, T.bit_count - @clz(T, value - 1));
+ comptime const PromotedType = @IntType(T.is_signed, T.bit_count + 1);
+ comptime const shiftType = std.math.Log2Int(PromotedType);
+ return @as(PromotedType, 1) << @intCast(shiftType, T.bit_count - @clz(T, value - 1));
}
/// Returns the next power of two (if the value is not already a power of two).
@@ -797,8 +800,8 @@ pub fn ceilPowerOfTwoPromote(comptime T: type, value: T) @IntType(T.is_signed, T
pub fn ceilPowerOfTwo(comptime T: type, value: T) (error{Overflow}!T) {
comptime assert(@typeId(T) == builtin.TypeId.Int);
comptime assert(!T.is_signed);
- comptime const promotedType = @IntType(T.is_signed, T.bit_count + 1);
- comptime const overflowBit = promotedType(1) << T.bit_count;
+ comptime const PromotedType = @IntType(T.is_signed, T.bit_count + 1);
+ comptime const overflowBit = @as(PromotedType, 1) << T.bit_count;
var x = ceilPowerOfTwoPromote(T, value);
if (overflowBit & x != 0) {
return error.Overflow;
@@ -812,15 +815,15 @@ test "math.ceilPowerOfTwoPromote" {
}
fn testCeilPowerOfTwoPromote() void {
- testing.expectEqual(u33(1), ceilPowerOfTwoPromote(u32, 1));
- testing.expectEqual(u33(2), ceilPowerOfTwoPromote(u32, 2));
- testing.expectEqual(u33(64), ceilPowerOfTwoPromote(u32, 63));
- testing.expectEqual(u33(64), ceilPowerOfTwoPromote(u32, 64));
- testing.expectEqual(u33(128), ceilPowerOfTwoPromote(u32, 65));
- testing.expectEqual(u6(8), ceilPowerOfTwoPromote(u5, 7));
- testing.expectEqual(u6(8), ceilPowerOfTwoPromote(u5, 8));
- testing.expectEqual(u6(16), ceilPowerOfTwoPromote(u5, 9));
- testing.expectEqual(u5(16), ceilPowerOfTwoPromote(u4, 9));
+ testing.expectEqual(@as(u33, 1), ceilPowerOfTwoPromote(u32, 1));
+ testing.expectEqual(@as(u33, 2), ceilPowerOfTwoPromote(u32, 2));
+ testing.expectEqual(@as(u33, 64), ceilPowerOfTwoPromote(u32, 63));
+ testing.expectEqual(@as(u33, 64), ceilPowerOfTwoPromote(u32, 64));
+ testing.expectEqual(@as(u33, 128), ceilPowerOfTwoPromote(u32, 65));
+ testing.expectEqual(@as(u6, 8), ceilPowerOfTwoPromote(u5, 7));
+ testing.expectEqual(@as(u6, 8), ceilPowerOfTwoPromote(u5, 8));
+ testing.expectEqual(@as(u6, 16), ceilPowerOfTwoPromote(u5, 9));
+ testing.expectEqual(@as(u5, 16), ceilPowerOfTwoPromote(u4, 9));
}
test "math.ceilPowerOfTwo" {
@@ -829,14 +832,14 @@ test "math.ceilPowerOfTwo" {
}
fn testCeilPowerOfTwo() !void {
- testing.expectEqual(u32(1), try ceilPowerOfTwo(u32, 1));
- testing.expectEqual(u32(2), try ceilPowerOfTwo(u32, 2));
- testing.expectEqual(u32(64), try ceilPowerOfTwo(u32, 63));
- testing.expectEqual(u32(64), try ceilPowerOfTwo(u32, 64));
- testing.expectEqual(u32(128), try ceilPowerOfTwo(u32, 65));
- testing.expectEqual(u5(8), try ceilPowerOfTwo(u5, 7));
- testing.expectEqual(u5(8), try ceilPowerOfTwo(u5, 8));
- testing.expectEqual(u5(16), try ceilPowerOfTwo(u5, 9));
+ testing.expectEqual(@as(u32, 1), try ceilPowerOfTwo(u32, 1));
+ testing.expectEqual(@as(u32, 2), try ceilPowerOfTwo(u32, 2));
+ testing.expectEqual(@as(u32, 64), try ceilPowerOfTwo(u32, 63));
+ testing.expectEqual(@as(u32, 64), try ceilPowerOfTwo(u32, 64));
+ testing.expectEqual(@as(u32, 128), try ceilPowerOfTwo(u32, 65));
+ testing.expectEqual(@as(u5, 8), try ceilPowerOfTwo(u5, 7));
+ testing.expectEqual(@as(u5, 8), try ceilPowerOfTwo(u5, 8));
+ testing.expectEqual(@as(u5, 16), try ceilPowerOfTwo(u5, 9));
testing.expectError(error.Overflow, ceilPowerOfTwo(u4, 9));
}
@@ -848,7 +851,7 @@ pub fn log2_int(comptime T: type, x: T) Log2Int(T) {
pub fn log2_int_ceil(comptime T: type, x: T) Log2Int(T) {
assert(x != 0);
const log2_val = log2_int(T, x);
- if (T(1) << log2_val == x)
+ if (@as(T, 1) << log2_val == x)
return log2_val;
return log2_val + 1;
}
@@ -870,8 +873,8 @@ pub fn lossyCast(comptime T: type, value: var) T {
switch (@typeInfo(@typeOf(value))) {
builtin.TypeId.Int => return @intToFloat(T, value),
builtin.TypeId.Float => return @floatCast(T, value),
- builtin.TypeId.ComptimeInt => return T(value),
- builtin.TypeId.ComptimeFloat => return T(value),
+ builtin.TypeId.ComptimeInt => return @as(T, value),
+ builtin.TypeId.ComptimeFloat => return @as(T, value),
else => @compileError("bad type"),
}
}
@@ -944,7 +947,7 @@ test "max value type" {
pub fn mulWide(comptime T: type, a: T, b: T) @IntType(T.is_signed, T.bit_count * 2) {
const ResultInt = @IntType(T.is_signed, T.bit_count * 2);
- return ResultInt(a) * ResultInt(b);
+ return @as(ResultInt, a) * @as(ResultInt, b);
}
test "math.mulWide" {
diff --git a/lib/std/math/acos.zig b/lib/std/math/acos.zig
index de07da8fe0..94b6fc3f8f 100644
--- a/lib/std/math/acos.zig
+++ b/lib/std/math/acos.zig
@@ -149,8 +149,8 @@ fn acos64(x: f64) f64 {
}
test "math.acos" {
- expect(acos(f32(0.0)) == acos32(0.0));
- expect(acos(f64(0.0)) == acos64(0.0));
+ expect(acos(@as(f32, 0.0)) == acos32(0.0));
+ expect(acos(@as(f64, 0.0)) == acos64(0.0));
}
test "math.acos32" {
diff --git a/lib/std/math/acosh.zig b/lib/std/math/acosh.zig
index 503c0433fc..065e4d39de 100644
--- a/lib/std/math/acosh.zig
+++ b/lib/std/math/acosh.zig
@@ -61,8 +61,8 @@ fn acosh64(x: f64) f64 {
}
test "math.acosh" {
- expect(acosh(f32(1.5)) == acosh32(1.5));
- expect(acosh(f64(1.5)) == acosh64(1.5));
+ expect(acosh(@as(f32, 1.5)) == acosh32(1.5));
+ expect(acosh(@as(f64, 1.5)) == acosh64(1.5));
}
test "math.acosh32" {
diff --git a/lib/std/math/asin.zig b/lib/std/math/asin.zig
index 2db9f86ff1..d354f8ceed 100644
--- a/lib/std/math/asin.zig
+++ b/lib/std/math/asin.zig
@@ -142,8 +142,8 @@ fn asin64(x: f64) f64 {
}
test "math.asin" {
- expect(asin(f32(0.0)) == asin32(0.0));
- expect(asin(f64(0.0)) == asin64(0.0));
+ expect(asin(@as(f32, 0.0)) == asin32(0.0));
+ expect(asin(@as(f64, 0.0)) == asin64(0.0));
}
test "math.asin32" {
diff --git a/lib/std/math/asinh.zig b/lib/std/math/asinh.zig
index 0fb51d1b43..b915df3171 100644
--- a/lib/std/math/asinh.zig
+++ b/lib/std/math/asinh.zig
@@ -89,8 +89,8 @@ fn asinh64(x: f64) f64 {
}
test "math.asinh" {
- expect(asinh(f32(0.0)) == asinh32(0.0));
- expect(asinh(f64(0.0)) == asinh64(0.0));
+ expect(asinh(@as(f32, 0.0)) == asinh32(0.0));
+ expect(asinh(@as(f64, 0.0)) == asinh64(0.0));
}
test "math.asinh32" {
diff --git a/lib/std/math/atan.zig b/lib/std/math/atan.zig
index 5790eba8cf..ea639872be 100644
--- a/lib/std/math/atan.zig
+++ b/lib/std/math/atan.zig
@@ -212,8 +212,8 @@ fn atan64(x_: f64) f64 {
}
test "math.atan" {
- expect(@bitCast(u32, atan(f32(0.2))) == @bitCast(u32, atan32(0.2)));
- expect(atan(f64(0.2)) == atan64(0.2));
+ expect(@bitCast(u32, atan(@as(f32, 0.2))) == @bitCast(u32, atan32(0.2)));
+ expect(atan(@as(f64, 0.2)) == atan64(0.2));
}
test "math.atan32" {
diff --git a/lib/std/math/atanh.zig b/lib/std/math/atanh.zig
index 8ba29be761..ae588f4fb8 100644
--- a/lib/std/math/atanh.zig
+++ b/lib/std/math/atanh.zig
@@ -84,8 +84,8 @@ fn atanh_64(x: f64) f64 {
}
test "math.atanh" {
- expect(atanh(f32(0.0)) == atanh_32(0.0));
- expect(atanh(f64(0.0)) == atanh_64(0.0));
+ expect(atanh(@as(f32, 0.0)) == atanh_32(0.0));
+ expect(atanh(@as(f64, 0.0)) == atanh_64(0.0));
}
test "math.atanh_32" {
diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig
index bfdc768375..0459b0b158 100644
--- a/lib/std/math/big/int.zig
+++ b/lib/std/math/big/int.zig
@@ -261,7 +261,7 @@ pub const Int = struct {
/// the minus sign. This is used for determining the number of characters needed to print the
/// value. It is inexact and may exceed the given value by ~1-2 bytes.
pub fn sizeInBase(self: Int, base: usize) usize {
- const bit_count = usize(@boolToInt(!self.isPositive())) + self.bitCountAbs();
+ const bit_count = @as(usize, @boolToInt(!self.isPositive())) + self.bitCountAbs();
return (bit_count / math.log2(base)) + 1;
}
@@ -281,7 +281,7 @@ pub const Int = struct {
var w_value: UT = if (value < 0) @intCast(UT, -value) else @intCast(UT, value);
if (info.bits <= Limb.bit_count) {
- self.limbs[0] = Limb(w_value);
+ self.limbs[0] = @as(Limb, w_value);
self.metadata += 1;
} else {
var i: usize = 0;
@@ -453,7 +453,7 @@ pub const Int = struct {
for (self.limbs[0..self.len()]) |limb| {
var shift: usize = 0;
while (shift < Limb.bit_count) : (shift += base_shift) {
- const r = @intCast(u8, (limb >> @intCast(Log2Limb, shift)) & Limb(base - 1));
+ const r = @intCast(u8, (limb >> @intCast(Log2Limb, shift)) & @as(Limb, base - 1));
const ch = try digitToChar(r, base);
try digits.append(ch);
}
@@ -560,7 +560,7 @@ pub const Int = struct {
/// Returns -1, 0, 1 if a < b, a == b or a > b respectively.
pub fn cmp(a: Int, b: Int) i8 {
if (a.isPositive() != b.isPositive()) {
- return if (a.isPositive()) i8(1) else -1;
+ return if (a.isPositive()) @as(i8, 1) else -1;
} else {
const r = cmpAbs(a, b);
return if (a.isPositive()) r else -r;
@@ -785,7 +785,7 @@ pub const Int = struct {
const c1: Limb = @boolToInt(@addWithOverflow(Limb, a, carry.*, &r1));
// r2 = b * c
- const bc = DoubleLimb(math.mulWide(Limb, b, c));
+ const bc = @as(DoubleLimb, math.mulWide(Limb, b, c));
const r2 = @truncate(Limb, bc);
const c2 = @truncate(Limb, bc >> Limb.bit_count);
@@ -1084,7 +1084,7 @@ pub const Int = struct {
rem.* = 0;
for (a) |_, ri| {
const i = a.len - ri - 1;
- const pdiv = ((DoubleLimb(rem.*) << Limb.bit_count) | a[i]);
+ const pdiv = ((@as(DoubleLimb, rem.*) << Limb.bit_count) | a[i]);
if (pdiv == 0) {
quo[i] = 0;
@@ -1143,9 +1143,9 @@ pub const Int = struct {
if (x.limbs[i] == y.limbs[t]) {
q.limbs[i - t - 1] = maxInt(Limb);
} else {
- const num = (DoubleLimb(x.limbs[i]) << Limb.bit_count) | DoubleLimb(x.limbs[i - 1]);
- const z = @intCast(Limb, num / DoubleLimb(y.limbs[t]));
- q.limbs[i - t - 1] = if (z > maxInt(Limb)) maxInt(Limb) else Limb(z);
+ const num = (@as(DoubleLimb, x.limbs[i]) << Limb.bit_count) | @as(DoubleLimb, x.limbs[i - 1]);
+ const z = @intCast(Limb, num / @as(DoubleLimb, y.limbs[t]));
+ q.limbs[i - t - 1] = if (z > maxInt(Limb)) maxInt(Limb) else @as(Limb, z);
}
// 3.2
@@ -1362,7 +1362,7 @@ test "big.int comptime_int set" {
comptime var i: usize = 0;
inline while (i < s_limb_count) : (i += 1) {
- const result = Limb(s & maxInt(Limb));
+ const result = @as(Limb, s & maxInt(Limb));
s >>= Limb.bit_count / 2;
s >>= Limb.bit_count / 2;
testing.expect(a.limbs[i] == result);
@@ -1377,7 +1377,7 @@ test "big.int comptime_int set negative" {
}
test "big.int int set unaligned small" {
- var a = try Int.initSet(al, u7(45));
+ var a = try Int.initSet(al, @as(u7, 45));
testing.expect(a.limbs[0] == 45);
testing.expect(a.isPositive() == true);
diff --git a/lib/std/math/cbrt.zig b/lib/std/math/cbrt.zig
index 5241e31323..c9e205a495 100644
--- a/lib/std/math/cbrt.zig
+++ b/lib/std/math/cbrt.zig
@@ -54,11 +54,11 @@ fn cbrt32(x: f32) f32 {
// first step newton to 16 bits
var t: f64 = @bitCast(f32, u);
var r: f64 = t * t * t;
- t = t * (f64(x) + x + r) / (x + r + r);
+ t = t * (@as(f64, x) + x + r) / (x + r + r);
// second step newton to 47 bits
r = t * t * t;
- t = t * (f64(x) + x + r) / (x + r + r);
+ t = t * (@as(f64, x) + x + r) / (x + r + r);
return @floatCast(f32, t);
}
@@ -97,7 +97,7 @@ fn cbrt64(x: f64) f64 {
}
u &= 1 << 63;
- u |= u64(hx) << 32;
+ u |= @as(u64, hx) << 32;
var t = @bitCast(f64, u);
// cbrt to 23 bits
@@ -120,8 +120,8 @@ fn cbrt64(x: f64) f64 {
}
test "math.cbrt" {
- expect(cbrt(f32(0.0)) == cbrt32(0.0));
- expect(cbrt(f64(0.0)) == cbrt64(0.0));
+ expect(cbrt(@as(f32, 0.0)) == cbrt32(0.0));
+ expect(cbrt(@as(f64, 0.0)) == cbrt64(0.0));
}
test "math.cbrt32" {
diff --git a/lib/std/math/ceil.zig b/lib/std/math/ceil.zig
index 5f86093a6d..b5a2238621 100644
--- a/lib/std/math/ceil.zig
+++ b/lib/std/math/ceil.zig
@@ -37,7 +37,7 @@ fn ceil32(x: f32) f32 {
if (e >= 23) {
return x;
} else if (e >= 0) {
- m = u32(0x007FFFFF) >> @intCast(u5, e);
+ m = @as(u32, 0x007FFFFF) >> @intCast(u5, e);
if (u & m == 0) {
return x;
}
@@ -87,8 +87,8 @@ fn ceil64(x: f64) f64 {
}
test "math.ceil" {
- expect(ceil(f32(0.0)) == ceil32(0.0));
- expect(ceil(f64(0.0)) == ceil64(0.0));
+ expect(ceil(@as(f32, 0.0)) == ceil32(0.0));
+ expect(ceil(@as(f64, 0.0)) == ceil64(0.0));
}
test "math.ceil32" {
diff --git a/lib/std/math/complex.zig b/lib/std/math/complex.zig
index e5574f9cee..8bff2313fc 100644
--- a/lib/std/math/complex.zig
+++ b/lib/std/math/complex.zig
@@ -133,8 +133,8 @@ test "complex.div" {
const b = Complex(f32).new(2, 7);
const c = a.div(b);
- testing.expect(math.approxEq(f32, c.re, f32(31) / 53, epsilon) and
- math.approxEq(f32, c.im, f32(-29) / 53, epsilon));
+ testing.expect(math.approxEq(f32, c.re, @as(f32, 31) / 53, epsilon) and
+ math.approxEq(f32, c.im, @as(f32, -29) / 53, epsilon));
}
test "complex.conjugate" {
@@ -148,8 +148,8 @@ test "complex.reciprocal" {
const a = Complex(f32).new(5, 3);
const c = a.reciprocal();
- testing.expect(math.approxEq(f32, c.re, f32(5) / 34, epsilon) and
- math.approxEq(f32, c.im, f32(-3) / 34, epsilon));
+ testing.expect(math.approxEq(f32, c.re, @as(f32, 5) / 34, epsilon) and
+ math.approxEq(f32, c.im, @as(f32, -3) / 34, epsilon));
}
test "complex.magnitude" {
diff --git a/lib/std/math/complex/acos.zig b/lib/std/math/complex/acos.zig
index f3526cc9ff..b078ebf345 100644
--- a/lib/std/math/complex/acos.zig
+++ b/lib/std/math/complex/acos.zig
@@ -8,7 +8,7 @@ const Complex = cmath.Complex;
pub fn acos(z: var) Complex(@typeOf(z.re)) {
const T = @typeOf(z.re);
const q = cmath.asin(z);
- return Complex(T).new(T(math.pi) / 2 - q.re, -q.im);
+ return Complex(T).new(@as(T, math.pi) / 2 - q.re, -q.im);
}
const epsilon = 0.0001;
diff --git a/lib/std/math/complex/ldexp.zig b/lib/std/math/complex/ldexp.zig
index d6f810793f..d5d4cc64a6 100644
--- a/lib/std/math/complex/ldexp.zig
+++ b/lib/std/math/complex/ldexp.zig
@@ -59,13 +59,13 @@ fn frexp_exp64(x: f64, expt: *i32) f64 {
expt.* = @intCast(i32, hx >> 20) - (0x3ff + 1023) + k;
const high_word = (hx & 0xfffff) | ((0x3ff + 1023) << 20);
- return @bitCast(f64, (u64(high_word) << 32) | lx);
+ return @bitCast(f64, (@as(u64, high_word) << 32) | lx);
}
fn ldexp_cexp64(z: Complex(f64), expt: i32) Complex(f64) {
var ex_expt: i32 = undefined;
const exp_x = frexp_exp64(z.re, &ex_expt);
- const exptf = i64(expt + ex_expt);
+ const exptf = @as(i64, expt + ex_expt);
const half_expt1 = @divTrunc(exptf, 2);
const scale1 = @bitCast(f64, (0x3ff + half_expt1) << 20);
diff --git a/lib/std/math/complex/sqrt.zig b/lib/std/math/complex/sqrt.zig
index 36f4c28e29..7e17f422bb 100644
--- a/lib/std/math/complex/sqrt.zig
+++ b/lib/std/math/complex/sqrt.zig
@@ -52,8 +52,8 @@ fn sqrt32(z: Complex(f32)) Complex(f32) {
// y = nan special case is handled fine below
// double-precision avoids overflow with correct rounding.
- const dx = f64(x);
- const dy = f64(y);
+ const dx = @as(f64, x);
+ const dy = @as(f64, y);
if (dx >= 0) {
const t = math.sqrt((dx + math.hypot(f64, dx, dy)) * 0.5);
diff --git a/lib/std/math/complex/tanh.zig b/lib/std/math/complex/tanh.zig
index 6895e8a769..fc7f4e9ea8 100644
--- a/lib/std/math/complex/tanh.zig
+++ b/lib/std/math/complex/tanh.zig
@@ -76,7 +76,7 @@ fn tanh64(z: Complex(f64)) Complex(f64) {
return Complex(f64).new(x, r);
}
- const xx = @bitCast(f64, (u64(hx - 0x40000000) << 32) | lx);
+ const xx = @bitCast(f64, (@as(u64, hx - 0x40000000) << 32) | lx);
const r = if (math.isInf(y)) y else math.sin(y) * math.cos(y);
return Complex(f64).new(xx, math.copysign(f64, 0, r));
}
diff --git a/lib/std/math/copysign.zig b/lib/std/math/copysign.zig
index e4d90c395e..e874da0bb9 100644
--- a/lib/std/math/copysign.zig
+++ b/lib/std/math/copysign.zig
@@ -24,7 +24,7 @@ fn copysign16(x: f16, y: f16) f16 {
const uy = @bitCast(u16, y);
const h1 = ux & (maxInt(u16) / 2);
- const h2 = uy & (u16(1) << 15);
+ const h2 = uy & (@as(u16, 1) << 15);
return @bitCast(f16, h1 | h2);
}
@@ -33,7 +33,7 @@ fn copysign32(x: f32, y: f32) f32 {
const uy = @bitCast(u32, y);
const h1 = ux & (maxInt(u32) / 2);
- const h2 = uy & (u32(1) << 31);
+ const h2 = uy & (@as(u32, 1) << 31);
return @bitCast(f32, h1 | h2);
}
@@ -42,7 +42,7 @@ fn copysign64(x: f64, y: f64) f64 {
const uy = @bitCast(u64, y);
const h1 = ux & (maxInt(u64) / 2);
- const h2 = uy & (u64(1) << 63);
+ const h2 = uy & (@as(u64, 1) << 63);
return @bitCast(f64, h1 | h2);
}
diff --git a/lib/std/math/cos.zig b/lib/std/math/cos.zig
index 5261a25f80..68e13e41bf 100644
--- a/lib/std/math/cos.zig
+++ b/lib/std/math/cos.zig
@@ -83,8 +83,8 @@ fn cos_(comptime T: type, x_: T) T {
}
test "math.cos" {
- expect(cos(f32(0.0)) == cos_(f32, 0.0));
- expect(cos(f64(0.0)) == cos_(f64, 0.0));
+ expect(cos(@as(f32, 0.0)) == cos_(f32, 0.0));
+ expect(cos(@as(f64, 0.0)) == cos_(f64, 0.0));
}
test "math.cos32" {
diff --git a/lib/std/math/cosh.zig b/lib/std/math/cosh.zig
index 75c5c15ec1..62bedeaa49 100644
--- a/lib/std/math/cosh.zig
+++ b/lib/std/math/cosh.zig
@@ -88,8 +88,8 @@ fn cosh64(x: f64) f64 {
}
test "math.cosh" {
- expect(cosh(f32(1.5)) == cosh32(1.5));
- expect(cosh(f64(1.5)) == cosh64(1.5));
+ expect(cosh(@as(f32, 1.5)) == cosh32(1.5));
+ expect(cosh(@as(f64, 1.5)) == cosh64(1.5));
}
test "math.cosh32" {
diff --git a/lib/std/math/exp.zig b/lib/std/math/exp.zig
index 718bbcd476..986c35bf0d 100644
--- a/lib/std/math/exp.zig
+++ b/lib/std/math/exp.zig
@@ -134,7 +134,7 @@ fn exp64(x_: f64) f64 {
}
if (x < -708.39641853226410622) {
// underflow if x != -inf
- // math.forceEval(f32(-0x1.0p-149 / x));
+ // math.forceEval(@as(f32, -0x1.0p-149 / x));
if (x < -745.13321910194110842) {
return 0;
}
@@ -183,8 +183,8 @@ fn exp64(x_: f64) f64 {
}
test "math.exp" {
- assert(exp(f32(0.0)) == exp32(0.0));
- assert(exp(f64(0.0)) == exp64(0.0));
+ assert(exp(@as(f32, 0.0)) == exp32(0.0));
+ assert(exp(@as(f64, 0.0)) == exp64(0.0));
}
test "math.exp32" {
diff --git a/lib/std/math/exp2.zig b/lib/std/math/exp2.zig
index 57f6620d77..f3e51e542e 100644
--- a/lib/std/math/exp2.zig
+++ b/lib/std/math/exp2.zig
@@ -85,7 +85,7 @@ fn exp2_32(x: f32) f32 {
const k = i_0 / tblsiz;
// NOTE: musl relies on undefined overflow shift behaviour. Appears that this produces the
// intended result but should confirm how GCC/Clang handle this to ensure.
- const uk = @bitCast(f64, u64(0x3FF + k) << 52);
+ const uk = @bitCast(f64, @as(u64, 0x3FF + k) << 52);
i_0 &= tblsiz - 1;
uf -= redux;
@@ -421,8 +421,8 @@ fn exp2_64(x: f64) f64 {
}
test "math.exp2" {
- expect(exp2(f32(0.8923)) == exp2_32(0.8923));
- expect(exp2(f64(0.8923)) == exp2_64(0.8923));
+ expect(exp2(@as(f32, 0.8923)) == exp2_32(0.8923));
+ expect(exp2(@as(f64, 0.8923)) == exp2_64(0.8923));
}
test "math.exp2_32" {
diff --git a/lib/std/math/expm1.zig b/lib/std/math/expm1.zig
index 5e347f86f6..871fa38449 100644
--- a/lib/std/math/expm1.zig
+++ b/lib/std/math/expm1.zig
@@ -287,8 +287,8 @@ fn expm1_64(x_: f64) f64 {
}
test "math.exp1m" {
- expect(expm1(f32(0.0)) == expm1_32(0.0));
- expect(expm1(f64(0.0)) == expm1_64(0.0));
+ expect(expm1(@as(f32, 0.0)) == expm1_32(0.0));
+ expect(expm1(@as(f64, 0.0)) == expm1_64(0.0));
}
test "math.expm1_32" {
diff --git a/lib/std/math/expo2.zig b/lib/std/math/expo2.zig
index c00098a5a7..590f36bb18 100644
--- a/lib/std/math/expo2.zig
+++ b/lib/std/math/expo2.zig
@@ -30,6 +30,6 @@ fn expo2d(x: f64) f64 {
const kln2 = 0x1.62066151ADD8BP+10;
const u = (0x3FF + k / 2) << 20;
- const scale = @bitCast(f64, u64(u) << 32);
+ const scale = @bitCast(f64, @as(u64, u) << 32);
return math.exp(x - kln2) * scale * scale;
}
diff --git a/lib/std/math/fabs.zig b/lib/std/math/fabs.zig
index 6469f38835..e0eadd0d00 100644
--- a/lib/std/math/fabs.zig
+++ b/lib/std/math/fabs.zig
@@ -50,10 +50,10 @@ fn fabs128(x: f128) f128 {
}
test "math.fabs" {
- expect(fabs(f16(1.0)) == fabs16(1.0));
- expect(fabs(f32(1.0)) == fabs32(1.0));
- expect(fabs(f64(1.0)) == fabs64(1.0));
- expect(fabs(f128(1.0)) == fabs128(1.0));
+ expect(fabs(@as(f16, 1.0)) == fabs16(1.0));
+ expect(fabs(@as(f32, 1.0)) == fabs32(1.0));
+ expect(fabs(@as(f64, 1.0)) == fabs64(1.0));
+ expect(fabs(@as(f128, 1.0)) == fabs128(1.0));
}
test "math.fabs16" {
diff --git a/lib/std/math/floor.zig b/lib/std/math/floor.zig
index e5ff2b1fc1..f2cabe8f02 100644
--- a/lib/std/math/floor.zig
+++ b/lib/std/math/floor.zig
@@ -40,7 +40,7 @@ fn floor16(x: f16) f16 {
}
if (e >= 0) {
- m = u16(1023) >> @intCast(u4, e);
+ m = @as(u16, 1023) >> @intCast(u4, e);
if (u & m == 0) {
return x;
}
@@ -74,7 +74,7 @@ fn floor32(x: f32) f32 {
}
if (e >= 0) {
- m = u32(0x007FFFFF) >> @intCast(u5, e);
+ m = @as(u32, 0x007FFFFF) >> @intCast(u5, e);
if (u & m == 0) {
return x;
}
@@ -123,9 +123,9 @@ fn floor64(x: f64) f64 {
}
test "math.floor" {
- expect(floor(f16(1.3)) == floor16(1.3));
- expect(floor(f32(1.3)) == floor32(1.3));
- expect(floor(f64(1.3)) == floor64(1.3));
+ expect(floor(@as(f16, 1.3)) == floor16(1.3));
+ expect(floor(@as(f32, 1.3)) == floor32(1.3));
+ expect(floor(@as(f64, 1.3)) == floor64(1.3));
}
test "math.floor16" {
diff --git a/lib/std/math/fma.zig b/lib/std/math/fma.zig
index 19c306fa2a..014593cda5 100644
--- a/lib/std/math/fma.zig
+++ b/lib/std/math/fma.zig
@@ -18,7 +18,7 @@ pub fn fma(comptime T: type, x: T, y: T, z: T) T {
}
fn fma32(x: f32, y: f32, z: f32) f32 {
- const xy = f64(x) * y;
+ const xy = @as(f64, x) * y;
const xy_z = xy + z;
const u = @bitCast(u64, xy_z);
const e = (u >> 52) & 0x7FF;
diff --git a/lib/std/math/frexp.zig b/lib/std/math/frexp.zig
index 2759cd6492..93705ae6a4 100644
--- a/lib/std/math/frexp.zig
+++ b/lib/std/math/frexp.zig
@@ -108,11 +108,11 @@ fn frexp64(x: f64) frexp64_result {
}
test "math.frexp" {
- const a = frexp(f32(1.3));
+ const a = frexp(@as(f32, 1.3));
const b = frexp32(1.3);
expect(a.significand == b.significand and a.exponent == b.exponent);
- const c = frexp(f64(1.3));
+ const c = frexp(@as(f64, 1.3));
const d = frexp64(1.3);
expect(c.significand == d.significand and c.exponent == d.exponent);
}
diff --git a/lib/std/math/hypot.zig b/lib/std/math/hypot.zig
index c15da1495e..59116014b3 100644
--- a/lib/std/math/hypot.zig
+++ b/lib/std/math/hypot.zig
@@ -56,7 +56,7 @@ fn hypot32(x: f32, y: f32) f32 {
yy *= 0x1.0p-90;
}
- return z * math.sqrt(@floatCast(f32, f64(x) * x + f64(y) * y));
+ return z * math.sqrt(@floatCast(f32, @as(f64, x) * x + @as(f64, y) * y));
}
fn sq(hi: *f64, lo: *f64, x: f64) void {
diff --git a/lib/std/math/ilogb.zig b/lib/std/math/ilogb.zig
index fe4158a6dd..8d23bb09a0 100644
--- a/lib/std/math/ilogb.zig
+++ b/lib/std/math/ilogb.zig
@@ -26,7 +26,7 @@ pub fn ilogb(x: var) i32 {
}
// NOTE: Should these be exposed publicly?
-const fp_ilogbnan = -1 - i32(maxInt(u32) >> 1);
+const fp_ilogbnan = -1 - @as(i32, maxInt(u32) >> 1);
const fp_ilogb0 = fp_ilogbnan;
fn ilogb32(x: f32) i32 {
@@ -101,8 +101,8 @@ fn ilogb64(x: f64) i32 {
}
test "math.ilogb" {
- expect(ilogb(f32(0.2)) == ilogb32(0.2));
- expect(ilogb(f64(0.2)) == ilogb64(0.2));
+ expect(ilogb(@as(f32, 0.2)) == ilogb32(0.2));
+ expect(ilogb(@as(f64, 0.2)) == ilogb64(0.2));
}
test "math.ilogb32" {
diff --git a/lib/std/math/isfinite.zig b/lib/std/math/isfinite.zig
index 99eba668f9..3d23a0f3bf 100644
--- a/lib/std/math/isfinite.zig
+++ b/lib/std/math/isfinite.zig
@@ -26,12 +26,12 @@ pub fn isFinite(x: var) bool {
}
test "math.isFinite" {
- expect(isFinite(f16(0.0)));
- expect(isFinite(f16(-0.0)));
- expect(isFinite(f32(0.0)));
- expect(isFinite(f32(-0.0)));
- expect(isFinite(f64(0.0)));
- expect(isFinite(f64(-0.0)));
+ expect(isFinite(@as(f16, 0.0)));
+ expect(isFinite(@as(f16, -0.0)));
+ expect(isFinite(@as(f32, 0.0)));
+ expect(isFinite(@as(f32, -0.0)));
+ expect(isFinite(@as(f64, 0.0)));
+ expect(isFinite(@as(f64, -0.0)));
expect(!isFinite(math.inf(f16)));
expect(!isFinite(-math.inf(f16)));
expect(!isFinite(math.inf(f32)));
diff --git a/lib/std/math/isinf.zig b/lib/std/math/isinf.zig
index 37934f4cf4..d691068be5 100644
--- a/lib/std/math/isinf.zig
+++ b/lib/std/math/isinf.zig
@@ -74,14 +74,14 @@ pub fn isNegativeInf(x: var) bool {
}
test "math.isInf" {
- expect(!isInf(f16(0.0)));
- expect(!isInf(f16(-0.0)));
- expect(!isInf(f32(0.0)));
- expect(!isInf(f32(-0.0)));
- expect(!isInf(f64(0.0)));
- expect(!isInf(f64(-0.0)));
- expect(!isInf(f128(0.0)));
- expect(!isInf(f128(-0.0)));
+ expect(!isInf(@as(f16, 0.0)));
+ expect(!isInf(@as(f16, -0.0)));
+ expect(!isInf(@as(f32, 0.0)));
+ expect(!isInf(@as(f32, -0.0)));
+ expect(!isInf(@as(f64, 0.0)));
+ expect(!isInf(@as(f64, -0.0)));
+ expect(!isInf(@as(f128, 0.0)));
+ expect(!isInf(@as(f128, -0.0)));
expect(isInf(math.inf(f16)));
expect(isInf(-math.inf(f16)));
expect(isInf(math.inf(f32)));
@@ -93,14 +93,14 @@ test "math.isInf" {
}
test "math.isPositiveInf" {
- expect(!isPositiveInf(f16(0.0)));
- expect(!isPositiveInf(f16(-0.0)));
- expect(!isPositiveInf(f32(0.0)));
- expect(!isPositiveInf(f32(-0.0)));
- expect(!isPositiveInf(f64(0.0)));
- expect(!isPositiveInf(f64(-0.0)));
- expect(!isPositiveInf(f128(0.0)));
- expect(!isPositiveInf(f128(-0.0)));
+ expect(!isPositiveInf(@as(f16, 0.0)));
+ expect(!isPositiveInf(@as(f16, -0.0)));
+ expect(!isPositiveInf(@as(f32, 0.0)));
+ expect(!isPositiveInf(@as(f32, -0.0)));
+ expect(!isPositiveInf(@as(f64, 0.0)));
+ expect(!isPositiveInf(@as(f64, -0.0)));
+ expect(!isPositiveInf(@as(f128, 0.0)));
+ expect(!isPositiveInf(@as(f128, -0.0)));
expect(isPositiveInf(math.inf(f16)));
expect(!isPositiveInf(-math.inf(f16)));
expect(isPositiveInf(math.inf(f32)));
@@ -112,14 +112,14 @@ test "math.isPositiveInf" {
}
test "math.isNegativeInf" {
- expect(!isNegativeInf(f16(0.0)));
- expect(!isNegativeInf(f16(-0.0)));
- expect(!isNegativeInf(f32(0.0)));
- expect(!isNegativeInf(f32(-0.0)));
- expect(!isNegativeInf(f64(0.0)));
- expect(!isNegativeInf(f64(-0.0)));
- expect(!isNegativeInf(f128(0.0)));
- expect(!isNegativeInf(f128(-0.0)));
+ expect(!isNegativeInf(@as(f16, 0.0)));
+ expect(!isNegativeInf(@as(f16, -0.0)));
+ expect(!isNegativeInf(@as(f32, 0.0)));
+ expect(!isNegativeInf(@as(f32, -0.0)));
+ expect(!isNegativeInf(@as(f64, 0.0)));
+ expect(!isNegativeInf(@as(f64, -0.0)));
+ expect(!isNegativeInf(@as(f128, 0.0)));
+ expect(!isNegativeInf(@as(f128, -0.0)));
expect(!isNegativeInf(math.inf(f16)));
expect(isNegativeInf(-math.inf(f16)));
expect(!isNegativeInf(math.inf(f32)));
diff --git a/lib/std/math/isnan.zig b/lib/std/math/isnan.zig
index cf8cd2e1c2..ac865f0d0c 100644
--- a/lib/std/math/isnan.zig
+++ b/lib/std/math/isnan.zig
@@ -20,8 +20,8 @@ test "math.isNan" {
expect(isNan(math.nan(f32)));
expect(isNan(math.nan(f64)));
expect(isNan(math.nan(f128)));
- expect(!isNan(f16(1.0)));
- expect(!isNan(f32(1.0)));
- expect(!isNan(f64(1.0)));
- expect(!isNan(f128(1.0)));
+ expect(!isNan(@as(f16, 1.0)));
+ expect(!isNan(@as(f32, 1.0)));
+ expect(!isNan(@as(f64, 1.0)));
+ expect(!isNan(@as(f128, 1.0)));
}
diff --git a/lib/std/math/isnormal.zig b/lib/std/math/isnormal.zig
index f8611ef805..01d919d417 100644
--- a/lib/std/math/isnormal.zig
+++ b/lib/std/math/isnormal.zig
@@ -29,10 +29,10 @@ test "math.isNormal" {
expect(!isNormal(math.nan(f16)));
expect(!isNormal(math.nan(f32)));
expect(!isNormal(math.nan(f64)));
- expect(!isNormal(f16(0)));
- expect(!isNormal(f32(0)));
- expect(!isNormal(f64(0)));
- expect(isNormal(f16(1.0)));
- expect(isNormal(f32(1.0)));
- expect(isNormal(f64(1.0)));
+ expect(!isNormal(@as(f16, 0)));
+ expect(!isNormal(@as(f32, 0)));
+ expect(!isNormal(@as(f64, 0)));
+ expect(isNormal(@as(f16, 1.0)));
+ expect(isNormal(@as(f32, 1.0)));
+ expect(isNormal(@as(f64, 1.0)));
}
diff --git a/lib/std/math/ln.zig b/lib/std/math/ln.zig
index c5d4c9ff25..fd5741a818 100644
--- a/lib/std/math/ln.zig
+++ b/lib/std/math/ln.zig
@@ -31,10 +31,10 @@ pub fn ln(x: var) @typeOf(x) {
};
},
TypeId.ComptimeInt => {
- return @typeOf(1)(math.floor(ln_64(f64(x))));
+ return @typeOf(1)(math.floor(ln_64(@as(f64, x))));
},
TypeId.Int => {
- return T(math.floor(ln_64(f64(x))));
+ return @as(T, math.floor(ln_64(@as(f64, x))));
},
else => @compileError("ln not implemented for " ++ @typeName(T)),
}
@@ -132,7 +132,7 @@ pub fn ln_64(x_: f64) f64 {
hx += 0x3FF00000 - 0x3FE6A09E;
k += @intCast(i32, hx >> 20) - 0x3FF;
hx = (hx & 0x000FFFFF) + 0x3FE6A09E;
- ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF);
+ ix = (@as(u64, hx) << 32) | (ix & 0xFFFFFFFF);
x = @bitCast(f64, ix);
const f = x - 1.0;
@@ -149,8 +149,8 @@ pub fn ln_64(x_: f64) f64 {
}
test "math.ln" {
- expect(ln(f32(0.2)) == ln_32(0.2));
- expect(ln(f64(0.2)) == ln_64(0.2));
+ expect(ln(@as(f32, 0.2)) == ln_32(0.2));
+ expect(ln(@as(f64, 0.2)) == ln_64(0.2));
}
test "math.ln32" {
diff --git a/lib/std/math/log.zig b/lib/std/math/log.zig
index 77f3639fd2..40b716b005 100644
--- a/lib/std/math/log.zig
+++ b/lib/std/math/log.zig
@@ -23,10 +23,10 @@ pub fn log(comptime T: type, base: T, x: T) T {
const float_base = math.lossyCast(f64, base);
switch (@typeId(T)) {
TypeId.ComptimeFloat => {
- return @typeOf(1.0)(math.ln(f64(x)) / math.ln(float_base));
+ return @typeOf(1.0)(math.ln(@as(f64, x)) / math.ln(float_base));
},
TypeId.ComptimeInt => {
- return @typeOf(1)(math.floor(math.ln(f64(x)) / math.ln(float_base)));
+ return @typeOf(1)(math.floor(math.ln(@as(f64, x)) / math.ln(float_base)));
},
builtin.TypeId.Int => {
// TODO implement integer log without using float math
@@ -35,7 +35,7 @@ pub fn log(comptime T: type, base: T, x: T) T {
builtin.TypeId.Float => {
switch (T) {
- f32 => return @floatCast(f32, math.ln(f64(x)) / math.ln(float_base)),
+ f32 => return @floatCast(f32, math.ln(@as(f64, x)) / math.ln(float_base)),
f64 => return math.ln(x) / math.ln(float_base),
else => @compileError("log not implemented for " ++ @typeName(T)),
}
@@ -64,9 +64,9 @@ test "math.log float" {
}
test "math.log float_special" {
- expect(log(f32, 2, 0.2301974) == math.log2(f32(0.2301974)));
- expect(log(f32, 10, 0.2301974) == math.log10(f32(0.2301974)));
+ expect(log(f32, 2, 0.2301974) == math.log2(@as(f32, 0.2301974)));
+ expect(log(f32, 10, 0.2301974) == math.log10(@as(f32, 0.2301974)));
- expect(log(f64, 2, 213.23019799993) == math.log2(f64(213.23019799993)));
- expect(log(f64, 10, 213.23019799993) == math.log10(f64(213.23019799993)));
+ expect(log(f64, 2, 213.23019799993) == math.log2(@as(f64, 213.23019799993)));
+ expect(log(f64, 10, 213.23019799993) == math.log10(@as(f64, 213.23019799993)));
}
diff --git a/lib/std/math/log10.zig b/lib/std/math/log10.zig
index 9b0bc3ac52..f895e102a0 100644
--- a/lib/std/math/log10.zig
+++ b/lib/std/math/log10.zig
@@ -32,7 +32,7 @@ pub fn log10(x: var) @typeOf(x) {
};
},
TypeId.ComptimeInt => {
- return @typeOf(1)(math.floor(log10_64(f64(x))));
+ return @typeOf(1)(math.floor(log10_64(@as(f64, x))));
},
TypeId.Int => {
return @floatToInt(T, math.floor(log10_64(@intToFloat(f64, x))));
@@ -143,7 +143,7 @@ pub fn log10_64(x_: f64) f64 {
hx += 0x3FF00000 - 0x3FE6A09E;
k += @intCast(i32, hx >> 20) - 0x3FF;
hx = (hx & 0x000FFFFF) + 0x3FE6A09E;
- ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF);
+ ix = (@as(u64, hx) << 32) | (ix & 0xFFFFFFFF);
x = @bitCast(f64, ix);
const f = x - 1.0;
@@ -158,7 +158,7 @@ pub fn log10_64(x_: f64) f64 {
// hi + lo = f - hfsq + s * (hfsq + R) ~ log(1 + f)
var hi = f - hfsq;
var hii = @bitCast(u64, hi);
- hii &= u64(maxInt(u64)) << 32;
+ hii &= @as(u64, maxInt(u64)) << 32;
hi = @bitCast(f64, hii);
const lo = f - hi - hfsq + s * (hfsq + R);
@@ -177,8 +177,8 @@ pub fn log10_64(x_: f64) f64 {
}
test "math.log10" {
- testing.expect(log10(f32(0.2)) == log10_32(0.2));
- testing.expect(log10(f64(0.2)) == log10_64(0.2));
+ testing.expect(log10(@as(f32, 0.2)) == log10_32(0.2));
+ testing.expect(log10(@as(f64, 0.2)) == log10_64(0.2));
}
test "math.log10_32" {
diff --git a/lib/std/math/log1p.zig b/lib/std/math/log1p.zig
index bae6deb536..047e089a91 100644
--- a/lib/std/math/log1p.zig
+++ b/lib/std/math/log1p.zig
@@ -166,7 +166,7 @@ fn log1p_64(x: f64) f64 {
// u into [sqrt(2)/2, sqrt(2)]
iu = (iu & 0x000FFFFF) + 0x3FE6A09E;
- const iq = (u64(iu) << 32) | (hu & 0xFFFFFFFF);
+ const iq = (@as(u64, iu) << 32) | (hu & 0xFFFFFFFF);
f = @bitCast(f64, iq) - 1;
}
@@ -183,8 +183,8 @@ fn log1p_64(x: f64) f64 {
}
test "math.log1p" {
- expect(log1p(f32(0.0)) == log1p_32(0.0));
- expect(log1p(f64(0.0)) == log1p_64(0.0));
+ expect(log1p(@as(f32, 0.0)) == log1p_32(0.0));
+ expect(log1p(@as(f64, 0.0)) == log1p_64(0.0));
}
test "math.log1p_32" {
diff --git a/lib/std/math/log2.zig b/lib/std/math/log2.zig
index 88450a7ffd..47b214d6cf 100644
--- a/lib/std/math/log2.zig
+++ b/lib/std/math/log2.zig
@@ -143,7 +143,7 @@ pub fn log2_64(x_: f64) f64 {
hx += 0x3FF00000 - 0x3FE6A09E;
k += @intCast(i32, hx >> 20) - 0x3FF;
hx = (hx & 0x000FFFFF) + 0x3FE6A09E;
- ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF);
+ ix = (@as(u64, hx) << 32) | (ix & 0xFFFFFFFF);
x = @bitCast(f64, ix);
const f = x - 1.0;
@@ -158,7 +158,7 @@ pub fn log2_64(x_: f64) f64 {
// hi + lo = f - hfsq + s * (hfsq + R) ~ log(1 + f)
var hi = f - hfsq;
var hii = @bitCast(u64, hi);
- hii &= u64(maxInt(u64)) << 32;
+ hii &= @as(u64, maxInt(u64)) << 32;
hi = @bitCast(f64, hii);
const lo = f - hi - hfsq + s * (hfsq + R);
@@ -175,8 +175,8 @@ pub fn log2_64(x_: f64) f64 {
}
test "math.log2" {
- expect(log2(f32(0.2)) == log2_32(0.2));
- expect(log2(f64(0.2)) == log2_64(0.2));
+ expect(log2(@as(f32, 0.2)) == log2_32(0.2));
+ expect(log2(@as(f64, 0.2)) == log2_64(0.2));
}
test "math.log2_32" {
diff --git a/lib/std/math/modf.zig b/lib/std/math/modf.zig
index 92194d4c75..6567cbc9ed 100644
--- a/lib/std/math/modf.zig
+++ b/lib/std/math/modf.zig
@@ -65,7 +65,7 @@ fn modf32(x: f32) modf32_result {
return result;
}
- const mask = u32(0x007FFFFF) >> @intCast(u5, e);
+ const mask = @as(u32, 0x007FFFFF) >> @intCast(u5, e);
if (u & mask == 0) {
result.ipart = x;
result.fpart = @bitCast(f32, us);
@@ -109,7 +109,7 @@ fn modf64(x: f64) modf64_result {
return result;
}
- const mask = u64(maxInt(u64) >> 12) >> @intCast(u6, e);
+ const mask = @as(u64, maxInt(u64) >> 12) >> @intCast(u6, e);
if (u & mask == 0) {
result.ipart = x;
result.fpart = @bitCast(f64, us);
@@ -123,12 +123,12 @@ fn modf64(x: f64) modf64_result {
}
test "math.modf" {
- const a = modf(f32(1.0));
+ const a = modf(@as(f32, 1.0));
const b = modf32(1.0);
// NOTE: No struct comparison on generic return type function? non-named, makes sense, but still.
expect(a.ipart == b.ipart and a.fpart == b.fpart);
- const c = modf(f64(1.0));
+ const c = modf(@as(f64, 1.0));
const d = modf64(1.0);
expect(a.ipart == b.ipart and a.fpart == b.fpart);
}
diff --git a/lib/std/math/round.zig b/lib/std/math/round.zig
index 0b80a46ce5..adedbf2e94 100644
--- a/lib/std/math/round.zig
+++ b/lib/std/math/round.zig
@@ -91,8 +91,8 @@ fn round64(x_: f64) f64 {
}
test "math.round" {
- expect(round(f32(1.3)) == round32(1.3));
- expect(round(f64(1.3)) == round64(1.3));
+ expect(round(@as(f32, 1.3)) == round32(1.3));
+ expect(round(@as(f64, 1.3)) == round64(1.3));
}
test "math.round32" {
diff --git a/lib/std/math/scalbn.zig b/lib/std/math/scalbn.zig
index d5716d621c..e3c457ade5 100644
--- a/lib/std/math/scalbn.zig
+++ b/lib/std/math/scalbn.zig
@@ -79,8 +79,8 @@ fn scalbn64(x: f64, n_: i32) f64 {
}
test "math.scalbn" {
- expect(scalbn(f32(1.5), 4) == scalbn32(1.5, 4));
- expect(scalbn(f64(1.5), 4) == scalbn64(1.5, 4));
+ expect(scalbn(@as(f32, 1.5), 4) == scalbn32(1.5, 4));
+ expect(scalbn(@as(f64, 1.5), 4) == scalbn64(1.5, 4));
}
test "math.scalbn32" {
diff --git a/lib/std/math/signbit.zig b/lib/std/math/signbit.zig
index e5c5909292..f20753f2ff 100644
--- a/lib/std/math/signbit.zig
+++ b/lib/std/math/signbit.zig
@@ -29,9 +29,9 @@ fn signbit64(x: f64) bool {
}
test "math.signbit" {
- expect(signbit(f16(4.0)) == signbit16(4.0));
- expect(signbit(f32(4.0)) == signbit32(4.0));
- expect(signbit(f64(4.0)) == signbit64(4.0));
+ expect(signbit(@as(f16, 4.0)) == signbit16(4.0));
+ expect(signbit(@as(f32, 4.0)) == signbit32(4.0));
+ expect(signbit(@as(f64, 4.0)) == signbit64(4.0));
}
test "math.signbit16" {
diff --git a/lib/std/math/sin.zig b/lib/std/math/sin.zig
index ee07b4f85e..3baa730123 100644
--- a/lib/std/math/sin.zig
+++ b/lib/std/math/sin.zig
@@ -88,9 +88,9 @@ test "math.sin" {
// TODO https://github.com/ziglang/zig/issues/3289
return error.SkipZigTest;
}
- expect(sin(f32(0.0)) == sin_(f32, 0.0));
- expect(sin(f64(0.0)) == sin_(f64, 0.0));
- expect(comptime (math.sin(f64(2))) == math.sin(f64(2)));
+ expect(sin(@as(f32, 0.0)) == sin_(f32, 0.0));
+ expect(sin(@as(f64, 0.0)) == sin_(f64, 0.0));
+ expect(comptime (math.sin(@as(f64, 2))) == math.sin(@as(f64, 2)));
}
test "math.sin32" {
diff --git a/lib/std/math/sinh.zig b/lib/std/math/sinh.zig
index 73ee65ea6f..c9718e3ce2 100644
--- a/lib/std/math/sinh.zig
+++ b/lib/std/math/sinh.zig
@@ -93,8 +93,8 @@ fn sinh64(x: f64) f64 {
}
test "math.sinh" {
- expect(sinh(f32(1.5)) == sinh32(1.5));
- expect(sinh(f64(1.5)) == sinh64(1.5));
+ expect(sinh(@as(f32, 1.5)) == sinh32(1.5));
+ expect(sinh(@as(f64, 1.5)) == sinh64(1.5));
}
test "math.sinh32" {
diff --git a/lib/std/math/sqrt.zig b/lib/std/math/sqrt.zig
index 30af5915d4..89eda4ea2b 100644
--- a/lib/std/math/sqrt.zig
+++ b/lib/std/math/sqrt.zig
@@ -15,7 +15,7 @@ const maxInt = std.math.maxInt;
pub fn sqrt(x: var) (if (@typeId(@typeOf(x)) == TypeId.Int) @IntType(false, @typeOf(x).bit_count / 2) else @typeOf(x)) {
const T = @typeOf(x);
switch (@typeId(T)) {
- TypeId.ComptimeFloat => return T(@sqrt(f64, x)), // TODO upgrade to f128
+ TypeId.ComptimeFloat => return @as(T, @sqrt(f64, x)), // TODO upgrade to f128
TypeId.Float => return @sqrt(T, x),
TypeId.ComptimeInt => comptime {
if (x > maxInt(u128)) {
@@ -24,7 +24,7 @@ pub fn sqrt(x: var) (if (@typeId(@typeOf(x)) == TypeId.Int) @IntType(false, @typ
if (x < 0) {
@compileError("sqrt on negative number");
}
- return T(sqrt_int(u128, x));
+ return @as(T, sqrt_int(u128, x));
},
TypeId.Int => return sqrt_int(T, x),
else => @compileError("sqrt not implemented for " ++ @typeName(T)),
@@ -32,9 +32,9 @@ pub fn sqrt(x: var) (if (@typeId(@typeOf(x)) == TypeId.Int) @IntType(false, @typ
}
test "math.sqrt" {
- expect(sqrt(f16(0.0)) == @sqrt(f16, 0.0));
- expect(sqrt(f32(0.0)) == @sqrt(f32, 0.0));
- expect(sqrt(f64(0.0)) == @sqrt(f64, 0.0));
+ expect(sqrt(@as(f16, 0.0)) == @sqrt(f16, 0.0));
+ expect(sqrt(@as(f32, 0.0)) == @sqrt(f32, 0.0));
+ expect(sqrt(@as(f64, 0.0)) == @sqrt(f64, 0.0));
}
test "math.sqrt16" {
diff --git a/lib/std/math/tan.zig b/lib/std/math/tan.zig
index 049c85df12..1a027cf403 100644
--- a/lib/std/math/tan.zig
+++ b/lib/std/math/tan.zig
@@ -75,8 +75,8 @@ fn tan_(comptime T: type, x_: T) T {
}
test "math.tan" {
- expect(tan(f32(0.0)) == tan_(f32, 0.0));
- expect(tan(f64(0.0)) == tan_(f64, 0.0));
+ expect(tan(@as(f32, 0.0)) == tan_(f32, 0.0));
+ expect(tan(@as(f64, 0.0)) == tan_(f64, 0.0));
}
test "math.tan32" {
diff --git a/lib/std/math/tanh.zig b/lib/std/math/tanh.zig
index 48d26d091e..ced5f58bcc 100644
--- a/lib/std/math/tanh.zig
+++ b/lib/std/math/tanh.zig
@@ -119,8 +119,8 @@ fn tanh64(x: f64) f64 {
}
test "math.tanh" {
- expect(tanh(f32(1.5)) == tanh32(1.5));
- expect(tanh(f64(1.5)) == tanh64(1.5));
+ expect(tanh(@as(f32, 1.5)) == tanh32(1.5));
+ expect(tanh(@as(f64, 1.5)) == tanh64(1.5));
}
test "math.tanh32" {
diff --git a/lib/std/math/trunc.zig b/lib/std/math/trunc.zig
index 219bcd4914..56a842345c 100644
--- a/lib/std/math/trunc.zig
+++ b/lib/std/math/trunc.zig
@@ -36,7 +36,7 @@ fn trunc32(x: f32) f32 {
e = 1;
}
- m = u32(maxInt(u32)) >> @intCast(u5, e);
+ m = @as(u32, maxInt(u32)) >> @intCast(u5, e);
if (u & m == 0) {
return x;
} else {
@@ -57,7 +57,7 @@ fn trunc64(x: f64) f64 {
e = 1;
}
- m = u64(maxInt(u64)) >> @intCast(u6, e);
+ m = @as(u64, maxInt(u64)) >> @intCast(u6, e);
if (u & m == 0) {
return x;
} else {
@@ -67,8 +67,8 @@ fn trunc64(x: f64) f64 {
}
test "math.trunc" {
- expect(trunc(f32(1.3)) == trunc32(1.3));
- expect(trunc(f64(1.3)) == trunc64(1.3));
+ expect(trunc(@as(f32, 1.3)) == trunc32(1.3));
+ expect(trunc(@as(f64, 1.3)) == trunc64(1.3));
}
test "math.trunc32" {
diff --git a/lib/std/mem.zig b/lib/std/mem.zig
index bf8f7b8be7..19e9634d5a 100644
--- a/lib/std/mem.zig
+++ b/lib/std/mem.zig
@@ -118,11 +118,11 @@ pub const Allocator = struct {
} else @alignOf(T);
if (n == 0) {
- return ([*]align(a) T)(undefined)[0..0];
+ return @as([*]align(a) T, undefined)[0..0];
}
const byte_count = math.mul(usize, @sizeOf(T), n) catch return Error.OutOfMemory;
- const byte_slice = try self.reallocFn(self, ([*]u8)(undefined)[0..0], undefined, byte_count, a);
+ const byte_slice = try self.reallocFn(self, &[0]u8{}, undefined, byte_count, a);
assert(byte_slice.len == byte_count);
@memset(byte_slice.ptr, undefined, byte_slice.len);
if (alignment == null) {
@@ -170,7 +170,7 @@ pub const Allocator = struct {
}
if (new_n == 0) {
self.free(old_mem);
- return ([*]align(new_alignment) T)(undefined)[0..0];
+ return @as([*]align(new_alignment) T, undefined)[0..0];
}
const old_byte_slice = @sliceToBytes(old_mem);
@@ -523,7 +523,7 @@ pub fn readVarInt(comptime ReturnType: type, bytes: []const u8, endian: builtin.
builtin.Endian.Little => {
const ShiftType = math.Log2Int(ReturnType);
for (bytes) |b, index| {
- result = result | (ReturnType(b) << @intCast(ShiftType, index * 8));
+ result = result | (@as(ReturnType, b) << @intCast(ShiftType, index * 8));
}
},
}
@@ -976,7 +976,7 @@ pub const SplitIterator = struct {
/// Naively combines a series of slices with a separator.
/// Allocates memory for the result, which must be freed by the caller.
pub fn join(allocator: *Allocator, separator: []const u8, slices: []const []const u8) ![]u8 {
- if (slices.len == 0) return (([*]u8)(undefined))[0..0];
+ if (slices.len == 0) return &[0]u8{};
const total_len = blk: {
var sum: usize = separator.len * (slices.len - 1);
@@ -1011,7 +1011,7 @@ test "mem.join" {
/// Copies each T from slices into a new slice that exactly holds all the elements.
pub fn concat(allocator: *Allocator, comptime T: type, slices: []const []const T) ![]T {
- if (slices.len == 0) return (([*]T)(undefined))[0..0];
+ if (slices.len == 0) return &[0]T{};
const total_len = blk: {
var sum: usize = 0;
@@ -1332,7 +1332,7 @@ fn AsBytesReturnType(comptime P: type) type {
if (comptime !trait.isSingleItemPtr(P))
@compileError("expected single item " ++ "pointer, passed " ++ @typeName(P));
- const size = usize(@sizeOf(meta.Child(P)));
+ const size = @as(usize, @sizeOf(meta.Child(P)));
const alignment = comptime meta.alignment(P);
if (alignment == 0) {
@@ -1353,7 +1353,7 @@ pub fn asBytes(ptr: var) AsBytesReturnType(@typeOf(ptr)) {
}
test "asBytes" {
- const deadbeef = u32(0xDEADBEEF);
+ const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (builtin.endian) {
builtin.Endian.Big => "\xDE\xAD\xBE\xEF",
builtin.Endian.Little => "\xEF\xBE\xAD\xDE",
@@ -1361,7 +1361,7 @@ test "asBytes" {
testing.expect(eql(u8, asBytes(&deadbeef), deadbeef_bytes));
- var codeface = u32(0xC0DEFACE);
+ var codeface = @as(u32, 0xC0DEFACE);
for (asBytes(&codeface).*) |*b|
b.* = 0;
testing.expect(codeface == 0);
@@ -1392,7 +1392,7 @@ pub fn toBytes(value: var) [@sizeOf(@typeOf(value))]u8 {
}
test "toBytes" {
- var my_bytes = toBytes(u32(0x12345678));
+ var my_bytes = toBytes(@as(u32, 0x12345678));
switch (builtin.endian) {
builtin.Endian.Big => testing.expect(eql(u8, my_bytes, "\x12\x34\x56\x78")),
builtin.Endian.Little => testing.expect(eql(u8, my_bytes, "\x78\x56\x34\x12")),
@@ -1406,7 +1406,7 @@ test "toBytes" {
}
fn BytesAsValueReturnType(comptime T: type, comptime B: type) type {
- const size = usize(@sizeOf(T));
+ const size = @as(usize, @sizeOf(T));
if (comptime !trait.is(builtin.TypeId.Pointer)(B) or meta.Child(B) != [size]u8) {
@compileError("expected *[N]u8 " ++ ", passed " ++ @typeName(B));
@@ -1424,7 +1424,7 @@ pub fn bytesAsValue(comptime T: type, bytes: var) BytesAsValueReturnType(T, @typ
}
test "bytesAsValue" {
- const deadbeef = u32(0xDEADBEEF);
+ const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (builtin.endian) {
builtin.Endian.Big => "\xDE\xAD\xBE\xEF",
builtin.Endian.Little => "\xEF\xBE\xAD\xDE",
@@ -1472,7 +1472,7 @@ test "bytesToValue" {
};
const deadbeef = bytesToValue(u32, deadbeef_bytes);
- testing.expect(deadbeef == u32(0xDEADBEEF));
+ testing.expect(deadbeef == @as(u32, 0xDEADBEEF));
}
fn SubArrayPtrReturnType(comptime T: type, comptime length: usize) type {
diff --git a/lib/std/meta.zig b/lib/std/meta.zig
index b29eb60201..903c3a12b3 100644
--- a/lib/std/meta.zig
+++ b/lib/std/meta.zig
@@ -341,7 +341,7 @@ test "std.meta.TagType" {
///Returns the active tag of a tagged union
pub fn activeTag(u: var) @TagType(@typeOf(u)) {
const T = @typeOf(u);
- return @TagType(T)(u);
+ return @as(@TagType(T), u);
}
test "std.meta.activeTag" {
@@ -505,7 +505,7 @@ test "std.meta.eql" {
const EU = struct {
fn tst(err: bool) !u8 {
if (err) return error.Error;
- return u8(5);
+ return @as(u8, 5);
}
};
diff --git a/lib/std/meta/trait.zig b/lib/std/meta/trait.zig
index 43be7f3dfb..8857b4aa9e 100644
--- a/lib/std/meta/trait.zig
+++ b/lib/std/meta/trait.zig
@@ -327,8 +327,8 @@ pub fn isConstPtr(comptime T: type) bool {
}
test "std.meta.trait.isConstPtr" {
- var t = u8(0);
- const c = u8(0);
+ var t = @as(u8, 0);
+ const c = @as(u8, 0);
testing.expect(isConstPtr(*const @typeOf(t)));
testing.expect(isConstPtr(@typeOf(&c)));
testing.expect(!isConstPtr(*@typeOf(t)));
diff --git a/lib/std/mutex.zig b/lib/std/mutex.zig
index 5f3b9272d9..706c699a87 100644
--- a/lib/std/mutex.zig
+++ b/lib/std/mutex.zig
@@ -1,19 +1,13 @@
const std = @import("std.zig");
const builtin = @import("builtin");
-const AtomicOrder = builtin.AtomicOrder;
-const AtomicRmwOp = builtin.AtomicRmwOp;
const testing = std.testing;
const SpinLock = std.SpinLock;
-const linux = std.os.linux;
-const windows = std.os.windows;
+const ThreadParker = std.ThreadParker;
/// Lock may be held only once. If the same thread
/// tries to acquire the same mutex twice, it deadlocks.
-/// This type must be initialized at runtime, and then deinitialized when no
-/// longer needed, to free resources.
-/// If you need static initialization, use std.StaticallyInitializedMutex.
-/// The Linux implementation is based on mutex3 from
-/// https://www.akkadia.org/drepper/futex.pdf
+/// This type supports static initialization and is based off of Golang 1.13 runtime.lock_futex:
+/// https://github.com/golang/go/blob/master/src/runtime/lock_futex.go
/// When an application is built in single threaded release mode, all the functions are
/// no-ops. In single threaded debug mode, there is deadlock detection.
pub const Mutex = if (builtin.single_threaded)
@@ -43,84 +37,85 @@ pub const Mutex = if (builtin.single_threaded)
return Held{ .mutex = self };
}
}
-else switch (builtin.os) {
- builtin.Os.linux => struct {
- /// 0: unlocked
- /// 1: locked, no waiters
- /// 2: locked, one or more waiters
- lock: i32,
-
- pub const Held = struct {
- mutex: *Mutex,
+else
+ struct {
+ state: State, // TODO: make this an enum
+ parker: ThreadParker,
- pub fn release(self: Held) void {
- const c = @atomicRmw(i32, &self.mutex.lock, AtomicRmwOp.Sub, 1, AtomicOrder.Release);
- if (c != 1) {
- _ = @atomicRmw(i32, &self.mutex.lock, AtomicRmwOp.Xchg, 0, AtomicOrder.Release);
- const rc = linux.futex_wake(&self.mutex.lock, linux.FUTEX_WAKE | linux.FUTEX_PRIVATE_FLAG, 1);
- switch (linux.getErrno(rc)) {
- 0 => {},
- linux.EINVAL => unreachable,
- else => unreachable,
- }
- }
- }
+ const State = enum(u32) {
+ Unlocked,
+ Sleeping,
+ Locked,
};
+ /// number of iterations to spin yielding the cpu
+ const SPIN_CPU = 4;
+
+ /// number of iterations to perform in the cpu yield loop
+ const SPIN_CPU_COUNT = 30;
+
+ /// number of iterations to spin yielding the thread
+ const SPIN_THREAD = 1;
+
pub fn init() Mutex {
- return Mutex{ .lock = 0 };
+ return Mutex{
+ .state = .Unlocked,
+ .parker = ThreadParker.init(),
+ };
}
- pub fn deinit(self: *Mutex) void {}
-
- pub fn acquire(self: *Mutex) Held {
- var c = @cmpxchgWeak(i32, &self.lock, 0, 1, AtomicOrder.Acquire, AtomicOrder.Monotonic) orelse
- return Held{ .mutex = self };
- if (c != 2)
- c = @atomicRmw(i32, &self.lock, AtomicRmwOp.Xchg, 2, AtomicOrder.Acquire);
- while (c != 0) {
- const rc = linux.futex_wait(&self.lock, linux.FUTEX_WAIT | linux.FUTEX_PRIVATE_FLAG, 2, null);
- switch (linux.getErrno(rc)) {
- 0, linux.EINTR, linux.EAGAIN => {},
- linux.EINVAL => unreachable,
- else => unreachable,
- }
- c = @atomicRmw(i32, &self.lock, AtomicRmwOp.Xchg, 2, AtomicOrder.Acquire);
- }
- return Held{ .mutex = self };
+ pub fn deinit(self: *Mutex) void {
+ self.parker.deinit();
}
- },
- // TODO once https://github.com/ziglang/zig/issues/287 (copy elision) is solved, we can make a
- // better implementation of this. The problem is we need the init() function to have access to
- // the address of the CRITICAL_SECTION, and then have it not move.
- builtin.Os.windows => std.StaticallyInitializedMutex,
- else => struct {
- /// TODO better implementation than spin lock.
- /// When changing this, one must also change the corresponding
- /// std.StaticallyInitializedMutex code, since it aliases this type,
- /// under the assumption that it works both statically and at runtime.
- lock: SpinLock,
pub const Held = struct {
mutex: *Mutex,
pub fn release(self: Held) void {
- SpinLock.Held.release(SpinLock.Held{ .spinlock = &self.mutex.lock });
+ switch (@atomicRmw(State, &self.mutex.state, .Xchg, .Unlocked, .Release)) {
+ .Locked => {},
+ .Sleeping => self.mutex.parker.unpark(@ptrCast(*const u32, &self.mutex.state)),
+ .Unlocked => unreachable, // unlocking an unlocked mutex
+ else => unreachable, // should never be anything else
+ }
}
};
- pub fn init() Mutex {
- return Mutex{ .lock = SpinLock.init() };
- }
+ pub fn acquire(self: *Mutex) Held {
+ // Try and speculatively grab the lock.
+ // If it fails, the state is either Locked or Sleeping
+ // depending on if theres a thread stuck sleeping below.
+ var state = @atomicRmw(State, &self.state, .Xchg, .Locked, .Acquire);
+ if (state == .Unlocked)
+ return Held{ .mutex = self };
- pub fn deinit(self: *Mutex) void {}
+ while (true) {
+ // try and acquire the lock using cpu spinning on failure
+ var spin: usize = 0;
+ while (spin < SPIN_CPU) : (spin += 1) {
+ var value = @atomicLoad(State, &self.state, .Monotonic);
+ while (value == .Unlocked)
+ value = @cmpxchgWeak(State, &self.state, .Unlocked, state, .Acquire, .Monotonic) orelse return Held{ .mutex = self };
+ SpinLock.yield(SPIN_CPU_COUNT);
+ }
- pub fn acquire(self: *Mutex) Held {
- _ = self.lock.acquire();
- return Held{ .mutex = self };
+ // try and acquire the lock using thread rescheduling on failure
+ spin = 0;
+ while (spin < SPIN_THREAD) : (spin += 1) {
+ var value = @atomicLoad(State, &self.state, .Monotonic);
+ while (value == .Unlocked)
+ value = @cmpxchgWeak(State, &self.state, .Unlocked, state, .Acquire, .Monotonic) orelse return Held{ .mutex = self };
+ std.os.sched_yield() catch std.time.sleep(1);
+ }
+
+ // failed to acquire the lock, go to sleep until woken up by `Held.release()`
+ if (@atomicRmw(State, &self.state, .Xchg, .Sleeping, .Acquire) == .Unlocked)
+ return Held{ .mutex = self };
+ state = .Sleeping;
+ self.parker.park(@ptrCast(*const u32, &self.state), @enumToInt(State.Sleeping));
+ }
}
- },
-};
+ };
const TestContext = struct {
mutex: *Mutex,
diff --git a/lib/std/net.zig b/lib/std/net.zig
index 95036707b6..f4cd09482b 100644
--- a/lib/std/net.zig
+++ b/lib/std/net.zig
@@ -10,15 +10,18 @@ test "" {
_ = @import("net/test.zig");
}
-pub const IpAddress = extern union {
+const has_unix_sockets = @hasDecl(os, "sockaddr_un");
+
+pub const Address = extern union {
any: os.sockaddr,
in: os.sockaddr_in,
in6: os.sockaddr_in6,
+ un: if (has_unix_sockets) os.sockaddr_un else void,
// TODO this crashed the compiler
//pub const localhost = initIp4(parseIp4("127.0.0.1") catch unreachable, 0);
- pub fn parse(name: []const u8, port: u16) !IpAddress {
+ pub fn parseIp(name: []const u8, port: u16) !Address {
if (parseIp4(name, port)) |ip4| return ip4 else |err| switch (err) {
error.Overflow,
error.InvalidEnd,
@@ -39,17 +42,17 @@ pub const IpAddress = extern union {
return error.InvalidIPAddressFormat;
}
- pub fn parseExpectingFamily(name: []const u8, family: os.sa_family_t, port: u16) !IpAddress {
+ pub fn parseExpectingFamily(name: []const u8, family: os.sa_family_t, port: u16) !Address {
switch (family) {
os.AF_INET => return parseIp4(name, port),
os.AF_INET6 => return parseIp6(name, port),
- os.AF_UNSPEC => return parse(name, port),
+ os.AF_UNSPEC => return parseIp(name, port),
else => unreachable,
}
}
- pub fn parseIp6(buf: []const u8, port: u16) !IpAddress {
- var result = IpAddress{
+ pub fn parseIp6(buf: []const u8, port: u16) !Address {
+ var result = Address{
.in6 = os.sockaddr_in6{
.scope_id = 0,
.port = mem.nativeToBig(u16, port),
@@ -117,7 +120,7 @@ pub const IpAddress = extern union {
ip_slice[10] = 0xff;
ip_slice[11] = 0xff;
- const ptr = @sliceToBytes((*const [1]u32)(&addr)[0..]);
+ const ptr = @sliceToBytes(@as(*const [1]u32, &addr)[0..]);
ip_slice[12] = ptr[0];
ip_slice[13] = ptr[1];
@@ -154,14 +157,14 @@ pub const IpAddress = extern union {
}
}
- pub fn parseIp4(buf: []const u8, port: u16) !IpAddress {
- var result = IpAddress{
+ pub fn parseIp4(buf: []const u8, port: u16) !Address {
+ var result = Address{
.in = os.sockaddr_in{
.port = mem.nativeToBig(u16, port),
.addr = undefined,
},
};
- const out_ptr = @sliceToBytes((*[1]u32)(&result.in.addr)[0..]);
+ const out_ptr = @sliceToBytes(@as(*[1]u32, &result.in.addr)[0..]);
var x: u8 = 0;
var index: u8 = 0;
@@ -194,8 +197,8 @@ pub const IpAddress = extern union {
return error.Incomplete;
}
- pub fn initIp4(addr: [4]u8, port: u16) IpAddress {
- return IpAddress{
+ pub fn initIp4(addr: [4]u8, port: u16) Address {
+ return Address{
.in = os.sockaddr_in{
.port = mem.nativeToBig(u16, port),
.addr = @ptrCast(*align(1) const u32, &addr).*,
@@ -203,8 +206,8 @@ pub const IpAddress = extern union {
};
}
- pub fn initIp6(addr: [16]u8, port: u16, flowinfo: u32, scope_id: u32) IpAddress {
- return IpAddress{
+ pub fn initIp6(addr: [16]u8, port: u16, flowinfo: u32, scope_id: u32) Address {
+ return Address{
.in6 = os.sockaddr_in6{
.addr = addr,
.port = mem.nativeToBig(u16, port),
@@ -214,8 +217,24 @@ pub const IpAddress = extern union {
};
}
+ pub fn initUnix(path: []const u8) !Address {
+ var sock_addr = os.sockaddr_un{
+ .family = os.AF_UNIX,
+ .path = undefined,
+ };
+
+ // this enables us to have the proper length of the socket in getOsSockLen
+ mem.set(u8, &sock_addr.path, 0);
+
+ if (path.len > sock_addr.path.len) return error.NameTooLong;
+ mem.copy(u8, &sock_addr.path, path);
+
+ return Address{ .un = sock_addr };
+ }
+
/// Returns the port in native endian.
- pub fn getPort(self: IpAddress) u16 {
+ /// Asserts that the address is ip4 or ip6.
+ pub fn getPort(self: Address) u16 {
const big_endian_port = switch (self.any.family) {
os.AF_INET => self.in.port,
os.AF_INET6 => self.in6.port,
@@ -225,7 +244,8 @@ pub const IpAddress = extern union {
}
/// `port` is native-endian.
- pub fn setPort(self: *IpAddress, port: u16) void {
+ /// Asserts that the address is ip4 or ip6.
+ pub fn setPort(self: *Address, port: u16) void {
const ptr = switch (self.any.family) {
os.AF_INET => &self.in.port,
os.AF_INET6 => &self.in6.port,
@@ -237,16 +257,16 @@ pub const IpAddress = extern union {
/// Asserts that `addr` is an IP address.
/// This function will read past the end of the pointer, with a size depending
/// on the address family.
- pub fn initPosix(addr: *align(4) const os.sockaddr) IpAddress {
+ pub fn initPosix(addr: *align(4) const os.sockaddr) Address {
switch (addr.family) {
- os.AF_INET => return IpAddress{ .in = @ptrCast(*const os.sockaddr_in, addr).* },
- os.AF_INET6 => return IpAddress{ .in6 = @ptrCast(*const os.sockaddr_in6, addr).* },
+ os.AF_INET => return Address{ .in = @ptrCast(*const os.sockaddr_in, addr).* },
+ os.AF_INET6 => return Address{ .in6 = @ptrCast(*const os.sockaddr_in6, addr).* },
else => unreachable,
}
}
pub fn format(
- self: IpAddress,
+ self: Address,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
context: var,
@@ -271,7 +291,7 @@ pub const IpAddress = extern union {
},
os.AF_INET6 => {
const port = mem.bigToNative(u16, self.in6.port);
- if (mem.eql(u8, self.in6.addr[0..12], [_]u8{0,0,0,0,0,0,0,0,0,0,0xff,0xff})) {
+ if (mem.eql(u8, self.in6.addr[0..12], [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff })) {
try std.fmt.format(
context,
Errors,
@@ -314,20 +334,35 @@ pub const IpAddress = extern union {
}
try std.fmt.format(context, Errors, output, "]:{}", port);
},
+ os.AF_UNIX => {
+ if (!has_unix_sockets) {
+ unreachable;
+ }
+
+ try std.fmt.format(context, Errors, output, "{}", self.un.path);
+ },
else => unreachable,
}
}
- pub fn eql(a: IpAddress, b: IpAddress) bool {
+ pub fn eql(a: Address, b: Address) bool {
const a_bytes = @ptrCast([*]const u8, &a.any)[0..a.getOsSockLen()];
const b_bytes = @ptrCast([*]const u8, &b.any)[0..b.getOsSockLen()];
return mem.eql(u8, a_bytes, b_bytes);
}
- fn getOsSockLen(self: IpAddress) os.socklen_t {
+ fn getOsSockLen(self: Address) os.socklen_t {
switch (self.any.family) {
os.AF_INET => return @sizeOf(os.sockaddr_in),
os.AF_INET6 => return @sizeOf(os.sockaddr_in6),
+ os.AF_UNIX => {
+ if (!has_unix_sockets) {
+ unreachable;
+ }
+
+ const path_len = std.mem.len(u8, &self.un.path);
+ return @intCast(os.socklen_t, @sizeOf(os.sockaddr_un) - self.un.path.len + path_len);
+ },
else => unreachable,
}
}
@@ -342,23 +377,20 @@ pub fn connectUnixSocket(path: []const u8) !fs.File {
);
errdefer os.close(sockfd);
- var sock_addr = os.sockaddr_un{
- .family = os.AF_UNIX,
- .path = undefined,
- };
-
- if (path.len > sock_addr.path.len) return error.NameTooLong;
- mem.copy(u8, &sock_addr.path, path);
+ var addr = try std.net.Address.initUnix(path);
- const size = @intCast(u32, @sizeOf(os.sockaddr_un) - sock_addr.path.len + path.len);
- try os.connect(sockfd, &sock_addr, size);
+ try os.connect(
+ sockfd,
+ &addr.any,
+ addr.getOsSockLen(),
+ );
return fs.File.openHandle(sockfd);
}
pub const AddressList = struct {
arena: std.heap.ArenaAllocator,
- addrs: []IpAddress,
+ addrs: []Address,
canon_name: ?[]u8,
fn deinit(self: *AddressList) void {
@@ -381,7 +413,7 @@ pub fn tcpConnectToHost(allocator: *mem.Allocator, name: []const u8, port: u16)
return tcpConnectToAddress(addrs[0], port);
}
-pub fn tcpConnectToAddress(address: IpAddress) !fs.File {
+pub fn tcpConnectToAddress(address: Address) !fs.File {
const nonblock = if (std.io.is_async) os.SOCK_NONBLOCK else 0;
const sock_flags = os.SOCK_STREAM | os.SOCK_CLOEXEC | nonblock;
const sockfd = try os.socket(address.any.family, sock_flags, os.IPPROTO_TCP);
@@ -456,13 +488,13 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
}
break :blk count;
};
- result.addrs = try arena.alloc(IpAddress, addr_count);
+ result.addrs = try arena.alloc(Address, addr_count);
var it: ?*os.addrinfo = res;
var i: usize = 0;
while (it) |info| : (it = info.next) {
const addr = info.addr orelse continue;
- result.addrs[i] = IpAddress.initPosix(@alignCast(4, addr));
+ result.addrs[i] = Address.initPosix(@alignCast(4, addr));
if (info.canonname) |n| {
if (result.canon_name == null) {
@@ -485,7 +517,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
try linuxLookupName(&lookup_addrs, &canon, name, family, flags, port);
- result.addrs = try arena.alloc(IpAddress, lookup_addrs.len);
+ result.addrs = try arena.alloc(Address, lookup_addrs.len);
if (!canon.isNull()) {
result.canon_name = canon.toOwnedSlice();
}
@@ -501,7 +533,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
}
const LookupAddr = struct {
- addr: IpAddress,
+ addr: Address,
sortkey: i32 = 0,
};
@@ -524,7 +556,7 @@ fn linuxLookupName(
if (opt_name) |name| {
// reject empty name and check len so it fits into temp bufs
try canon.replaceContents(name);
- if (IpAddress.parseExpectingFamily(name, family, port)) |addr| {
+ if (Address.parseExpectingFamily(name, family, port)) |addr| {
try addrs.append(LookupAddr{ .addr = addr });
} else |name_err| if ((flags & std.c.AI_NUMERICHOST) != 0) {
return name_err;
@@ -611,7 +643,7 @@ fn linuxLookupName(
// TODO sa6.addr[12..16] should return *[4]u8, making this cast unnecessary.
mem.writeIntNative(u32, @ptrCast(*[4]u8, &sa6.addr[12]), sa4.addr);
}
- if (dscope == i32(scopeOf(sa6.addr))) key |= DAS_MATCHINGSCOPE;
+ if (dscope == @as(i32, scopeOf(sa6.addr))) key |= DAS_MATCHINGSCOPE;
if (dlabel == labelOf(sa6.addr)) key |= DAS_MATCHINGLABEL;
prefixlen = prefixMatch(sa6.addr, da6.addr);
} else |_| {}
@@ -710,7 +742,7 @@ fn prefixMatch(s: [16]u8, d: [16]u8) u8 {
// address. However the definition of the source prefix length is
// not clear and thus this limiting is not yet implemented.
var i: u8 = 0;
- while (i < 128 and ((s[i / 8] ^ d[i / 8]) & (u8(128) >> @intCast(u3, i % 8))) == 0) : (i += 1) {}
+ while (i < 128 and ((s[i / 8] ^ d[i / 8]) & (@as(u8, 128) >> @intCast(u3, i % 8))) == 0) : (i += 1) {}
return i;
}
@@ -751,23 +783,23 @@ fn linuxLookupNameFromNull(
if ((flags & std.c.AI_PASSIVE) != 0) {
if (family != os.AF_INET6) {
(try addrs.addOne()).* = LookupAddr{
- .addr = IpAddress.initIp4([1]u8{0} ** 4, port),
+ .addr = Address.initIp4([1]u8{0} ** 4, port),
};
}
if (family != os.AF_INET) {
(try addrs.addOne()).* = LookupAddr{
- .addr = IpAddress.initIp6([1]u8{0} ** 16, port, 0, 0),
+ .addr = Address.initIp6([1]u8{0} ** 16, port, 0, 0),
};
}
} else {
if (family != os.AF_INET6) {
(try addrs.addOne()).* = LookupAddr{
- .addr = IpAddress.initIp4([4]u8{ 127, 0, 0, 1 }, port),
+ .addr = Address.initIp4([4]u8{ 127, 0, 0, 1 }, port),
};
}
if (family != os.AF_INET) {
(try addrs.addOne()).* = LookupAddr{
- .addr = IpAddress.initIp6(([1]u8{0} ** 15) ++ [1]u8{1}, port, 0, 0),
+ .addr = Address.initIp6(([1]u8{0} ** 15) ++ [1]u8{1}, port, 0, 0),
};
}
}
@@ -812,7 +844,7 @@ fn linuxLookupNameFromHosts(
}
} else continue;
- const addr = IpAddress.parseExpectingFamily(ip_text, family, port) catch |err| switch (err) {
+ const addr = Address.parseExpectingFamily(ip_text, family, port) catch |err| switch (err) {
error.Overflow,
error.InvalidEnd,
error.InvalidCharacter,
@@ -1033,7 +1065,7 @@ fn linuxLookupNameFromNumericUnspec(
name: []const u8,
port: u16,
) !void {
- const addr = try IpAddress.parse(name, port);
+ const addr = try Address.parseIp(name, port);
(try addrs.addOne()).* = LookupAddr{ .addr = addr };
}
@@ -1049,7 +1081,7 @@ fn resMSendRc(
var sl: os.socklen_t = @sizeOf(os.sockaddr_in);
var family: os.sa_family_t = os.AF_INET;
- var ns_list = std.ArrayList(IpAddress).init(rc.ns.allocator);
+ var ns_list = std.ArrayList(Address).init(rc.ns.allocator);
defer ns_list.deinit();
try ns_list.resize(rc.ns.len);
@@ -1065,8 +1097,8 @@ fn resMSendRc(
}
// Get local address and open/bind a socket
- var sa: IpAddress = undefined;
- @memset(@ptrCast([*]u8, &sa), 0, @sizeOf(IpAddress));
+ var sa: Address = undefined;
+ @memset(@ptrCast([*]u8, &sa), 0, @sizeOf(Address));
sa.any.family = family;
const flags = os.SOCK_DGRAM | os.SOCK_CLOEXEC | os.SOCK_NONBLOCK;
const fd = os.socket(family, flags, 0) catch |err| switch (err) {
@@ -1133,7 +1165,7 @@ fn resMSendRc(
}
// Wait for a response, or until time to retry
- const clamped_timeout = std.math.min(u31(std.math.maxInt(u31)), t1 + retry_interval - t2);
+ const clamped_timeout = std.math.min(@as(u31, std.math.maxInt(u31)), t1 + retry_interval - t2);
const nevents = os.poll(&pfd, clamped_timeout) catch 0;
if (nevents == 0) continue;
@@ -1194,23 +1226,23 @@ fn dnsParse(
if (r.len < 12) return error.InvalidDnsPacket;
if ((r[3] & 15) != 0) return;
var p = r.ptr + 12;
- var qdcount = r[4] * usize(256) + r[5];
- var ancount = r[6] * usize(256) + r[7];
+ var qdcount = r[4] * @as(usize, 256) + r[5];
+ var ancount = r[6] * @as(usize, 256) + r[7];
if (qdcount + ancount > 64) return error.InvalidDnsPacket;
while (qdcount != 0) {
qdcount -= 1;
while (@ptrToInt(p) - @ptrToInt(r.ptr) < r.len and p[0] -% 1 < 127) p += 1;
if (p[0] > 193 or (p[0] == 193 and p[1] > 254) or @ptrToInt(p) > @ptrToInt(r.ptr) + r.len - 6)
return error.InvalidDnsPacket;
- p += usize(5) + @boolToInt(p[0] != 0);
+ p += @as(usize, 5) + @boolToInt(p[0] != 0);
}
while (ancount != 0) {
ancount -= 1;
while (@ptrToInt(p) - @ptrToInt(r.ptr) < r.len and p[0] -% 1 < 127) p += 1;
if (p[0] > 193 or (p[0] == 193 and p[1] > 254) or @ptrToInt(p) > @ptrToInt(r.ptr) + r.len - 6)
return error.InvalidDnsPacket;
- p += usize(1) + @boolToInt(p[0] != 0);
- const len = p[8] * usize(256) + p[9];
+ p += @as(usize, 1) + @boolToInt(p[0] != 0);
+ const len = p[8] * @as(usize, 256) + p[9];
if (@ptrToInt(p) + len > @ptrToInt(r.ptr) + r.len) return error.InvalidDnsPacket;
try callback(ctx, p[1], p[10 .. 10 + len], r);
p += 10 + len;
@@ -1224,7 +1256,7 @@ fn dnsParseCallback(ctx: dpc_ctx, rr: u8, data: []const u8, packet: []const u8)
const new_addr = try ctx.addrs.addOne();
new_addr.* = LookupAddr{
// TODO slice [0..4] to make this *[4]u8 without @ptrCast
- .addr = IpAddress.initIp4(@ptrCast(*const [4]u8, data.ptr).*, ctx.port),
+ .addr = Address.initIp4(@ptrCast(*const [4]u8, data.ptr).*, ctx.port),
};
},
os.RR_AAAA => {
@@ -1232,7 +1264,7 @@ fn dnsParseCallback(ctx: dpc_ctx, rr: u8, data: []const u8, packet: []const u8)
const new_addr = try ctx.addrs.addOne();
new_addr.* = LookupAddr{
// TODO slice [0..16] to make this *[16]u8 without @ptrCast
- .addr = IpAddress.initIp6(@ptrCast(*const [16]u8, data.ptr).*, ctx.port, 0, 0),
+ .addr = Address.initIp6(@ptrCast(*const [16]u8, data.ptr).*, ctx.port, 0, 0),
};
},
os.RR_CNAME => {
@@ -1248,12 +1280,12 @@ fn dnsParseCallback(ctx: dpc_ctx, rr: u8, data: []const u8, packet: []const u8)
}
}
-pub const TcpServer = struct {
+pub const StreamServer = struct {
/// Copied from `Options` on `init`.
kernel_backlog: u32,
/// `undefined` until `listen` returns successfully.
- listen_address: IpAddress,
+ listen_address: Address,
sockfd: ?os.fd_t,
@@ -1266,24 +1298,26 @@ pub const TcpServer = struct {
/// After this call succeeds, resources have been acquired and must
/// be released with `deinit`.
- pub fn init(options: Options) TcpServer {
- return TcpServer{
+ pub fn init(options: Options) StreamServer {
+ return StreamServer{
.sockfd = null,
.kernel_backlog = options.kernel_backlog,
.listen_address = undefined,
};
}
- /// Release all resources. The `TcpServer` memory becomes `undefined`.
- pub fn deinit(self: *TcpServer) void {
+ /// Release all resources. The `StreamServer` memory becomes `undefined`.
+ pub fn deinit(self: *StreamServer) void {
self.close();
self.* = undefined;
}
- pub fn listen(self: *TcpServer, address: IpAddress) !void {
+ pub fn listen(self: *StreamServer, address: Address) !void {
const nonblock = if (std.io.is_async) os.SOCK_NONBLOCK else 0;
const sock_flags = os.SOCK_STREAM | os.SOCK_CLOEXEC | nonblock;
- const sockfd = try os.socket(os.AF_INET, sock_flags, os.IPPROTO_TCP);
+ const proto = if (address.any.family == os.AF_UNIX) @as(u32, 0) else os.IPPROTO_TCP;
+
+ const sockfd = try os.socket(address.any.family, sock_flags, proto);
self.sockfd = sockfd;
errdefer {
os.close(sockfd);
@@ -1299,7 +1333,7 @@ pub const TcpServer = struct {
/// Stop listening. It is still necessary to call `deinit` after stopping listening.
/// Calling `deinit` will automatically call `close`. It is safe to call `close` when
/// not listening.
- pub fn close(self: *TcpServer) void {
+ pub fn close(self: *StreamServer) void {
if (self.sockfd) |fd| {
os.close(fd);
self.sockfd = null;
@@ -1326,14 +1360,22 @@ pub const TcpServer = struct {
BlockedByFirewall,
} || os.UnexpectedError;
- /// If this function succeeds, the returned `fs.File` is a caller-managed resource.
- pub fn accept(self: *TcpServer) AcceptError!fs.File {
+ pub const Connection = struct {
+ file: fs.File,
+ address: Address
+ };
+
+ /// If this function succeeds, the returned `Connection` is a caller-managed resource.
+ pub fn accept(self: *StreamServer) AcceptError!Connection {
const nonblock = if (std.io.is_async) os.SOCK_NONBLOCK else 0;
const accept_flags = nonblock | os.SOCK_CLOEXEC;
- var accepted_addr: IpAddress = undefined;
- var adr_len: os.socklen_t = @sizeOf(IpAddress);
+ var accepted_addr: Address = undefined;
+ var adr_len: os.socklen_t = @sizeOf(Address);
if (os.accept4(self.sockfd.?, &accepted_addr.any, &adr_len, accept_flags)) |fd| {
- return fs.File.openHandle(fd);
+ return Connection{
+ .file = fs.File.openHandle(fd),
+ .address = accepted_addr,
+ };
} else |err| switch (err) {
// We only give SOCK_NONBLOCK when I/O mode is async, in which case this error
// is handled by os.accept4.
diff --git a/lib/std/net/test.zig b/lib/std/net/test.zig
index 90986049da..6400b022c6 100644
--- a/lib/std/net/test.zig
+++ b/lib/std/net/test.zig
@@ -28,17 +28,17 @@ test "parse and render IPv6 addresses" {
"::ffff:123.5.123.5",
};
for (ips) |ip, i| {
- var addr = net.IpAddress.parseIp6(ip, 0) catch unreachable;
+ var addr = net.Address.parseIp6(ip, 0) catch unreachable;
var newIp = std.fmt.bufPrint(buffer[0..], "{}", addr) catch unreachable;
std.testing.expect(std.mem.eql(u8, printed[i], newIp[1 .. newIp.len - 3]));
}
- testing.expectError(error.InvalidCharacter, net.IpAddress.parseIp6(":::", 0));
- testing.expectError(error.Overflow, net.IpAddress.parseIp6("FF001::FB", 0));
- testing.expectError(error.InvalidCharacter, net.IpAddress.parseIp6("FF01::Fb:zig", 0));
- testing.expectError(error.InvalidEnd, net.IpAddress.parseIp6("FF01:0:0:0:0:0:0:FB:", 0));
- testing.expectError(error.Incomplete, net.IpAddress.parseIp6("FF01:", 0));
- testing.expectError(error.InvalidIpv4Mapping, net.IpAddress.parseIp6("::123.123.123.123", 0));
+ testing.expectError(error.InvalidCharacter, net.Address.parseIp6(":::", 0));
+ testing.expectError(error.Overflow, net.Address.parseIp6("FF001::FB", 0));
+ testing.expectError(error.InvalidCharacter, net.Address.parseIp6("FF01::Fb:zig", 0));
+ testing.expectError(error.InvalidEnd, net.Address.parseIp6("FF01:0:0:0:0:0:0:FB:", 0));
+ testing.expectError(error.Incomplete, net.Address.parseIp6("FF01:", 0));
+ testing.expectError(error.InvalidIpv4Mapping, net.Address.parseIp6("::123.123.123.123", 0));
}
test "parse and render IPv4 addresses" {
@@ -50,16 +50,16 @@ test "parse and render IPv4 addresses" {
"123.255.0.91",
"127.0.0.1",
}) |ip| {
- var addr = net.IpAddress.parseIp4(ip, 0) catch unreachable;
+ var addr = net.Address.parseIp4(ip, 0) catch unreachable;
var newIp = std.fmt.bufPrint(buffer[0..], "{}", addr) catch unreachable;
std.testing.expect(std.mem.eql(u8, ip, newIp[0 .. newIp.len - 2]));
}
- testing.expectError(error.Overflow, net.IpAddress.parseIp4("256.0.0.1", 0));
- testing.expectError(error.InvalidCharacter, net.IpAddress.parseIp4("x.0.0.1", 0));
- testing.expectError(error.InvalidEnd, net.IpAddress.parseIp4("127.0.0.1.1", 0));
- testing.expectError(error.Incomplete, net.IpAddress.parseIp4("127.0.0.", 0));
- testing.expectError(error.InvalidCharacter, net.IpAddress.parseIp4("100..0.1", 0));
+ testing.expectError(error.Overflow, net.Address.parseIp4("256.0.0.1", 0));
+ testing.expectError(error.InvalidCharacter, net.Address.parseIp4("x.0.0.1", 0));
+ testing.expectError(error.InvalidEnd, net.Address.parseIp4("127.0.0.1.1", 0));
+ testing.expectError(error.Incomplete, net.Address.parseIp4("127.0.0.", 0));
+ testing.expectError(error.InvalidCharacter, net.Address.parseIp4("100..0.1", 0));
}
test "resolve DNS" {
@@ -91,9 +91,9 @@ test "listen on a port, send bytes, receive bytes" {
}
// TODO doing this at comptime crashed the compiler
- const localhost = net.IpAddress.parse("127.0.0.1", 0);
+ const localhost = net.Address.parseIp("127.0.0.1", 0);
- var server = net.TcpServer.init(net.TcpServer.Options{});
+ var server = net.StreamServer.init(net.StreamServer.Options{});
defer server.deinit();
try server.listen(localhost);
@@ -104,7 +104,7 @@ test "listen on a port, send bytes, receive bytes" {
try await client_frame;
}
-fn testClient(addr: net.IpAddress) anyerror!void {
+fn testClient(addr: net.Address) anyerror!void {
const socket_file = try net.tcpConnectToAddress(addr);
defer socket_file.close();
@@ -114,9 +114,9 @@ fn testClient(addr: net.IpAddress) anyerror!void {
testing.expect(mem.eql(u8, msg, "hello from server\n"));
}
-fn testServer(server: *net.TcpServer) anyerror!void {
- var client_file = try server.accept();
+fn testServer(server: *net.StreamServer) anyerror!void {
+ var client = try server.accept();
- const stream = &client_file.outStream().stream;
+ const stream = &client.file.outStream().stream;
try stream.print("hello from server\n");
}
diff --git a/lib/std/os.zig b/lib/std/os.zig
index f45b03130c..68a3a6e9f6 100644
--- a/lib/std/os.zig
+++ b/lib/std/os.zig
@@ -472,7 +472,7 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!void {
var index: usize = 0;
while (index < bytes.len) {
- const amt_to_write = math.min(bytes.len - index, usize(max_bytes_len));
+ const amt_to_write = math.min(bytes.len - index, @as(usize, max_bytes_len));
const rc = system.write(fd, bytes.ptr + index, amt_to_write);
switch (errno(rc)) {
0 => {
@@ -1126,9 +1126,9 @@ pub fn unlinkatW(dirfd: fd_t, sub_path_w: [*]const u16, flags: u32) UnlinkatErro
const want_rmdir_behavior = (flags & AT_REMOVEDIR) != 0;
const create_options_flags = if (want_rmdir_behavior)
- w.ULONG(w.FILE_DELETE_ON_CLOSE)
+ @as(w.ULONG, w.FILE_DELETE_ON_CLOSE)
else
- w.ULONG(w.FILE_DELETE_ON_CLOSE | w.FILE_NON_DIRECTORY_FILE);
+ @as(w.ULONG, w.FILE_DELETE_ON_CLOSE | w.FILE_NON_DIRECTORY_FILE);
const path_len_bytes = @intCast(u16, mem.toSliceConst(u16, sub_path_w).len * 2);
var nt_name = w.UNICODE_STRING{
@@ -1526,7 +1526,7 @@ pub fn isatty(handle: fd_t) bool {
}
if (builtin.os == .linux) {
var wsz: linux.winsize = undefined;
- return linux.syscall3(linux.SYS_ioctl, @bitCast(usize, isize(handle)), linux.TIOCGWINSZ, @ptrToInt(&wsz)) == 0;
+ return linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, handle)), linux.TIOCGWINSZ, @ptrToInt(&wsz)) == 0;
}
unreachable;
}
@@ -1547,7 +1547,7 @@ pub fn isCygwinPty(handle: fd_t) bool {
}
const name_info = @ptrCast(*const windows.FILE_NAME_INFO, &name_info_bytes[0]);
- const name_bytes = name_info_bytes[size .. size + usize(name_info.FileNameLength)];
+ const name_bytes = name_info_bytes[size .. size + @as(usize, name_info.FileNameLength)];
const name_wide = @bytesToSlice(u16, name_bytes);
return mem.indexOf(u16, name_wide, [_]u16{ 'm', 's', 'y', 's', '-' }) != null or
mem.indexOf(u16, name_wide, [_]u16{ '-', 'p', 't', 'y' }) != null;
@@ -2897,7 +2897,7 @@ pub fn res_mkquery(
// Construct query template - ID will be filled later
var q: [280]u8 = undefined;
@memset(&q, 0, n);
- q[2] = u8(op) * 8 + 1;
+ q[2] = @as(u8, op) * 8 + 1;
q[5] = 1;
mem.copy(u8, q[13..], name);
var i: usize = 13;
@@ -3143,7 +3143,7 @@ pub fn dn_expand(
// loop invariants: p<end, dest<dend
if ((p[0] & 0xc0) != 0) {
if (p + 1 == end) return error.InvalidDnsPacket;
- var j = ((p[0] & usize(0x3f)) << 8) | p[1];
+ var j = ((p[0] & @as(usize, 0x3f)) << 8) | p[1];
if (len == std.math.maxInt(usize)) len = @ptrToInt(p) + 2 - @ptrToInt(comp_dn.ptr);
if (j >= msg.len) return error.InvalidDnsPacket;
p = msg.ptr + j;
@@ -3171,3 +3171,22 @@ pub fn dn_expand(
}
return error.InvalidDnsPacket;
}
+
+pub const SchedYieldError = error{
+ /// The system is not configured to allow yielding
+ SystemCannotYield,
+};
+
+pub fn sched_yield() SchedYieldError!void {
+ if (builtin.os == .windows) {
+ // The return value has to do with how many other threads there are; it is not
+ // an error condition on Windows.
+ _ = windows.kernel32.SwitchToThread();
+ return;
+ }
+ switch (errno(system.sched_yield())) {
+ 0 => return,
+ ENOSYS => return error.SystemCannotYield,
+ else => return error.SystemCannotYield,
+ }
+}
diff --git a/lib/std/os/bits.zig b/lib/std/os/bits.zig
index 6d6163b8fa..7dd968e473 100644
--- a/lib/std/os/bits.zig
+++ b/lib/std/os/bits.zig
@@ -14,9 +14,6 @@ pub usingnamespace switch (builtin.os) {
else => struct {},
};
-pub const pthread_t = *@OpaqueType();
-pub const FILE = @OpaqueType();
-
pub const iovec = extern struct {
iov_base: [*]u8,
iov_len: usize,
diff --git a/lib/std/os/bits/darwin.zig b/lib/std/os/bits/darwin.zig
index ca7f663661..9451df6e19 100644
--- a/lib/std/os/bits/darwin.zig
+++ b/lib/std/os/bits/darwin.zig
@@ -133,11 +133,6 @@ pub const dirent = extern struct {
}
};
-pub const pthread_attr_t = extern struct {
- __sig: c_long,
- __opaque: [56]u8,
-};
-
/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
pub const Kevent = extern struct {
ident: usize,
@@ -272,7 +267,6 @@ pub const SA_USERTRAMP = 0x0100;
/// signal handler with SA_SIGINFO args with 64bit regs information
pub const SA_64REGSET = 0x0200;
-pub const O_LARGEFILE = 0x0000;
pub const O_PATH = 0x0000;
pub const F_OK = 0;
diff --git a/lib/std/os/bits/dragonfly.zig b/lib/std/os/bits/dragonfly.zig
index d1b65707f4..a7f8f75719 100644
--- a/lib/std/os/bits/dragonfly.zig
+++ b/lib/std/os/bits/dragonfly.zig
@@ -241,7 +241,6 @@ pub const KERN_MAXID = 37;
pub const HOST_NAME_MAX = 255;
-pub const O_LARGEFILE = 0; // faked support
pub const O_RDONLY = 0;
pub const O_NDELAY = O_NONBLOCK;
pub const O_WRONLY = 1;
@@ -315,7 +314,7 @@ pub const dirent = extern struct {
d_name: [256]u8,
pub fn reclen(self: dirent) u16 {
- return (@byteOffsetOf(dirent, "d_name") + self.d_namlen + 1 + 7) & ~u16(7);
+ return (@byteOffsetOf(dirent, "d_name") + self.d_namlen + 1 + 7) & ~@as(u16, 7);
}
};
@@ -360,11 +359,6 @@ pub const Kevent = extern struct {
udata: usize,
};
-pub const pthread_attr_t = extern struct { // copied from freebsd
- __size: [56]u8,
- __align: c_long,
-};
-
pub const EVFILT_FS = -10;
pub const EVFILT_USER = -9;
pub const EVFILT_EXCEPT = -8;
@@ -515,13 +509,13 @@ pub const sigset_t = extern struct {
pub const sig_atomic_t = c_int;
pub const Sigaction = extern struct {
__sigaction_u: extern union {
- __sa_handler: ?extern fn(c_int) void,
- __sa_sigaction: ?extern fn(c_int, [*c]siginfo_t, ?*c_void) void,
+ __sa_handler: ?extern fn (c_int) void,
+ __sa_sigaction: ?extern fn (c_int, [*c]siginfo_t, ?*c_void) void,
},
sa_flags: c_int,
sa_mask: sigset_t,
};
-pub const sig_t = [*c]extern fn(c_int) void;
+pub const sig_t = [*c]extern fn (c_int) void;
pub const sigvec = extern struct {
sv_handler: [*c]__sighandler_t,
diff --git a/lib/std/os/bits/freebsd.zig b/lib/std/os/bits/freebsd.zig
index b0506ad0e1..39be83a4b1 100644
--- a/lib/std/os/bits/freebsd.zig
+++ b/lib/std/os/bits/freebsd.zig
@@ -15,11 +15,6 @@ pub const Kevent = extern struct {
// TODO ext
};
-pub const pthread_attr_t = extern struct {
- __size: [56]u8,
- __align: c_long,
-};
-
pub const dl_phdr_info = extern struct {
dlpi_addr: usize,
dlpi_name: ?[*]const u8,
@@ -305,7 +300,6 @@ pub const O_CLOEXEC = 0x00100000;
pub const O_ASYNC = 0x0040;
pub const O_DIRECT = 0x00010000;
-pub const O_LARGEFILE = 0;
pub const O_NOATIME = 0o1000000;
pub const O_PATH = 0o10000000;
pub const O_TMPFILE = 0o20200000;
diff --git a/lib/std/os/bits/linux.zig b/lib/std/os/bits/linux.zig
index 0cf30920e4..e101337c3a 100644
--- a/lib/std/os/bits/linux.zig
+++ b/lib/std/os/bits/linux.zig
@@ -559,10 +559,10 @@ pub const EPOLLMSG = 0x400;
pub const EPOLLERR = 0x008;
pub const EPOLLHUP = 0x010;
pub const EPOLLRDHUP = 0x2000;
-pub const EPOLLEXCLUSIVE = (u32(1) << 28);
-pub const EPOLLWAKEUP = (u32(1) << 29);
-pub const EPOLLONESHOT = (u32(1) << 30);
-pub const EPOLLET = (u32(1) << 31);
+pub const EPOLLEXCLUSIVE = (@as(u32, 1) << 28);
+pub const EPOLLWAKEUP = (@as(u32, 1) << 29);
+pub const EPOLLONESHOT = (@as(u32, 1) << 30);
+pub const EPOLLET = (@as(u32, 1) << 31);
pub const CLOCK_REALTIME = 0;
pub const CLOCK_MONOTONIC = 1;
@@ -950,7 +950,7 @@ pub fn cap_valid(u8: x) bool {
}
pub fn CAP_TO_MASK(cap: u8) u32 {
- return u32(1) << u5(cap & 31);
+ return @as(u32, 1) << u5(cap & 31);
}
pub fn CAP_TO_INDEX(cap: u8) u8 {
@@ -1000,11 +1000,6 @@ pub const dl_phdr_info = extern struct {
dlpi_phnum: u16,
};
-pub const pthread_attr_t = extern struct {
- __size: [56]u8,
- __align: c_long,
-};
-
pub const CPU_SETSIZE = 128;
pub const cpu_set_t = [CPU_SETSIZE / @sizeOf(usize)]usize;
pub const cpu_count_t = @IntType(false, std.math.log2(CPU_SETSIZE * 8));
diff --git a/lib/std/os/bits/netbsd.zig b/lib/std/os/bits/netbsd.zig
index f93bbbf106..de1d72eca2 100644
--- a/lib/std/os/bits/netbsd.zig
+++ b/lib/std/os/bits/netbsd.zig
@@ -14,12 +14,6 @@ pub const Kevent = extern struct {
udata: usize,
};
-pub const pthread_attr_t = extern struct {
- pta_magic: u32,
- pta_flags: c_int,
- pta_private: *c_void,
-};
-
pub const dl_phdr_info = extern struct {
dlpi_addr: usize,
dlpi_name: ?[*]const u8,
@@ -298,7 +292,6 @@ pub const O_CLOEXEC = 0x00400000;
pub const O_ASYNC = 0x0040;
pub const O_DIRECT = 0x00080000;
-pub const O_LARGEFILE = 0;
pub const O_NOATIME = 0;
pub const O_PATH = 0;
pub const O_TMPFILE = 0;
diff --git a/lib/std/os/bits/windows.zig b/lib/std/os/bits/windows.zig
index 178811bb1e..a1ceb8ff5c 100644
--- a/lib/std/os/bits/windows.zig
+++ b/lib/std/os/bits/windows.zig
@@ -186,6 +186,11 @@ pub const sockaddr_in6 = extern struct {
pub const in6_addr = [16]u8;
pub const in_addr = u32;
+pub const sockaddr_un = extern struct {
+ family: sa_family_t = AF_UNIX,
+ path: [108]u8,
+};
+
pub const AF_UNSPEC = 0;
pub const AF_UNIX = 1;
pub const AF_INET = 2;
@@ -221,3 +226,17 @@ pub const AF_TCNMESSAGE = 30;
pub const AF_ICLFXBM = 31;
pub const AF_BTH = 32;
pub const AF_MAX = 33;
+
+pub const SOCK_STREAM = 1;
+pub const SOCK_DGRAM = 2;
+pub const SOCK_RAW = 3;
+pub const SOCK_RDM = 4;
+pub const SOCK_SEQPACKET = 5;
+
+pub const IPPROTO_ICMP = 1;
+pub const IPPROTO_IGMP = 2;
+pub const BTHPROTO_RFCOMM = 3;
+pub const IPPROTO_TCP = 6;
+pub const IPPROTO_UDP = 17;
+pub const IPPROTO_ICMPV6 = 58;
+pub const IPPROTO_RM = 113;
diff --git a/lib/std/os/linux.zig b/lib/std/os/linux.zig
index d9f1f4e311..7e2f14021f 100644
--- a/lib/std/os/linux.zig
+++ b/lib/std/os/linux.zig
@@ -46,22 +46,22 @@ pub fn getErrno(r: usize) u12 {
pub fn dup2(old: i32, new: i32) usize {
if (@hasDecl(@This(), "SYS_dup2")) {
- return syscall2(SYS_dup2, @bitCast(usize, isize(old)), @bitCast(usize, isize(new)));
+ return syscall2(SYS_dup2, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)));
} else {
if (old == new) {
if (std.debug.runtime_safety) {
- const rc = syscall2(SYS_fcntl, @bitCast(usize, isize(old)), F_GETFD);
+ const rc = syscall2(SYS_fcntl, @bitCast(usize, @as(isize, old)), F_GETFD);
if (@bitCast(isize, rc) < 0) return rc;
}
return @intCast(usize, old);
} else {
- return syscall3(SYS_dup3, @bitCast(usize, isize(old)), @bitCast(usize, isize(new)), 0);
+ return syscall3(SYS_dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), 0);
}
}
}
pub fn dup3(old: i32, new: i32, flags: u32) usize {
- return syscall3(SYS_dup3, @bitCast(usize, isize(old)), @bitCast(usize, isize(new)), flags);
+ return syscall3(SYS_dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), flags);
}
// TODO https://github.com/ziglang/zig/issues/265
@@ -102,7 +102,7 @@ pub fn futimens(fd: i32, times: *const [2]timespec) usize {
// TODO https://github.com/ziglang/zig/issues/265
pub fn utimensat(dirfd: i32, path: ?[*]const u8, times: *const [2]timespec, flags: u32) usize {
- return syscall4(SYS_utimensat, @bitCast(usize, isize(dirfd)), @ptrToInt(path), @ptrToInt(times), flags);
+ return syscall4(SYS_utimensat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(times), flags);
}
pub fn futex_wait(uaddr: *const i32, futex_op: u32, val: i32, timeout: ?*timespec) usize {
@@ -120,7 +120,7 @@ pub fn getcwd(buf: [*]u8, size: usize) usize {
pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize {
return syscall3(
SYS_getdents,
- @bitCast(usize, isize(fd)),
+ @bitCast(usize, @as(isize, fd)),
@ptrToInt(dirp),
std.math.min(len, maxInt(c_int)),
);
@@ -129,7 +129,7 @@ pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize {
pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize {
return syscall3(
SYS_getdents64,
- @bitCast(usize, isize(fd)),
+ @bitCast(usize, @as(isize, fd)),
@ptrToInt(dirp),
std.math.min(len, maxInt(c_int)),
);
@@ -140,11 +140,11 @@ pub fn inotify_init1(flags: u32) usize {
}
pub fn inotify_add_watch(fd: i32, pathname: [*]const u8, mask: u32) usize {
- return syscall3(SYS_inotify_add_watch, @bitCast(usize, isize(fd)), @ptrToInt(pathname), mask);
+ return syscall3(SYS_inotify_add_watch, @bitCast(usize, @as(isize, fd)), @ptrToInt(pathname), mask);
}
pub fn inotify_rm_watch(fd: i32, wd: i32) usize {
- return syscall2(SYS_inotify_rm_watch, @bitCast(usize, isize(fd)), @bitCast(usize, isize(wd)));
+ return syscall2(SYS_inotify_rm_watch, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, wd)));
}
// TODO https://github.com/ziglang/zig/issues/265
@@ -152,13 +152,13 @@ pub fn readlink(noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usiz
if (@hasDecl(@This(), "SYS_readlink")) {
return syscall3(SYS_readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
} else {
- return syscall4(SYS_readlinkat, @bitCast(usize, isize(AT_FDCWD)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
+ return syscall4(SYS_readlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn readlinkat(dirfd: i32, noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {
- return syscall4(SYS_readlinkat, @bitCast(usize, isize(dirfd)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
+ return syscall4(SYS_readlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
}
// TODO https://github.com/ziglang/zig/issues/265
@@ -166,13 +166,13 @@ pub fn mkdir(path: [*]const u8, mode: u32) usize {
if (@hasDecl(@This(), "SYS_mkdir")) {
return syscall2(SYS_mkdir, @ptrToInt(path), mode);
} else {
- return syscall3(SYS_mkdirat, @bitCast(usize, isize(AT_FDCWD)), @ptrToInt(path), mode);
+ return syscall3(SYS_mkdirat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn mkdirat(dirfd: i32, path: [*]const u8, mode: u32) usize {
- return syscall3(SYS_mkdirat, @bitCast(usize, isize(dirfd)), @ptrToInt(path), mode);
+ return syscall3(SYS_mkdirat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode);
}
// TODO https://github.com/ziglang/zig/issues/265
@@ -194,7 +194,7 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of
if (@hasDecl(@This(), "SYS_mmap2")) {
// Make sure the offset is also specified in multiples of page size
if ((offset & (MMAP2_UNIT - 1)) != 0)
- return @bitCast(usize, isize(-EINVAL));
+ return @bitCast(usize, @as(isize, -EINVAL));
return syscall6(
SYS_mmap2,
@@ -202,7 +202,7 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of
length,
prot,
flags,
- @bitCast(usize, isize(fd)),
+ @bitCast(usize, @as(isize, fd)),
@truncate(usize, offset / MMAP2_UNIT),
);
} else {
@@ -212,7 +212,7 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of
length,
prot,
flags,
- @bitCast(usize, isize(fd)),
+ @bitCast(usize, @as(isize, fd)),
offset,
);
}
@@ -249,13 +249,13 @@ pub fn poll(fds: [*]pollfd, n: nfds_t, timeout: i32) usize {
}
pub fn read(fd: i32, buf: [*]u8, count: usize) usize {
- return syscall3(SYS_read, @bitCast(usize, isize(fd)), @ptrToInt(buf), count);
+ return syscall3(SYS_read, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);
}
pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: u64) usize {
return syscall5(
SYS_preadv,
- @bitCast(usize, isize(fd)),
+ @bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
@truncate(usize, offset),
@@ -266,7 +266,7 @@ pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: u64) usize {
pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: u64, flags: kernel_rwf) usize {
return syscall6(
SYS_preadv2,
- @bitCast(usize, isize(fd)),
+ @bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
@truncate(usize, offset),
@@ -276,17 +276,17 @@ pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: u64, flags: k
}
pub fn readv(fd: i32, iov: [*]const iovec, count: usize) usize {
- return syscall3(SYS_readv, @bitCast(usize, isize(fd)), @ptrToInt(iov), count);
+ return syscall3(SYS_readv, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count);
}
pub fn writev(fd: i32, iov: [*]const iovec_const, count: usize) usize {
- return syscall3(SYS_writev, @bitCast(usize, isize(fd)), @ptrToInt(iov), count);
+ return syscall3(SYS_writev, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count);
}
pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64) usize {
return syscall5(
SYS_pwritev,
- @bitCast(usize, isize(fd)),
+ @bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
@truncate(usize, offset),
@@ -297,7 +297,7 @@ pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64) us
pub fn pwritev2(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64, flags: kernel_rwf) usize {
return syscall6(
SYS_pwritev2,
- @bitCast(usize, isize(fd)),
+ @bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
@truncate(usize, offset),
@@ -311,7 +311,7 @@ pub fn rmdir(path: [*]const u8) usize {
if (@hasDecl(@This(), "SYS_rmdir")) {
return syscall1(SYS_rmdir, @ptrToInt(path));
} else {
- return syscall3(SYS_unlinkat, @bitCast(usize, isize(AT_FDCWD)), @ptrToInt(path), AT_REMOVEDIR);
+ return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), AT_REMOVEDIR);
}
}
@@ -320,18 +320,18 @@ pub fn symlink(existing: [*]const u8, new: [*]const u8) usize {
if (@hasDecl(@This(), "SYS_symlink")) {
return syscall2(SYS_symlink, @ptrToInt(existing), @ptrToInt(new));
} else {
- return syscall3(SYS_symlinkat, @ptrToInt(existing), @bitCast(usize, isize(AT_FDCWD)), @ptrToInt(new));
+ return syscall3(SYS_symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new));
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn symlinkat(existing: [*]const u8, newfd: i32, newpath: [*]const u8) usize {
- return syscall3(SYS_symlinkat, @ptrToInt(existing), @bitCast(usize, isize(newfd)), @ptrToInt(newpath));
+ return syscall3(SYS_symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath));
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: usize) usize {
- return syscall4(SYS_pread, @bitCast(usize, isize(fd)), @ptrToInt(buf), count, offset);
+ return syscall4(SYS_pread, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, offset);
}
// TODO https://github.com/ziglang/zig/issues/265
@@ -339,13 +339,13 @@ pub fn access(path: [*]const u8, mode: u32) usize {
if (@hasDecl(@This(), "SYS_access")) {
return syscall2(SYS_access, @ptrToInt(path), mode);
} else {
- return syscall4(SYS_faccessat, @bitCast(usize, isize(AT_FDCWD)), @ptrToInt(path), mode, 0);
+ return syscall4(SYS_faccessat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode, 0);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn faccessat(dirfd: i32, path: [*]const u8, mode: u32, flags: u32) usize {
- return syscall4(SYS_faccessat, @bitCast(usize, isize(dirfd)), @ptrToInt(path), mode, flags);
+ return syscall4(SYS_faccessat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode, flags);
}
pub fn pipe(fd: *[2]i32) usize {
@@ -363,11 +363,11 @@ pub fn pipe2(fd: *[2]i32, flags: u32) usize {
}
pub fn write(fd: i32, buf: [*]const u8, count: usize) usize {
- return syscall3(SYS_write, @bitCast(usize, isize(fd)), @ptrToInt(buf), count);
+ return syscall3(SYS_write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);
}
pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {
- return syscall4(SYS_pwrite, @bitCast(usize, isize(fd)), @ptrToInt(buf), count, offset);
+ return syscall4(SYS_pwrite, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, offset);
}
// TODO https://github.com/ziglang/zig/issues/265
@@ -375,9 +375,9 @@ pub fn rename(old: [*]const u8, new: [*]const u8) usize {
if (@hasDecl(@This(), "SYS_rename")) {
return syscall2(SYS_rename, @ptrToInt(old), @ptrToInt(new));
} else if (@hasDecl(@This(), "SYS_renameat")) {
- return syscall4(SYS_renameat, @bitCast(usize, isize(AT_FDCWD)), @ptrToInt(old), @bitCast(usize, isize(AT_FDCWD)), @ptrToInt(new));
+ return syscall4(SYS_renameat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new));
} else {
- return syscall5(SYS_renameat2, @bitCast(usize, isize(AT_FDCWD)), @ptrToInt(old), @bitCast(usize, isize(AT_FDCWD)), @ptrToInt(new), 0);
+ return syscall5(SYS_renameat2, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new), 0);
}
}
@@ -385,17 +385,17 @@ pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const
if (@hasDecl(@This(), "SYS_renameat")) {
return syscall4(
SYS_renameat,
- @bitCast(usize, isize(oldfd)),
+ @bitCast(usize, @as(isize, oldfd)),
@ptrToInt(old),
- @bitCast(usize, isize(newfd)),
+ @bitCast(usize, @as(isize, newfd)),
@ptrToInt(new),
);
} else {
return syscall5(
SYS_renameat2,
- @bitCast(usize, isize(oldfd)),
+ @bitCast(usize, @as(isize, oldfd)),
@ptrToInt(old),
- @bitCast(usize, isize(newfd)),
+ @bitCast(usize, @as(isize, newfd)),
@ptrToInt(new),
0,
);
@@ -406,9 +406,9 @@ pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const
pub fn renameat2(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const u8, flags: u32) usize {
return syscall5(
SYS_renameat2,
- @bitCast(usize, isize(oldfd)),
+ @bitCast(usize, @as(isize, oldfd)),
@ptrToInt(oldpath),
- @bitCast(usize, isize(newfd)),
+ @bitCast(usize, @as(isize, newfd)),
@ptrToInt(newpath),
flags,
);
@@ -421,7 +421,7 @@ pub fn open(path: [*]const u8, flags: u32, perm: usize) usize {
} else {
return syscall4(
SYS_openat,
- @bitCast(usize, isize(AT_FDCWD)),
+ @bitCast(usize, @as(isize, AT_FDCWD)),
@ptrToInt(path),
flags,
perm,
@@ -437,7 +437,7 @@ pub fn create(path: [*]const u8, perm: usize) usize {
// TODO https://github.com/ziglang/zig/issues/265
pub fn openat(dirfd: i32, path: [*]const u8, flags: u32, mode: usize) usize {
// dirfd could be negative, for example AT_FDCWD is -100
- return syscall4(SYS_openat, @bitCast(usize, isize(dirfd)), @ptrToInt(path), flags, mode);
+ return syscall4(SYS_openat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags, mode);
}
/// See also `clone` (from the arch-specific include)
@@ -451,14 +451,14 @@ pub fn clone2(flags: u32, child_stack_ptr: usize) usize {
}
pub fn close(fd: i32) usize {
- return syscall1(SYS_close, @bitCast(usize, isize(fd)));
+ return syscall1(SYS_close, @bitCast(usize, @as(isize, fd)));
}
/// Can only be called on 32 bit systems. For 64 bit see `lseek`.
pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize {
return syscall5(
SYS__llseek,
- @bitCast(usize, isize(fd)),
+ @bitCast(usize, @as(isize, fd)),
@truncate(usize, offset >> 32),
@truncate(usize, offset),
@ptrToInt(result),
@@ -468,16 +468,16 @@ pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize {
/// Can only be called on 64 bit systems. For 32 bit see `llseek`.
pub fn lseek(fd: i32, offset: i64, whence: usize) usize {
- return syscall3(SYS_lseek, @bitCast(usize, isize(fd)), @bitCast(usize, offset), whence);
+ return syscall3(SYS_lseek, @bitCast(usize, @as(isize, fd)), @bitCast(usize, offset), whence);
}
pub fn exit(status: i32) noreturn {
- _ = syscall1(SYS_exit, @bitCast(usize, isize(status)));
+ _ = syscall1(SYS_exit, @bitCast(usize, @as(isize, status)));
unreachable;
}
pub fn exit_group(status: i32) noreturn {
- _ = syscall1(SYS_exit_group, @bitCast(usize, isize(status)));
+ _ = syscall1(SYS_exit_group, @bitCast(usize, @as(isize, status)));
unreachable;
}
@@ -486,7 +486,7 @@ pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize {
}
pub fn kill(pid: i32, sig: i32) usize {
- return syscall2(SYS_kill, @bitCast(usize, isize(pid)), @bitCast(usize, isize(sig)));
+ return syscall2(SYS_kill, @bitCast(usize, @as(isize, pid)), @bitCast(usize, @as(isize, sig)));
}
// TODO https://github.com/ziglang/zig/issues/265
@@ -494,17 +494,17 @@ pub fn unlink(path: [*]const u8) usize {
if (@hasDecl(@This(), "SYS_unlink")) {
return syscall1(SYS_unlink, @ptrToInt(path));
} else {
- return syscall3(SYS_unlinkat, @bitCast(usize, isize(AT_FDCWD)), @ptrToInt(path), 0);
+ return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), 0);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn unlinkat(dirfd: i32, path: [*]const u8, flags: u32) usize {
- return syscall3(SYS_unlinkat, @bitCast(usize, isize(dirfd)), @ptrToInt(path), flags);
+ return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags);
}
pub fn waitpid(pid: i32, status: *u32, flags: u32) usize {
- return syscall4(SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), flags, 0);
+ return syscall4(SYS_wait4, @bitCast(usize, @as(isize, pid)), @ptrToInt(status), flags, 0);
}
var vdso_clock_gettime = @ptrCast(?*const c_void, init_vdso_clock_gettime);
@@ -519,33 +519,33 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) usize {
const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);
const rc = f(clk_id, tp);
switch (rc) {
- 0, @bitCast(usize, isize(-EINVAL)) => return rc,
+ 0, @bitCast(usize, @as(isize, -EINVAL)) => return rc,
else => {},
}
}
}
- return syscall2(SYS_clock_gettime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
+ return syscall2(SYS_clock_gettime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
}
extern fn init_vdso_clock_gettime(clk: i32, ts: *timespec) usize {
const ptr = @intToPtr(?*const c_void, vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM));
// Note that we may not have a VDSO at all, update the stub address anyway
// so that clock_gettime will fall back on the good old (and slow) syscall
- _ = @cmpxchgStrong(?*const c_void, &vdso_clock_gettime, &init_vdso_clock_gettime, ptr, .Monotonic, .Monotonic);
+ @atomicStore(?*const c_void, &vdso_clock_gettime, ptr, .Monotonic);
// Call into the VDSO if available
if (ptr) |fn_ptr| {
const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);
return f(clk, ts);
}
- return @bitCast(usize, isize(-ENOSYS));
+ return @bitCast(usize, @as(isize, -ENOSYS));
}
pub fn clock_getres(clk_id: i32, tp: *timespec) usize {
- return syscall2(SYS_clock_getres, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
+ return syscall2(SYS_clock_getres, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
}
pub fn clock_settime(clk_id: i32, tp: *const timespec) usize {
- return syscall2(SYS_clock_settime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
+ return syscall2(SYS_clock_settime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
}
pub fn gettimeofday(tv: *timeval, tz: *timezone) usize {
@@ -594,33 +594,33 @@ pub fn setregid(rgid: u32, egid: u32) usize {
pub fn getuid() u32 {
if (@hasDecl(@This(), "SYS_getuid32")) {
- return u32(syscall0(SYS_getuid32));
+ return @as(u32, syscall0(SYS_getuid32));
} else {
- return u32(syscall0(SYS_getuid));
+ return @as(u32, syscall0(SYS_getuid));
}
}
pub fn getgid() u32 {
if (@hasDecl(@This(), "SYS_getgid32")) {
- return u32(syscall0(SYS_getgid32));
+ return @as(u32, syscall0(SYS_getgid32));
} else {
- return u32(syscall0(SYS_getgid));
+ return @as(u32, syscall0(SYS_getgid));
}
}
pub fn geteuid() u32 {
if (@hasDecl(@This(), "SYS_geteuid32")) {
- return u32(syscall0(SYS_geteuid32));
+ return @as(u32, syscall0(SYS_geteuid32));
} else {
- return u32(syscall0(SYS_geteuid));
+ return @as(u32, syscall0(SYS_geteuid));
}
}
pub fn getegid() u32 {
if (@hasDecl(@This(), "SYS_getegid32")) {
- return u32(syscall0(SYS_getegid32));
+ return @as(u32, syscall0(SYS_getegid32));
} else {
- return u32(syscall0(SYS_getegid));
+ return @as(u32, syscall0(SYS_getegid));
}
}
@@ -743,11 +743,11 @@ pub fn sigismember(set: *const sigset_t, sig: u6) bool {
}
pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
- return syscall3(SYS_getsockname, @bitCast(usize, isize(fd)), @ptrToInt(addr), @ptrToInt(len));
+ return syscall3(SYS_getsockname, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len));
}
pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
- return syscall3(SYS_getpeername, @bitCast(usize, isize(fd)), @ptrToInt(addr), @ptrToInt(len));
+ return syscall3(SYS_getpeername, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len));
}
pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize {
@@ -755,15 +755,15 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize {
}
pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize {
- return syscall5(SYS_setsockopt, @bitCast(usize, isize(fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen));
+ return syscall5(SYS_setsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen));
}
pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize {
- return syscall5(SYS_getsockopt, @bitCast(usize, isize(fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen));
+ return syscall5(SYS_getsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen));
}
pub fn sendmsg(fd: i32, msg: *msghdr_const, flags: u32) usize {
- return syscall3(SYS_sendmsg, @bitCast(usize, isize(fd)), @ptrToInt(msg), flags);
+ return syscall3(SYS_sendmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags);
}
pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize {
@@ -781,7 +781,7 @@ pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize
// batch-send all messages up to the current message
if (next_unsent < i) {
const batch_size = i - next_unsent;
- const r = syscall4(SYS_sendmmsg, @bitCast(usize, isize(fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);
+ const r = syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);
if (getErrno(r) != 0) return next_unsent;
if (r < batch_size) return next_unsent + r;
}
@@ -797,41 +797,41 @@ pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize
}
if (next_unsent < kvlen or next_unsent == 0) { // want to make sure at least one syscall occurs (e.g. to trigger MSG_EOR)
const batch_size = kvlen - next_unsent;
- const r = syscall4(SYS_sendmmsg, @bitCast(usize, isize(fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);
+ const r = syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);
if (getErrno(r) != 0) return r;
return next_unsent + r;
}
return kvlen;
}
- return syscall4(SYS_sendmmsg, @bitCast(usize, isize(fd)), @ptrToInt(msgvec), vlen, flags);
+ return syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msgvec), vlen, flags);
}
pub fn connect(fd: i32, addr: *const c_void, len: socklen_t) usize {
- return syscall3(SYS_connect, @bitCast(usize, isize(fd)), @ptrToInt(addr), len);
+ return syscall3(SYS_connect, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len);
}
pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize {
- return syscall3(SYS_recvmsg, @bitCast(usize, isize(fd)), @ptrToInt(msg), flags);
+ return syscall3(SYS_recvmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags);
}
pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize {
- return syscall6(SYS_recvfrom, @bitCast(usize, isize(fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen));
+ return syscall6(SYS_recvfrom, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen));
}
pub fn shutdown(fd: i32, how: i32) usize {
- return syscall2(SYS_shutdown, @bitCast(usize, isize(fd)), @bitCast(usize, isize(how)));
+ return syscall2(SYS_shutdown, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)));
}
pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize {
- return syscall3(SYS_bind, @bitCast(usize, isize(fd)), @ptrToInt(addr), @intCast(usize, len));
+ return syscall3(SYS_bind, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len));
}
pub fn listen(fd: i32, backlog: u32) usize {
- return syscall2(SYS_listen, @bitCast(usize, isize(fd)), backlog);
+ return syscall2(SYS_listen, @bitCast(usize, @as(isize, fd)), backlog);
}
pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize {
- return syscall6(SYS_sendto, @bitCast(usize, isize(fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen));
+ return syscall6(SYS_sendto, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen));
}
pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usize {
@@ -843,14 +843,14 @@ pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
}
pub fn accept4(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t, flags: u32) usize {
- return syscall4(SYS_accept4, @bitCast(usize, isize(fd)), @ptrToInt(addr), @ptrToInt(len), flags);
+ return syscall4(SYS_accept4, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags);
}
pub fn fstat(fd: i32, stat_buf: *Stat) usize {
if (@hasDecl(@This(), "SYS_fstat64")) {
- return syscall2(SYS_fstat64, @bitCast(usize, isize(fd)), @ptrToInt(stat_buf));
+ return syscall2(SYS_fstat64, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf));
} else {
- return syscall2(SYS_fstat, @bitCast(usize, isize(fd)), @ptrToInt(stat_buf));
+ return syscall2(SYS_fstat, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf));
}
}
@@ -875,9 +875,9 @@ pub fn lstat(pathname: [*]const u8, statbuf: *Stat) usize {
// TODO https://github.com/ziglang/zig/issues/265
pub fn fstatat(dirfd: i32, path: [*]const u8, stat_buf: *Stat, flags: u32) usize {
if (@hasDecl(@This(), "SYS_fstatat64")) {
- return syscall4(SYS_fstatat64, @bitCast(usize, isize(dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);
+ return syscall4(SYS_fstatat64, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);
} else {
- return syscall4(SYS_fstatat, @bitCast(usize, isize(dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);
+ return syscall4(SYS_fstatat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);
}
}
@@ -885,14 +885,14 @@ pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *S
if (@hasDecl(@This(), "SYS_statx")) {
return syscall5(
SYS_statx,
- @bitCast(usize, isize(dirfd)),
+ @bitCast(usize, @as(isize, dirfd)),
@ptrToInt(path),
flags,
mask,
@ptrToInt(statx_buf),
);
}
- return @bitCast(usize, isize(-ENOSYS));
+ return @bitCast(usize, @as(isize, -ENOSYS));
}
// TODO https://github.com/ziglang/zig/issues/265
@@ -954,8 +954,12 @@ pub fn fremovexattr(fd: usize, name: [*]const u8) usize {
return syscall2(SYS_fremovexattr, fd, @ptrToInt(name));
}
+pub fn sched_yield() usize {
+ return syscall0(SYS_sched_yield);
+}
+
pub fn sched_getaffinity(pid: i32, size: usize, set: *cpu_set_t) usize {
- const rc = syscall3(SYS_sched_getaffinity, @bitCast(usize, isize(pid)), size, @ptrToInt(set));
+ const rc = syscall3(SYS_sched_getaffinity, @bitCast(usize, @as(isize, pid)), size, @ptrToInt(set));
if (@bitCast(isize, rc) < 0) return rc;
if (rc < size) @memset(@ptrCast([*]u8, set) + rc, 0, size - rc);
return 0;
@@ -970,7 +974,7 @@ pub fn epoll_create1(flags: usize) usize {
}
pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: ?*epoll_event) usize {
- return syscall4(SYS_epoll_ctl, @bitCast(usize, isize(epoll_fd)), @intCast(usize, op), @bitCast(usize, isize(fd)), @ptrToInt(ev));
+ return syscall4(SYS_epoll_ctl, @bitCast(usize, @as(isize, epoll_fd)), @intCast(usize, op), @bitCast(usize, @as(isize, fd)), @ptrToInt(ev));
}
pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize {
@@ -980,10 +984,10 @@ pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout
pub fn epoll_pwait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32, sigmask: ?*sigset_t) usize {
return syscall6(
SYS_epoll_pwait,
- @bitCast(usize, isize(epoll_fd)),
+ @bitCast(usize, @as(isize, epoll_fd)),
@ptrToInt(events),
@intCast(usize, maxevents),
- @bitCast(usize, isize(timeout)),
+ @bitCast(usize, @as(isize, timeout)),
@ptrToInt(sigmask),
@sizeOf(sigset_t),
);
@@ -994,7 +998,7 @@ pub fn eventfd(count: u32, flags: u32) usize {
}
pub fn timerfd_create(clockid: i32, flags: u32) usize {
- return syscall2(SYS_timerfd_create, @bitCast(usize, isize(clockid)), flags);
+ return syscall2(SYS_timerfd_create, @bitCast(usize, @as(isize, clockid)), flags);
}
pub const itimerspec = extern struct {
@@ -1003,11 +1007,11 @@ pub const itimerspec = extern struct {
};
pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize {
- return syscall2(SYS_timerfd_gettime, @bitCast(usize, isize(fd)), @ptrToInt(curr_value));
+ return syscall2(SYS_timerfd_gettime, @bitCast(usize, @as(isize, fd)), @ptrToInt(curr_value));
}
pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize {
- return syscall4(SYS_timerfd_settime, @bitCast(usize, isize(fd)), flags, @ptrToInt(new_value), @ptrToInt(old_value));
+ return syscall4(SYS_timerfd_settime, @bitCast(usize, @as(isize, fd)), flags, @ptrToInt(new_value), @ptrToInt(old_value));
}
pub fn unshare(flags: usize) usize {
@@ -1092,11 +1096,11 @@ pub fn io_uring_setup(entries: u32, p: *io_uring_params) usize {
}
pub fn io_uring_enter(fd: i32, to_submit: u32, min_complete: u32, flags: u32, sig: ?*sigset_t) usize {
- return syscall6(SYS_io_uring_enter, @bitCast(usize, isize(fd)), to_submit, min_complete, flags, @ptrToInt(sig), NSIG / 8);
+ return syscall6(SYS_io_uring_enter, @bitCast(usize, @as(isize, fd)), to_submit, min_complete, flags, @ptrToInt(sig), NSIG / 8);
}
pub fn io_uring_register(fd: i32, opcode: u32, arg: ?*const c_void, nr_args: u32) usize {
- return syscall4(SYS_io_uring_register, @bitCast(usize, isize(fd)), opcode, @ptrToInt(arg), nr_args);
+ return syscall4(SYS_io_uring_register, @bitCast(usize, @as(isize, fd)), opcode, @ptrToInt(arg), nr_args);
}
test "" {
diff --git a/lib/std/os/linux/arm-eabi.zig b/lib/std/os/linux/arm-eabi.zig
index c7371fc28d..c457e10beb 100644
--- a/lib/std/os/linux/arm-eabi.zig
+++ b/lib/std/os/linux/arm-eabi.zig
@@ -100,7 +100,7 @@ pub extern fn getThreadPointer() usize {
pub nakedcc fn restore() void {
return asm volatile ("svc #0"
:
- : [number] "{r7}" (usize(SYS_sigreturn))
+ : [number] "{r7}" (@as(usize, SYS_sigreturn))
: "memory"
);
}
@@ -108,7 +108,7 @@ pub nakedcc fn restore() void {
pub nakedcc fn restore_rt() void {
return asm volatile ("svc #0"
:
- : [number] "{r7}" (usize(SYS_rt_sigreturn))
+ : [number] "{r7}" (@as(usize, SYS_rt_sigreturn))
: "memory"
);
}
diff --git a/lib/std/os/linux/arm64.zig b/lib/std/os/linux/arm64.zig
index b8d8a1636b..ac2bb3bfdf 100644
--- a/lib/std/os/linux/arm64.zig
+++ b/lib/std/os/linux/arm64.zig
@@ -93,7 +93,7 @@ pub const restore = restore_rt;
pub nakedcc fn restore_rt() void {
return asm volatile ("svc #0"
:
- : [number] "{x8}" (usize(SYS_rt_sigreturn))
+ : [number] "{x8}" (@as(usize, SYS_rt_sigreturn))
: "memory", "cc"
);
}
diff --git a/lib/std/os/linux/mipsel.zig b/lib/std/os/linux/mipsel.zig
index 791bec6a12..60408c1e84 100644
--- a/lib/std/os/linux/mipsel.zig
+++ b/lib/std/os/linux/mipsel.zig
@@ -26,7 +26,7 @@ pub fn syscall_pipe(fd: *[2]i32) usize {
\\ sw $3, 4($4)
\\ 2:
: [ret] "={$2}" (-> usize)
- : [number] "{$2}" (usize(SYS_pipe))
+ : [number] "{$2}" (@as(usize, SYS_pipe))
: "memory", "cc", "$7"
);
}
@@ -147,7 +147,7 @@ pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, a
pub nakedcc fn restore() void {
return asm volatile ("syscall"
:
- : [number] "{$2}" (usize(SYS_sigreturn))
+ : [number] "{$2}" (@as(usize, SYS_sigreturn))
: "memory", "cc", "$7"
);
}
@@ -155,7 +155,7 @@ pub nakedcc fn restore() void {
pub nakedcc fn restore_rt() void {
return asm volatile ("syscall"
:
- : [number] "{$2}" (usize(SYS_rt_sigreturn))
+ : [number] "{$2}" (@as(usize, SYS_rt_sigreturn))
: "memory", "cc", "$7"
);
}
diff --git a/lib/std/os/linux/riscv64.zig b/lib/std/os/linux/riscv64.zig
index 64facede89..b7c59a9039 100644
--- a/lib/std/os/linux/riscv64.zig
+++ b/lib/std/os/linux/riscv64.zig
@@ -92,7 +92,7 @@ pub const restore = restore_rt;
pub nakedcc fn restore_rt() void {
return asm volatile ("ecall"
:
- : [number] "{x17}" (usize(SYS_rt_sigreturn))
+ : [number] "{x17}" (@as(usize, SYS_rt_sigreturn))
: "memory"
);
}
diff --git a/lib/std/os/linux/test.zig b/lib/std/os/linux/test.zig
index e089a02445..bccb7beb1e 100644
--- a/lib/std/os/linux/test.zig
+++ b/lib/std/os/linux/test.zig
@@ -72,7 +72,7 @@ test "statx" {
expect(stat_buf.mode == statx_buf.mode);
expect(@bitCast(u32, stat_buf.uid) == statx_buf.uid);
expect(@bitCast(u32, stat_buf.gid) == statx_buf.gid);
- expect(@bitCast(u64, i64(stat_buf.size)) == statx_buf.size);
- expect(@bitCast(u64, i64(stat_buf.blksize)) == statx_buf.blksize);
- expect(@bitCast(u64, i64(stat_buf.blocks)) == statx_buf.blocks);
+ expect(@bitCast(u64, @as(i64, stat_buf.size)) == statx_buf.size);
+ expect(@bitCast(u64, @as(i64, stat_buf.blksize)) == statx_buf.blksize);
+ expect(@bitCast(u64, @as(i64, stat_buf.blocks)) == statx_buf.blocks);
}
diff --git a/lib/std/os/linux/vdso.zig b/lib/std/os/linux/vdso.zig
index 86d54bfbf8..d3e00b8673 100644
--- a/lib/std/os/linux/vdso.zig
+++ b/lib/std/os/linux/vdso.zig
@@ -62,8 +62,8 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {
var i: usize = 0;
while (i < hashtab[1]) : (i += 1) {
- if (0 == (u32(1) << @intCast(u5, syms[i].st_info & 0xf) & OK_TYPES)) continue;
- if (0 == (u32(1) << @intCast(u5, syms[i].st_info >> 4) & OK_BINDS)) continue;
+ if (0 == (@as(u32, 1) << @intCast(u5, syms[i].st_info & 0xf) & OK_TYPES)) continue;
+ if (0 == (@as(u32, 1) << @intCast(u5, syms[i].st_info >> 4) & OK_BINDS)) continue;
if (0 == syms[i].st_shndx) continue;
if (!mem.eql(u8, name, mem.toSliceConst(u8, strings + syms[i].st_name))) continue;
if (maybe_versym) |versym| {
diff --git a/lib/std/os/linux/x86_64.zig b/lib/std/os/linux/x86_64.zig
index e0e4687c9f..d037b3c6ae 100644
--- a/lib/std/os/linux/x86_64.zig
+++ b/lib/std/os/linux/x86_64.zig
@@ -93,7 +93,7 @@ pub const restore = restore_rt;
pub nakedcc fn restore_rt() void {
return asm volatile ("syscall"
:
- : [number] "{rax}" (usize(SYS_rt_sigreturn))
+ : [number] "{rax}" (@as(usize, SYS_rt_sigreturn))
: "rcx", "r11", "memory"
);
}
diff --git a/lib/std/os/test.zig b/lib/std/os/test.zig
index 1d61548396..741f108eea 100644
--- a/lib/std/os/test.zig
+++ b/lib/std/os/test.zig
@@ -172,7 +172,7 @@ export fn iter_fn(info: *dl_phdr_info, size: usize, data: ?*usize) i32 {
var counter = data.?;
// Count how many libraries are loaded
- counter.* += usize(1);
+ counter.* += @as(usize, 1);
// The image should contain at least a PT_LOAD segment
if (info.dlpi_phnum < 1) return -1;
diff --git a/lib/std/os/uefi/protocols.zig b/lib/std/os/uefi/protocols.zig
index ff0040860b..f3c3747e1e 100644
--- a/lib/std/os/uefi/protocols.zig
+++ b/lib/std/os/uefi/protocols.zig
@@ -1,3 +1,7 @@
+pub const LoadedImageProtocol = @import("protocols/loaded_image_protocol.zig").LoadedImageProtocol;
+
+pub const DevicePathProtocol = @import("protocols/device_path_protocol.zig").DevicePathProtocol;
+
pub const InputKey = @import("protocols/simple_text_input_ex_protocol.zig").InputKey;
pub const KeyData = @import("protocols/simple_text_input_ex_protocol.zig").KeyData;
pub const KeyState = @import("protocols/simple_text_input_ex_protocol.zig").KeyState;
@@ -29,6 +33,46 @@ pub const EdidActiveProtocol = @import("protocols/edid_active_protocol.zig").Edi
pub const EdidOverrideProtocol = @import("protocols/edid_override_protocol.zig").EdidOverrideProtocol;
pub const EdidOverrideProtocolAttributes = @import("protocols/edid_override_protocol.zig").EdidOverrideProtocolAttributes;
+pub const SimpleNetworkProtocol = @import("protocols/simple_network_protocol.zig").SimpleNetworkProtocol;
+pub const MacAddress = @import("protocols/simple_network_protocol.zig").MacAddress;
+pub const SimpleNetworkMode = @import("protocols/simple_network_protocol.zig").SimpleNetworkMode;
+pub const SimpleNetworkReceiveFilter = @import("protocols/simple_network_protocol.zig").SimpleNetworkReceiveFilter;
+pub const SimpleNetworkState = @import("protocols/simple_network_protocol.zig").SimpleNetworkState;
+pub const NetworkStatistics = @import("protocols/simple_network_protocol.zig").NetworkStatistics;
+pub const SimpleNetworkInterruptStatus = @import("protocols/simple_network_protocol.zig").SimpleNetworkInterruptStatus;
+
+pub const ManagedNetworkServiceBindingProtocol = @import("protocols/managed_network_service_binding_protocol.zig").ManagedNetworkServiceBindingProtocol;
+pub const ManagedNetworkProtocol = @import("protocols/managed_network_protocol.zig").ManagedNetworkProtocol;
+pub const ManagedNetworkConfigData = @import("protocols/managed_network_protocol.zig").ManagedNetworkConfigData;
+pub const ManagedNetworkCompletionToken = @import("protocols/managed_network_protocol.zig").ManagedNetworkCompletionToken;
+pub const ManagedNetworkReceiveData = @import("protocols/managed_network_protocol.zig").ManagedNetworkReceiveData;
+pub const ManagedNetworkTransmitData = @import("protocols/managed_network_protocol.zig").ManagedNetworkTransmitData;
+pub const ManagedNetworkFragmentData = @import("protocols/managed_network_protocol.zig").ManagedNetworkFragmentData;
+
+pub const Ip6ServiceBindingProtocol = @import("protocols/ip6_service_binding_protocol.zig").Ip6ServiceBindingProtocol;
+pub const Ip6Protocol = @import("protocols/ip6_protocol.zig").Ip6Protocol;
+pub const Ip6ModeData = @import("protocols/ip6_protocol.zig").Ip6ModeData;
+pub const Ip6ConfigData = @import("protocols/ip6_protocol.zig").Ip6ConfigData;
+pub const Ip6Address = @import("protocols/ip6_protocol.zig").Ip6Address;
+pub const Ip6AddressInfo = @import("protocols/ip6_protocol.zig").Ip6AddressInfo;
+pub const Ip6RouteTable = @import("protocols/ip6_protocol.zig").Ip6RouteTable;
+pub const Ip6NeighborState = @import("protocols/ip6_protocol.zig").Ip6NeighborState;
+pub const Ip6NeighborCache = @import("protocols/ip6_protocol.zig").Ip6NeighborCache;
+pub const Ip6IcmpType = @import("protocols/ip6_protocol.zig").Ip6IcmpType;
+pub const Ip6CompletionToken = @import("protocols/ip6_protocol.zig").Ip6CompletionToken;
+
+pub const Ip6ConfigProtocol = @import("protocols/ip6_config_protocol.zig").Ip6ConfigProtocol;
+pub const Ip6ConfigDataType = @import("protocols/ip6_config_protocol.zig").Ip6ConfigDataType;
+
+pub const Udp6ServiceBindingProtocol = @import("protocols/udp6_service_binding_protocol.zig").Udp6ServiceBindingProtocol;
+pub const Udp6Protocol = @import("protocols/udp6_protocol.zig").Udp6Protocol;
+pub const Udp6ConfigData = @import("protocols/udp6_protocol.zig").Udp6ConfigData;
+pub const Udp6CompletionToken = @import("protocols/udp6_protocol.zig").Udp6CompletionToken;
+pub const Udp6ReceiveData = @import("protocols/udp6_protocol.zig").Udp6ReceiveData;
+pub const Udp6TransmitData = @import("protocols/udp6_protocol.zig").Udp6TransmitData;
+pub const Udp6SessionData = @import("protocols/udp6_protocol.zig").Udp6SessionData;
+pub const Udp6FragmentData = @import("protocols/udp6_protocol.zig").Udp6FragmentData;
+
pub const hii = @import("protocols/hii.zig");
pub const HIIDatabaseProtocol = @import("protocols/hii_database_protocol.zig").HIIDatabaseProtocol;
pub const HIIPopupProtocol = @import("protocols/hii_popup_protocol.zig").HIIPopupProtocol;
diff --git a/lib/std/os/uefi/protocols/device_path_protocol.zig b/lib/std/os/uefi/protocols/device_path_protocol.zig
new file mode 100644
index 0000000000..a945608f88
--- /dev/null
+++ b/lib/std/os/uefi/protocols/device_path_protocol.zig
@@ -0,0 +1,17 @@
+const uefi = @import("std").os.uefi;
+const Guid = uefi.Guid;
+
+pub const DevicePathProtocol = extern struct {
+ type: u8,
+ subtype: u8,
+ length: u16,
+
+ pub const guid align(8) = Guid{
+ .time_low = 0x09576e91,
+ .time_mid = 0x6d3f,
+ .time_high_and_version = 0x11d2,
+ .clock_seq_high_and_reserved = 0x8e,
+ .clock_seq_low = 0x39,
+ .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },
+ };
+};
diff --git a/lib/std/os/uefi/protocols/ip6_config_protocol.zig b/lib/std/os/uefi/protocols/ip6_config_protocol.zig
new file mode 100644
index 0000000000..a86e2cbba2
--- /dev/null
+++ b/lib/std/os/uefi/protocols/ip6_config_protocol.zig
@@ -0,0 +1,45 @@
+const uefi = @import("std").os.uefi;
+const Guid = uefi.Guid;
+const Event = uefi.Event;
+
+pub const Ip6ConfigProtocol = extern struct {
+ _set_data: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, usize, *const c_void) usize,
+ _get_data: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, *usize, ?*const c_void) usize,
+ _register_data_notify: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, Event) usize,
+ _unregister_data_notify: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, Event) usize,
+
+ pub fn setData(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, data_size: usize, data: *const c_void) usize {
+ return self._set_data(self, data_type, data_size, data);
+ }
+
+ pub fn getData(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, data_size: *usize, data: ?*const c_void) usize {
+ return self._get_data(self, data_type, data_size, data);
+ }
+
+ pub fn registerDataNotify(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, event: Event) usize {
+ return self._register_data_notify(self, data_type, event);
+ }
+
+ pub fn unregisterDataNotify(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, event: Event) usize {
+ return self._unregister_data_notify(self, data_type, event);
+ }
+
+ pub const guid align(8) = Guid{
+ .time_low = 0x937fe521,
+ .time_mid = 0x95ae,
+ .time_high_and_version = 0x4d1a,
+ .clock_seq_high_and_reserved = 0x89,
+ .clock_seq_low = 0x29,
+ .node = [_]u8{ 0x48, 0xbc, 0xd9, 0x0a, 0xd3, 0x1a },
+ };
+};
+
+pub const Ip6ConfigDataType = extern enum(u32) {
+ InterfaceInfo,
+ AltInterfaceId,
+ Policy,
+ DupAddrDetectTransmits,
+ ManualAddress,
+ Gateway,
+ DnsServer,
+};
diff --git a/lib/std/os/uefi/protocols/ip6_protocol.zig b/lib/std/os/uefi/protocols/ip6_protocol.zig
new file mode 100644
index 0000000000..a412dc3c7b
--- /dev/null
+++ b/lib/std/os/uefi/protocols/ip6_protocol.zig
@@ -0,0 +1,143 @@
+const uefi = @import("std").os.uefi;
+const Guid = uefi.Guid;
+const Event = uefi.Event;
+const MacAddress = uefi.protocols.MacAddress;
+const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData;
+const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;
+
+pub const Ip6Protocol = extern struct {
+ _get_mode_data: extern fn (*const Ip6Protocol, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) usize,
+ _configure: extern fn (*const Ip6Protocol, ?*const Ip6ConfigData) usize,
+ _groups: extern fn (*const Ip6Protocol, bool, ?*const Ip6Address) usize,
+ _routes: extern fn (*const Ip6Protocol, bool, ?*const Ip6Address, u8, ?*const Ip6Address) usize,
+ _neighbors: extern fn (*const Ip6Protocol, bool, *const Ip6Address, ?*const MacAddress, u32, bool) usize,
+ _transmit: extern fn (*const Ip6Protocol, *Ip6CompletionToken) usize,
+ _receive: extern fn (*const Ip6Protocol, *Ip6CompletionToken) usize,
+ _cancel: extern fn (*const Ip6Protocol, ?*Ip6CompletionToken) usize,
+ _poll: extern fn (*const Ip6Protocol) usize,
+
+ /// Gets the current operational settings for this instance of the EFI IPv6 Protocol driver.
+ pub fn getModeData(self: *const Ip6Protocol, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) usize {
+ return self._get_mode_data(self, ip6_mode_data, mnp_config_data, snp_mode_data);
+ }
+
+ /// Assign IPv6 address and other configuration parameter to this EFI IPv6 Protocol driver instance.
+ pub fn configure(self: *const Ip6Protocol, ip6_config_data: ?*const Ip6ConfigData) usize {
+ return self._configure(self, ip6_config_data);
+ }
+
+ /// Joins and leaves multicast groups.
+ pub fn groups(self: *const Ip6Protocol, join_flag: bool, group_address: ?*const Ip6Address) usize {
+ return self._groups(self, join_flag, group_address);
+ }
+
+ /// Adds and deletes routing table entries.
+ pub fn routes(self: *const Ip6Protocol, delete_route: bool, destination: ?*const Ip6Address, prefix_length: u8, gateway_address: ?*const Ip6Address) usize {
+ return self._routes(self, delete_route, destination, prefix_length, gateway_address);
+ }
+
+ /// Add or delete Neighbor cache entries.
+ pub fn neighbors(self: *const Ip6Protocol, delete_flag: bool, target_ip6_address: *const Ip6Address, target_link_address: ?*const MacAddress, timeout: u32, override: bool) usize {
+ return self._neighbors(self, delete_flag, target_ip6_address, target_link_address, timeout, override);
+ }
+
+ /// Places outgoing data packets into the transmit queue.
+ pub fn transmit(self: *const Ip6Protocol, token: *Ip6CompletionToken) usize {
+ return self._transmit(self, token);
+ }
+
+ /// Places a receiving request into the receiving queue.
+ pub fn receive(self: *const Ip6Protocol, token: *Ip6CompletionToken) usize {
+ return self._receive(self, token);
+ }
+
+ /// Abort an asynchronous transmits or receive request.
+ pub fn cancel(self: *const Ip6Protocol, token: ?*Ip6CompletionToken) usize {
+ return self._cancel(self, token);
+ }
+
+ /// Polls for incoming data packets and processes outgoing data packets.
+ pub fn poll(self: *const Ip6Protocol) usize {
+ return self._poll(self);
+ }
+
+ pub const guid align(8) = Guid{
+ .time_low = 0x2c8759d5,
+ .time_mid = 0x5c2d,
+ .time_high_and_version = 0x66ef,
+ .clock_seq_high_and_reserved = 0x92,
+ .clock_seq_low = 0x5f,
+ .node = [_]u8{ 0xb6, 0x6c, 0x10, 0x19, 0x57, 0xe2 },
+ };
+};
+
+pub const Ip6ModeData = extern struct {
+ is_started: bool,
+ max_packet_size: u32,
+ config_data: Ip6ConfigData,
+ is_configured: bool,
+ address_count: u32,
+ address_list: [*]Ip6AddressInfo,
+ group_count: u32,
+ group_table: [*]Ip6Address,
+ route_count: u32,
+ route_table: [*]Ip6RouteTable,
+ neighbor_count: u32,
+ neighbor_cache: [*]Ip6NeighborCache,
+ prefix_count: u32,
+ prefix_table: [*]Ip6AddressInfo,
+ icmp_type_count: u32,
+ icmp_type_list: [*]Ip6IcmpType,
+};
+
+pub const Ip6ConfigData = extern struct {
+ default_protocol: u8,
+ accept_any_protocol: bool,
+ accept_icmp_errors: bool,
+ accept_promiscuous: bool,
+ destination_address: Ip6Address,
+ station_address: Ip6Address,
+ traffic_class: u8,
+ hop_limit: u8,
+ flow_label: u32,
+ receive_timeout: u32,
+ transmit_timeout: u32,
+};
+
+pub const Ip6Address = [16]u8;
+
+pub const Ip6AddressInfo = extern struct {
+ address: Ip6Address,
+ prefix_length: u8,
+};
+
+pub const Ip6RouteTable = extern struct {
+ gateway: Ip6Address,
+ destination: Ip6Address,
+ prefix_length: u8,
+};
+
+pub const Ip6NeighborState = extern enum(u32) {
+ Incomplete,
+ Reachable,
+ Stale,
+ Delay,
+ Probe,
+};
+
+pub const Ip6NeighborCache = extern struct {
+ neighbor: Ip6Address,
+ link_address: MacAddress,
+ state: Ip6NeighborState,
+};
+
+pub const Ip6IcmpType = extern struct {
+ type: u8,
+ code: u8,
+};
+
+pub const Ip6CompletionToken = extern struct {
+ event: Event,
+ status: usize,
+ packet: *c_void, // union TODO
+};
diff --git a/lib/std/os/uefi/protocols/ip6_service_binding_protocol.zig b/lib/std/os/uefi/protocols/ip6_service_binding_protocol.zig
new file mode 100644
index 0000000000..9ecbb29607
--- /dev/null
+++ b/lib/std/os/uefi/protocols/ip6_service_binding_protocol.zig
@@ -0,0 +1,25 @@
+const uefi = @import("std").os.uefi;
+const Handle = uefi.Handle;
+const Guid = uefi.Guid;
+
+pub const Ip6ServiceBindingProtocol = extern struct {
+ _create_child: extern fn (*const Ip6ServiceBindingProtocol, *?Handle) usize,
+ _destroy_child: extern fn (*const Ip6ServiceBindingProtocol, Handle) usize,
+
+ pub fn createChild(self: *const Ip6ServiceBindingProtocol, handle: *?Handle) usize {
+ return self._create_child(self, handle);
+ }
+
+ pub fn destroyChild(self: *const Ip6ServiceBindingProtocol, handle: Handle) usize {
+ return self._destroy_child(self, handle);
+ }
+
+ pub const guid align(8) = Guid{
+ .time_low = 0xec835dd3,
+ .time_mid = 0xfe0f,
+ .time_high_and_version = 0x617b,
+ .clock_seq_high_and_reserved = 0xa6,
+ .clock_seq_low = 0x21,
+ .node = [_]u8{ 0xb3, 0x50, 0xc3, 0xe1, 0x33, 0x88 },
+ };
+};
diff --git a/lib/std/os/uefi/protocols/loaded_image_protocol.zig b/lib/std/os/uefi/protocols/loaded_image_protocol.zig
new file mode 100644
index 0000000000..b7b281e249
--- /dev/null
+++ b/lib/std/os/uefi/protocols/loaded_image_protocol.zig
@@ -0,0 +1,36 @@
+const uefi = @import("std").os.uefi;
+const Guid = uefi.Guid;
+const Handle = uefi.Handle;
+const SystemTable = uefi.tables.SystemTable;
+const MemoryType = uefi.tables.MemoryType;
+const DevicePathProtocol = uefi.protocols.DevicePathProtocol;
+
+pub const LoadedImageProtocol = extern struct {
+ revision: u32,
+ parent_handle: Handle,
+ system_table: *SystemTable,
+ device_handle: ?Handle,
+ file_path: *DevicePathProtocol,
+ reserved: *c_void,
+ load_options_size: u32,
+ load_options: *c_void,
+ image_base: [*]u8,
+ image_size: u64,
+ image_code_type: MemoryType,
+ image_data_type: MemoryType,
+ _unload: extern fn (*const LoadedImageProtocol, Handle) usize,
+
+ /// Unloads an image from memory.
+ pub fn unload(self: *const LoadedImageProtocol, handle: Handle) usize {
+ return self._unload(self, handle);
+ }
+
+ pub const guid align(8) = Guid{
+ .time_low = 0x5b1b31a1,
+ .time_mid = 0x9562,
+ .time_high_and_version = 0x11d2,
+ .clock_seq_high_and_reserved = 0x8e,
+ .clock_seq_low = 0x3f,
+ .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },
+ };
+};
diff --git a/lib/std/os/uefi/protocols/managed_network_protocol.zig b/lib/std/os/uefi/protocols/managed_network_protocol.zig
new file mode 100644
index 0000000000..a2cf6e2eca
--- /dev/null
+++ b/lib/std/os/uefi/protocols/managed_network_protocol.zig
@@ -0,0 +1,126 @@
+const uefi = @import("std").os.uefi;
+const Guid = uefi.Guid;
+const Event = uefi.Event;
+const Time = uefi.Time;
+const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;
+const MacAddress = uefi.protocols.MacAddress;
+
+pub const ManagedNetworkProtocol = extern struct {
+ _get_mode_data: extern fn (*const ManagedNetworkProtocol, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) usize,
+ _configure: extern fn (*const ManagedNetworkProtocol, ?*const ManagedNetworkConfigData) usize,
+ _mcast_ip_to_mac: extern fn (*const ManagedNetworkProtocol, bool, *const c_void, *MacAddress) usize,
+ _groups: extern fn (*const ManagedNetworkProtocol, bool, ?*const MacAddress) usize,
+ _transmit: extern fn (*const ManagedNetworkProtocol, *const ManagedNetworkCompletionToken) usize,
+ _receive: extern fn (*const ManagedNetworkProtocol, *const ManagedNetworkCompletionToken) usize,
+ _cancel: extern fn (*const ManagedNetworkProtocol, ?*const ManagedNetworkCompletionToken) usize,
+ _poll: extern fn (*const ManagedNetworkProtocol) usize,
+
+ /// Returns the operational parameters for the current MNP child driver.
+ /// May also support returning the underlying SNP driver mode data.
+ pub fn getModeData(self: *const ManagedNetworkProtocol, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) usize {
+ return self._get_mode_data(self, mnp_config_data, snp_mode_data);
+ }
+
+ /// Sets or clears the operational parameters for the MNP child driver.
+ pub fn configure(self: *const ManagedNetworkProtocol, mnp_config_data: ?*const ManagedNetworkConfigData) usize {
+ return self._configure(self, mnp_config_data);
+ }
+
+ /// Translates an IP multicast address to a hardware (MAC) multicast address.
+ /// This function may be unsupported in some MNP implementations.
+ pub fn mcastIpToMac(self: *const ManagedNetworkProtocol, ipv6flag: bool, ipaddress: *const c_void, mac_address: *MacAddress) usize {
+ return self._mcast_ip_to_mac(self, ipv6flag, ipaddress);
+ }
+
+ /// Enables and disables receive filters for multicast address.
+ /// This function may be unsupported in some MNP implementations.
+ pub fn groups(self: *const ManagedNetworkProtocol, join_flag: bool, mac_address: ?*const MacAddress) usiz {
+ return self._groups(self, join_flag, mac_address);
+ }
+
+ /// Places asynchronous outgoing data packets into the transmit queue.
+ pub fn transmit(self: *const ManagedNetworkProtocol, token: *const ManagedNetworkCompletionToken) usize {
+ return self._transmit(self, token);
+ }
+
+ /// Places an asynchronous receiving request into the receiving queue.
+ pub fn receive(self: *const ManagedNetworkProtocol, token: *const ManagedNetworkCompletionToken) usize {
+ return self._receive(self, token);
+ }
+
+ /// Aborts an asynchronous transmit or receive request.
+ pub fn cancel(self: *const ManagedNetworkProtocol, token: ?*const ManagedNetworkCompletionToken) usize {
+ return self._cancel(self, token);
+ }
+
+ /// Polls for incoming data packets and processes outgoing data packets.
+ pub fn poll(self: *const ManagedNetworkProtocol) usize {
+ return self._poll(self);
+ }
+
+ pub const guid align(8) = Guid{
+ .time_low = 0x7ab33a91,
+ .time_mid = 0xace5,
+ .time_high_and_version = 0x4326,
+ .clock_seq_high_and_reserved = 0xb5,
+ .clock_seq_low = 0x72,
+ .node = [_]u8{ 0xe7, 0xee, 0x33, 0xd3, 0x9f, 0x16 },
+ };
+};
+
+pub const ManagedNetworkConfigData = extern struct {
+ received_queue_timeout_value: u32,
+ transmit_queue_timeout_value: u32,
+ protocol_type_filter: u16,
+ enable_unicast_receive: bool,
+ enable_multicast_receive: bool,
+ enable_broadcast_receive: bool,
+ enable_promiscuous_receive: bool,
+ flush_queues_on_reset: bool,
+ enable_receive_timestamps: bool,
+ disable_background_polling: bool,
+};
+
+pub const ManagedNetworkCompletionToken = extern struct {
+ event: Event,
+ status: usize,
+ packet: extern union {
+ RxData: *ManagedNetworkReceiveData,
+ TxData: *ManagedNetworkTransmitData,
+ },
+};
+
+pub const ManagedNetworkReceiveData = extern struct {
+ timestamp: Time,
+ recycle_event: Event,
+ packet_length: u32,
+ header_length: u32,
+ address_length: u32,
+ data_length: u32,
+ broadcast_flag: bool,
+ multicast_flag: bool,
+ promiscuous_flag: bool,
+ protocol_type: u16,
+ destination_address: [*]u8,
+ source_address: [*]u8,
+ media_header: [*]u8,
+ packet_data: [*]u8,
+};
+
+pub const ManagedNetworkTransmitData = extern struct {
+ destination_address: ?*MacAddress,
+ source_address: ?*MacAddress,
+ protocol_type: u16,
+ data_length: u32,
+ header_length: u16,
+ fragment_count: u16,
+
+ pub fn getFragments(self: *ManagedNetworkTransmitData) []ManagedNetworkFragmentData {
+ return @ptrCast([*]ManagedNetworkFragmentData, @ptrCast([*]u8, self) + @sizeOf(ManagedNetworkTransmitData))[0..self.fragment_count];
+ }
+};
+
+pub const ManagedNetworkFragmentData = extern struct {
+ fragment_length: u32,
+ fragment_buffer: [*]u8,
+};
diff --git a/lib/std/os/uefi/protocols/managed_network_service_binding_protocol.zig b/lib/std/os/uefi/protocols/managed_network_service_binding_protocol.zig
new file mode 100644
index 0000000000..492fe450ba
--- /dev/null
+++ b/lib/std/os/uefi/protocols/managed_network_service_binding_protocol.zig
@@ -0,0 +1,25 @@
+const uefi = @import("std").os.uefi;
+const Handle = uefi.Handle;
+const Guid = uefi.Guid;
+
+pub const ManagedNetworkServiceBindingProtocol = extern struct {
+ _create_child: extern fn (*const ManagedNetworkServiceBindingProtocol, *?Handle) usize,
+ _destroy_child: extern fn (*const ManagedNetworkServiceBindingProtocol, Handle) usize,
+
+ pub fn createChild(self: *const ManagedNetworkServiceBindingProtocol, handle: *?Handle) usize {
+ return self._create_child(self, handle);
+ }
+
+ pub fn destroyChild(self: *const ManagedNetworkServiceBindingProtocol, handle: Handle) usize {
+ return self._destroy_child(self, handle);
+ }
+
+ pub const guid align(8) = Guid{
+ .time_low = 0xf36ff770,
+ .time_mid = 0xa7e1,
+ .time_high_and_version = 0x42cf,
+ .clock_seq_high_and_reserved = 0x9e,
+ .clock_seq_low = 0xd2,
+ .node = [_]u8{ 0x56, 0xf0, 0xf2, 0x71, 0xf4, 0x4c },
+ };
+};
diff --git a/lib/std/os/uefi/protocols/simple_network_protocol.zig b/lib/std/os/uefi/protocols/simple_network_protocol.zig
new file mode 100644
index 0000000000..f5e62734b6
--- /dev/null
+++ b/lib/std/os/uefi/protocols/simple_network_protocol.zig
@@ -0,0 +1,172 @@
+const uefi = @import("std").os.uefi;
+const Event = uefi.Event;
+const Guid = uefi.Guid;
+
+pub const SimpleNetworkProtocol = extern struct {
+ revision: u64,
+ _start: extern fn (*const SimpleNetworkProtocol) usize,
+ _stop: extern fn (*const SimpleNetworkProtocol) usize,
+ _initialize: extern fn (*const SimpleNetworkProtocol, usize, usize) usize,
+ _reset: extern fn (*const SimpleNetworkProtocol, bool) usize,
+ _shutdown: extern fn (*const SimpleNetworkProtocol) usize,
+ _receive_filters: extern fn (*const SimpleNetworkProtocol, SimpleNetworkReceiveFilter, SimpleNetworkReceiveFilter, bool, usize, ?[*]const MacAddress) usize,
+ _station_address: extern fn (*const SimpleNetworkProtocol, bool, ?*const MacAddress) usize,
+ _statistics: extern fn (*const SimpleNetworkProtocol, bool, ?*usize, ?*NetworkStatistics) usize,
+ _mcast_ip_to_mac: extern fn (*const SimpleNetworkProtocol, bool, *const c_void, *MacAddress) usize,
+ _nvdata: extern fn (*const SimpleNetworkProtocol, bool, usize, usize, [*]u8) usize,
+ _get_status: extern fn (*const SimpleNetworkProtocol, *SimpleNetworkInterruptStatus, ?*?[*]u8) usize,
+ _transmit: extern fn (*const SimpleNetworkProtocol, usize, usize, [*]const u8, ?*const MacAddress, ?*const MacAddress, ?*const u16) usize,
+ _receive: extern fn (*const SimpleNetworkProtocol, ?*usize, *usize, [*]u8, ?*MacAddress, ?*MacAddress, ?*u16) usize,
+ wait_for_packet: Event,
+ mode: *SimpleNetworkMode,
+
+ /// Changes the state of a network interface from "stopped" to "started".
+ pub fn start(self: *const SimpleNetworkProtocol) usize {
+ return self._start(self);
+ }
+
+ /// Changes the state of a network interface from "started" to "stopped".
+ pub fn stop(self: *const SimpleNetworkProtocol) usize {
+ return self._stop(self);
+ }
+
+ /// Resets a network adapter and allocates the transmit and receive buffers required by the network interface.
+ pub fn initialize(self: *const SimpleNetworkProtocol, extra_rx_buffer_size: usize, extra_tx_buffer_size: usize) usize {
+ return self._initialize(self, extra_rx_buffer_size, extra_tx_buffer_size);
+ }
+
+ /// Resets a network adapter and reinitializes it with the parameters that were provided in the previous call to initialize().
+ pub fn reset(self: *const SimpleNetworkProtocol, extended_verification: bool) usize {
+ return self._reset(self, extended_verification);
+ }
+
+ /// Resets a network adapter and leaves it in a state that is safe for another driver to initialize.
+ pub fn shutdown(self: *const SimpleNetworkProtocol) usize {
+ return self._shutdown(self);
+ }
+
+ /// Manages the multicast receive filters of a network interface.
+ pub fn receiveFilters(self: *const SimpleNetworkProtocol, enable: SimpleNetworkReceiveFilter, disable: SimpleNetworkReceiveFilter, reset_mcast_filter: bool, mcast_filter_cnt: usize, mcast_filter: ?[*]const MacAddress) usize {
+ return self._receive_filters(self, enable, disable, reset_mcast_filter, mcast_filter_cnt, mcast_filter);
+ }
+
+ /// Modifies or resets the current station address, if supported.
+ pub fn stationAddress(self: *const SimpleNetworkProtocol, reset: bool, new: ?*const MacAddress) usize {
+ return self._station_address(self, reset, new);
+ }
+
+ /// Resets or collects the statistics on a network interface.
+ pub fn statistics(self: *const SimpleNetworkProtocol, reset_: bool, statistics_size: ?*usize, statistics_table: ?*NetworkStatistics) usize {
+ return self._statistics(self, reset_, statistics_size, statistics_table);
+ }
+
+ /// Converts a multicast IP address to a multicast HW MAC address.
+ pub fn mcastIpToMac(self: *const SimpleNetworkProtocol, ipv6: bool, ip: *const c_void, mac: *MacAddress) usize {
+ return self._mcast_ip_to_mac(self, ipv6, ip, mac);
+ }
+
+ /// Performs read and write operations on the NVRAM device attached to a network interface.
+ pub fn nvdata(self: *const SimpleNetworkProtocol, read_write: bool, offset: usize, buffer_size: usize, buffer: [*]u8) usize {
+ return self._nvdata(self, read_write, offset, buffer_size, buffer);
+ }
+
+ /// Reads the current interrupt status and recycled transmit buffer status from a network interface.
+ pub fn getStatus(self: *const SimpleNetworkProtocol, interrupt_status: *SimpleNetworkInterruptStatus, tx_buf: ?*?[*]u8) usize {
+ return self._get_status(self, interrupt_status, tx_buf);
+ }
+
+ /// Places a packet in the transmit queue of a network interface.
+ pub fn transmit(self: *const SimpleNetworkProtocol, header_size: usize, buffer_size: usize, buffer: [*]const u8, src_addr: ?*const MacAddress, dest_addr: ?*const MacAddress, protocol: ?*const u16) usize {
+ return self._transmit(self, header_size, buffer_size, buffer, src_addr, dest_addr, protocol);
+ }
+
+ /// Receives a packet from a network interface.
+ pub fn receive(self: *const SimpleNetworkProtocol, header_size: ?*usize, buffer_size: *usize, buffer: [*]u8, src_addr: ?*MacAddress, dest_addr: ?*MacAddress, protocol: ?*u16) usize {
+ return self._receive(self, header_size, buffer_size, buffer, src_addr, dest_addr, protocol);
+ }
+
+ pub const guid align(8) = Guid{
+ .time_low = 0xa19832b9,
+ .time_mid = 0xac25,
+ .time_high_and_version = 0x11d3,
+ .clock_seq_high_and_reserved = 0x9a,
+ .clock_seq_low = 0x2d,
+ .node = [_]u8{ 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d },
+ };
+};
+
+pub const MacAddress = [32]u8;
+
+pub const SimpleNetworkMode = extern struct {
+ state: SimpleNetworkState,
+ hw_address_size: u32,
+ media_header_size: u32,
+ max_packet_size: u32,
+ nvram_size: u32,
+ nvram_access_size: u32,
+ receive_filter_mask: SimpleNetworkReceiveFilter,
+ receive_filter_setting: SimpleNetworkReceiveFilter,
+ max_mcast_filter_count: u32,
+ mcast_filter_count: u32,
+ mcast_filter: [16]MacAddress,
+ current_address: MacAddress,
+ broadcast_address: MacAddress,
+ permanent_address: MacAddress,
+ if_type: u8,
+ mac_address_changeable: bool,
+ multiple_tx_supported: bool,
+ media_present_supported: bool,
+ media_present: bool,
+};
+
+pub const SimpleNetworkReceiveFilter = packed struct {
+ receive_unicast: bool,
+ receive_multicast: bool,
+ receive_broadcast: bool,
+ receive_promiscuous: bool,
+ receive_promiscuous_multicast: bool,
+ _pad: u27 = undefined,
+};
+
+pub const SimpleNetworkState = extern enum(u32) {
+ Stopped,
+ Started,
+ Initialized,
+};
+
+pub const NetworkStatistics = extern struct {
+ rx_total_frames: u64,
+ rx_good_frames: u64,
+ rx_undersize_frames: u64,
+ rx_oversize_frames: u64,
+ rx_dropped_frames: u64,
+ rx_unicast_frames: u64,
+ rx_broadcast_frames: u64,
+ rx_multicast_frames: u64,
+ rx_crc_error_frames: u64,
+ rx_total_bytes: u64,
+ tx_total_frames: u64,
+ tx_good_frames: u64,
+ tx_undersize_frames: u64,
+ tx_oversize_frames: u64,
+ tx_dropped_frames: u64,
+ tx_unicast_frames: u64,
+ tx_broadcast_frames: u64,
+ tx_multicast_frames: u64,
+ tx_crc_error_frames: u64,
+ tx_total_bytes: u64,
+ collisions: u64,
+ unsupported_protocol: u64,
+ rx_duplicated_frames: u64,
+ rx_decryptError_frames: u64,
+ tx_error_frames: u64,
+ tx_retry_frames: u64,
+};
+
+pub const SimpleNetworkInterruptStatus = packed struct {
+ receive_interrupt: bool,
+ transmit_interrupt: bool,
+ command_interrupt: bool,
+ software_interrupt: bool,
+ _pad: u28,
+};
diff --git a/lib/std/os/uefi/protocols/udp6_protocol.zig b/lib/std/os/uefi/protocols/udp6_protocol.zig
new file mode 100644
index 0000000000..266f2964f9
--- /dev/null
+++ b/lib/std/os/uefi/protocols/udp6_protocol.zig
@@ -0,0 +1,112 @@
+const uefi = @import("std").os.uefi;
+const Guid = uefi.Guid;
+const Event = uefi.Event;
+const Time = uefi.Time;
+const Ip6ModeData = uefi.protocols.Ip6ModeData;
+const Ip6Address = uefi.protocols.Ip6Address;
+const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData;
+const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;
+
+pub const Udp6Protocol = extern struct {
+ _get_mode_data: extern fn (*const Udp6Protocol, ?*Udp6ConfigData, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) usize,
+ _configure: extern fn (*const Udp6Protocol, ?*const Udp6ConfigData) usize,
+ _groups: extern fn (*const Udp6Protocol, bool, ?*const Ip6Address) usize,
+ _transmit: extern fn (*const Udp6Protocol, *Udp6CompletionToken) usize,
+ _receive: extern fn (*const Udp6Protocol, *Udp6CompletionToken) usize,
+ _cancel: extern fn (*const Udp6Protocol, ?*Udp6CompletionToken) usize,
+ _poll: extern fn (*const Udp6Protocol) usize,
+
+ pub fn getModeData(self: *const Udp6Protocol, udp6_config_data: ?*Udp6ConfigData, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) usize {
+ return self._get_mode_data(self, udp6_config_data, ip6_mode_data, mnp_config_data, snp_mode_data);
+ }
+
+ pub fn configure(self: *const Udp6Protocol, udp6_config_data: ?*const Udp6ConfigData) usize {
+ return self._configure(self, udp6_config_data);
+ }
+
+ pub fn groups(self: *const Udp6Protocol, join_flag: bool, multicast_address: ?*const Ip6Address) usize {
+ return self._groups(self, join_flag, multicast_address);
+ }
+
+ pub fn transmit(self: *const Udp6Protocol, token: *Udp6CompletionToken) usize {
+ return self._transmit(self, token);
+ }
+
+ pub fn receive(self: *const Udp6Protocol, token: *Udp6CompletionToken) usize {
+ return self._receive(self, token);
+ }
+
+ pub fn cancel(self: *const Udp6Protocol, token: ?*Udp6CompletionToken) usize {
+ return self._cancel(self, token);
+ }
+
+ pub fn poll(self: *const Udp6Protocol) usize {
+ return self._poll(self);
+ }
+
+ pub const guid align(8) = uefi.Guid{
+ .time_low = 0x4f948815,
+ .time_mid = 0xb4b9,
+ .time_high_and_version = 0x43cb,
+ .clock_seq_high_and_reserved = 0x8a,
+ .clock_seq_low = 0x33,
+ .node = [_]u8{ 0x90, 0xe0, 0x60, 0xb3, 0x49, 0x55 },
+ };
+};
+
+pub const Udp6ConfigData = extern struct {
+ accept_promiscuous: bool,
+ accept_any_port: bool,
+ allow_duplicate_port: bool,
+ traffic_class: u8,
+ hop_limit: u8,
+ receive_timeout: u32,
+ transmit_timeout: u32,
+ station_address: Ip6Address,
+ station_port: u16,
+ remote_address: Ip6Address,
+ remote_port: u16,
+};
+
+pub const Udp6CompletionToken = extern struct {
+ event: Event,
+ status: usize,
+ packet: extern union {
+ RxData: *Udp6ReceiveData,
+ TxData: *Udp6TransmitData,
+ },
+};
+
+pub const Udp6ReceiveData = extern struct {
+ timestamp: Time,
+ recycle_signal: Event,
+ udp6_session: Udp6SessionData,
+ data_length: u32,
+ fragment_count: u32,
+
+ pub fn getFragments(self: *Udp6ReceiveData) []Udp6FragmentData {
+ return @ptrCast([*]Udp6FragmentData, @ptrCast([*]u8, self) + @sizeOf(Udp6ReceiveData))[0..self.fragment_count];
+ }
+};
+
+pub const Udp6TransmitData = extern struct {
+ udp6_session_data: ?*Udp6SessionData,
+ data_length: u32,
+ fragment_count: u32,
+
+ pub fn getFragments(self: *Udp6TransmitData) []Udp6FragmentData {
+ return @ptrCast([*]Udp6FragmentData, @ptrCast([*]u8, self) + @sizeOf(Udp6TransmitData))[0..self.fragment_count];
+ }
+};
+
+pub const Udp6SessionData = extern struct {
+ source_address: Ip6Address,
+ source_port: u16,
+ destination_address: Ip6Address,
+ destination_port: u16,
+};
+
+pub const Udp6FragmentData = extern struct {
+ fragment_length: u32,
+ fragment_buffer: [*]u8,
+};
diff --git a/lib/std/os/uefi/protocols/udp6_service_binding_protocol.zig b/lib/std/os/uefi/protocols/udp6_service_binding_protocol.zig
new file mode 100644
index 0000000000..2f499b50c6
--- /dev/null
+++ b/lib/std/os/uefi/protocols/udp6_service_binding_protocol.zig
@@ -0,0 +1,25 @@
+const uefi = @import("std").os.uefi;
+const Handle = uefi.Handle;
+const Guid = uefi.Guid;
+
+pub const Udp6ServiceBindingProtocol = extern struct {
+ _create_child: extern fn (*const Udp6ServiceBindingProtocol, *?Handle) usize,
+ _destroy_child: extern fn (*const Udp6ServiceBindingProtocol, Handle) usize,
+
+ pub fn createChild(self: *const Udp6ServiceBindingProtocol, handle: *?Handle) usize {
+ return self._create_child(self, handle);
+ }
+
+ pub fn destroyChild(self: *const Udp6ServiceBindingProtocol, handle: Handle) usize {
+ return self._destroy_child(self, handle);
+ }
+
+ pub const guid align(8) = Guid{
+ .time_low = 0x66ed4721,
+ .time_mid = 0x3c98,
+ .time_high_and_version = 0x4d3e,
+ .clock_seq_high_and_reserved = 0x81,
+ .clock_seq_low = 0xe3,
+ .node = [_]u8{ 0xd0, 0x3d, 0xd3, 0x9a, 0x72, 0x54 },
+ };
+};
diff --git a/lib/std/os/uefi/tables.zig b/lib/std/os/uefi/tables.zig
index c66a50802a..d34408dfba 100644
--- a/lib/std/os/uefi/tables.zig
+++ b/lib/std/os/uefi/tables.zig
@@ -1,8 +1,11 @@
pub const BootServices = @import("tables/boot_services.zig").BootServices;
pub const ConfigurationTable = @import("tables/configuration_table.zig").ConfigurationTable;
pub const global_variable align(8) = @import("tables/runtime_services.zig").global_variable;
+pub const LocateSearchType = @import("tables/boot_services.zig").LocateSearchType;
pub const MemoryDescriptor = @import("tables/boot_services.zig").MemoryDescriptor;
pub const MemoryType = @import("tables/boot_services.zig").MemoryType;
+pub const OpenProtocolAttributes = @import("tables/boot_services.zig").OpenProtocolAttributes;
+pub const ProtocolInformationEntry = @import("tables/boot_services.zig").ProtocolInformationEntry;
pub const ResetType = @import("tables/runtime_services.zig").ResetType;
pub const RuntimeServices = @import("tables/runtime_services.zig").RuntimeServices;
pub const SystemTable = @import("tables/system_table.zig").SystemTable;
diff --git a/lib/std/os/uefi/tables/boot_services.zig b/lib/std/os/uefi/tables/boot_services.zig
index 18fb082235..2358b4f842 100644
--- a/lib/std/os/uefi/tables/boot_services.zig
+++ b/lib/std/os/uefi/tables/boot_services.zig
@@ -3,6 +3,7 @@ const Event = uefi.Event;
const Guid = uefi.Guid;
const Handle = uefi.Handle;
const TableHeader = uefi.tables.TableHeader;
+const DevicePathProtocol = uefi.protocols.DevicePathProtocol;
/// Boot services are services provided by the system's firmware until the operating system takes
/// over control over the hardware by calling exitBootServices.
@@ -17,56 +18,96 @@ const TableHeader = uefi.tables.TableHeader;
/// As the boot_services table may grow with new UEFI versions, it is important to check hdr.header_size.
pub const BootServices = extern struct {
hdr: TableHeader,
+
raiseTpl: usize, // TODO
restoreTpl: usize, // TODO
allocatePages: usize, // TODO
freePages: usize, // TODO
+
/// Returns the current memory map.
getMemoryMap: extern fn (*usize, [*]MemoryDescriptor, *usize, *usize, *u32) usize,
+
/// Allocates pool memory.
allocatePool: extern fn (MemoryType, usize, *align(8) [*]u8) usize,
- freePool: usize, // TODO
+
+ /// Returns pool memory to the system.
+ freePool: extern fn ([*]align(8) u8) usize,
+
/// Creates an event.
- createEvent: extern fn (u32, usize, ?extern fn (Event, ?*const c_void) void, ?*const c_void, *Event) usize,
+ createEvent: extern fn (u32, usize, ?extern fn (Event, ?*c_void) void, ?*const c_void, *Event) usize,
+
/// Sets the type of timer and the trigger time for a timer event.
setTimer: extern fn (Event, TimerDelay, u64) usize,
+
/// Stops execution until an event is signaled.
waitForEvent: extern fn (usize, [*]const Event, *usize) usize,
+
/// Signals an event.
signalEvent: extern fn (Event) usize,
+
/// Closes an event.
closeEvent: extern fn (Event) usize,
- checkEvent: usize, // TODO
+
+ /// Checks whether an event is in the signaled state.
+ checkEvent: extern fn (Event) usize,
+
installProtocolInterface: usize, // TODO
reinstallProtocolInterface: usize, // TODO
uninstallProtocolInterface: usize, // TODO
- handleProtocol: usize, // TODO
+
+ /// Queries a handle to determine if it supports a specified protocol.
+ handleProtocol: extern fn (Handle, *align(8) const Guid, *?*c_void) usize,
+
reserved: *c_void,
+
registerProtocolNotify: usize, // TODO
locateHandle: usize, // TODO
locateDevicePath: usize, // TODO
installConfigurationTable: usize, // TODO
- imageLoad: usize, // TODO
- imageStart: usize, // TODO
+
+ /// Loads an EFI image into memory.
+ loadImage: extern fn (bool, Handle, ?*const DevicePathProtocol, ?[*]const u8, usize, *?Handle) usize,
+
+ /// Transfers control to a loaded image's entry point.
+ startImage: extern fn (Handle, ?*usize, ?*[*]u16) usize,
+
/// Terminates a loaded EFI image and returns control to boot services.
exit: extern fn (Handle, usize, usize, ?*const c_void) usize,
- imageUnload: usize, // TODO
+
+ /// Unloads an image.
+ unloadImage: extern fn (Handle) usize,
+
/// Terminates all boot services.
exitBootServices: extern fn (Handle, usize) usize,
+
getNextMonotonicCount: usize, // TODO
+
/// Induces a fine-grained stall.
stall: extern fn (usize) usize,
+
/// Sets the system's watchdog timer.
setWatchdogTimer: extern fn (usize, u64, usize, ?[*]const u16) usize,
+
connectController: usize, // TODO
disconnectController: usize, // TODO
- openProtocol: usize, // TODO
- closeProtocol: usize, // TODO
- openProtocolInformation: usize, // TODO
+
+ /// Queries a handle to determine if it supports a specified protocol.
+ openProtocol: extern fn (Handle, *align(8) const Guid, *?*c_void, ?Handle, ?Handle, OpenProtocolAttributes) usize,
+
+ /// Closes a protocol on a handle that was opened using openProtocol().
+ closeProtocol: extern fn (Handle, *align(8) const Guid, Handle, ?Handle) usize,
+
+ /// Retrieves the list of agents that currently have a protocol interface opened.
+ openProtocolInformation: extern fn (Handle, *align(8) const Guid, *[*]ProtocolInformationEntry, *usize) usize,
+
protocolsPerHandle: usize, // TODO
- locateHandleBuffer: usize, // TODO
+
+ /// Returns an array of handles that support the requested protocol in a buffer allocated from pool.
+ locateHandleBuffer: extern fn (LocateSearchType, ?*align(8) const Guid, ?*const c_void, *usize, *[*]Handle) usize,
+
/// Returns the first protocol instance that matches the given protocol.
locateProtocol: extern fn (*align(8) const Guid, ?*const c_void, *?*c_void) usize,
+
installMultipleProtocolInterfaces: usize, // TODO
uninstallMultipleProtocolInterfaces: usize, // TODO
calculateCrc32: usize, // TODO
@@ -138,3 +179,26 @@ pub const MemoryDescriptor = extern struct {
memory_runtime: bool,
},
};
+
+pub const LocateSearchType = extern enum(u32) {
+ AllHandles,
+ ByRegisterNotify,
+ ByProtocol,
+};
+
+pub const OpenProtocolAttributes = packed struct {
+ by_handle_protocol: bool,
+ get_protocol: bool,
+ test_protocol: bool,
+ by_child_controller: bool,
+ by_driver: bool,
+ exclusive: bool,
+ _pad: u26,
+};
+
+pub const ProtocolInformationEntry = extern struct {
+ agent_handle: ?Handle,
+ controller_handle: ?Handle,
+ attributes: OpenProtocolAttributes,
+ open_count: u32,
+};
diff --git a/lib/std/os/uefi/tables/runtime_services.zig b/lib/std/os/uefi/tables/runtime_services.zig
index 89231b51a8..39d1aa2e3e 100644
--- a/lib/std/os/uefi/tables/runtime_services.zig
+++ b/lib/std/os/uefi/tables/runtime_services.zig
@@ -14,22 +14,30 @@ const TimeCapabilities = uefi.TimeCapabilities;
/// Some functions may not be called while other functions are running.
pub const RuntimeServices = extern struct {
hdr: TableHeader,
+
/// Returns the current time and date information, and the time-keeping capabilities of the hardware platform.
getTime: extern fn (*uefi.Time, ?*TimeCapabilities) usize,
+
setTime: usize, // TODO
getWakeupTime: usize, // TODO
setWakeupTime: usize, // TODO
setVirtualAddressMap: usize, // TODO
convertPointer: usize, // TODO
+
/// Returns the value of a variable.
getVariable: extern fn ([*]const u16, *align(8) const Guid, ?*u32, *usize, ?*c_void) usize,
+
/// Enumerates the current variable names.
getNextVariableName: extern fn (*usize, [*]u16, *align(8) Guid) usize,
+
/// Sets the value of a variable.
setVariable: extern fn ([*]const u16, *align(8) const Guid, u32, usize, *c_void) usize,
+
getNextHighMonotonicCount: usize, // TODO
+
/// Resets the entire platform.
resetSystem: extern fn (ResetType, usize, usize, ?*const c_void) noreturn,
+
updateCapsule: usize, // TODO
queryCapsuleCapabilities: usize, // TODO
queryVariableInfo: usize, // TODO
diff --git a/lib/std/os/uefi/tables/system_table.zig b/lib/std/os/uefi/tables/system_table.zig
index 6ace8e4001..3e0fd589e3 100644
--- a/lib/std/os/uefi/tables/system_table.zig
+++ b/lib/std/os/uefi/tables/system_table.zig
@@ -17,6 +17,7 @@ const TableHeader = uefi.tables.TableHeader;
/// hdr.crc32 must be recomputed.
pub const SystemTable = extern struct {
hdr: TableHeader,
+
/// A null-terminated string that identifies the vendor that produces the system firmware of the platform.
firmware_vendor: [*]u16,
firmware_revision: u32,
diff --git a/lib/std/os/windows.zig b/lib/std/os/windows.zig
index c8c99c6a59..a04e351799 100644
--- a/lib/std/os/windows.zig
+++ b/lib/std/os/windows.zig
@@ -16,6 +16,7 @@ pub const kernel32 = @import("windows/kernel32.zig");
pub const ntdll = @import("windows/ntdll.zig");
pub const ole32 = @import("windows/ole32.zig");
pub const shell32 = @import("windows/shell32.zig");
+pub const ws2_32 = @import("windows/ws2_32.zig");
pub usingnamespace @import("windows/bits.zig");
@@ -96,6 +97,42 @@ pub fn CreatePipe(rd: *HANDLE, wr: *HANDLE, sattr: *const SECURITY_ATTRIBUTES) C
}
}
+pub fn DeviceIoControl(
+ h: HANDLE,
+ ioControlCode: DWORD,
+ in: ?[]const u8,
+ out: ?[]u8,
+ overlapped: ?*OVERLAPPED,
+) !DWORD {
+ var bytes: DWORD = undefined;
+ if (kernel32.DeviceIoControl(
+ h,
+ ioControlCode,
+ if (in) |i| i.ptr else null,
+ if (in) |i| @intCast(u32, i.len) else 0,
+ if (out) |o| o.ptr else null,
+ if (out) |o| @intCast(u32, o.len) else 0,
+ &bytes,
+ overlapped,
+ ) == 0) {
+ switch (kernel32.GetLastError()) {
+ else => |err| return unexpectedError(err),
+ }
+ }
+ return bytes;
+}
+
+pub fn GetOverlappedResult(h: HANDLE, overlapped: *OVERLAPPED, wait: bool) !DWORD {
+ var bytes: DWORD = undefined;
+ if (kernel32.GetOverlappedResult(h, overlapped, &bytes, wait) == 0) {
+ switch (kernel32.GetLastError()) {
+ ERROR_IO_INCOMPLETE => if (!wait) return error.WouldBlock else unreachable,
+ else => |err| return unexpectedError(err),
+ }
+ }
+ return bytes;
+}
+
pub const SetHandleInformationError = error{Unexpected};
pub fn SetHandleInformation(h: HANDLE, mask: DWORD, flags: DWORD) SetHandleInformationError!void {
@@ -262,7 +299,7 @@ pub const ReadFileError = error{Unexpected};
pub fn ReadFile(in_hFile: HANDLE, buffer: []u8) ReadFileError!usize {
var index: usize = 0;
while (index < buffer.len) {
- const want_read_count = @intCast(DWORD, math.min(DWORD(maxInt(DWORD)), buffer.len - index));
+ const want_read_count = @intCast(DWORD, math.min(@as(DWORD, maxInt(DWORD)), buffer.len - index));
var amt_read: DWORD = undefined;
if (kernel32.ReadFile(in_hFile, buffer.ptr + index, want_read_count, &amt_read, null) == 0) {
switch (kernel32.GetLastError()) {
@@ -571,6 +608,74 @@ pub fn GetFileAttributesW(lpFileName: [*]const u16) GetFileAttributesError!DWORD
return rc;
}
+pub fn WSAStartup(majorVersion: u8, minorVersion: u8) !ws2_32.WSADATA {
+ var wsadata: ws2_32.WSADATA = undefined;
+ return switch (ws2_32.WSAStartup((@as(WORD, minorVersion) << 8) | majorVersion, &wsadata)) {
+ 0 => wsadata,
+ else => |err| unexpectedWSAError(err),
+ };
+}
+
+pub fn WSACleanup() !void {
+ return switch (ws2_32.WSACleanup()) {
+ 0 => {},
+ ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
+ else => |err| return unexpectedWSAError(err),
+ },
+ else => unreachable,
+ };
+}
+
+pub fn WSASocketW(
+ af: i32,
+ socket_type: i32,
+ protocol: i32,
+ protocolInfo: ?*ws2_32.WSAPROTOCOL_INFOW,
+ g: ws2_32.GROUP,
+ dwFlags: DWORD,
+) !ws2_32.SOCKET {
+ const rc = ws2_32.WSASocketW(af, socket_type, protocol, protocolInfo, g, dwFlags);
+ if (rc == ws2_32.INVALID_SOCKET) {
+ switch (ws2_32.WSAGetLastError()) {
+ ws2_32.WSAEAFNOSUPPORT => return error.AddressFamilyNotSupported,
+ ws2_32.WSAEMFILE => return error.ProcessFdQuotaExceeded,
+ ws2_32.WSAENOBUFS => return error.SystemResources,
+ ws2_32.WSAEPROTONOSUPPORT => return error.ProtocolNotSupported,
+ else => |err| return unexpectedWSAError(err),
+ }
+ }
+ return rc;
+}
+
+pub fn WSAIoctl(
+ s: ws2_32.SOCKET,
+ dwIoControlCode: DWORD,
+ inBuffer: ?[]const u8,
+ outBuffer: []u8,
+ overlapped: ?*ws2_32.WSAOVERLAPPED,
+ completionRoutine: ?*ws2_32.WSAOVERLAPPED_COMPLETION_ROUTINE,
+) !DWORD {
+ var bytes: DWORD = undefined;
+ switch (ws2_32.WSAIoctl(
+ s,
+ dwIoControlCode,
+ if (inBuffer) |i| i.ptr else null,
+ if (inBuffer) |i| @intCast(DWORD, i.len) else 0,
+ outBuffer.ptr,
+ @intCast(DWORD, outBuffer.len),
+ &bytes,
+ overlapped,
+ completionRoutine,
+ )) {
+ 0 => {},
+ ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
+ else => |err| return unexpectedWSAError(err),
+ },
+ else => unreachable,
+ }
+ return bytes;
+}
+
const GetModuleFileNameError = error{Unexpected};
pub fn GetModuleFileNameW(hModule: ?HMODULE, buf_ptr: [*]u16, buf_len: DWORD) GetModuleFileNameError![]u16 {
@@ -801,7 +906,7 @@ pub fn toSysTime(ns: i64) i64 {
}
pub fn fileTimeToNanoSeconds(ft: FILETIME) i64 {
- const hns = @bitCast(i64, (u64(ft.dwHighDateTime) << 32) | ft.dwLowDateTime);
+ const hns = @bitCast(i64, (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime);
return fromSysTime(hns);
}
@@ -822,6 +927,24 @@ pub fn sliceToPrefixedFileW(s: []const u8) ![PATH_MAX_WIDE + 1]u16 {
return sliceToPrefixedSuffixedFileW(s, [_]u16{0});
}
+/// Assumes an absolute path.
+pub fn wToPrefixedFileW(s: []const u16) ![PATH_MAX_WIDE + 1]u16 {
+ // TODO https://github.com/ziglang/zig/issues/2765
+ var result: [PATH_MAX_WIDE + 1]u16 = undefined;
+
+ const start_index = if (mem.startsWith(u16, s, [_]u16{'\\', '?'})) 0 else blk: {
+ const prefix = [_]u16{ '\\', '?', '?', '\\' };
+ mem.copy(u16, result[0..], prefix);
+ break :blk prefix.len;
+ };
+ const end_index = start_index + s.len;
+ if (end_index + 1 > result.len) return error.NameTooLong;
+ mem.copy(u16, result[start_index..], s);
+ result[end_index] = 0;
+ return result;
+
+}
+
pub fn sliceToPrefixedSuffixedFileW(s: []const u8, comptime suffix: []const u16) ![PATH_MAX_WIDE + suffix.len]u16 {
// TODO https://github.com/ziglang/zig/issues/2765
var result: [PATH_MAX_WIDE + suffix.len]u16 = undefined;
@@ -843,7 +966,6 @@ pub fn sliceToPrefixedSuffixedFileW(s: []const u8, comptime suffix: []const u16)
break :blk prefix.len;
};
const end_index = start_index + try std.unicode.utf8ToUtf16Le(result[start_index..], s);
- assert(end_index <= result.len);
if (end_index + suffix.len > result.len) return error.NameTooLong;
mem.copy(u16, result[end_index..], suffix);
return result;
@@ -868,6 +990,10 @@ pub fn unexpectedError(err: DWORD) std.os.UnexpectedError {
return error.Unexpected;
}
+pub fn unexpectedWSAError(err: c_int) std.os.UnexpectedError {
+ return unexpectedError(@intCast(DWORD, err));
+}
+
/// Call this when you made a windows NtDll call
/// and you get an unexpected status.
pub fn unexpectedStatus(status: NTSTATUS) std.os.UnexpectedError {
diff --git a/lib/std/os/windows/bits.zig b/lib/std/os/windows/bits.zig
index 214f75186f..2f65c27e47 100644
--- a/lib/std/os/windows/bits.zig
+++ b/lib/std/os/windows/bits.zig
@@ -67,9 +67,116 @@ pub const va_list = *@OpaqueType();
pub const TRUE = 1;
pub const FALSE = 0;
+pub const DEVICE_TYPE = ULONG;
+pub const FILE_DEVICE_BEEP: DEVICE_TYPE = 0x0001;
+pub const FILE_DEVICE_CD_ROM: DEVICE_TYPE = 0x0002;
+pub const FILE_DEVICE_CD_ROM_FILE_SYSTEM: DEVICE_TYPE = 0x0003;
+pub const FILE_DEVICE_CONTROLLER: DEVICE_TYPE = 0x0004;
+pub const FILE_DEVICE_DATALINK: DEVICE_TYPE = 0x0005;
+pub const FILE_DEVICE_DFS: DEVICE_TYPE = 0x0006;
+pub const FILE_DEVICE_DISK: DEVICE_TYPE = 0x0007;
+pub const FILE_DEVICE_DISK_FILE_SYSTEM: DEVICE_TYPE = 0x0008;
+pub const FILE_DEVICE_FILE_SYSTEM: DEVICE_TYPE = 0x0009;
+pub const FILE_DEVICE_INPORT_PORT: DEVICE_TYPE = 0x000a;
+pub const FILE_DEVICE_KEYBOARD: DEVICE_TYPE = 0x000b;
+pub const FILE_DEVICE_MAILSLOT: DEVICE_TYPE = 0x000c;
+pub const FILE_DEVICE_MIDI_IN: DEVICE_TYPE = 0x000d;
+pub const FILE_DEVICE_MIDI_OUT: DEVICE_TYPE = 0x000e;
+pub const FILE_DEVICE_MOUSE: DEVICE_TYPE = 0x000f;
+pub const FILE_DEVICE_MULTI_UNC_PROVIDER: DEVICE_TYPE = 0x0010;
+pub const FILE_DEVICE_NAMED_PIPE: DEVICE_TYPE = 0x0011;
+pub const FILE_DEVICE_NETWORK: DEVICE_TYPE = 0x0012;
+pub const FILE_DEVICE_NETWORK_BROWSER: DEVICE_TYPE = 0x0013;
+pub const FILE_DEVICE_NETWORK_FILE_SYSTEM: DEVICE_TYPE = 0x0014;
+pub const FILE_DEVICE_NULL: DEVICE_TYPE = 0x0015;
+pub const FILE_DEVICE_PARALLEL_PORT: DEVICE_TYPE = 0x0016;
+pub const FILE_DEVICE_PHYSICAL_NETCARD: DEVICE_TYPE = 0x0017;
+pub const FILE_DEVICE_PRINTER: DEVICE_TYPE = 0x0018;
+pub const FILE_DEVICE_SCANNER: DEVICE_TYPE = 0x0019;
+pub const FILE_DEVICE_SERIAL_MOUSE_PORT: DEVICE_TYPE = 0x001a;
+pub const FILE_DEVICE_SERIAL_PORT: DEVICE_TYPE = 0x001b;
+pub const FILE_DEVICE_SCREEN: DEVICE_TYPE = 0x001c;
+pub const FILE_DEVICE_SOUND: DEVICE_TYPE = 0x001d;
+pub const FILE_DEVICE_STREAMS: DEVICE_TYPE = 0x001e;
+pub const FILE_DEVICE_TAPE: DEVICE_TYPE = 0x001f;
+pub const FILE_DEVICE_TAPE_FILE_SYSTEM: DEVICE_TYPE = 0x0020;
+pub const FILE_DEVICE_TRANSPORT: DEVICE_TYPE = 0x0021;
+pub const FILE_DEVICE_UNKNOWN: DEVICE_TYPE = 0x0022;
+pub const FILE_DEVICE_VIDEO: DEVICE_TYPE = 0x0023;
+pub const FILE_DEVICE_VIRTUAL_DISK: DEVICE_TYPE = 0x0024;
+pub const FILE_DEVICE_WAVE_IN: DEVICE_TYPE = 0x0025;
+pub const FILE_DEVICE_WAVE_OUT: DEVICE_TYPE = 0x0026;
+pub const FILE_DEVICE_8042_PORT: DEVICE_TYPE = 0x0027;
+pub const FILE_DEVICE_NETWORK_REDIRECTOR: DEVICE_TYPE = 0x0028;
+pub const FILE_DEVICE_BATTERY: DEVICE_TYPE = 0x0029;
+pub const FILE_DEVICE_BUS_EXTENDER: DEVICE_TYPE = 0x002a;
+pub const FILE_DEVICE_MODEM: DEVICE_TYPE = 0x002b;
+pub const FILE_DEVICE_VDM: DEVICE_TYPE = 0x002c;
+pub const FILE_DEVICE_MASS_STORAGE: DEVICE_TYPE = 0x002d;
+pub const FILE_DEVICE_SMB: DEVICE_TYPE = 0x002e;
+pub const FILE_DEVICE_KS: DEVICE_TYPE = 0x002f;
+pub const FILE_DEVICE_CHANGER: DEVICE_TYPE = 0x0030;
+pub const FILE_DEVICE_SMARTCARD: DEVICE_TYPE = 0x0031;
+pub const FILE_DEVICE_ACPI: DEVICE_TYPE = 0x0032;
+pub const FILE_DEVICE_DVD: DEVICE_TYPE = 0x0033;
+pub const FILE_DEVICE_FULLSCREEN_VIDEO: DEVICE_TYPE = 0x0034;
+pub const FILE_DEVICE_DFS_FILE_SYSTEM: DEVICE_TYPE = 0x0035;
+pub const FILE_DEVICE_DFS_VOLUME: DEVICE_TYPE = 0x0036;
+pub const FILE_DEVICE_SERENUM: DEVICE_TYPE = 0x0037;
+pub const FILE_DEVICE_TERMSRV: DEVICE_TYPE = 0x0038;
+pub const FILE_DEVICE_KSEC: DEVICE_TYPE = 0x0039;
+pub const FILE_DEVICE_FIPS: DEVICE_TYPE = 0x003a;
+pub const FILE_DEVICE_INFINIBAND: DEVICE_TYPE = 0x003b;
+// TODO: missing values?
+pub const FILE_DEVICE_VMBUS: DEVICE_TYPE = 0x003e;
+pub const FILE_DEVICE_CRYPT_PROVIDER: DEVICE_TYPE = 0x003f;
+pub const FILE_DEVICE_WPD: DEVICE_TYPE = 0x0040;
+pub const FILE_DEVICE_BLUETOOTH: DEVICE_TYPE = 0x0041;
+pub const FILE_DEVICE_MT_COMPOSITE: DEVICE_TYPE = 0x0042;
+pub const FILE_DEVICE_MT_TRANSPORT: DEVICE_TYPE = 0x0043;
+pub const FILE_DEVICE_BIOMETRIC: DEVICE_TYPE = 0x0044;
+pub const FILE_DEVICE_PMI: DEVICE_TYPE = 0x0045;
+pub const FILE_DEVICE_EHSTOR: DEVICE_TYPE = 0x0046;
+pub const FILE_DEVICE_DEVAPI: DEVICE_TYPE = 0x0047;
+pub const FILE_DEVICE_GPIO: DEVICE_TYPE = 0x0048;
+pub const FILE_DEVICE_USBEX: DEVICE_TYPE = 0x0049;
+pub const FILE_DEVICE_CONSOLE: DEVICE_TYPE = 0x0050;
+pub const FILE_DEVICE_NFP: DEVICE_TYPE = 0x0051;
+pub const FILE_DEVICE_SYSENV: DEVICE_TYPE = 0x0052;
+pub const FILE_DEVICE_VIRTUAL_BLOCK: DEVICE_TYPE = 0x0053;
+pub const FILE_DEVICE_POINT_OF_SERVICE: DEVICE_TYPE = 0x0054;
+pub const FILE_DEVICE_STORAGE_REPLICATION: DEVICE_TYPE = 0x0055;
+pub const FILE_DEVICE_TRUST_ENV: DEVICE_TYPE = 0x0056;
+pub const FILE_DEVICE_UCM: DEVICE_TYPE = 0x0057;
+pub const FILE_DEVICE_UCMTCPCI: DEVICE_TYPE = 0x0058;
+pub const FILE_DEVICE_PERSISTENT_MEMORY: DEVICE_TYPE = 0x0059;
+pub const FILE_DEVICE_NVDIMM: DEVICE_TYPE = 0x005a;
+pub const FILE_DEVICE_HOLOGRAPHIC: DEVICE_TYPE = 0x005b;
+pub const FILE_DEVICE_SDFXHCI: DEVICE_TYPE = 0x005c;
+
+/// https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/buffer-descriptions-for-i-o-control-codes
+pub const TransferType = enum(u2) {
+ METHOD_BUFFERED = 0,
+ METHOD_IN_DIRECT = 1,
+ METHOD_OUT_DIRECT = 2,
+ METHOD_NEITHER = 3,
+};
+
+pub const FILE_ANY_ACCESS = 0;
+pub const FILE_READ_ACCESS = 1;
+pub const FILE_WRITE_ACCESS = 2;
+
+/// https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/defining-i-o-control-codes
+pub fn CTL_CODE(deviceType: u16, function: u12, method: TransferType, access: u2) DWORD {
+ return (@as(DWORD, deviceType) << 16) |
+ (@as(DWORD, access) << 14) |
+ (@as(DWORD, function) << 2) |
+ @enumToInt(method);
+}
+
pub const INVALID_HANDLE_VALUE = @intToPtr(HANDLE, maxInt(usize));
-pub const INVALID_FILE_ATTRIBUTES = DWORD(maxInt(DWORD));
+pub const INVALID_FILE_ATTRIBUTES = @as(DWORD, maxInt(DWORD));
pub const FILE_ALL_INFORMATION = extern struct {
BasicInformation: FILE_BASIC_INFORMATION,
@@ -571,16 +678,16 @@ pub const KF_FLAG_SIMPLE_IDLIST = 256;
pub const KF_FLAG_ALIAS_ONLY = -2147483648;
pub const S_OK = 0;
-pub const E_NOTIMPL = @bitCast(c_long, c_ulong(0x80004001));
-pub const E_NOINTERFACE = @bitCast(c_long, c_ulong(0x80004002));
-pub const E_POINTER = @bitCast(c_long, c_ulong(0x80004003));
-pub const E_ABORT = @bitCast(c_long, c_ulong(0x80004004));
-pub const E_FAIL = @bitCast(c_long, c_ulong(0x80004005));
-pub const E_UNEXPECTED = @bitCast(c_long, c_ulong(0x8000FFFF));
-pub const E_ACCESSDENIED = @bitCast(c_long, c_ulong(0x80070005));
-pub const E_HANDLE = @bitCast(c_long, c_ulong(0x80070006));
-pub const E_OUTOFMEMORY = @bitCast(c_long, c_ulong(0x8007000E));
-pub const E_INVALIDARG = @bitCast(c_long, c_ulong(0x80070057));
+pub const E_NOTIMPL = @bitCast(c_long, @as(c_ulong, 0x80004001));
+pub const E_NOINTERFACE = @bitCast(c_long, @as(c_ulong, 0x80004002));
+pub const E_POINTER = @bitCast(c_long, @as(c_ulong, 0x80004003));
+pub const E_ABORT = @bitCast(c_long, @as(c_ulong, 0x80004004));
+pub const E_FAIL = @bitCast(c_long, @as(c_ulong, 0x80004005));
+pub const E_UNEXPECTED = @bitCast(c_long, @as(c_ulong, 0x8000FFFF));
+pub const E_ACCESSDENIED = @bitCast(c_long, @as(c_ulong, 0x80070005));
+pub const E_HANDLE = @bitCast(c_long, @as(c_ulong, 0x80070006));
+pub const E_OUTOFMEMORY = @bitCast(c_long, @as(c_ulong, 0x8007000E));
+pub const E_INVALIDARG = @bitCast(c_long, @as(c_ulong, 0x80070057));
pub const FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
pub const FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;
@@ -873,4 +980,4 @@ pub const CURDIR = extern struct {
Handle: HANDLE,
};
-pub const DUPLICATE_SAME_ACCESS = 2; \ No newline at end of file
+pub const DUPLICATE_SAME_ACCESS = 2;
diff --git a/lib/std/os/windows/kernel32.zig b/lib/std/os/windows/kernel32.zig
index 736d81ae58..30c4cf4785 100644
--- a/lib/std/os/windows/kernel32.zig
+++ b/lib/std/os/windows/kernel32.zig
@@ -45,6 +45,17 @@ pub extern "kernel32" stdcallcc fn CreateIoCompletionPort(FileHandle: HANDLE, Ex
pub extern "kernel32" stdcallcc fn CreateThread(lpThreadAttributes: ?LPSECURITY_ATTRIBUTES, dwStackSize: SIZE_T, lpStartAddress: LPTHREAD_START_ROUTINE, lpParameter: ?LPVOID, dwCreationFlags: DWORD, lpThreadId: ?LPDWORD) ?HANDLE;
+pub extern "kernel32" stdcallcc fn DeviceIoControl(
+ h: HANDLE,
+ dwIoControlCode: DWORD,
+ lpInBuffer: ?*const c_void,
+ nInBufferSize: DWORD,
+ lpOutBuffer: ?LPVOID,
+ nOutBufferSize: DWORD,
+ lpBytesReturned: LPDWORD,
+ lpOverlapped: ?*OVERLAPPED,
+) BOOL;
+
pub extern "kernel32" stdcallcc fn DeleteFileW(lpFileName: [*]const u16) BOOL;
pub extern "kernel32" stdcallcc fn DuplicateHandle(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE, hTargetProcessHandle: HANDLE, lpTargetHandle: *HANDLE, dwDesiredAccess: DWORD, bInheritHandle: BOOL, dwOptions: DWORD) BOOL;
@@ -184,6 +195,8 @@ pub extern "kernel32" stdcallcc fn SetHandleInformation(hObject: HANDLE, dwMask:
pub extern "kernel32" stdcallcc fn Sleep(dwMilliseconds: DWORD) void;
+pub extern "kernel32" stdcallcc fn SwitchToThread() BOOL;
+
pub extern "kernel32" stdcallcc fn TerminateProcess(hProcess: HANDLE, uExitCode: UINT) BOOL;
pub extern "kernel32" stdcallcc fn TlsAlloc() DWORD;
diff --git a/lib/std/os/windows/ntdll.zig b/lib/std/os/windows/ntdll.zig
index f914920093..d70b1cfefa 100644
--- a/lib/std/os/windows/ntdll.zig
+++ b/lib/std/os/windows/ntdll.zig
@@ -21,6 +21,18 @@ pub extern "NtDll" stdcallcc fn NtCreateFile(
EaBuffer: ?*c_void,
EaLength: ULONG,
) NTSTATUS;
+pub extern "NtDll" stdcallcc fn NtDeviceIoControlFile(
+ FileHandle: HANDLE,
+ Event: ?HANDLE,
+ ApcRoutine: ?*IO_APC_ROUTINE,
+ ApcContext: usize,
+ IoStatusBlock: *IO_STATUS_BLOCK,
+ IoControlCode: ULONG,
+ InputBuffer: ?*const c_void,
+ InputBufferLength: ULONG,
+ OutputBuffer: ?PVOID,
+ OutputBufferLength: ULONG,
+) NTSTATUS;
pub extern "NtDll" stdcallcc fn NtClose(Handle: HANDLE) NTSTATUS;
pub extern "NtDll" stdcallcc fn RtlDosPathNameToNtPathName_U(
DosPathName: [*]const u16,
@@ -43,3 +55,21 @@ pub extern "NtDll" stdcallcc fn NtQueryDirectoryFile(
FileName: ?*UNICODE_STRING,
RestartScan: BOOLEAN,
) NTSTATUS;
+pub extern "NtDll" stdcallcc fn NtCreateKeyedEvent(
+ KeyedEventHandle: *HANDLE,
+ DesiredAccess: ACCESS_MASK,
+ ObjectAttributes: ?PVOID,
+ Flags: ULONG,
+) NTSTATUS;
+pub extern "NtDll" stdcallcc fn NtReleaseKeyedEvent(
+ EventHandle: HANDLE,
+ Key: *const c_void,
+ Alertable: BOOLEAN,
+ Timeout: ?*LARGE_INTEGER,
+) NTSTATUS;
+pub extern "NtDll" stdcallcc fn NtWaitForKeyedEvent(
+ EventHandle: HANDLE,
+ Key: *const c_void,
+ Alertable: BOOLEAN,
+ Timeout: ?*LARGE_INTEGER,
+) NTSTATUS;
diff --git a/lib/std/os/windows/status.zig b/lib/std/os/windows/status.zig
index 5f38948620..23e5ade7c2 100644
--- a/lib/std/os/windows/status.zig
+++ b/lib/std/os/windows/status.zig
@@ -1,13 +1,1663 @@
/// The operation completed successfully.
pub const SUCCESS = 0x00000000;
-/// The data was too large to fit into the specified buffer.
+pub const WAIT_0 = 0x00000000;
+pub const WAIT_1 = 0x00000001;
+pub const WAIT_2 = 0x00000002;
+pub const WAIT_3 = 0x00000003;
+pub const WAIT_63 = 0x0000003F;
+pub const ABANDONED = 0x00000080;
+pub const ABANDONED_WAIT_0 = 0x00000080;
+pub const ABANDONED_WAIT_63 = 0x000000BF;
+pub const USER_APC = 0x000000C0;
+pub const ALERTED = 0x00000101;
+pub const TIMEOUT = 0x00000102;
+pub const PENDING = 0x00000103;
+pub const REPARSE = 0x00000104;
+pub const MORE_ENTRIES = 0x00000105;
+pub const NOT_ALL_ASSIGNED = 0x00000106;
+pub const SOME_NOT_MAPPED = 0x00000107;
+pub const OPLOCK_BREAK_IN_PROGRESS = 0x00000108;
+pub const VOLUME_MOUNTED = 0x00000109;
+pub const RXACT_COMMITTED = 0x0000010A;
+pub const NOTIFY_CLEANUP = 0x0000010B;
+pub const NOTIFY_ENUM_DIR = 0x0000010C;
+pub const NO_QUOTAS_FOR_ACCOUNT = 0x0000010D;
+pub const PRIMARY_TRANSPORT_CONNECT_FAILED = 0x0000010E;
+pub const PAGE_FAULT_TRANSITION = 0x00000110;
+pub const PAGE_FAULT_DEMAND_ZERO = 0x00000111;
+pub const PAGE_FAULT_COPY_ON_WRITE = 0x00000112;
+pub const PAGE_FAULT_GUARD_PAGE = 0x00000113;
+pub const PAGE_FAULT_PAGING_FILE = 0x00000114;
+pub const CACHE_PAGE_LOCKED = 0x00000115;
+pub const CRASH_DUMP = 0x00000116;
+pub const BUFFER_ALL_ZEROS = 0x00000117;
+pub const REPARSE_OBJECT = 0x00000118;
+pub const RESOURCE_REQUIREMENTS_CHANGED = 0x00000119;
+pub const TRANSLATION_COMPLETE = 0x00000120;
+pub const DS_MEMBERSHIP_EVALUATED_LOCALLY = 0x00000121;
+pub const NOTHING_TO_TERMINATE = 0x00000122;
+pub const PROCESS_NOT_IN_JOB = 0x00000123;
+pub const PROCESS_IN_JOB = 0x00000124;
+pub const VOLSNAP_HIBERNATE_READY = 0x00000125;
+pub const FSFILTER_OP_COMPLETED_SUCCESSFULLY = 0x00000126;
+pub const INTERRUPT_VECTOR_ALREADY_CONNECTED = 0x00000127;
+pub const INTERRUPT_STILL_CONNECTED = 0x00000128;
+pub const PROCESS_CLONED = 0x00000129;
+pub const FILE_LOCKED_WITH_ONLY_READERS = 0x0000012A;
+pub const FILE_LOCKED_WITH_WRITERS = 0x0000012B;
+pub const RESOURCEMANAGER_READ_ONLY = 0x00000202;
+pub const WAIT_FOR_OPLOCK = 0x00000367;
+pub const FLT_IO_COMPLETE = 0x001C0001;
+pub const FILE_NOT_AVAILABLE = 0xC0000467;
+pub const OBJECT_NAME_EXISTS = 0x40000000;
+pub const THREAD_WAS_SUSPENDED = 0x40000001;
+pub const WORKING_SET_LIMIT_RANGE = 0x40000002;
+pub const IMAGE_NOT_AT_BASE = 0x40000003;
+pub const RXACT_STATE_CREATED = 0x40000004;
+pub const SEGMENT_NOTIFICATION = 0x40000005;
+pub const LOCAL_USER_SESSION_KEY = 0x40000006;
+pub const BAD_CURRENT_DIRECTORY = 0x40000007;
+pub const SERIAL_MORE_WRITES = 0x40000008;
+pub const REGISTRY_RECOVERED = 0x40000009;
+pub const FT_READ_RECOVERY_FROM_BACKUP = 0x4000000A;
+pub const FT_WRITE_RECOVERY = 0x4000000B;
+pub const SERIAL_COUNTER_TIMEOUT = 0x4000000C;
+pub const NULL_LM_PASSWORD = 0x4000000D;
+pub const IMAGE_MACHINE_TYPE_MISMATCH = 0x4000000E;
+pub const RECEIVE_PARTIAL = 0x4000000F;
+pub const RECEIVE_EXPEDITED = 0x40000010;
+pub const RECEIVE_PARTIAL_EXPEDITED = 0x40000011;
+pub const EVENT_DONE = 0x40000012;
+pub const EVENT_PENDING = 0x40000013;
+pub const CHECKING_FILE_SYSTEM = 0x40000014;
+pub const FATAL_APP_EXIT = 0x40000015;
+pub const PREDEFINED_HANDLE = 0x40000016;
+pub const WAS_UNLOCKED = 0x40000017;
+pub const SERVICE_NOTIFICATION = 0x40000018;
+pub const WAS_LOCKED = 0x40000019;
+pub const LOG_HARD_ERROR = 0x4000001A;
+pub const ALREADY_WIN32 = 0x4000001B;
+pub const WX86_UNSIMULATE = 0x4000001C;
+pub const WX86_CONTINUE = 0x4000001D;
+pub const WX86_SINGLE_STEP = 0x4000001E;
+pub const WX86_BREAKPOINT = 0x4000001F;
+pub const WX86_EXCEPTION_CONTINUE = 0x40000020;
+pub const WX86_EXCEPTION_LASTCHANCE = 0x40000021;
+pub const WX86_EXCEPTION_CHAIN = 0x40000022;
+pub const IMAGE_MACHINE_TYPE_MISMATCH_EXE = 0x40000023;
+pub const NO_YIELD_PERFORMED = 0x40000024;
+pub const TIMER_RESUME_IGNORED = 0x40000025;
+pub const ARBITRATION_UNHANDLED = 0x40000026;
+pub const CARDBUS_NOT_SUPPORTED = 0x40000027;
+pub const WX86_CREATEWX86TIB = 0x40000028;
+pub const MP_PROCESSOR_MISMATCH = 0x40000029;
+pub const HIBERNATED = 0x4000002A;
+pub const RESUME_HIBERNATION = 0x4000002B;
+pub const FIRMWARE_UPDATED = 0x4000002C;
+pub const DRIVERS_LEAKING_LOCKED_PAGES = 0x4000002D;
+pub const MESSAGE_RETRIEVED = 0x4000002E;
+pub const SYSTEM_POWERSTATE_TRANSITION = 0x4000002F;
+pub const ALPC_CHECK_COMPLETION_LIST = 0x40000030;
+pub const SYSTEM_POWERSTATE_COMPLEX_TRANSITION = 0x40000031;
+pub const ACCESS_AUDIT_BY_POLICY = 0x40000032;
+pub const ABANDON_HIBERFILE = 0x40000033;
+pub const BIZRULES_NOT_ENABLED = 0x40000034;
+pub const WAKE_SYSTEM = 0x40000294;
+pub const DS_SHUTTING_DOWN = 0x40000370;
+pub const CTX_CDM_CONNECT = 0x400A0004;
+pub const CTX_CDM_DISCONNECT = 0x400A0005;
+pub const SXS_RELEASE_ACTIVATION_CONTEXT = 0x4015000D;
+pub const RECOVERY_NOT_NEEDED = 0x40190034;
+pub const RM_ALREADY_STARTED = 0x40190035;
+pub const LOG_NO_RESTART = 0x401A000C;
+pub const VIDEO_DRIVER_DEBUG_REPORT_REQUEST = 0x401B00EC;
+pub const GRAPHICS_PARTIAL_DATA_POPULATED = 0x401E000A;
+pub const GRAPHICS_DRIVER_MISMATCH = 0x401E0117;
+pub const GRAPHICS_MODE_NOT_PINNED = 0x401E0307;
+pub const GRAPHICS_NO_PREFERRED_MODE = 0x401E031E;
+pub const GRAPHICS_DATASET_IS_EMPTY = 0x401E034B;
+pub const GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET = 0x401E034C;
+pub const GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED = 0x401E0351;
+pub const GRAPHICS_UNKNOWN_CHILD_STATUS = 0x401E042F;
+pub const GRAPHICS_LEADLINK_START_DEFERRED = 0x401E0437;
+pub const GRAPHICS_POLLING_TOO_FREQUENTLY = 0x401E0439;
+pub const GRAPHICS_START_DEFERRED = 0x401E043A;
+pub const NDIS_INDICATION_REQUIRED = 0x40230001;
+pub const GUARD_PAGE_VIOLATION = 0x80000001;
+pub const DATATYPE_MISALIGNMENT = 0x80000002;
+pub const BREAKPOINT = 0x80000003;
+pub const SINGLE_STEP = 0x80000004;
pub const BUFFER_OVERFLOW = 0x80000005;
-
+pub const NO_MORE_FILES = 0x80000006;
+pub const WAKE_SYSTEM_DEBUGGER = 0x80000007;
+pub const HANDLES_CLOSED = 0x8000000A;
+pub const NO_INHERITANCE = 0x8000000B;
+pub const GUID_SUBSTITUTION_MADE = 0x8000000C;
+pub const PARTIAL_COPY = 0x8000000D;
+pub const DEVICE_PAPER_EMPTY = 0x8000000E;
+pub const DEVICE_POWERED_OFF = 0x8000000F;
+pub const DEVICE_OFF_LINE = 0x80000010;
+pub const DEVICE_BUSY = 0x80000011;
+pub const NO_MORE_EAS = 0x80000012;
+pub const INVALID_EA_NAME = 0x80000013;
+pub const EA_LIST_INCONSISTENT = 0x80000014;
+pub const INVALID_EA_FLAG = 0x80000015;
+pub const VERIFY_REQUIRED = 0x80000016;
+pub const EXTRANEOUS_INFORMATION = 0x80000017;
+pub const RXACT_COMMIT_NECESSARY = 0x80000018;
+pub const NO_MORE_ENTRIES = 0x8000001A;
+pub const FILEMARK_DETECTED = 0x8000001B;
+pub const MEDIA_CHANGED = 0x8000001C;
+pub const BUS_RESET = 0x8000001D;
+pub const END_OF_MEDIA = 0x8000001E;
+pub const BEGINNING_OF_MEDIA = 0x8000001F;
+pub const MEDIA_CHECK = 0x80000020;
+pub const SETMARK_DETECTED = 0x80000021;
+pub const NO_DATA_DETECTED = 0x80000022;
+pub const REDIRECTOR_HAS_OPEN_HANDLES = 0x80000023;
+pub const SERVER_HAS_OPEN_HANDLES = 0x80000024;
+pub const ALREADY_DISCONNECTED = 0x80000025;
+pub const LONGJUMP = 0x80000026;
+pub const CLEANER_CARTRIDGE_INSTALLED = 0x80000027;
+pub const PLUGPLAY_QUERY_VETOED = 0x80000028;
+pub const UNWIND_CONSOLIDATE = 0x80000029;
+pub const REGISTRY_HIVE_RECOVERED = 0x8000002A;
+pub const DLL_MIGHT_BE_INSECURE = 0x8000002B;
+pub const DLL_MIGHT_BE_INCOMPATIBLE = 0x8000002C;
+pub const STOPPED_ON_SYMLINK = 0x8000002D;
+pub const DEVICE_REQUIRES_CLEANING = 0x80000288;
+pub const DEVICE_DOOR_OPEN = 0x80000289;
+pub const DATA_LOST_REPAIR = 0x80000803;
+pub const CLUSTER_NODE_ALREADY_UP = 0x80130001;
+pub const CLUSTER_NODE_ALREADY_DOWN = 0x80130002;
+pub const CLUSTER_NETWORK_ALREADY_ONLINE = 0x80130003;
+pub const CLUSTER_NETWORK_ALREADY_OFFLINE = 0x80130004;
+pub const CLUSTER_NODE_ALREADY_MEMBER = 0x80130005;
+pub const COULD_NOT_RESIZE_LOG = 0x80190009;
+pub const NO_TXF_METADATA = 0x80190029;
+pub const CANT_RECOVER_WITH_HANDLE_OPEN = 0x80190031;
+pub const TXF_METADATA_ALREADY_PRESENT = 0x80190041;
+pub const TRANSACTION_SCOPE_CALLBACKS_NOT_SET = 0x80190042;
+pub const VIDEO_HUNG_DISPLAY_DRIVER_THREAD_RECOVERED = 0x801B00EB;
+pub const FLT_BUFFER_TOO_SMALL = 0x801C0001;
+pub const FVE_PARTIAL_METADATA = 0x80210001;
+pub const FVE_TRANSIENT_STATE = 0x80210002;
+pub const UNSUCCESSFUL = 0xC0000001;
+pub const NOT_IMPLEMENTED = 0xC0000002;
+pub const INVALID_INFO_CLASS = 0xC0000003;
+pub const INFO_LENGTH_MISMATCH = 0xC0000004;
+pub const ACCESS_VIOLATION = 0xC0000005;
+pub const IN_PAGE_ERROR = 0xC0000006;
+pub const PAGEFILE_QUOTA = 0xC0000007;
+pub const INVALID_HANDLE = 0xC0000008;
+pub const BAD_INITIAL_STACK = 0xC0000009;
+pub const BAD_INITIAL_PC = 0xC000000A;
+pub const INVALID_CID = 0xC000000B;
+pub const TIMER_NOT_CANCELED = 0xC000000C;
pub const INVALID_PARAMETER = 0xC000000D;
+pub const NO_SUCH_DEVICE = 0xC000000E;
+pub const NO_SUCH_FILE = 0xC000000F;
+pub const INVALID_DEVICE_REQUEST = 0xC0000010;
+pub const END_OF_FILE = 0xC0000011;
+pub const WRONG_VOLUME = 0xC0000012;
+pub const NO_MEDIA_IN_DEVICE = 0xC0000013;
+pub const UNRECOGNIZED_MEDIA = 0xC0000014;
+pub const NONEXISTENT_SECTOR = 0xC0000015;
+pub const MORE_PROCESSING_REQUIRED = 0xC0000016;
+pub const NO_MEMORY = 0xC0000017;
+pub const CONFLICTING_ADDRESSES = 0xC0000018;
+pub const NOT_MAPPED_VIEW = 0xC0000019;
+pub const UNABLE_TO_FREE_VM = 0xC000001A;
+pub const UNABLE_TO_DELETE_SECTION = 0xC000001B;
+pub const INVALID_SYSTEM_SERVICE = 0xC000001C;
+pub const ILLEGAL_INSTRUCTION = 0xC000001D;
+pub const INVALID_LOCK_SEQUENCE = 0xC000001E;
+pub const INVALID_VIEW_SIZE = 0xC000001F;
+pub const INVALID_FILE_FOR_SECTION = 0xC0000020;
+pub const ALREADY_COMMITTED = 0xC0000021;
pub const ACCESS_DENIED = 0xC0000022;
+pub const BUFFER_TOO_SMALL = 0xC0000023;
+pub const OBJECT_TYPE_MISMATCH = 0xC0000024;
+pub const NONCONTINUABLE_EXCEPTION = 0xC0000025;
+pub const INVALID_DISPOSITION = 0xC0000026;
+pub const UNWIND = 0xC0000027;
+pub const BAD_STACK = 0xC0000028;
+pub const INVALID_UNWIND_TARGET = 0xC0000029;
+pub const NOT_LOCKED = 0xC000002A;
+pub const PARITY_ERROR = 0xC000002B;
+pub const UNABLE_TO_DECOMMIT_VM = 0xC000002C;
+pub const NOT_COMMITTED = 0xC000002D;
+pub const INVALID_PORT_ATTRIBUTES = 0xC000002E;
+pub const PORT_MESSAGE_TOO_LONG = 0xC000002F;
+pub const INVALID_PARAMETER_MIX = 0xC0000030;
+pub const INVALID_QUOTA_LOWER = 0xC0000031;
+pub const DISK_CORRUPT_ERROR = 0xC0000032;
pub const OBJECT_NAME_INVALID = 0xC0000033;
pub const OBJECT_NAME_NOT_FOUND = 0xC0000034;
+pub const OBJECT_NAME_COLLISION = 0xC0000035;
+pub const PORT_DISCONNECTED = 0xC0000037;
+pub const DEVICE_ALREADY_ATTACHED = 0xC0000038;
+pub const OBJECT_PATH_INVALID = 0xC0000039;
pub const OBJECT_PATH_NOT_FOUND = 0xC000003A;
pub const OBJECT_PATH_SYNTAX_BAD = 0xC000003B;
+pub const DATA_OVERRUN = 0xC000003C;
+pub const DATA_LATE_ERROR = 0xC000003D;
+pub const DATA_ERROR = 0xC000003E;
+pub const CRC_ERROR = 0xC000003F;
+pub const SECTION_TOO_BIG = 0xC0000040;
+pub const PORT_CONNECTION_REFUSED = 0xC0000041;
+pub const INVALID_PORT_HANDLE = 0xC0000042;
+pub const SHARING_VIOLATION = 0xC0000043;
+pub const QUOTA_EXCEEDED = 0xC0000044;
+pub const INVALID_PAGE_PROTECTION = 0xC0000045;
+pub const MUTANT_NOT_OWNED = 0xC0000046;
+pub const SEMAPHORE_LIMIT_EXCEEDED = 0xC0000047;
+pub const PORT_ALREADY_SET = 0xC0000048;
+pub const SECTION_NOT_IMAGE = 0xC0000049;
+pub const SUSPEND_COUNT_EXCEEDED = 0xC000004A;
+pub const THREAD_IS_TERMINATING = 0xC000004B;
+pub const BAD_WORKING_SET_LIMIT = 0xC000004C;
+pub const INCOMPATIBLE_FILE_MAP = 0xC000004D;
+pub const SECTION_PROTECTION = 0xC000004E;
+pub const EAS_NOT_SUPPORTED = 0xC000004F;
+pub const EA_TOO_LARGE = 0xC0000050;
+pub const NONEXISTENT_EA_ENTRY = 0xC0000051;
+pub const NO_EAS_ON_FILE = 0xC0000052;
+pub const EA_CORRUPT_ERROR = 0xC0000053;
+pub const FILE_LOCK_CONFLICT = 0xC0000054;
+pub const LOCK_NOT_GRANTED = 0xC0000055;
+pub const DELETE_PENDING = 0xC0000056;
+pub const CTL_FILE_NOT_SUPPORTED = 0xC0000057;
+pub const UNKNOWN_REVISION = 0xC0000058;
+pub const REVISION_MISMATCH = 0xC0000059;
+pub const INVALID_OWNER = 0xC000005A;
+pub const INVALID_PRIMARY_GROUP = 0xC000005B;
+pub const NO_IMPERSONATION_TOKEN = 0xC000005C;
+pub const CANT_DISABLE_MANDATORY = 0xC000005D;
+pub const NO_LOGON_SERVERS = 0xC000005E;
+pub const NO_SUCH_LOGON_SESSION = 0xC000005F;
+pub const NO_SUCH_PRIVILEGE = 0xC0000060;
+pub const PRIVILEGE_NOT_HELD = 0xC0000061;
+pub const INVALID_ACCOUNT_NAME = 0xC0000062;
+pub const USER_EXISTS = 0xC0000063;
+pub const NO_SUCH_USER = 0xC0000064;
+pub const GROUP_EXISTS = 0xC0000065;
+pub const NO_SUCH_GROUP = 0xC0000066;
+pub const MEMBER_IN_GROUP = 0xC0000067;
+pub const MEMBER_NOT_IN_GROUP = 0xC0000068;
+pub const LAST_ADMIN = 0xC0000069;
+pub const WRONG_PASSWORD = 0xC000006A;
+pub const ILL_FORMED_PASSWORD = 0xC000006B;
+pub const PASSWORD_RESTRICTION = 0xC000006C;
+pub const LOGON_FAILURE = 0xC000006D;
+pub const ACCOUNT_RESTRICTION = 0xC000006E;
+pub const INVALID_LOGON_HOURS = 0xC000006F;
+pub const INVALID_WORKSTATION = 0xC0000070;
+pub const PASSWORD_EXPIRED = 0xC0000071;
+pub const ACCOUNT_DISABLED = 0xC0000072;
+pub const NONE_MAPPED = 0xC0000073;
+pub const TOO_MANY_LUIDS_REQUESTED = 0xC0000074;
+pub const LUIDS_EXHAUSTED = 0xC0000075;
+pub const INVALID_SUB_AUTHORITY = 0xC0000076;
+pub const INVALID_ACL = 0xC0000077;
+pub const INVALID_SID = 0xC0000078;
+pub const INVALID_SECURITY_DESCR = 0xC0000079;
+pub const PROCEDURE_NOT_FOUND = 0xC000007A;
+pub const INVALID_IMAGE_FORMAT = 0xC000007B;
+pub const NO_TOKEN = 0xC000007C;
+pub const BAD_INHERITANCE_ACL = 0xC000007D;
+pub const RANGE_NOT_LOCKED = 0xC000007E;
+pub const DISK_FULL = 0xC000007F;
+pub const SERVER_DISABLED = 0xC0000080;
+pub const SERVER_NOT_DISABLED = 0xC0000081;
+pub const TOO_MANY_GUIDS_REQUESTED = 0xC0000082;
+pub const GUIDS_EXHAUSTED = 0xC0000083;
+pub const INVALID_ID_AUTHORITY = 0xC0000084;
+pub const AGENTS_EXHAUSTED = 0xC0000085;
+pub const INVALID_VOLUME_LABEL = 0xC0000086;
+pub const SECTION_NOT_EXTENDED = 0xC0000087;
+pub const NOT_MAPPED_DATA = 0xC0000088;
+pub const RESOURCE_DATA_NOT_FOUND = 0xC0000089;
+pub const RESOURCE_TYPE_NOT_FOUND = 0xC000008A;
+pub const RESOURCE_NAME_NOT_FOUND = 0xC000008B;
+pub const ARRAY_BOUNDS_EXCEEDED = 0xC000008C;
+pub const FLOAT_DENORMAL_OPERAND = 0xC000008D;
+pub const FLOAT_DIVIDE_BY_ZERO = 0xC000008E;
+pub const FLOAT_INEXACT_RESULT = 0xC000008F;
+pub const FLOAT_INVALID_OPERATION = 0xC0000090;
+pub const FLOAT_OVERFLOW = 0xC0000091;
+pub const FLOAT_STACK_CHECK = 0xC0000092;
+pub const FLOAT_UNDERFLOW = 0xC0000093;
+pub const INTEGER_DIVIDE_BY_ZERO = 0xC0000094;
+pub const INTEGER_OVERFLOW = 0xC0000095;
+pub const PRIVILEGED_INSTRUCTION = 0xC0000096;
+pub const TOO_MANY_PAGING_FILES = 0xC0000097;
+pub const FILE_INVALID = 0xC0000098;
+pub const ALLOTTED_SPACE_EXCEEDED = 0xC0000099;
+pub const INSUFFICIENT_RESOURCES = 0xC000009A;
+pub const DFS_EXIT_PATH_FOUND = 0xC000009B;
+pub const DEVICE_DATA_ERROR = 0xC000009C;
+pub const DEVICE_NOT_CONNECTED = 0xC000009D;
+pub const FREE_VM_NOT_AT_BASE = 0xC000009F;
+pub const MEMORY_NOT_ALLOCATED = 0xC00000A0;
+pub const WORKING_SET_QUOTA = 0xC00000A1;
+pub const MEDIA_WRITE_PROTECTED = 0xC00000A2;
+pub const DEVICE_NOT_READY = 0xC00000A3;
+pub const INVALID_GROUP_ATTRIBUTES = 0xC00000A4;
+pub const BAD_IMPERSONATION_LEVEL = 0xC00000A5;
+pub const CANT_OPEN_ANONYMOUS = 0xC00000A6;
+pub const BAD_VALIDATION_CLASS = 0xC00000A7;
+pub const BAD_TOKEN_TYPE = 0xC00000A8;
+pub const BAD_MASTER_BOOT_RECORD = 0xC00000A9;
+pub const INSTRUCTION_MISALIGNMENT = 0xC00000AA;
+pub const INSTANCE_NOT_AVAILABLE = 0xC00000AB;
+pub const PIPE_NOT_AVAILABLE = 0xC00000AC;
+pub const INVALID_PIPE_STATE = 0xC00000AD;
+pub const PIPE_BUSY = 0xC00000AE;
+pub const ILLEGAL_FUNCTION = 0xC00000AF;
+pub const PIPE_DISCONNECTED = 0xC00000B0;
+pub const PIPE_CLOSING = 0xC00000B1;
+pub const PIPE_CONNECTED = 0xC00000B2;
+pub const PIPE_LISTENING = 0xC00000B3;
+pub const INVALID_READ_MODE = 0xC00000B4;
+pub const IO_TIMEOUT = 0xC00000B5;
+pub const FILE_FORCED_CLOSED = 0xC00000B6;
+pub const PROFILING_NOT_STARTED = 0xC00000B7;
+pub const PROFILING_NOT_STOPPED = 0xC00000B8;
+pub const COULD_NOT_INTERPRET = 0xC00000B9;
pub const FILE_IS_A_DIRECTORY = 0xC00000BA;
+pub const NOT_SUPPORTED = 0xC00000BB;
+pub const REMOTE_NOT_LISTENING = 0xC00000BC;
+pub const DUPLICATE_NAME = 0xC00000BD;
+pub const BAD_NETWORK_PATH = 0xC00000BE;
+pub const NETWORK_BUSY = 0xC00000BF;
+pub const DEVICE_DOES_NOT_EXIST = 0xC00000C0;
+pub const TOO_MANY_COMMANDS = 0xC00000C1;
+pub const ADAPTER_HARDWARE_ERROR = 0xC00000C2;
+pub const INVALID_NETWORK_RESPONSE = 0xC00000C3;
+pub const UNEXPECTED_NETWORK_ERROR = 0xC00000C4;
+pub const BAD_REMOTE_ADAPTER = 0xC00000C5;
+pub const PRINT_QUEUE_FULL = 0xC00000C6;
+pub const NO_SPOOL_SPACE = 0xC00000C7;
+pub const PRINT_CANCELLED = 0xC00000C8;
+pub const NETWORK_NAME_DELETED = 0xC00000C9;
+pub const NETWORK_ACCESS_DENIED = 0xC00000CA;
+pub const BAD_DEVICE_TYPE = 0xC00000CB;
+pub const BAD_NETWORK_NAME = 0xC00000CC;
+pub const TOO_MANY_NAMES = 0xC00000CD;
+pub const TOO_MANY_SESSIONS = 0xC00000CE;
+pub const SHARING_PAUSED = 0xC00000CF;
+pub const REQUEST_NOT_ACCEPTED = 0xC00000D0;
+pub const REDIRECTOR_PAUSED = 0xC00000D1;
+pub const NET_WRITE_FAULT = 0xC00000D2;
+pub const PROFILING_AT_LIMIT = 0xC00000D3;
+pub const NOT_SAME_DEVICE = 0xC00000D4;
+pub const FILE_RENAMED = 0xC00000D5;
+pub const VIRTUAL_CIRCUIT_CLOSED = 0xC00000D6;
+pub const NO_SECURITY_ON_OBJECT = 0xC00000D7;
+pub const CANT_WAIT = 0xC00000D8;
+pub const PIPE_EMPTY = 0xC00000D9;
+pub const CANT_ACCESS_DOMAIN_INFO = 0xC00000DA;
+pub const CANT_TERMINATE_SELF = 0xC00000DB;
+pub const INVALID_SERVER_STATE = 0xC00000DC;
+pub const INVALID_DOMAIN_STATE = 0xC00000DD;
+pub const INVALID_DOMAIN_ROLE = 0xC00000DE;
+pub const NO_SUCH_DOMAIN = 0xC00000DF;
+pub const DOMAIN_EXISTS = 0xC00000E0;
+pub const DOMAIN_LIMIT_EXCEEDED = 0xC00000E1;
+pub const OPLOCK_NOT_GRANTED = 0xC00000E2;
+pub const INVALID_OPLOCK_PROTOCOL = 0xC00000E3;
+pub const INTERNAL_DB_CORRUPTION = 0xC00000E4;
+pub const INTERNAL_ERROR = 0xC00000E5;
+pub const GENERIC_NOT_MAPPED = 0xC00000E6;
+pub const BAD_DESCRIPTOR_FORMAT = 0xC00000E7;
+pub const INVALID_USER_BUFFER = 0xC00000E8;
+pub const UNEXPECTED_IO_ERROR = 0xC00000E9;
+pub const UNEXPECTED_MM_CREATE_ERR = 0xC00000EA;
+pub const UNEXPECTED_MM_MAP_ERROR = 0xC00000EB;
+pub const UNEXPECTED_MM_EXTEND_ERR = 0xC00000EC;
+pub const NOT_LOGON_PROCESS = 0xC00000ED;
+pub const LOGON_SESSION_EXISTS = 0xC00000EE;
+pub const INVALID_PARAMETER_1 = 0xC00000EF;
+pub const INVALID_PARAMETER_2 = 0xC00000F0;
+pub const INVALID_PARAMETER_3 = 0xC00000F1;
+pub const INVALID_PARAMETER_4 = 0xC00000F2;
+pub const INVALID_PARAMETER_5 = 0xC00000F3;
+pub const INVALID_PARAMETER_6 = 0xC00000F4;
+pub const INVALID_PARAMETER_7 = 0xC00000F5;
+pub const INVALID_PARAMETER_8 = 0xC00000F6;
+pub const INVALID_PARAMETER_9 = 0xC00000F7;
+pub const INVALID_PARAMETER_10 = 0xC00000F8;
+pub const INVALID_PARAMETER_11 = 0xC00000F9;
+pub const INVALID_PARAMETER_12 = 0xC00000FA;
+pub const REDIRECTOR_NOT_STARTED = 0xC00000FB;
+pub const REDIRECTOR_STARTED = 0xC00000FC;
+pub const STACK_OVERFLOW = 0xC00000FD;
+pub const NO_SUCH_PACKAGE = 0xC00000FE;
+pub const BAD_FUNCTION_TABLE = 0xC00000FF;
+pub const VARIABLE_NOT_FOUND = 0xC0000100;
+pub const DIRECTORY_NOT_EMPTY = 0xC0000101;
+pub const FILE_CORRUPT_ERROR = 0xC0000102;
+pub const NOT_A_DIRECTORY = 0xC0000103;
+pub const BAD_LOGON_SESSION_STATE = 0xC0000104;
+pub const LOGON_SESSION_COLLISION = 0xC0000105;
+pub const NAME_TOO_LONG = 0xC0000106;
+pub const FILES_OPEN = 0xC0000107;
+pub const CONNECTION_IN_USE = 0xC0000108;
+pub const MESSAGE_NOT_FOUND = 0xC0000109;
+pub const PROCESS_IS_TERMINATING = 0xC000010A;
+pub const INVALID_LOGON_TYPE = 0xC000010B;
+pub const NO_GUID_TRANSLATION = 0xC000010C;
+pub const CANNOT_IMPERSONATE = 0xC000010D;
+pub const IMAGE_ALREADY_LOADED = 0xC000010E;
+pub const NO_LDT = 0xC0000117;
+pub const INVALID_LDT_SIZE = 0xC0000118;
+pub const INVALID_LDT_OFFSET = 0xC0000119;
+pub const INVALID_LDT_DESCRIPTOR = 0xC000011A;
+pub const INVALID_IMAGE_NE_FORMAT = 0xC000011B;
+pub const RXACT_INVALID_STATE = 0xC000011C;
+pub const RXACT_COMMIT_FAILURE = 0xC000011D;
+pub const MAPPED_FILE_SIZE_ZERO = 0xC000011E;
+pub const TOO_MANY_OPENED_FILES = 0xC000011F;
+pub const CANCELLED = 0xC0000120;
+pub const CANNOT_DELETE = 0xC0000121;
+pub const INVALID_COMPUTER_NAME = 0xC0000122;
+pub const FILE_DELETED = 0xC0000123;
+pub const SPECIAL_ACCOUNT = 0xC0000124;
+pub const SPECIAL_GROUP = 0xC0000125;
+pub const SPECIAL_USER = 0xC0000126;
+pub const MEMBERS_PRIMARY_GROUP = 0xC0000127;
+pub const FILE_CLOSED = 0xC0000128;
+pub const TOO_MANY_THREADS = 0xC0000129;
+pub const THREAD_NOT_IN_PROCESS = 0xC000012A;
+pub const TOKEN_ALREADY_IN_USE = 0xC000012B;
+pub const PAGEFILE_QUOTA_EXCEEDED = 0xC000012C;
+pub const COMMITMENT_LIMIT = 0xC000012D;
+pub const INVALID_IMAGE_LE_FORMAT = 0xC000012E;
+pub const INVALID_IMAGE_NOT_MZ = 0xC000012F;
+pub const INVALID_IMAGE_PROTECT = 0xC0000130;
+pub const INVALID_IMAGE_WIN_16 = 0xC0000131;
+pub const LOGON_SERVER_CONFLICT = 0xC0000132;
+pub const TIME_DIFFERENCE_AT_DC = 0xC0000133;
+pub const SYNCHRONIZATION_REQUIRED = 0xC0000134;
+pub const DLL_NOT_FOUND = 0xC0000135;
+pub const OPEN_FAILED = 0xC0000136;
+pub const IO_PRIVILEGE_FAILED = 0xC0000137;
+pub const ORDINAL_NOT_FOUND = 0xC0000138;
+pub const ENTRYPOINT_NOT_FOUND = 0xC0000139;
+pub const CONTROL_C_EXIT = 0xC000013A;
+pub const LOCAL_DISCONNECT = 0xC000013B;
+pub const REMOTE_DISCONNECT = 0xC000013C;
+pub const REMOTE_RESOURCES = 0xC000013D;
+pub const LINK_FAILED = 0xC000013E;
+pub const LINK_TIMEOUT = 0xC000013F;
+pub const INVALID_CONNECTION = 0xC0000140;
+pub const INVALID_ADDRESS = 0xC0000141;
+pub const DLL_INIT_FAILED = 0xC0000142;
+pub const MISSING_SYSTEMFILE = 0xC0000143;
+pub const UNHANDLED_EXCEPTION = 0xC0000144;
+pub const APP_INIT_FAILURE = 0xC0000145;
+pub const PAGEFILE_CREATE_FAILED = 0xC0000146;
+pub const NO_PAGEFILE = 0xC0000147;
+pub const INVALID_LEVEL = 0xC0000148;
+pub const WRONG_PASSWORD_CORE = 0xC0000149;
+pub const ILLEGAL_FLOAT_CONTEXT = 0xC000014A;
+pub const PIPE_BROKEN = 0xC000014B;
+pub const REGISTRY_CORRUPT = 0xC000014C;
+pub const REGISTRY_IO_FAILED = 0xC000014D;
+pub const NO_EVENT_PAIR = 0xC000014E;
+pub const UNRECOGNIZED_VOLUME = 0xC000014F;
+pub const SERIAL_NO_DEVICE_INITED = 0xC0000150;
+pub const NO_SUCH_ALIAS = 0xC0000151;
+pub const MEMBER_NOT_IN_ALIAS = 0xC0000152;
+pub const MEMBER_IN_ALIAS = 0xC0000153;
+pub const ALIAS_EXISTS = 0xC0000154;
+pub const LOGON_NOT_GRANTED = 0xC0000155;
+pub const TOO_MANY_SECRETS = 0xC0000156;
+pub const SECRET_TOO_LONG = 0xC0000157;
+pub const INTERNAL_DB_ERROR = 0xC0000158;
+pub const FULLSCREEN_MODE = 0xC0000159;
+pub const TOO_MANY_CONTEXT_IDS = 0xC000015A;
+pub const LOGON_TYPE_NOT_GRANTED = 0xC000015B;
+pub const NOT_REGISTRY_FILE = 0xC000015C;
+pub const NT_CROSS_ENCRYPTION_REQUIRED = 0xC000015D;
+pub const DOMAIN_CTRLR_CONFIG_ERROR = 0xC000015E;
+pub const FT_MISSING_MEMBER = 0xC000015F;
+pub const ILL_FORMED_SERVICE_ENTRY = 0xC0000160;
+pub const ILLEGAL_CHARACTER = 0xC0000161;
+pub const UNMAPPABLE_CHARACTER = 0xC0000162;
+pub const UNDEFINED_CHARACTER = 0xC0000163;
+pub const FLOPPY_VOLUME = 0xC0000164;
+pub const FLOPPY_ID_MARK_NOT_FOUND = 0xC0000165;
+pub const FLOPPY_WRONG_CYLINDER = 0xC0000166;
+pub const FLOPPY_UNKNOWN_ERROR = 0xC0000167;
+pub const FLOPPY_BAD_REGISTERS = 0xC0000168;
+pub const DISK_RECALIBRATE_FAILED = 0xC0000169;
+pub const DISK_OPERATION_FAILED = 0xC000016A;
+pub const DISK_RESET_FAILED = 0xC000016B;
+pub const SHARED_IRQ_BUSY = 0xC000016C;
+pub const FT_ORPHANING = 0xC000016D;
+pub const BIOS_FAILED_TO_CONNECT_INTERRUPT = 0xC000016E;
+pub const PARTITION_FAILURE = 0xC0000172;
+pub const INVALID_BLOCK_LENGTH = 0xC0000173;
+pub const DEVICE_NOT_PARTITIONED = 0xC0000174;
+pub const UNABLE_TO_LOCK_MEDIA = 0xC0000175;
+pub const UNABLE_TO_UNLOAD_MEDIA = 0xC0000176;
+pub const EOM_OVERFLOW = 0xC0000177;
+pub const NO_MEDIA = 0xC0000178;
+pub const NO_SUCH_MEMBER = 0xC000017A;
+pub const INVALID_MEMBER = 0xC000017B;
+pub const KEY_DELETED = 0xC000017C;
+pub const NO_LOG_SPACE = 0xC000017D;
+pub const TOO_MANY_SIDS = 0xC000017E;
+pub const LM_CROSS_ENCRYPTION_REQUIRED = 0xC000017F;
+pub const KEY_HAS_CHILDREN = 0xC0000180;
+pub const CHILD_MUST_BE_VOLATILE = 0xC0000181;
+pub const DEVICE_CONFIGURATION_ERROR = 0xC0000182;
+pub const DRIVER_INTERNAL_ERROR = 0xC0000183;
+pub const INVALID_DEVICE_STATE = 0xC0000184;
+pub const IO_DEVICE_ERROR = 0xC0000185;
+pub const DEVICE_PROTOCOL_ERROR = 0xC0000186;
+pub const BACKUP_CONTROLLER = 0xC0000187;
+pub const LOG_FILE_FULL = 0xC0000188;
+pub const TOO_LATE = 0xC0000189;
+pub const NO_TRUST_LSA_SECRET = 0xC000018A;
+pub const NO_TRUST_SAM_ACCOUNT = 0xC000018B;
+pub const TRUSTED_DOMAIN_FAILURE = 0xC000018C;
+pub const TRUSTED_RELATIONSHIP_FAILURE = 0xC000018D;
+pub const EVENTLOG_FILE_CORRUPT = 0xC000018E;
+pub const EVENTLOG_CANT_START = 0xC000018F;
+pub const TRUST_FAILURE = 0xC0000190;
+pub const MUTANT_LIMIT_EXCEEDED = 0xC0000191;
+pub const NETLOGON_NOT_STARTED = 0xC0000192;
+pub const ACCOUNT_EXPIRED = 0xC0000193;
+pub const POSSIBLE_DEADLOCK = 0xC0000194;
+pub const NETWORK_CREDENTIAL_CONFLICT = 0xC0000195;
+pub const REMOTE_SESSION_LIMIT = 0xC0000196;
+pub const EVENTLOG_FILE_CHANGED = 0xC0000197;
+pub const NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 0xC0000198;
+pub const NOLOGON_WORKSTATION_TRUST_ACCOUNT = 0xC0000199;
+pub const NOLOGON_SERVER_TRUST_ACCOUNT = 0xC000019A;
+pub const DOMAIN_TRUST_INCONSISTENT = 0xC000019B;
+pub const FS_DRIVER_REQUIRED = 0xC000019C;
+pub const IMAGE_ALREADY_LOADED_AS_DLL = 0xC000019D;
+pub const INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING = 0xC000019E;
+pub const SHORT_NAMES_NOT_ENABLED_ON_VOLUME = 0xC000019F;
+pub const SECURITY_STREAM_IS_INCONSISTENT = 0xC00001A0;
+pub const INVALID_LOCK_RANGE = 0xC00001A1;
+pub const INVALID_ACE_CONDITION = 0xC00001A2;
+pub const IMAGE_SUBSYSTEM_NOT_PRESENT = 0xC00001A3;
+pub const NOTIFICATION_GUID_ALREADY_DEFINED = 0xC00001A4;
+pub const NETWORK_OPEN_RESTRICTION = 0xC0000201;
+pub const NO_USER_SESSION_KEY = 0xC0000202;
+pub const USER_SESSION_DELETED = 0xC0000203;
+pub const RESOURCE_LANG_NOT_FOUND = 0xC0000204;
+pub const INSUFF_SERVER_RESOURCES = 0xC0000205;
+pub const INVALID_BUFFER_SIZE = 0xC0000206;
+pub const INVALID_ADDRESS_COMPONENT = 0xC0000207;
+pub const INVALID_ADDRESS_WILDCARD = 0xC0000208;
+pub const TOO_MANY_ADDRESSES = 0xC0000209;
+pub const ADDRESS_ALREADY_EXISTS = 0xC000020A;
+pub const ADDRESS_CLOSED = 0xC000020B;
+pub const CONNECTION_DISCONNECTED = 0xC000020C;
+pub const CONNECTION_RESET = 0xC000020D;
+pub const TOO_MANY_NODES = 0xC000020E;
+pub const TRANSACTION_ABORTED = 0xC000020F;
+pub const TRANSACTION_TIMED_OUT = 0xC0000210;
+pub const TRANSACTION_NO_RELEASE = 0xC0000211;
+pub const TRANSACTION_NO_MATCH = 0xC0000212;
+pub const TRANSACTION_RESPONDED = 0xC0000213;
+pub const TRANSACTION_INVALID_ID = 0xC0000214;
+pub const TRANSACTION_INVALID_TYPE = 0xC0000215;
+pub const NOT_SERVER_SESSION = 0xC0000216;
+pub const NOT_CLIENT_SESSION = 0xC0000217;
+pub const CANNOT_LOAD_REGISTRY_FILE = 0xC0000218;
+pub const DEBUG_ATTACH_FAILED = 0xC0000219;
+pub const SYSTEM_PROCESS_TERMINATED = 0xC000021A;
+pub const DATA_NOT_ACCEPTED = 0xC000021B;
+pub const NO_BROWSER_SERVERS_FOUND = 0xC000021C;
+pub const VDM_HARD_ERROR = 0xC000021D;
+pub const DRIVER_CANCEL_TIMEOUT = 0xC000021E;
+pub const REPLY_MESSAGE_MISMATCH = 0xC000021F;
+pub const MAPPED_ALIGNMENT = 0xC0000220;
+pub const IMAGE_CHECKSUM_MISMATCH = 0xC0000221;
+pub const LOST_WRITEBEHIND_DATA = 0xC0000222;
+pub const CLIENT_SERVER_PARAMETERS_INVALID = 0xC0000223;
+pub const PASSWORD_MUST_CHANGE = 0xC0000224;
+pub const NOT_FOUND = 0xC0000225;
+pub const NOT_TINY_STREAM = 0xC0000226;
+pub const RECOVERY_FAILURE = 0xC0000227;
+pub const STACK_OVERFLOW_READ = 0xC0000228;
+pub const FAIL_CHECK = 0xC0000229;
+pub const DUPLICATE_OBJECTID = 0xC000022A;
+pub const OBJECTID_EXISTS = 0xC000022B;
+pub const CONVERT_TO_LARGE = 0xC000022C;
+pub const RETRY = 0xC000022D;
+pub const FOUND_OUT_OF_SCOPE = 0xC000022E;
+pub const ALLOCATE_BUCKET = 0xC000022F;
+pub const PROPSET_NOT_FOUND = 0xC0000230;
+pub const MARSHALL_OVERFLOW = 0xC0000231;
+pub const INVALID_VARIANT = 0xC0000232;
+pub const DOMAIN_CONTROLLER_NOT_FOUND = 0xC0000233;
+pub const ACCOUNT_LOCKED_OUT = 0xC0000234;
+pub const HANDLE_NOT_CLOSABLE = 0xC0000235;
+pub const CONNECTION_REFUSED = 0xC0000236;
+pub const GRACEFUL_DISCONNECT = 0xC0000237;
+pub const ADDRESS_ALREADY_ASSOCIATED = 0xC0000238;
+pub const ADDRESS_NOT_ASSOCIATED = 0xC0000239;
+pub const CONNECTION_INVALID = 0xC000023A;
+pub const CONNECTION_ACTIVE = 0xC000023B;
+pub const NETWORK_UNREACHABLE = 0xC000023C;
+pub const HOST_UNREACHABLE = 0xC000023D;
+pub const PROTOCOL_UNREACHABLE = 0xC000023E;
+pub const PORT_UNREACHABLE = 0xC000023F;
+pub const REQUEST_ABORTED = 0xC0000240;
+pub const CONNECTION_ABORTED = 0xC0000241;
+pub const BAD_COMPRESSION_BUFFER = 0xC0000242;
+pub const USER_MAPPED_FILE = 0xC0000243;
+pub const AUDIT_FAILED = 0xC0000244;
+pub const TIMER_RESOLUTION_NOT_SET = 0xC0000245;
+pub const CONNECTION_COUNT_LIMIT = 0xC0000246;
+pub const LOGIN_TIME_RESTRICTION = 0xC0000247;
+pub const LOGIN_WKSTA_RESTRICTION = 0xC0000248;
+pub const IMAGE_MP_UP_MISMATCH = 0xC0000249;
+pub const INSUFFICIENT_LOGON_INFO = 0xC0000250;
+pub const BAD_DLL_ENTRYPOINT = 0xC0000251;
+pub const BAD_SERVICE_ENTRYPOINT = 0xC0000252;
+pub const LPC_REPLY_LOST = 0xC0000253;
+pub const IP_ADDRESS_CONFLICT1 = 0xC0000254;
+pub const IP_ADDRESS_CONFLICT2 = 0xC0000255;
+pub const REGISTRY_QUOTA_LIMIT = 0xC0000256;
+pub const PATH_NOT_COVERED = 0xC0000257;
+pub const NO_CALLBACK_ACTIVE = 0xC0000258;
+pub const LICENSE_QUOTA_EXCEEDED = 0xC0000259;
+pub const PWD_TOO_SHORT = 0xC000025A;
+pub const PWD_TOO_RECENT = 0xC000025B;
+pub const PWD_HISTORY_CONFLICT = 0xC000025C;
+pub const PLUGPLAY_NO_DEVICE = 0xC000025E;
+pub const UNSUPPORTED_COMPRESSION = 0xC000025F;
+pub const INVALID_HW_PROFILE = 0xC0000260;
+pub const INVALID_PLUGPLAY_DEVICE_PATH = 0xC0000261;
+pub const DRIVER_ORDINAL_NOT_FOUND = 0xC0000262;
+pub const DRIVER_ENTRYPOINT_NOT_FOUND = 0xC0000263;
+pub const RESOURCE_NOT_OWNED = 0xC0000264;
+pub const TOO_MANY_LINKS = 0xC0000265;
+pub const QUOTA_LIST_INCONSISTENT = 0xC0000266;
+pub const FILE_IS_OFFLINE = 0xC0000267;
+pub const EVALUATION_EXPIRATION = 0xC0000268;
+pub const ILLEGAL_DLL_RELOCATION = 0xC0000269;
+pub const LICENSE_VIOLATION = 0xC000026A;
+pub const DLL_INIT_FAILED_LOGOFF = 0xC000026B;
+pub const DRIVER_UNABLE_TO_LOAD = 0xC000026C;
+pub const DFS_UNAVAILABLE = 0xC000026D;
+pub const VOLUME_DISMOUNTED = 0xC000026E;
+pub const WX86_INTERNAL_ERROR = 0xC000026F;
+pub const WX86_FLOAT_STACK_CHECK = 0xC0000270;
+pub const VALIDATE_CONTINUE = 0xC0000271;
+pub const NO_MATCH = 0xC0000272;
+pub const NO_MORE_MATCHES = 0xC0000273;
+pub const NOT_A_REPARSE_POINT = 0xC0000275;
+pub const IO_REPARSE_TAG_INVALID = 0xC0000276;
+pub const IO_REPARSE_TAG_MISMATCH = 0xC0000277;
+pub const IO_REPARSE_DATA_INVALID = 0xC0000278;
+pub const IO_REPARSE_TAG_NOT_HANDLED = 0xC0000279;
+pub const REPARSE_POINT_NOT_RESOLVED = 0xC0000280;
+pub const DIRECTORY_IS_A_REPARSE_POINT = 0xC0000281;
+pub const RANGE_LIST_CONFLICT = 0xC0000282;
+pub const SOURCE_ELEMENT_EMPTY = 0xC0000283;
+pub const DESTINATION_ELEMENT_FULL = 0xC0000284;
+pub const ILLEGAL_ELEMENT_ADDRESS = 0xC0000285;
+pub const MAGAZINE_NOT_PRESENT = 0xC0000286;
+pub const REINITIALIZATION_NEEDED = 0xC0000287;
+pub const ENCRYPTION_FAILED = 0xC000028A;
+pub const DECRYPTION_FAILED = 0xC000028B;
+pub const RANGE_NOT_FOUND = 0xC000028C;
+pub const NO_RECOVERY_POLICY = 0xC000028D;
+pub const NO_EFS = 0xC000028E;
+pub const WRONG_EFS = 0xC000028F;
+pub const NO_USER_KEYS = 0xC0000290;
+pub const FILE_NOT_ENCRYPTED = 0xC0000291;
+pub const NOT_EXPORT_FORMAT = 0xC0000292;
+pub const FILE_ENCRYPTED = 0xC0000293;
+pub const WMI_GUID_NOT_FOUND = 0xC0000295;
+pub const WMI_INSTANCE_NOT_FOUND = 0xC0000296;
+pub const WMI_ITEMID_NOT_FOUND = 0xC0000297;
+pub const WMI_TRY_AGAIN = 0xC0000298;
+pub const SHARED_POLICY = 0xC0000299;
+pub const POLICY_OBJECT_NOT_FOUND = 0xC000029A;
+pub const POLICY_ONLY_IN_DS = 0xC000029B;
+pub const VOLUME_NOT_UPGRADED = 0xC000029C;
+pub const REMOTE_STORAGE_NOT_ACTIVE = 0xC000029D;
+pub const REMOTE_STORAGE_MEDIA_ERROR = 0xC000029E;
+pub const NO_TRACKING_SERVICE = 0xC000029F;
+pub const SERVER_SID_MISMATCH = 0xC00002A0;
+pub const DS_NO_ATTRIBUTE_OR_VALUE = 0xC00002A1;
+pub const DS_INVALID_ATTRIBUTE_SYNTAX = 0xC00002A2;
+pub const DS_ATTRIBUTE_TYPE_UNDEFINED = 0xC00002A3;
+pub const DS_ATTRIBUTE_OR_VALUE_EXISTS = 0xC00002A4;
+pub const DS_BUSY = 0xC00002A5;
+pub const DS_UNAVAILABLE = 0xC00002A6;
+pub const DS_NO_RIDS_ALLOCATED = 0xC00002A7;
+pub const DS_NO_MORE_RIDS = 0xC00002A8;
+pub const DS_INCORRECT_ROLE_OWNER = 0xC00002A9;
+pub const DS_RIDMGR_INIT_ERROR = 0xC00002AA;
+pub const DS_OBJ_CLASS_VIOLATION = 0xC00002AB;
+pub const DS_CANT_ON_NON_LEAF = 0xC00002AC;
+pub const DS_CANT_ON_RDN = 0xC00002AD;
+pub const DS_CANT_MOD_OBJ_CLASS = 0xC00002AE;
+pub const DS_CROSS_DOM_MOVE_FAILED = 0xC00002AF;
+pub const DS_GC_NOT_AVAILABLE = 0xC00002B0;
+pub const DIRECTORY_SERVICE_REQUIRED = 0xC00002B1;
+pub const REPARSE_ATTRIBUTE_CONFLICT = 0xC00002B2;
+pub const CANT_ENABLE_DENY_ONLY = 0xC00002B3;
+pub const FLOAT_MULTIPLE_FAULTS = 0xC00002B4;
+pub const FLOAT_MULTIPLE_TRAPS = 0xC00002B5;
+pub const DEVICE_REMOVED = 0xC00002B6;
+pub const JOURNAL_DELETE_IN_PROGRESS = 0xC00002B7;
+pub const JOURNAL_NOT_ACTIVE = 0xC00002B8;
+pub const NOINTERFACE = 0xC00002B9;
+pub const DS_ADMIN_LIMIT_EXCEEDED = 0xC00002C1;
+pub const DRIVER_FAILED_SLEEP = 0xC00002C2;
+pub const MUTUAL_AUTHENTICATION_FAILED = 0xC00002C3;
+pub const CORRUPT_SYSTEM_FILE = 0xC00002C4;
+pub const DATATYPE_MISALIGNMENT_ERROR = 0xC00002C5;
+pub const WMI_READ_ONLY = 0xC00002C6;
+pub const WMI_SET_FAILURE = 0xC00002C7;
+pub const COMMITMENT_MINIMUM = 0xC00002C8;
+pub const REG_NAT_CONSUMPTION = 0xC00002C9;
+pub const TRANSPORT_FULL = 0xC00002CA;
+pub const DS_SAM_INIT_FAILURE = 0xC00002CB;
+pub const ONLY_IF_CONNECTED = 0xC00002CC;
+pub const DS_SENSITIVE_GROUP_VIOLATION = 0xC00002CD;
+pub const PNP_RESTART_ENUMERATION = 0xC00002CE;
+pub const JOURNAL_ENTRY_DELETED = 0xC00002CF;
+pub const DS_CANT_MOD_PRIMARYGROUPID = 0xC00002D0;
+pub const SYSTEM_IMAGE_BAD_SIGNATURE = 0xC00002D1;
+pub const PNP_REBOOT_REQUIRED = 0xC00002D2;
+pub const POWER_STATE_INVALID = 0xC00002D3;
+pub const DS_INVALID_GROUP_TYPE = 0xC00002D4;
+pub const DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN = 0xC00002D5;
+pub const DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN = 0xC00002D6;
+pub const DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER = 0xC00002D7;
+pub const DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER = 0xC00002D8;
+pub const DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER = 0xC00002D9;
+pub const DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER = 0xC00002DA;
+pub const DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER = 0xC00002DB;
+pub const DS_HAVE_PRIMARY_MEMBERS = 0xC00002DC;
+pub const WMI_NOT_SUPPORTED = 0xC00002DD;
+pub const INSUFFICIENT_POWER = 0xC00002DE;
+pub const SAM_NEED_BOOTKEY_PASSWORD = 0xC00002DF;
+pub const SAM_NEED_BOOTKEY_FLOPPY = 0xC00002E0;
+pub const DS_CANT_START = 0xC00002E1;
+pub const DS_INIT_FAILURE = 0xC00002E2;
+pub const SAM_INIT_FAILURE = 0xC00002E3;
+pub const DS_GC_REQUIRED = 0xC00002E4;
+pub const DS_LOCAL_MEMBER_OF_LOCAL_ONLY = 0xC00002E5;
+pub const DS_NO_FPO_IN_UNIVERSAL_GROUPS = 0xC00002E6;
+pub const DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED = 0xC00002E7;
+pub const CURRENT_DOMAIN_NOT_ALLOWED = 0xC00002E9;
+pub const CANNOT_MAKE = 0xC00002EA;
+pub const SYSTEM_SHUTDOWN = 0xC00002EB;
+pub const DS_INIT_FAILURE_CONSOLE = 0xC00002EC;
+pub const DS_SAM_INIT_FAILURE_CONSOLE = 0xC00002ED;
+pub const UNFINISHED_CONTEXT_DELETED = 0xC00002EE;
+pub const NO_TGT_REPLY = 0xC00002EF;
+pub const OBJECTID_NOT_FOUND = 0xC00002F0;
+pub const NO_IP_ADDRESSES = 0xC00002F1;
+pub const WRONG_CREDENTIAL_HANDLE = 0xC00002F2;
+pub const CRYPTO_SYSTEM_INVALID = 0xC00002F3;
+pub const MAX_REFERRALS_EXCEEDED = 0xC00002F4;
+pub const MUST_BE_KDC = 0xC00002F5;
+pub const STRONG_CRYPTO_NOT_SUPPORTED = 0xC00002F6;
+pub const TOO_MANY_PRINCIPALS = 0xC00002F7;
+pub const NO_PA_DATA = 0xC00002F8;
+pub const PKINIT_NAME_MISMATCH = 0xC00002F9;
+pub const SMARTCARD_LOGON_REQUIRED = 0xC00002FA;
+pub const KDC_INVALID_REQUEST = 0xC00002FB;
+pub const KDC_UNABLE_TO_REFER = 0xC00002FC;
+pub const KDC_UNKNOWN_ETYPE = 0xC00002FD;
+pub const SHUTDOWN_IN_PROGRESS = 0xC00002FE;
+pub const SERVER_SHUTDOWN_IN_PROGRESS = 0xC00002FF;
+pub const NOT_SUPPORTED_ON_SBS = 0xC0000300;
+pub const WMI_GUID_DISCONNECTED = 0xC0000301;
+pub const WMI_ALREADY_DISABLED = 0xC0000302;
+pub const WMI_ALREADY_ENABLED = 0xC0000303;
+pub const MFT_TOO_FRAGMENTED = 0xC0000304;
+pub const COPY_PROTECTION_FAILURE = 0xC0000305;
+pub const CSS_AUTHENTICATION_FAILURE = 0xC0000306;
+pub const CSS_KEY_NOT_PRESENT = 0xC0000307;
+pub const CSS_KEY_NOT_ESTABLISHED = 0xC0000308;
+pub const CSS_SCRAMBLED_SECTOR = 0xC0000309;
+pub const CSS_REGION_MISMATCH = 0xC000030A;
+pub const CSS_RESETS_EXHAUSTED = 0xC000030B;
+pub const PKINIT_FAILURE = 0xC0000320;
+pub const SMARTCARD_SUBSYSTEM_FAILURE = 0xC0000321;
+pub const NO_KERB_KEY = 0xC0000322;
+pub const HOST_DOWN = 0xC0000350;
+pub const UNSUPPORTED_PREAUTH = 0xC0000351;
+pub const EFS_ALG_BLOB_TOO_BIG = 0xC0000352;
+pub const PORT_NOT_SET = 0xC0000353;
+pub const DEBUGGER_INACTIVE = 0xC0000354;
+pub const DS_VERSION_CHECK_FAILURE = 0xC0000355;
+pub const AUDITING_DISABLED = 0xC0000356;
+pub const PRENT4_MACHINE_ACCOUNT = 0xC0000357;
+pub const DS_AG_CANT_HAVE_UNIVERSAL_MEMBER = 0xC0000358;
+pub const INVALID_IMAGE_WIN_32 = 0xC0000359;
+pub const INVALID_IMAGE_WIN_64 = 0xC000035A;
+pub const BAD_BINDINGS = 0xC000035B;
+pub const NETWORK_SESSION_EXPIRED = 0xC000035C;
+pub const APPHELP_BLOCK = 0xC000035D;
+pub const ALL_SIDS_FILTERED = 0xC000035E;
+pub const NOT_SAFE_MODE_DRIVER = 0xC000035F;
+pub const ACCESS_DISABLED_BY_POLICY_DEFAULT = 0xC0000361;
+pub const ACCESS_DISABLED_BY_POLICY_PATH = 0xC0000362;
+pub const ACCESS_DISABLED_BY_POLICY_PUBLISHER = 0xC0000363;
+pub const ACCESS_DISABLED_BY_POLICY_OTHER = 0xC0000364;
+pub const FAILED_DRIVER_ENTRY = 0xC0000365;
+pub const DEVICE_ENUMERATION_ERROR = 0xC0000366;
+pub const MOUNT_POINT_NOT_RESOLVED = 0xC0000368;
+pub const INVALID_DEVICE_OBJECT_PARAMETER = 0xC0000369;
+pub const MCA_OCCURED = 0xC000036A;
+pub const DRIVER_BLOCKED_CRITICAL = 0xC000036B;
+pub const DRIVER_BLOCKED = 0xC000036C;
+pub const DRIVER_DATABASE_ERROR = 0xC000036D;
+pub const SYSTEM_HIVE_TOO_LARGE = 0xC000036E;
+pub const INVALID_IMPORT_OF_NON_DLL = 0xC000036F;
+pub const NO_SECRETS = 0xC0000371;
+pub const ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY = 0xC0000372;
+pub const FAILED_STACK_SWITCH = 0xC0000373;
+pub const HEAP_CORRUPTION = 0xC0000374;
+pub const SMARTCARD_WRONG_PIN = 0xC0000380;
+pub const SMARTCARD_CARD_BLOCKED = 0xC0000381;
+pub const SMARTCARD_CARD_NOT_AUTHENTICATED = 0xC0000382;
+pub const SMARTCARD_NO_CARD = 0xC0000383;
+pub const SMARTCARD_NO_KEY_CONTAINER = 0xC0000384;
+pub const SMARTCARD_NO_CERTIFICATE = 0xC0000385;
+pub const SMARTCARD_NO_KEYSET = 0xC0000386;
+pub const SMARTCARD_IO_ERROR = 0xC0000387;
+pub const DOWNGRADE_DETECTED = 0xC0000388;
+pub const SMARTCARD_CERT_REVOKED = 0xC0000389;
+pub const ISSUING_CA_UNTRUSTED = 0xC000038A;
+pub const REVOCATION_OFFLINE_C = 0xC000038B;
+pub const PKINIT_CLIENT_FAILURE = 0xC000038C;
+pub const SMARTCARD_CERT_EXPIRED = 0xC000038D;
+pub const DRIVER_FAILED_PRIOR_UNLOAD = 0xC000038E;
+pub const SMARTCARD_SILENT_CONTEXT = 0xC000038F;
+pub const PER_USER_TRUST_QUOTA_EXCEEDED = 0xC0000401;
+pub const ALL_USER_TRUST_QUOTA_EXCEEDED = 0xC0000402;
+pub const USER_DELETE_TRUST_QUOTA_EXCEEDED = 0xC0000403;
+pub const DS_NAME_NOT_UNIQUE = 0xC0000404;
+pub const DS_DUPLICATE_ID_FOUND = 0xC0000405;
+pub const DS_GROUP_CONVERSION_ERROR = 0xC0000406;
+pub const VOLSNAP_PREPARE_HIBERNATE = 0xC0000407;
+pub const USER2USER_REQUIRED = 0xC0000408;
+pub const STACK_BUFFER_OVERRUN = 0xC0000409;
+pub const NO_S4U_PROT_SUPPORT = 0xC000040A;
+pub const CROSSREALM_DELEGATION_FAILURE = 0xC000040B;
+pub const REVOCATION_OFFLINE_KDC = 0xC000040C;
+pub const ISSUING_CA_UNTRUSTED_KDC = 0xC000040D;
+pub const KDC_CERT_EXPIRED = 0xC000040E;
+pub const KDC_CERT_REVOKED = 0xC000040F;
+pub const PARAMETER_QUOTA_EXCEEDED = 0xC0000410;
+pub const HIBERNATION_FAILURE = 0xC0000411;
+pub const DELAY_LOAD_FAILED = 0xC0000412;
+pub const AUTHENTICATION_FIREWALL_FAILED = 0xC0000413;
+pub const VDM_DISALLOWED = 0xC0000414;
+pub const HUNG_DISPLAY_DRIVER_THREAD = 0xC0000415;
+pub const INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE = 0xC0000416;
+pub const INVALID_CRUNTIME_PARAMETER = 0xC0000417;
+pub const NTLM_BLOCKED = 0xC0000418;
+pub const DS_SRC_SID_EXISTS_IN_FOREST = 0xC0000419;
+pub const DS_DOMAIN_NAME_EXISTS_IN_FOREST = 0xC000041A;
+pub const DS_FLAT_NAME_EXISTS_IN_FOREST = 0xC000041B;
+pub const INVALID_USER_PRINCIPAL_NAME = 0xC000041C;
+pub const ASSERTION_FAILURE = 0xC0000420;
+pub const VERIFIER_STOP = 0xC0000421;
+pub const CALLBACK_POP_STACK = 0xC0000423;
+pub const INCOMPATIBLE_DRIVER_BLOCKED = 0xC0000424;
+pub const HIVE_UNLOADED = 0xC0000425;
+pub const COMPRESSION_DISABLED = 0xC0000426;
+pub const FILE_SYSTEM_LIMITATION = 0xC0000427;
+pub const INVALID_IMAGE_HASH = 0xC0000428;
+pub const NOT_CAPABLE = 0xC0000429;
+pub const REQUEST_OUT_OF_SEQUENCE = 0xC000042A;
+pub const IMPLEMENTATION_LIMIT = 0xC000042B;
+pub const ELEVATION_REQUIRED = 0xC000042C;
+pub const NO_SECURITY_CONTEXT = 0xC000042D;
+pub const PKU2U_CERT_FAILURE = 0xC000042E;
+pub const BEYOND_VDL = 0xC0000432;
+pub const ENCOUNTERED_WRITE_IN_PROGRESS = 0xC0000433;
+pub const PTE_CHANGED = 0xC0000434;
+pub const PURGE_FAILED = 0xC0000435;
+pub const CRED_REQUIRES_CONFIRMATION = 0xC0000440;
+pub const CS_ENCRYPTION_INVALID_SERVER_RESPONSE = 0xC0000441;
+pub const CS_ENCRYPTION_UNSUPPORTED_SERVER = 0xC0000442;
+pub const CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE = 0xC0000443;
+pub const CS_ENCRYPTION_NEW_ENCRYPTED_FILE = 0xC0000444;
+pub const CS_ENCRYPTION_FILE_NOT_CSE = 0xC0000445;
+pub const INVALID_LABEL = 0xC0000446;
+pub const DRIVER_PROCESS_TERMINATED = 0xC0000450;
+pub const AMBIGUOUS_SYSTEM_DEVICE = 0xC0000451;
+pub const SYSTEM_DEVICE_NOT_FOUND = 0xC0000452;
+pub const RESTART_BOOT_APPLICATION = 0xC0000453;
+pub const INSUFFICIENT_NVRAM_RESOURCES = 0xC0000454;
+pub const INVALID_TASK_NAME = 0xC0000500;
+pub const INVALID_TASK_INDEX = 0xC0000501;
+pub const THREAD_ALREADY_IN_TASK = 0xC0000502;
+pub const CALLBACK_BYPASS = 0xC0000503;
+pub const FAIL_FAST_EXCEPTION = 0xC0000602;
+pub const IMAGE_CERT_REVOKED = 0xC0000603;
+pub const PORT_CLOSED = 0xC0000700;
+pub const MESSAGE_LOST = 0xC0000701;
+pub const INVALID_MESSAGE = 0xC0000702;
+pub const REQUEST_CANCELED = 0xC0000703;
+pub const RECURSIVE_DISPATCH = 0xC0000704;
+pub const LPC_RECEIVE_BUFFER_EXPECTED = 0xC0000705;
+pub const LPC_INVALID_CONNECTION_USAGE = 0xC0000706;
+pub const LPC_REQUESTS_NOT_ALLOWED = 0xC0000707;
+pub const RESOURCE_IN_USE = 0xC0000708;
+pub const HARDWARE_MEMORY_ERROR = 0xC0000709;
+pub const THREADPOOL_HANDLE_EXCEPTION = 0xC000070A;
+pub const THREADPOOL_SET_EVENT_ON_COMPLETION_FAILED = 0xC000070B;
+pub const THREADPOOL_RELEASE_SEMAPHORE_ON_COMPLETION_FAILED = 0xC000070C;
+pub const THREADPOOL_RELEASE_MUTEX_ON_COMPLETION_FAILED = 0xC000070D;
+pub const THREADPOOL_FREE_LIBRARY_ON_COMPLETION_FAILED = 0xC000070E;
+pub const THREADPOOL_RELEASED_DURING_OPERATION = 0xC000070F;
+pub const CALLBACK_RETURNED_WHILE_IMPERSONATING = 0xC0000710;
+pub const APC_RETURNED_WHILE_IMPERSONATING = 0xC0000711;
+pub const PROCESS_IS_PROTECTED = 0xC0000712;
+pub const MCA_EXCEPTION = 0xC0000713;
+pub const CERTIFICATE_MAPPING_NOT_UNIQUE = 0xC0000714;
+pub const SYMLINK_CLASS_DISABLED = 0xC0000715;
+pub const INVALID_IDN_NORMALIZATION = 0xC0000716;
+pub const NO_UNICODE_TRANSLATION = 0xC0000717;
+pub const ALREADY_REGISTERED = 0xC0000718;
+pub const CONTEXT_MISMATCH = 0xC0000719;
+pub const PORT_ALREADY_HAS_COMPLETION_LIST = 0xC000071A;
+pub const CALLBACK_RETURNED_THREAD_PRIORITY = 0xC000071B;
+pub const INVALID_THREAD = 0xC000071C;
+pub const CALLBACK_RETURNED_TRANSACTION = 0xC000071D;
+pub const CALLBACK_RETURNED_LDR_LOCK = 0xC000071E;
+pub const CALLBACK_RETURNED_LANG = 0xC000071F;
+pub const CALLBACK_RETURNED_PRI_BACK = 0xC0000720;
+pub const DISK_REPAIR_DISABLED = 0xC0000800;
+pub const DS_DOMAIN_RENAME_IN_PROGRESS = 0xC0000801;
+pub const DISK_QUOTA_EXCEEDED = 0xC0000802;
+pub const CONTENT_BLOCKED = 0xC0000804;
+pub const BAD_CLUSTERS = 0xC0000805;
+pub const VOLUME_DIRTY = 0xC0000806;
+pub const FILE_CHECKED_OUT = 0xC0000901;
+pub const CHECKOUT_REQUIRED = 0xC0000902;
+pub const BAD_FILE_TYPE = 0xC0000903;
+pub const FILE_TOO_LARGE = 0xC0000904;
+pub const FORMS_AUTH_REQUIRED = 0xC0000905;
+pub const VIRUS_INFECTED = 0xC0000906;
+pub const VIRUS_DELETED = 0xC0000907;
+pub const BAD_MCFG_TABLE = 0xC0000908;
+pub const CANNOT_BREAK_OPLOCK = 0xC0000909;
+pub const WOW_ASSERTION = 0xC0009898;
+pub const INVALID_SIGNATURE = 0xC000A000;
+pub const HMAC_NOT_SUPPORTED = 0xC000A001;
+pub const IPSEC_QUEUE_OVERFLOW = 0xC000A010;
+pub const ND_QUEUE_OVERFLOW = 0xC000A011;
+pub const HOPLIMIT_EXCEEDED = 0xC000A012;
+pub const PROTOCOL_NOT_SUPPORTED = 0xC000A013;
+pub const LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED = 0xC000A080;
+pub const LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR = 0xC000A081;
+pub const LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR = 0xC000A082;
+pub const XML_PARSE_ERROR = 0xC000A083;
+pub const XMLDSIG_ERROR = 0xC000A084;
+pub const WRONG_COMPARTMENT = 0xC000A085;
+pub const AUTHIP_FAILURE = 0xC000A086;
+pub const DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS = 0xC000A087;
+pub const DS_OID_NOT_FOUND = 0xC000A088;
+pub const HASH_NOT_SUPPORTED = 0xC000A100;
+pub const HASH_NOT_PRESENT = 0xC000A101;
+pub const PNP_BAD_MPS_TABLE = 0xC0040035;
+pub const PNP_TRANSLATION_FAILED = 0xC0040036;
+pub const PNP_IRQ_TRANSLATION_FAILED = 0xC0040037;
+pub const PNP_INVALID_ID = 0xC0040038;
+pub const IO_REISSUE_AS_CACHED = 0xC0040039;
+pub const CTX_WINSTATION_NAME_INVALID = 0xC00A0001;
+pub const CTX_INVALID_PD = 0xC00A0002;
+pub const CTX_PD_NOT_FOUND = 0xC00A0003;
+pub const CTX_CLOSE_PENDING = 0xC00A0006;
+pub const CTX_NO_OUTBUF = 0xC00A0007;
+pub const CTX_MODEM_INF_NOT_FOUND = 0xC00A0008;
+pub const CTX_INVALID_MODEMNAME = 0xC00A0009;
+pub const CTX_RESPONSE_ERROR = 0xC00A000A;
+pub const CTX_MODEM_RESPONSE_TIMEOUT = 0xC00A000B;
+pub const CTX_MODEM_RESPONSE_NO_CARRIER = 0xC00A000C;
+pub const CTX_MODEM_RESPONSE_NO_DIALTONE = 0xC00A000D;
+pub const CTX_MODEM_RESPONSE_BUSY = 0xC00A000E;
+pub const CTX_MODEM_RESPONSE_VOICE = 0xC00A000F;
+pub const CTX_TD_ERROR = 0xC00A0010;
+pub const CTX_LICENSE_CLIENT_INVALID = 0xC00A0012;
+pub const CTX_LICENSE_NOT_AVAILABLE = 0xC00A0013;
+pub const CTX_LICENSE_EXPIRED = 0xC00A0014;
+pub const CTX_WINSTATION_NOT_FOUND = 0xC00A0015;
+pub const CTX_WINSTATION_NAME_COLLISION = 0xC00A0016;
+pub const CTX_WINSTATION_BUSY = 0xC00A0017;
+pub const CTX_BAD_VIDEO_MODE = 0xC00A0018;
+pub const CTX_GRAPHICS_INVALID = 0xC00A0022;
+pub const CTX_NOT_CONSOLE = 0xC00A0024;
+pub const CTX_CLIENT_QUERY_TIMEOUT = 0xC00A0026;
+pub const CTX_CONSOLE_DISCONNECT = 0xC00A0027;
+pub const CTX_CONSOLE_CONNECT = 0xC00A0028;
+pub const CTX_SHADOW_DENIED = 0xC00A002A;
+pub const CTX_WINSTATION_ACCESS_DENIED = 0xC00A002B;
+pub const CTX_INVALID_WD = 0xC00A002E;
+pub const CTX_WD_NOT_FOUND = 0xC00A002F;
+pub const CTX_SHADOW_INVALID = 0xC00A0030;
+pub const CTX_SHADOW_DISABLED = 0xC00A0031;
+pub const RDP_PROTOCOL_ERROR = 0xC00A0032;
+pub const CTX_CLIENT_LICENSE_NOT_SET = 0xC00A0033;
+pub const CTX_CLIENT_LICENSE_IN_USE = 0xC00A0034;
+pub const CTX_SHADOW_ENDED_BY_MODE_CHANGE = 0xC00A0035;
+pub const CTX_SHADOW_NOT_RUNNING = 0xC00A0036;
+pub const CTX_LOGON_DISABLED = 0xC00A0037;
+pub const CTX_SECURITY_LAYER_ERROR = 0xC00A0038;
+pub const TS_INCOMPATIBLE_SESSIONS = 0xC00A0039;
+pub const MUI_FILE_NOT_FOUND = 0xC00B0001;
+pub const MUI_INVALID_FILE = 0xC00B0002;
+pub const MUI_INVALID_RC_CONFIG = 0xC00B0003;
+pub const MUI_INVALID_LOCALE_NAME = 0xC00B0004;
+pub const MUI_INVALID_ULTIMATEFALLBACK_NAME = 0xC00B0005;
+pub const MUI_FILE_NOT_LOADED = 0xC00B0006;
+pub const RESOURCE_ENUM_USER_STOP = 0xC00B0007;
+pub const CLUSTER_INVALID_NODE = 0xC0130001;
+pub const CLUSTER_NODE_EXISTS = 0xC0130002;
+pub const CLUSTER_JOIN_IN_PROGRESS = 0xC0130003;
+pub const CLUSTER_NODE_NOT_FOUND = 0xC0130004;
+pub const CLUSTER_LOCAL_NODE_NOT_FOUND = 0xC0130005;
+pub const CLUSTER_NETWORK_EXISTS = 0xC0130006;
+pub const CLUSTER_NETWORK_NOT_FOUND = 0xC0130007;
+pub const CLUSTER_NETINTERFACE_EXISTS = 0xC0130008;
+pub const CLUSTER_NETINTERFACE_NOT_FOUND = 0xC0130009;
+pub const CLUSTER_INVALID_REQUEST = 0xC013000A;
+pub const CLUSTER_INVALID_NETWORK_PROVIDER = 0xC013000B;
+pub const CLUSTER_NODE_DOWN = 0xC013000C;
+pub const CLUSTER_NODE_UNREACHABLE = 0xC013000D;
+pub const CLUSTER_NODE_NOT_MEMBER = 0xC013000E;
+pub const CLUSTER_JOIN_NOT_IN_PROGRESS = 0xC013000F;
+pub const CLUSTER_INVALID_NETWORK = 0xC0130010;
+pub const CLUSTER_NO_NET_ADAPTERS = 0xC0130011;
+pub const CLUSTER_NODE_UP = 0xC0130012;
+pub const CLUSTER_NODE_PAUSED = 0xC0130013;
+pub const CLUSTER_NODE_NOT_PAUSED = 0xC0130014;
+pub const CLUSTER_NO_SECURITY_CONTEXT = 0xC0130015;
+pub const CLUSTER_NETWORK_NOT_INTERNAL = 0xC0130016;
+pub const CLUSTER_POISONED = 0xC0130017;
+pub const ACPI_INVALID_OPCODE = 0xC0140001;
+pub const ACPI_STACK_OVERFLOW = 0xC0140002;
+pub const ACPI_ASSERT_FAILED = 0xC0140003;
+pub const ACPI_INVALID_INDEX = 0xC0140004;
+pub const ACPI_INVALID_ARGUMENT = 0xC0140005;
+pub const ACPI_FATAL = 0xC0140006;
+pub const ACPI_INVALID_SUPERNAME = 0xC0140007;
+pub const ACPI_INVALID_ARGTYPE = 0xC0140008;
+pub const ACPI_INVALID_OBJTYPE = 0xC0140009;
+pub const ACPI_INVALID_TARGETTYPE = 0xC014000A;
+pub const ACPI_INCORRECT_ARGUMENT_COUNT = 0xC014000B;
+pub const ACPI_ADDRESS_NOT_MAPPED = 0xC014000C;
+pub const ACPI_INVALID_EVENTTYPE = 0xC014000D;
+pub const ACPI_HANDLER_COLLISION = 0xC014000E;
+pub const ACPI_INVALID_DATA = 0xC014000F;
+pub const ACPI_INVALID_REGION = 0xC0140010;
+pub const ACPI_INVALID_ACCESS_SIZE = 0xC0140011;
+pub const ACPI_ACQUIRE_GLOBAL_LOCK = 0xC0140012;
+pub const ACPI_ALREADY_INITIALIZED = 0xC0140013;
+pub const ACPI_NOT_INITIALIZED = 0xC0140014;
+pub const ACPI_INVALID_MUTEX_LEVEL = 0xC0140015;
+pub const ACPI_MUTEX_NOT_OWNED = 0xC0140016;
+pub const ACPI_MUTEX_NOT_OWNER = 0xC0140017;
+pub const ACPI_RS_ACCESS = 0xC0140018;
+pub const ACPI_INVALID_TABLE = 0xC0140019;
+pub const ACPI_REG_HANDLER_FAILED = 0xC0140020;
+pub const ACPI_POWER_REQUEST_FAILED = 0xC0140021;
+pub const SXS_SECTION_NOT_FOUND = 0xC0150001;
+pub const SXS_CANT_GEN_ACTCTX = 0xC0150002;
+pub const SXS_INVALID_ACTCTXDATA_FORMAT = 0xC0150003;
+pub const SXS_ASSEMBLY_NOT_FOUND = 0xC0150004;
+pub const SXS_MANIFEST_FORMAT_ERROR = 0xC0150005;
+pub const SXS_MANIFEST_PARSE_ERROR = 0xC0150006;
+pub const SXS_ACTIVATION_CONTEXT_DISABLED = 0xC0150007;
+pub const SXS_KEY_NOT_FOUND = 0xC0150008;
+pub const SXS_VERSION_CONFLICT = 0xC0150009;
+pub const SXS_WRONG_SECTION_TYPE = 0xC015000A;
+pub const SXS_THREAD_QUERIES_DISABLED = 0xC015000B;
+pub const SXS_ASSEMBLY_MISSING = 0xC015000C;
+pub const SXS_PROCESS_DEFAULT_ALREADY_SET = 0xC015000E;
+pub const SXS_EARLY_DEACTIVATION = 0xC015000F;
+pub const SXS_INVALID_DEACTIVATION = 0xC0150010;
+pub const SXS_MULTIPLE_DEACTIVATION = 0xC0150011;
+pub const SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY = 0xC0150012;
+pub const SXS_PROCESS_TERMINATION_REQUESTED = 0xC0150013;
+pub const SXS_CORRUPT_ACTIVATION_STACK = 0xC0150014;
+pub const SXS_CORRUPTION = 0xC0150015;
+pub const SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE = 0xC0150016;
+pub const SXS_INVALID_IDENTITY_ATTRIBUTE_NAME = 0xC0150017;
+pub const SXS_IDENTITY_DUPLICATE_ATTRIBUTE = 0xC0150018;
+pub const SXS_IDENTITY_PARSE_ERROR = 0xC0150019;
+pub const SXS_COMPONENT_STORE_CORRUPT = 0xC015001A;
+pub const SXS_FILE_HASH_MISMATCH = 0xC015001B;
+pub const SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT = 0xC015001C;
+pub const SXS_IDENTITIES_DIFFERENT = 0xC015001D;
+pub const SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT = 0xC015001E;
+pub const SXS_FILE_NOT_PART_OF_ASSEMBLY = 0xC015001F;
+pub const ADVANCED_INSTALLER_FAILED = 0xC0150020;
+pub const XML_ENCODING_MISMATCH = 0xC0150021;
+pub const SXS_MANIFEST_TOO_BIG = 0xC0150022;
+pub const SXS_SETTING_NOT_REGISTERED = 0xC0150023;
+pub const SXS_TRANSACTION_CLOSURE_INCOMPLETE = 0xC0150024;
+pub const SMI_PRIMITIVE_INSTALLER_FAILED = 0xC0150025;
+pub const GENERIC_COMMAND_FAILED = 0xC0150026;
+pub const SXS_FILE_HASH_MISSING = 0xC0150027;
+pub const TRANSACTIONAL_CONFLICT = 0xC0190001;
+pub const INVALID_TRANSACTION = 0xC0190002;
+pub const TRANSACTION_NOT_ACTIVE = 0xC0190003;
+pub const TM_INITIALIZATION_FAILED = 0xC0190004;
+pub const RM_NOT_ACTIVE = 0xC0190005;
+pub const RM_METADATA_CORRUPT = 0xC0190006;
+pub const TRANSACTION_NOT_JOINED = 0xC0190007;
+pub const DIRECTORY_NOT_RM = 0xC0190008;
+pub const TRANSACTIONS_UNSUPPORTED_REMOTE = 0xC019000A;
+pub const LOG_RESIZE_INVALID_SIZE = 0xC019000B;
+pub const REMOTE_FILE_VERSION_MISMATCH = 0xC019000C;
+pub const CRM_PROTOCOL_ALREADY_EXISTS = 0xC019000F;
+pub const TRANSACTION_PROPAGATION_FAILED = 0xC0190010;
+pub const CRM_PROTOCOL_NOT_FOUND = 0xC0190011;
+pub const TRANSACTION_SUPERIOR_EXISTS = 0xC0190012;
+pub const TRANSACTION_REQUEST_NOT_VALID = 0xC0190013;
+pub const TRANSACTION_NOT_REQUESTED = 0xC0190014;
+pub const TRANSACTION_ALREADY_ABORTED = 0xC0190015;
+pub const TRANSACTION_ALREADY_COMMITTED = 0xC0190016;
+pub const TRANSACTION_INVALID_MARSHALL_BUFFER = 0xC0190017;
+pub const CURRENT_TRANSACTION_NOT_VALID = 0xC0190018;
+pub const LOG_GROWTH_FAILED = 0xC0190019;
+pub const OBJECT_NO_LONGER_EXISTS = 0xC0190021;
+pub const STREAM_MINIVERSION_NOT_FOUND = 0xC0190022;
+pub const STREAM_MINIVERSION_NOT_VALID = 0xC0190023;
+pub const MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION = 0xC0190024;
+pub const CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT = 0xC0190025;
+pub const CANT_CREATE_MORE_STREAM_MINIVERSIONS = 0xC0190026;
+pub const HANDLE_NO_LONGER_VALID = 0xC0190028;
+pub const LOG_CORRUPTION_DETECTED = 0xC0190030;
+pub const RM_DISCONNECTED = 0xC0190032;
+pub const ENLISTMENT_NOT_SUPERIOR = 0xC0190033;
+pub const FILE_IDENTITY_NOT_PERSISTENT = 0xC0190036;
+pub const CANT_BREAK_TRANSACTIONAL_DEPENDENCY = 0xC0190037;
+pub const CANT_CROSS_RM_BOUNDARY = 0xC0190038;
+pub const TXF_DIR_NOT_EMPTY = 0xC0190039;
+pub const INDOUBT_TRANSACTIONS_EXIST = 0xC019003A;
+pub const TM_VOLATILE = 0xC019003B;
+pub const ROLLBACK_TIMER_EXPIRED = 0xC019003C;
+pub const TXF_ATTRIBUTE_CORRUPT = 0xC019003D;
+pub const EFS_NOT_ALLOWED_IN_TRANSACTION = 0xC019003E;
+pub const TRANSACTIONAL_OPEN_NOT_ALLOWED = 0xC019003F;
+pub const TRANSACTED_MAPPING_UNSUPPORTED_REMOTE = 0xC0190040;
+pub const TRANSACTION_REQUIRED_PROMOTION = 0xC0190043;
+pub const CANNOT_EXECUTE_FILE_IN_TRANSACTION = 0xC0190044;
+pub const TRANSACTIONS_NOT_FROZEN = 0xC0190045;
+pub const TRANSACTION_FREEZE_IN_PROGRESS = 0xC0190046;
+pub const NOT_SNAPSHOT_VOLUME = 0xC0190047;
+pub const NO_SAVEPOINT_WITH_OPEN_FILES = 0xC0190048;
+pub const SPARSE_NOT_ALLOWED_IN_TRANSACTION = 0xC0190049;
+pub const TM_IDENTITY_MISMATCH = 0xC019004A;
+pub const FLOATED_SECTION = 0xC019004B;
+pub const CANNOT_ACCEPT_TRANSACTED_WORK = 0xC019004C;
+pub const CANNOT_ABORT_TRANSACTIONS = 0xC019004D;
+pub const TRANSACTION_NOT_FOUND = 0xC019004E;
+pub const RESOURCEMANAGER_NOT_FOUND = 0xC019004F;
+pub const ENLISTMENT_NOT_FOUND = 0xC0190050;
+pub const TRANSACTIONMANAGER_NOT_FOUND = 0xC0190051;
+pub const TRANSACTIONMANAGER_NOT_ONLINE = 0xC0190052;
+pub const TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION = 0xC0190053;
+pub const TRANSACTION_NOT_ROOT = 0xC0190054;
+pub const TRANSACTION_OBJECT_EXPIRED = 0xC0190055;
+pub const COMPRESSION_NOT_ALLOWED_IN_TRANSACTION = 0xC0190056;
+pub const TRANSACTION_RESPONSE_NOT_ENLISTED = 0xC0190057;
+pub const TRANSACTION_RECORD_TOO_LONG = 0xC0190058;
+pub const NO_LINK_TRACKING_IN_TRANSACTION = 0xC0190059;
+pub const OPERATION_NOT_SUPPORTED_IN_TRANSACTION = 0xC019005A;
+pub const TRANSACTION_INTEGRITY_VIOLATED = 0xC019005B;
+pub const EXPIRED_HANDLE = 0xC0190060;
+pub const TRANSACTION_NOT_ENLISTED = 0xC0190061;
+pub const LOG_SECTOR_INVALID = 0xC01A0001;
+pub const LOG_SECTOR_PARITY_INVALID = 0xC01A0002;
+pub const LOG_SECTOR_REMAPPED = 0xC01A0003;
+pub const LOG_BLOCK_INCOMPLETE = 0xC01A0004;
+pub const LOG_INVALID_RANGE = 0xC01A0005;
+pub const LOG_BLOCKS_EXHAUSTED = 0xC01A0006;
+pub const LOG_READ_CONTEXT_INVALID = 0xC01A0007;
+pub const LOG_RESTART_INVALID = 0xC01A0008;
+pub const LOG_BLOCK_VERSION = 0xC01A0009;
+pub const LOG_BLOCK_INVALID = 0xC01A000A;
+pub const LOG_READ_MODE_INVALID = 0xC01A000B;
+pub const LOG_METADATA_CORRUPT = 0xC01A000D;
+pub const LOG_METADATA_INVALID = 0xC01A000E;
+pub const LOG_METADATA_INCONSISTENT = 0xC01A000F;
+pub const LOG_RESERVATION_INVALID = 0xC01A0010;
+pub const LOG_CANT_DELETE = 0xC01A0011;
+pub const LOG_CONTAINER_LIMIT_EXCEEDED = 0xC01A0012;
+pub const LOG_START_OF_LOG = 0xC01A0013;
+pub const LOG_POLICY_ALREADY_INSTALLED = 0xC01A0014;
+pub const LOG_POLICY_NOT_INSTALLED = 0xC01A0015;
+pub const LOG_POLICY_INVALID = 0xC01A0016;
+pub const LOG_POLICY_CONFLICT = 0xC01A0017;
+pub const LOG_PINNED_ARCHIVE_TAIL = 0xC01A0018;
+pub const LOG_RECORD_NONEXISTENT = 0xC01A0019;
+pub const LOG_RECORDS_RESERVED_INVALID = 0xC01A001A;
+pub const LOG_SPACE_RESERVED_INVALID = 0xC01A001B;
+pub const LOG_TAIL_INVALID = 0xC01A001C;
+pub const LOG_FULL = 0xC01A001D;
+pub const LOG_MULTIPLEXED = 0xC01A001E;
+pub const LOG_DEDICATED = 0xC01A001F;
+pub const LOG_ARCHIVE_NOT_IN_PROGRESS = 0xC01A0020;
+pub const LOG_ARCHIVE_IN_PROGRESS = 0xC01A0021;
+pub const LOG_EPHEMERAL = 0xC01A0022;
+pub const LOG_NOT_ENOUGH_CONTAINERS = 0xC01A0023;
+pub const LOG_CLIENT_ALREADY_REGISTERED = 0xC01A0024;
+pub const LOG_CLIENT_NOT_REGISTERED = 0xC01A0025;
+pub const LOG_FULL_HANDLER_IN_PROGRESS = 0xC01A0026;
+pub const LOG_CONTAINER_READ_FAILED = 0xC01A0027;
+pub const LOG_CONTAINER_WRITE_FAILED = 0xC01A0028;
+pub const LOG_CONTAINER_OPEN_FAILED = 0xC01A0029;
+pub const LOG_CONTAINER_STATE_INVALID = 0xC01A002A;
+pub const LOG_STATE_INVALID = 0xC01A002B;
+pub const LOG_PINNED = 0xC01A002C;
+pub const LOG_METADATA_FLUSH_FAILED = 0xC01A002D;
+pub const LOG_INCONSISTENT_SECURITY = 0xC01A002E;
+pub const LOG_APPENDED_FLUSH_FAILED = 0xC01A002F;
+pub const LOG_PINNED_RESERVATION = 0xC01A0030;
+pub const VIDEO_HUNG_DISPLAY_DRIVER_THREAD = 0xC01B00EA;
+pub const FLT_NO_HANDLER_DEFINED = 0xC01C0001;
+pub const FLT_CONTEXT_ALREADY_DEFINED = 0xC01C0002;
+pub const FLT_INVALID_ASYNCHRONOUS_REQUEST = 0xC01C0003;
+pub const FLT_DISALLOW_FAST_IO = 0xC01C0004;
+pub const FLT_INVALID_NAME_REQUEST = 0xC01C0005;
+pub const FLT_NOT_SAFE_TO_POST_OPERATION = 0xC01C0006;
+pub const FLT_NOT_INITIALIZED = 0xC01C0007;
+pub const FLT_FILTER_NOT_READY = 0xC01C0008;
+pub const FLT_POST_OPERATION_CLEANUP = 0xC01C0009;
+pub const FLT_INTERNAL_ERROR = 0xC01C000A;
+pub const FLT_DELETING_OBJECT = 0xC01C000B;
+pub const FLT_MUST_BE_NONPAGED_POOL = 0xC01C000C;
+pub const FLT_DUPLICATE_ENTRY = 0xC01C000D;
+pub const FLT_CBDQ_DISABLED = 0xC01C000E;
+pub const FLT_DO_NOT_ATTACH = 0xC01C000F;
+pub const FLT_DO_NOT_DETACH = 0xC01C0010;
+pub const FLT_INSTANCE_ALTITUDE_COLLISION = 0xC01C0011;
+pub const FLT_INSTANCE_NAME_COLLISION = 0xC01C0012;
+pub const FLT_FILTER_NOT_FOUND = 0xC01C0013;
+pub const FLT_VOLUME_NOT_FOUND = 0xC01C0014;
+pub const FLT_INSTANCE_NOT_FOUND = 0xC01C0015;
+pub const FLT_CONTEXT_ALLOCATION_NOT_FOUND = 0xC01C0016;
+pub const FLT_INVALID_CONTEXT_REGISTRATION = 0xC01C0017;
+pub const FLT_NAME_CACHE_MISS = 0xC01C0018;
+pub const FLT_NO_DEVICE_OBJECT = 0xC01C0019;
+pub const FLT_VOLUME_ALREADY_MOUNTED = 0xC01C001A;
+pub const FLT_ALREADY_ENLISTED = 0xC01C001B;
+pub const FLT_CONTEXT_ALREADY_LINKED = 0xC01C001C;
+pub const FLT_NO_WAITER_FOR_REPLY = 0xC01C0020;
+pub const MONITOR_NO_DESCRIPTOR = 0xC01D0001;
+pub const MONITOR_UNKNOWN_DESCRIPTOR_FORMAT = 0xC01D0002;
+pub const MONITOR_INVALID_DESCRIPTOR_CHECKSUM = 0xC01D0003;
+pub const MONITOR_INVALID_STANDARD_TIMING_BLOCK = 0xC01D0004;
+pub const MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED = 0xC01D0005;
+pub const MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK = 0xC01D0006;
+pub const MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK = 0xC01D0007;
+pub const MONITOR_NO_MORE_DESCRIPTOR_DATA = 0xC01D0008;
+pub const MONITOR_INVALID_DETAILED_TIMING_BLOCK = 0xC01D0009;
+pub const MONITOR_INVALID_MANUFACTURE_DATE = 0xC01D000A;
+pub const GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER = 0xC01E0000;
+pub const GRAPHICS_INSUFFICIENT_DMA_BUFFER = 0xC01E0001;
+pub const GRAPHICS_INVALID_DISPLAY_ADAPTER = 0xC01E0002;
+pub const GRAPHICS_ADAPTER_WAS_RESET = 0xC01E0003;
+pub const GRAPHICS_INVALID_DRIVER_MODEL = 0xC01E0004;
+pub const GRAPHICS_PRESENT_MODE_CHANGED = 0xC01E0005;
+pub const GRAPHICS_PRESENT_OCCLUDED = 0xC01E0006;
+pub const GRAPHICS_PRESENT_DENIED = 0xC01E0007;
+pub const GRAPHICS_CANNOTCOLORCONVERT = 0xC01E0008;
+pub const GRAPHICS_PRESENT_REDIRECTION_DISABLED = 0xC01E000B;
+pub const GRAPHICS_PRESENT_UNOCCLUDED = 0xC01E000C;
+pub const GRAPHICS_NO_VIDEO_MEMORY = 0xC01E0100;
+pub const GRAPHICS_CANT_LOCK_MEMORY = 0xC01E0101;
+pub const GRAPHICS_ALLOCATION_BUSY = 0xC01E0102;
+pub const GRAPHICS_TOO_MANY_REFERENCES = 0xC01E0103;
+pub const GRAPHICS_TRY_AGAIN_LATER = 0xC01E0104;
+pub const GRAPHICS_TRY_AGAIN_NOW = 0xC01E0105;
+pub const GRAPHICS_ALLOCATION_INVALID = 0xC01E0106;
+pub const GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE = 0xC01E0107;
+pub const GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED = 0xC01E0108;
+pub const GRAPHICS_CANT_EVICT_PINNED_ALLOCATION = 0xC01E0109;
+pub const GRAPHICS_INVALID_ALLOCATION_USAGE = 0xC01E0110;
+pub const GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION = 0xC01E0111;
+pub const GRAPHICS_ALLOCATION_CLOSED = 0xC01E0112;
+pub const GRAPHICS_INVALID_ALLOCATION_INSTANCE = 0xC01E0113;
+pub const GRAPHICS_INVALID_ALLOCATION_HANDLE = 0xC01E0114;
+pub const GRAPHICS_WRONG_ALLOCATION_DEVICE = 0xC01E0115;
+pub const GRAPHICS_ALLOCATION_CONTENT_LOST = 0xC01E0116;
+pub const GRAPHICS_GPU_EXCEPTION_ON_DEVICE = 0xC01E0200;
+pub const GRAPHICS_INVALID_VIDPN_TOPOLOGY = 0xC01E0300;
+pub const GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED = 0xC01E0301;
+pub const GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED = 0xC01E0302;
+pub const GRAPHICS_INVALID_VIDPN = 0xC01E0303;
+pub const GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE = 0xC01E0304;
+pub const GRAPHICS_INVALID_VIDEO_PRESENT_TARGET = 0xC01E0305;
+pub const GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED = 0xC01E0306;
+pub const GRAPHICS_INVALID_VIDPN_SOURCEMODESET = 0xC01E0308;
+pub const GRAPHICS_INVALID_VIDPN_TARGETMODESET = 0xC01E0309;
+pub const GRAPHICS_INVALID_FREQUENCY = 0xC01E030A;
+pub const GRAPHICS_INVALID_ACTIVE_REGION = 0xC01E030B;
+pub const GRAPHICS_INVALID_TOTAL_REGION = 0xC01E030C;
+pub const GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE = 0xC01E0310;
+pub const GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE = 0xC01E0311;
+pub const GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET = 0xC01E0312;
+pub const GRAPHICS_PATH_ALREADY_IN_TOPOLOGY = 0xC01E0313;
+pub const GRAPHICS_MODE_ALREADY_IN_MODESET = 0xC01E0314;
+pub const GRAPHICS_INVALID_VIDEOPRESENTSOURCESET = 0xC01E0315;
+pub const GRAPHICS_INVALID_VIDEOPRESENTTARGETSET = 0xC01E0316;
+pub const GRAPHICS_SOURCE_ALREADY_IN_SET = 0xC01E0317;
+pub const GRAPHICS_TARGET_ALREADY_IN_SET = 0xC01E0318;
+pub const GRAPHICS_INVALID_VIDPN_PRESENT_PATH = 0xC01E0319;
+pub const GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY = 0xC01E031A;
+pub const GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET = 0xC01E031B;
+pub const GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE = 0xC01E031C;
+pub const GRAPHICS_FREQUENCYRANGE_NOT_IN_SET = 0xC01E031D;
+pub const GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET = 0xC01E031F;
+pub const GRAPHICS_STALE_MODESET = 0xC01E0320;
+pub const GRAPHICS_INVALID_MONITOR_SOURCEMODESET = 0xC01E0321;
+pub const GRAPHICS_INVALID_MONITOR_SOURCE_MODE = 0xC01E0322;
+pub const GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN = 0xC01E0323;
+pub const GRAPHICS_MODE_ID_MUST_BE_UNIQUE = 0xC01E0324;
+pub const GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION = 0xC01E0325;
+pub const GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES = 0xC01E0326;
+pub const GRAPHICS_PATH_NOT_IN_TOPOLOGY = 0xC01E0327;
+pub const GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE = 0xC01E0328;
+pub const GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET = 0xC01E0329;
+pub const GRAPHICS_INVALID_MONITORDESCRIPTORSET = 0xC01E032A;
+pub const GRAPHICS_INVALID_MONITORDESCRIPTOR = 0xC01E032B;
+pub const GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET = 0xC01E032C;
+pub const GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET = 0xC01E032D;
+pub const GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE = 0xC01E032E;
+pub const GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE = 0xC01E032F;
+pub const GRAPHICS_RESOURCES_NOT_RELATED = 0xC01E0330;
+pub const GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE = 0xC01E0331;
+pub const GRAPHICS_TARGET_ID_MUST_BE_UNIQUE = 0xC01E0332;
+pub const GRAPHICS_NO_AVAILABLE_VIDPN_TARGET = 0xC01E0333;
+pub const GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER = 0xC01E0334;
+pub const GRAPHICS_NO_VIDPNMGR = 0xC01E0335;
+pub const GRAPHICS_NO_ACTIVE_VIDPN = 0xC01E0336;
+pub const GRAPHICS_STALE_VIDPN_TOPOLOGY = 0xC01E0337;
+pub const GRAPHICS_MONITOR_NOT_CONNECTED = 0xC01E0338;
+pub const GRAPHICS_SOURCE_NOT_IN_TOPOLOGY = 0xC01E0339;
+pub const GRAPHICS_INVALID_PRIMARYSURFACE_SIZE = 0xC01E033A;
+pub const GRAPHICS_INVALID_VISIBLEREGION_SIZE = 0xC01E033B;
+pub const GRAPHICS_INVALID_STRIDE = 0xC01E033C;
+pub const GRAPHICS_INVALID_PIXELFORMAT = 0xC01E033D;
+pub const GRAPHICS_INVALID_COLORBASIS = 0xC01E033E;
+pub const GRAPHICS_INVALID_PIXELVALUEACCESSMODE = 0xC01E033F;
+pub const GRAPHICS_TARGET_NOT_IN_TOPOLOGY = 0xC01E0340;
+pub const GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT = 0xC01E0341;
+pub const GRAPHICS_VIDPN_SOURCE_IN_USE = 0xC01E0342;
+pub const GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN = 0xC01E0343;
+pub const GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL = 0xC01E0344;
+pub const GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION = 0xC01E0345;
+pub const GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED = 0xC01E0346;
+pub const GRAPHICS_INVALID_GAMMA_RAMP = 0xC01E0347;
+pub const GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED = 0xC01E0348;
+pub const GRAPHICS_MULTISAMPLING_NOT_SUPPORTED = 0xC01E0349;
+pub const GRAPHICS_MODE_NOT_IN_MODESET = 0xC01E034A;
+pub const GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON = 0xC01E034D;
+pub const GRAPHICS_INVALID_PATH_CONTENT_TYPE = 0xC01E034E;
+pub const GRAPHICS_INVALID_COPYPROTECTION_TYPE = 0xC01E034F;
+pub const GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS = 0xC01E0350;
+pub const GRAPHICS_INVALID_SCANLINE_ORDERING = 0xC01E0352;
+pub const GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED = 0xC01E0353;
+pub const GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS = 0xC01E0354;
+pub const GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT = 0xC01E0355;
+pub const GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM = 0xC01E0356;
+pub const GRAPHICS_INVALID_MONITOR_CAPABILITY_ORIGIN = 0xC01E0357;
+pub const GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE_CONSTRAINT = 0xC01E0358;
+pub const GRAPHICS_MAX_NUM_PATHS_REACHED = 0xC01E0359;
+pub const GRAPHICS_CANCEL_VIDPN_TOPOLOGY_AUGMENTATION = 0xC01E035A;
+pub const GRAPHICS_INVALID_CLIENT_TYPE = 0xC01E035B;
+pub const GRAPHICS_CLIENTVIDPN_NOT_SET = 0xC01E035C;
+pub const GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED = 0xC01E0400;
+pub const GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED = 0xC01E0401;
+pub const GRAPHICS_NOT_A_LINKED_ADAPTER = 0xC01E0430;
+pub const GRAPHICS_LEADLINK_NOT_ENUMERATED = 0xC01E0431;
+pub const GRAPHICS_CHAINLINKS_NOT_ENUMERATED = 0xC01E0432;
+pub const GRAPHICS_ADAPTER_CHAIN_NOT_READY = 0xC01E0433;
+pub const GRAPHICS_CHAINLINKS_NOT_STARTED = 0xC01E0434;
+pub const GRAPHICS_CHAINLINKS_NOT_POWERED_ON = 0xC01E0435;
+pub const GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE = 0xC01E0436;
+pub const GRAPHICS_NOT_POST_DEVICE_DRIVER = 0xC01E0438;
+pub const GRAPHICS_ADAPTER_ACCESS_NOT_EXCLUDED = 0xC01E043B;
+pub const GRAPHICS_OPM_NOT_SUPPORTED = 0xC01E0500;
+pub const GRAPHICS_COPP_NOT_SUPPORTED = 0xC01E0501;
+pub const GRAPHICS_UAB_NOT_SUPPORTED = 0xC01E0502;
+pub const GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS = 0xC01E0503;
+pub const GRAPHICS_OPM_PARAMETER_ARRAY_TOO_SMALL = 0xC01E0504;
+pub const GRAPHICS_OPM_NO_PROTECTED_OUTPUTS_EXIST = 0xC01E0505;
+pub const GRAPHICS_PVP_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME = 0xC01E0506;
+pub const GRAPHICS_PVP_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP = 0xC01E0507;
+pub const GRAPHICS_PVP_MIRRORING_DEVICES_NOT_SUPPORTED = 0xC01E0508;
+pub const GRAPHICS_OPM_INVALID_POINTER = 0xC01E050A;
+pub const GRAPHICS_OPM_INTERNAL_ERROR = 0xC01E050B;
+pub const GRAPHICS_OPM_INVALID_HANDLE = 0xC01E050C;
+pub const GRAPHICS_PVP_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE = 0xC01E050D;
+pub const GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH = 0xC01E050E;
+pub const GRAPHICS_OPM_SPANNING_MODE_ENABLED = 0xC01E050F;
+pub const GRAPHICS_OPM_THEATER_MODE_ENABLED = 0xC01E0510;
+pub const GRAPHICS_PVP_HFS_FAILED = 0xC01E0511;
+pub const GRAPHICS_OPM_INVALID_SRM = 0xC01E0512;
+pub const GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP = 0xC01E0513;
+pub const GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP = 0xC01E0514;
+pub const GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA = 0xC01E0515;
+pub const GRAPHICS_OPM_HDCP_SRM_NEVER_SET = 0xC01E0516;
+pub const GRAPHICS_OPM_RESOLUTION_TOO_HIGH = 0xC01E0517;
+pub const GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE = 0xC01E0518;
+pub const GRAPHICS_OPM_PROTECTED_OUTPUT_NO_LONGER_EXISTS = 0xC01E051A;
+pub const GRAPHICS_OPM_SESSION_TYPE_CHANGE_IN_PROGRESS = 0xC01E051B;
+pub const GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_COPP_SEMANTICS = 0xC01E051C;
+pub const GRAPHICS_OPM_INVALID_INFORMATION_REQUEST = 0xC01E051D;
+pub const GRAPHICS_OPM_DRIVER_INTERNAL_ERROR = 0xC01E051E;
+pub const GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_OPM_SEMANTICS = 0xC01E051F;
+pub const GRAPHICS_OPM_SIGNALING_NOT_SUPPORTED = 0xC01E0520;
+pub const GRAPHICS_OPM_INVALID_CONFIGURATION_REQUEST = 0xC01E0521;
+pub const GRAPHICS_I2C_NOT_SUPPORTED = 0xC01E0580;
+pub const GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST = 0xC01E0581;
+pub const GRAPHICS_I2C_ERROR_TRANSMITTING_DATA = 0xC01E0582;
+pub const GRAPHICS_I2C_ERROR_RECEIVING_DATA = 0xC01E0583;
+pub const GRAPHICS_DDCCI_VCP_NOT_SUPPORTED = 0xC01E0584;
+pub const GRAPHICS_DDCCI_INVALID_DATA = 0xC01E0585;
+pub const GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE = 0xC01E0586;
+pub const GRAPHICS_DDCCI_INVALID_CAPABILITIES_STRING = 0xC01E0587;
+pub const GRAPHICS_MCA_INTERNAL_ERROR = 0xC01E0588;
+pub const GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND = 0xC01E0589;
+pub const GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH = 0xC01E058A;
+pub const GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM = 0xC01E058B;
+pub const GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE = 0xC01E058C;
+pub const GRAPHICS_MONITOR_NO_LONGER_EXISTS = 0xC01E058D;
+pub const GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED = 0xC01E05E0;
+pub const GRAPHICS_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME = 0xC01E05E1;
+pub const GRAPHICS_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP = 0xC01E05E2;
+pub const GRAPHICS_MIRRORING_DEVICES_NOT_SUPPORTED = 0xC01E05E3;
+pub const GRAPHICS_INVALID_POINTER = 0xC01E05E4;
+pub const GRAPHICS_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE = 0xC01E05E5;
+pub const GRAPHICS_PARAMETER_ARRAY_TOO_SMALL = 0xC01E05E6;
+pub const GRAPHICS_INTERNAL_ERROR = 0xC01E05E7;
+pub const GRAPHICS_SESSION_TYPE_CHANGE_IN_PROGRESS = 0xC01E05E8;
+pub const FVE_LOCKED_VOLUME = 0xC0210000;
+pub const FVE_NOT_ENCRYPTED = 0xC0210001;
+pub const FVE_BAD_INFORMATION = 0xC0210002;
+pub const FVE_TOO_SMALL = 0xC0210003;
+pub const FVE_FAILED_WRONG_FS = 0xC0210004;
+pub const FVE_FAILED_BAD_FS = 0xC0210005;
+pub const FVE_FS_NOT_EXTENDED = 0xC0210006;
+pub const FVE_FS_MOUNTED = 0xC0210007;
+pub const FVE_NO_LICENSE = 0xC0210008;
+pub const FVE_ACTION_NOT_ALLOWED = 0xC0210009;
+pub const FVE_BAD_DATA = 0xC021000A;
+pub const FVE_VOLUME_NOT_BOUND = 0xC021000B;
+pub const FVE_NOT_DATA_VOLUME = 0xC021000C;
+pub const FVE_CONV_READ_ERROR = 0xC021000D;
+pub const FVE_CONV_WRITE_ERROR = 0xC021000E;
+pub const FVE_OVERLAPPED_UPDATE = 0xC021000F;
+pub const FVE_FAILED_SECTOR_SIZE = 0xC0210010;
+pub const FVE_FAILED_AUTHENTICATION = 0xC0210011;
+pub const FVE_NOT_OS_VOLUME = 0xC0210012;
+pub const FVE_KEYFILE_NOT_FOUND = 0xC0210013;
+pub const FVE_KEYFILE_INVALID = 0xC0210014;
+pub const FVE_KEYFILE_NO_VMK = 0xC0210015;
+pub const FVE_TPM_DISABLED = 0xC0210016;
+pub const FVE_TPM_SRK_AUTH_NOT_ZERO = 0xC0210017;
+pub const FVE_TPM_INVALID_PCR = 0xC0210018;
+pub const FVE_TPM_NO_VMK = 0xC0210019;
+pub const FVE_PIN_INVALID = 0xC021001A;
+pub const FVE_AUTH_INVALID_APPLICATION = 0xC021001B;
+pub const FVE_AUTH_INVALID_CONFIG = 0xC021001C;
+pub const FVE_DEBUGGER_ENABLED = 0xC021001D;
+pub const FVE_DRY_RUN_FAILED = 0xC021001E;
+pub const FVE_BAD_METADATA_POINTER = 0xC021001F;
+pub const FVE_OLD_METADATA_COPY = 0xC0210020;
+pub const FVE_REBOOT_REQUIRED = 0xC0210021;
+pub const FVE_RAW_ACCESS = 0xC0210022;
+pub const FVE_RAW_BLOCKED = 0xC0210023;
+pub const FVE_NO_FEATURE_LICENSE = 0xC0210026;
+pub const FVE_POLICY_USER_DISABLE_RDV_NOT_ALLOWED = 0xC0210027;
+pub const FVE_CONV_RECOVERY_FAILED = 0xC0210028;
+pub const FVE_VIRTUALIZED_SPACE_TOO_BIG = 0xC0210029;
+pub const FVE_VOLUME_TOO_SMALL = 0xC0210030;
+pub const FWP_CALLOUT_NOT_FOUND = 0xC0220001;
+pub const FWP_CONDITION_NOT_FOUND = 0xC0220002;
+pub const FWP_FILTER_NOT_FOUND = 0xC0220003;
+pub const FWP_LAYER_NOT_FOUND = 0xC0220004;
+pub const FWP_PROVIDER_NOT_FOUND = 0xC0220005;
+pub const FWP_PROVIDER_CONTEXT_NOT_FOUND = 0xC0220006;
+pub const FWP_SUBLAYER_NOT_FOUND = 0xC0220007;
+pub const FWP_NOT_FOUND = 0xC0220008;
+pub const FWP_ALREADY_EXISTS = 0xC0220009;
+pub const FWP_IN_USE = 0xC022000A;
+pub const FWP_DYNAMIC_SESSION_IN_PROGRESS = 0xC022000B;
+pub const FWP_WRONG_SESSION = 0xC022000C;
+pub const FWP_NO_TXN_IN_PROGRESS = 0xC022000D;
+pub const FWP_TXN_IN_PROGRESS = 0xC022000E;
+pub const FWP_TXN_ABORTED = 0xC022000F;
+pub const FWP_SESSION_ABORTED = 0xC0220010;
+pub const FWP_INCOMPATIBLE_TXN = 0xC0220011;
+pub const FWP_TIMEOUT = 0xC0220012;
+pub const FWP_NET_EVENTS_DISABLED = 0xC0220013;
+pub const FWP_INCOMPATIBLE_LAYER = 0xC0220014;
+pub const FWP_KM_CLIENTS_ONLY = 0xC0220015;
+pub const FWP_LIFETIME_MISMATCH = 0xC0220016;
+pub const FWP_BUILTIN_OBJECT = 0xC0220017;
+pub const FWP_TOO_MANY_BOOTTIME_FILTERS = 0xC0220018;
+pub const FWP_TOO_MANY_CALLOUTS = 0xC0220018;
+pub const FWP_NOTIFICATION_DROPPED = 0xC0220019;
+pub const FWP_TRAFFIC_MISMATCH = 0xC022001A;
+pub const FWP_INCOMPATIBLE_SA_STATE = 0xC022001B;
+pub const FWP_NULL_POINTER = 0xC022001C;
+pub const FWP_INVALID_ENUMERATOR = 0xC022001D;
+pub const FWP_INVALID_FLAGS = 0xC022001E;
+pub const FWP_INVALID_NET_MASK = 0xC022001F;
+pub const FWP_INVALID_RANGE = 0xC0220020;
+pub const FWP_INVALID_INTERVAL = 0xC0220021;
+pub const FWP_ZERO_LENGTH_ARRAY = 0xC0220022;
+pub const FWP_NULL_DISPLAY_NAME = 0xC0220023;
+pub const FWP_INVALID_ACTION_TYPE = 0xC0220024;
+pub const FWP_INVALID_WEIGHT = 0xC0220025;
+pub const FWP_MATCH_TYPE_MISMATCH = 0xC0220026;
+pub const FWP_TYPE_MISMATCH = 0xC0220027;
+pub const FWP_OUT_OF_BOUNDS = 0xC0220028;
+pub const FWP_RESERVED = 0xC0220029;
+pub const FWP_DUPLICATE_CONDITION = 0xC022002A;
+pub const FWP_DUPLICATE_KEYMOD = 0xC022002B;
+pub const FWP_ACTION_INCOMPATIBLE_WITH_LAYER = 0xC022002C;
+pub const FWP_ACTION_INCOMPATIBLE_WITH_SUBLAYER = 0xC022002D;
+pub const FWP_CONTEXT_INCOMPATIBLE_WITH_LAYER = 0xC022002E;
+pub const FWP_CONTEXT_INCOMPATIBLE_WITH_CALLOUT = 0xC022002F;
+pub const FWP_INCOMPATIBLE_AUTH_METHOD = 0xC0220030;
+pub const FWP_INCOMPATIBLE_DH_GROUP = 0xC0220031;
+pub const FWP_EM_NOT_SUPPORTED = 0xC0220032;
+pub const FWP_NEVER_MATCH = 0xC0220033;
+pub const FWP_PROVIDER_CONTEXT_MISMATCH = 0xC0220034;
+pub const FWP_INVALID_PARAMETER = 0xC0220035;
+pub const FWP_TOO_MANY_SUBLAYERS = 0xC0220036;
+pub const FWP_CALLOUT_NOTIFICATION_FAILED = 0xC0220037;
+pub const FWP_INCOMPATIBLE_AUTH_CONFIG = 0xC0220038;
+pub const FWP_INCOMPATIBLE_CIPHER_CONFIG = 0xC0220039;
+pub const FWP_DUPLICATE_AUTH_METHOD = 0xC022003C;
+pub const FWP_TCPIP_NOT_READY = 0xC0220100;
+pub const FWP_INJECT_HANDLE_CLOSING = 0xC0220101;
+pub const FWP_INJECT_HANDLE_STALE = 0xC0220102;
+pub const FWP_CANNOT_PEND = 0xC0220103;
+pub const NDIS_CLOSING = 0xC0230002;
+pub const NDIS_BAD_VERSION = 0xC0230004;
+pub const NDIS_BAD_CHARACTERISTICS = 0xC0230005;
+pub const NDIS_ADAPTER_NOT_FOUND = 0xC0230006;
+pub const NDIS_OPEN_FAILED = 0xC0230007;
+pub const NDIS_DEVICE_FAILED = 0xC0230008;
+pub const NDIS_MULTICAST_FULL = 0xC0230009;
+pub const NDIS_MULTICAST_EXISTS = 0xC023000A;
+pub const NDIS_MULTICAST_NOT_FOUND = 0xC023000B;
+pub const NDIS_REQUEST_ABORTED = 0xC023000C;
+pub const NDIS_RESET_IN_PROGRESS = 0xC023000D;
+pub const NDIS_INVALID_PACKET = 0xC023000F;
+pub const NDIS_INVALID_DEVICE_REQUEST = 0xC0230010;
+pub const NDIS_ADAPTER_NOT_READY = 0xC0230011;
+pub const NDIS_INVALID_LENGTH = 0xC0230014;
+pub const NDIS_INVALID_DATA = 0xC0230015;
+pub const NDIS_BUFFER_TOO_SHORT = 0xC0230016;
+pub const NDIS_INVALID_OID = 0xC0230017;
+pub const NDIS_ADAPTER_REMOVED = 0xC0230018;
+pub const NDIS_UNSUPPORTED_MEDIA = 0xC0230019;
+pub const NDIS_GROUP_ADDRESS_IN_USE = 0xC023001A;
+pub const NDIS_FILE_NOT_FOUND = 0xC023001B;
+pub const NDIS_ERROR_READING_FILE = 0xC023001C;
+pub const NDIS_ALREADY_MAPPED = 0xC023001D;
+pub const NDIS_RESOURCE_CONFLICT = 0xC023001E;
+pub const NDIS_MEDIA_DISCONNECTED = 0xC023001F;
+pub const NDIS_INVALID_ADDRESS = 0xC0230022;
+pub const NDIS_PAUSED = 0xC023002A;
+pub const NDIS_INTERFACE_NOT_FOUND = 0xC023002B;
+pub const NDIS_UNSUPPORTED_REVISION = 0xC023002C;
+pub const NDIS_INVALID_PORT = 0xC023002D;
+pub const NDIS_INVALID_PORT_STATE = 0xC023002E;
+pub const NDIS_LOW_POWER_STATE = 0xC023002F;
+pub const NDIS_NOT_SUPPORTED = 0xC02300BB;
+pub const NDIS_OFFLOAD_POLICY = 0xC023100F;
+pub const NDIS_OFFLOAD_CONNECTION_REJECTED = 0xC0231012;
+pub const NDIS_OFFLOAD_PATH_REJECTED = 0xC0231013;
+pub const NDIS_DOT11_AUTO_CONFIG_ENABLED = 0xC0232000;
+pub const NDIS_DOT11_MEDIA_IN_USE = 0xC0232001;
+pub const NDIS_DOT11_POWER_STATE_INVALID = 0xC0232002;
+pub const NDIS_PM_WOL_PATTERN_LIST_FULL = 0xC0232003;
+pub const NDIS_PM_PROTOCOL_OFFLOAD_LIST_FULL = 0xC0232004;
+pub const IPSEC_BAD_SPI = 0xC0360001;
+pub const IPSEC_SA_LIFETIME_EXPIRED = 0xC0360002;
+pub const IPSEC_WRONG_SA = 0xC0360003;
+pub const IPSEC_REPLAY_CHECK_FAILED = 0xC0360004;
+pub const IPSEC_INVALID_PACKET = 0xC0360005;
+pub const IPSEC_INTEGRITY_CHECK_FAILED = 0xC0360006;
+pub const IPSEC_CLEAR_TEXT_DROP = 0xC0360007;
+pub const IPSEC_AUTH_FIREWALL_DROP = 0xC0360008;
+pub const IPSEC_THROTTLE_DROP = 0xC0360009;
+pub const IPSEC_DOSP_BLOCK = 0xC0368000;
+pub const IPSEC_DOSP_RECEIVED_MULTICAST = 0xC0368001;
+pub const IPSEC_DOSP_INVALID_PACKET = 0xC0368002;
+pub const IPSEC_DOSP_STATE_LOOKUP_FAILED = 0xC0368003;
+pub const IPSEC_DOSP_MAX_ENTRIES = 0xC0368004;
+pub const IPSEC_DOSP_KEYMOD_NOT_ALLOWED = 0xC0368005;
+pub const IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES = 0xC0368006;
+pub const VOLMGR_MIRROR_NOT_SUPPORTED = 0xC038005B;
+pub const VOLMGR_RAID5_NOT_SUPPORTED = 0xC038005C;
+pub const VIRTDISK_PROVIDER_NOT_FOUND = 0xC03A0014;
+pub const VIRTDISK_NOT_VIRTUAL_DISK = 0xC03A0015;
+pub const VHD_PARENT_VHD_ACCESS_DENIED = 0xC03A0016;
+pub const VHD_CHILD_PARENT_SIZE_MISMATCH = 0xC03A0017;
+pub const VHD_DIFFERENCING_CHAIN_CYCLE_DETECTED = 0xC03A0018;
+pub const VHD_DIFFERENCING_CHAIN_ERROR_IN_PARENT = 0xC03A0019;
diff --git a/lib/std/os/windows/ws2_32.zig b/lib/std/os/windows/ws2_32.zig
new file mode 100644
index 0000000000..c34077a9dc
--- /dev/null
+++ b/lib/std/os/windows/ws2_32.zig
@@ -0,0 +1,257 @@
+usingnamespace @import("bits.zig");
+
+pub const SOCKET = *@OpaqueType();
+pub const INVALID_SOCKET = @intToPtr(SOCKET, ~@as(usize, 0));
+pub const SOCKET_ERROR = -1;
+
+pub const WSADESCRIPTION_LEN = 256;
+pub const WSASYS_STATUS_LEN = 128;
+
+pub const WSADATA = if (usize.bit_count == u64.bit_count)
+ extern struct {
+ wVersion: WORD,
+ wHighVersion: WORD,
+ iMaxSockets: u16,
+ iMaxUdpDg: u16,
+ lpVendorInfo: *u8,
+ szDescription: [WSADESCRIPTION_LEN + 1]u8,
+ szSystemStatus: [WSASYS_STATUS_LEN + 1]u8,
+ }
+else
+ extern struct {
+ wVersion: WORD,
+ wHighVersion: WORD,
+ szDescription: [WSADESCRIPTION_LEN + 1]u8,
+ szSystemStatus: [WSASYS_STATUS_LEN + 1]u8,
+ iMaxSockets: u16,
+ iMaxUdpDg: u16,
+ lpVendorInfo: *u8,
+ };
+
+pub const MAX_PROTOCOL_CHAIN = 7;
+
+pub const WSAPROTOCOLCHAIN = extern struct {
+ ChainLen: c_int,
+ ChainEntries: [MAX_PROTOCOL_CHAIN]DWORD,
+};
+
+pub const WSAPROTOCOL_LEN = 255;
+
+pub const WSAPROTOCOL_INFOA = extern struct {
+ dwServiceFlags1: DWORD,
+ dwServiceFlags2: DWORD,
+ dwServiceFlags3: DWORD,
+ dwServiceFlags4: DWORD,
+ dwProviderFlags: DWORD,
+ ProviderId: GUID,
+ dwCatalogEntryId: DWORD,
+ ProtocolChain: WSAPROTOCOLCHAIN,
+ iVersion: c_int,
+ iAddressFamily: c_int,
+ iMaxSockAddr: c_int,
+ iMinSockAddr: c_int,
+ iSocketType: c_int,
+ iProtocol: c_int,
+ iProtocolMaxOffset: c_int,
+ iNetworkByteOrder: c_int,
+ iSecurityScheme: c_int,
+ dwMessageSize: DWORD,
+ dwProviderReserved: DWORD,
+ szProtocol: [WSAPROTOCOL_LEN + 1]CHAR,
+};
+
+pub const WSAPROTOCOL_INFOW = extern struct {
+ dwServiceFlags1: DWORD,
+ dwServiceFlags2: DWORD,
+ dwServiceFlags3: DWORD,
+ dwServiceFlags4: DWORD,
+ dwProviderFlags: DWORD,
+ ProviderId: GUID,
+ dwCatalogEntryId: DWORD,
+ ProtocolChain: WSAPROTOCOLCHAIN,
+ iVersion: c_int,
+ iAddressFamily: c_int,
+ iMaxSockAddr: c_int,
+ iMinSockAddr: c_int,
+ iSocketType: c_int,
+ iProtocol: c_int,
+ iProtocolMaxOffset: c_int,
+ iNetworkByteOrder: c_int,
+ iSecurityScheme: c_int,
+ dwMessageSize: DWORD,
+ dwProviderReserved: DWORD,
+ szProtocol: [WSAPROTOCOL_LEN + 1]WCHAR,
+};
+
+pub const GROUP = u32;
+
+pub const SG_UNCONSTRAINED_GROUP = 0x1;
+pub const SG_CONSTRAINED_GROUP = 0x2;
+
+pub const WSA_FLAG_OVERLAPPED = 0x01;
+pub const WSA_FLAG_MULTIPOINT_C_ROOT = 0x02;
+pub const WSA_FLAG_MULTIPOINT_C_LEAF = 0x04;
+pub const WSA_FLAG_MULTIPOINT_D_ROOT = 0x08;
+pub const WSA_FLAG_MULTIPOINT_D_LEAF = 0x10;
+pub const WSA_FLAG_ACCESS_SYSTEM_SECURITY = 0x40;
+pub const WSA_FLAG_NO_HANDLE_INHERIT = 0x80;
+
+pub const WSAEVENT = HANDLE;
+
+pub const WSAOVERLAPPED = extern struct {
+ Internal: DWORD,
+ InternalHigh: DWORD,
+ Offset: DWORD,
+ OffsetHigh: DWORD,
+ hEvent: ?WSAEVENT,
+};
+
+pub const WSAOVERLAPPED_COMPLETION_ROUTINE = extern fn (
+ dwError: DWORD,
+ cbTransferred: DWORD,
+ lpOverlapped: *WSAOVERLAPPED,
+ dwFlags: DWORD
+) void;
+
+pub const WSA_INVALID_HANDLE = 6;
+pub const WSA_NOT_ENOUGH_MEMORY = 8;
+pub const WSA_INVALID_PARAMETER = 87;
+pub const WSA_OPERATION_ABORTED = 995;
+pub const WSA_IO_INCOMPLETE = 996;
+pub const WSA_IO_PENDING = 997;
+pub const WSAEINTR = 10004;
+pub const WSAEBADF = 10009;
+pub const WSAEACCES = 10013;
+pub const WSAEFAULT = 10014;
+pub const WSAEINVAL = 10022;
+pub const WSAEMFILE = 10024;
+pub const WSAEWOULDBLOCK = 10035;
+pub const WSAEINPROGRESS = 10036;
+pub const WSAEALREADY = 10037;
+pub const WSAENOTSOCK = 10038;
+pub const WSAEDESTADDRREQ = 10039;
+pub const WSAEMSGSIZE = 10040;
+pub const WSAEPROTOTYPE = 10041;
+pub const WSAENOPROTOOPT = 10042;
+pub const WSAEPROTONOSUPPORT = 10043;
+pub const WSAESOCKTNOSUPPORT = 10044;
+pub const WSAEOPNOTSUPP = 10045;
+pub const WSAEPFNOSUPPORT = 10046;
+pub const WSAEAFNOSUPPORT = 10047;
+pub const WSAEADDRINUSE = 10048;
+pub const WSAEADDRNOTAVAIL = 10049;
+pub const WSAENETDOWN = 10050;
+pub const WSAENETUNREACH = 10051;
+pub const WSAENETRESET = 10052;
+pub const WSAECONNABORTED = 10053;
+pub const WSAECONNRESET = 10054;
+pub const WSAENOBUFS = 10055;
+pub const WSAEISCONN = 10056;
+pub const WSAENOTCONN = 10057;
+pub const WSAESHUTDOWN = 10058;
+pub const WSAETOOMANYREFS = 10059;
+pub const WSAETIMEDOUT = 10060;
+pub const WSAECONNREFUSED = 10061;
+pub const WSAELOOP = 10062;
+pub const WSAENAMETOOLONG = 10063;
+pub const WSAEHOSTDOWN = 10064;
+pub const WSAEHOSTUNREACH = 10065;
+pub const WSAENOTEMPTY = 10066;
+pub const WSAEPROCLIM = 10067;
+pub const WSAEUSERS = 10068;
+pub const WSAEDQUOT = 10069;
+pub const WSAESTALE = 10070;
+pub const WSAEREMOTE = 10071;
+pub const WSASYSNOTREADY = 10091;
+pub const WSAVERNOTSUPPORTED = 10092;
+pub const WSANOTINITIALISED = 10093;
+pub const WSAEDISCON = 10101;
+pub const WSAENOMORE = 10102;
+pub const WSAECANCELLED = 10103;
+pub const WSAEINVALIDPROCTABLE = 10104;
+pub const WSAEINVALIDPROVIDER = 10105;
+pub const WSAEPROVIDERFAILEDINIT = 10106;
+pub const WSASYSCALLFAILURE = 10107;
+pub const WSASERVICE_NOT_FOUND = 10108;
+pub const WSATYPE_NOT_FOUND = 10109;
+pub const WSA_E_NO_MORE = 10110;
+pub const WSA_E_CANCELLED = 10111;
+pub const WSAEREFUSED = 10112;
+pub const WSAHOST_NOT_FOUND = 11001;
+pub const WSATRY_AGAIN = 11002;
+pub const WSANO_RECOVERY = 11003;
+pub const WSANO_DATA = 11004;
+pub const WSA_QOS_RECEIVERS = 11005;
+pub const WSA_QOS_SENDERS = 11006;
+pub const WSA_QOS_NO_SENDERS = 11007;
+pub const WSA_QOS_NO_RECEIVERS = 11008;
+pub const WSA_QOS_REQUEST_CONFIRMED = 11009;
+pub const WSA_QOS_ADMISSION_FAILURE = 11010;
+pub const WSA_QOS_POLICY_FAILURE = 11011;
+pub const WSA_QOS_BAD_STYLE = 11012;
+pub const WSA_QOS_BAD_OBJECT = 11013;
+pub const WSA_QOS_TRAFFIC_CTRL_ERROR = 11014;
+pub const WSA_QOS_GENERIC_ERROR = 11015;
+pub const WSA_QOS_ESERVICETYPE = 11016;
+pub const WSA_QOS_EFLOWSPEC = 11017;
+pub const WSA_QOS_EPROVSPECBUF = 11018;
+pub const WSA_QOS_EFILTERSTYLE = 11019;
+pub const WSA_QOS_EFILTERTYPE = 11020;
+pub const WSA_QOS_EFILTERCOUNT = 11021;
+pub const WSA_QOS_EOBJLENGTH = 11022;
+pub const WSA_QOS_EFLOWCOUNT = 11023;
+pub const WSA_QOS_EUNKOWNPSOBJ = 11024;
+pub const WSA_QOS_EPOLICYOBJ = 11025;
+pub const WSA_QOS_EFLOWDESC = 11026;
+pub const WSA_QOS_EPSFLOWSPEC = 11027;
+pub const WSA_QOS_EPSFILTERSPEC = 11028;
+pub const WSA_QOS_ESDMODEOBJ = 11029;
+pub const WSA_QOS_ESHAPERATEOBJ = 11030;
+pub const WSA_QOS_RESERVED_PETYPE = 11031;
+
+
+/// no parameters
+const IOC_VOID = 0x80000000;
+/// copy out parameters
+const IOC_OUT = 0x40000000;
+/// copy in parameters
+const IOC_IN = 0x80000000;
+
+/// The IOCTL is a generic Windows Sockets 2 IOCTL code. New IOCTL codes defined for Windows Sockets 2 will have T == 1.
+const IOC_WS2 = 0x08000000;
+
+pub const SIO_BASE_HANDLE = IOC_OUT | IOC_WS2 | 34;
+
+pub extern "ws2_32" stdcallcc fn WSAStartup(
+ wVersionRequired: WORD,
+ lpWSAData: *WSADATA,
+) c_int;
+pub extern "ws2_32" stdcallcc fn WSACleanup() c_int;
+pub extern "ws2_32" stdcallcc fn WSAGetLastError() c_int;
+pub extern "ws2_32" stdcallcc fn WSASocketA(
+ af: c_int,
+ type: c_int,
+ protocol: c_int,
+ lpProtocolInfo: ?*WSAPROTOCOL_INFOA,
+ g: GROUP,
+ dwFlags: DWORD,
+) SOCKET;
+pub extern "ws2_32" stdcallcc fn WSASocketW(
+ af: c_int,
+ type: c_int,
+ protocol: c_int,
+ lpProtocolInfo: ?*WSAPROTOCOL_INFOW,
+ g: GROUP,
+ dwFlags: DWORD,
+) SOCKET;
+pub extern "ws2_32" stdcallcc fn WSAIoctl(
+ s: SOCKET,
+ dwIoControlCode: DWORD,
+ lpvInBuffer: ?*const c_void,
+ cbInBuffer: DWORD,
+ lpvOutBuffer: ?LPVOID,
+ cbOutBuffer: DWORD,
+ lpcbBytesReturned: LPDWORD,
+ lpOverlapped: ?*WSAOVERLAPPED,
+ lpCompletionRoutine: ?*WSAOVERLAPPED_COMPLETION_ROUTINE,
+) c_int;
diff --git a/lib/std/os/zen.zig b/lib/std/os/zen.zig
index 9d111d98ae..190b7ffe08 100644
--- a/lib/std/os/zen.zig
+++ b/lib/std/os/zen.zig
@@ -138,7 +138,7 @@ pub const Syscall = enum(usize) {
////////////////////
pub fn exit(status: i32) noreturn {
- _ = syscall1(Syscall.exit, @bitCast(usize, isize(status)));
+ _ = syscall1(Syscall.exit, @bitCast(usize, @as(isize, status)));
unreachable;
}
@@ -167,7 +167,7 @@ pub fn map(v_addr: usize, p_addr: usize, size: usize, writable: bool) bool {
}
pub fn createThread(function: fn () void) u16 {
- return u16(syscall1(Syscall.createThread, @ptrToInt(function)));
+ return @as(u16, syscall1(Syscall.createThread, @ptrToInt(function)));
}
/////////////////////////
diff --git a/lib/std/packed_int_array.zig b/lib/std/packed_int_array.zig
index 5cbab2d33b..d8c77db59b 100644
--- a/lib/std/packed_int_array.zig
+++ b/lib/std/packed_int_array.zig
@@ -193,7 +193,7 @@ pub fn PackedIntArrayEndian(comptime Int: type, comptime endian: builtin.Endian,
///Initialize a packed array using an unpacked array
/// or, more likely, an array literal.
pub fn init(ints: [int_count]Int) Self {
- var self = Self(undefined);
+ var self = @as(Self, undefined);
for (ints) |int, i| self.set(i, int);
return self;
}
@@ -328,11 +328,11 @@ test "PackedIntArray" {
const expected_bytes = ((bits * int_count) + 7) / 8;
testing.expect(@sizeOf(PackedArray) == expected_bytes);
- var data = PackedArray(undefined);
+ var data = @as(PackedArray, undefined);
//write values, counting up
- var i = usize(0);
- var count = I(0);
+ var i = @as(usize, 0);
+ var count = @as(I, 0);
while (i < data.len()) : (i += 1) {
data.set(i, count);
if (bits > 0) count +%= 1;
@@ -352,7 +352,7 @@ test "PackedIntArray" {
test "PackedIntArray init" {
const PackedArray = PackedIntArray(u3, 8);
var packed_array = PackedArray.init([_]u3{ 0, 1, 2, 3, 4, 5, 6, 7 });
- var i = usize(0);
+ var i = @as(usize, 0);
while (i < packed_array.len()) : (i += 1) testing.expect(packed_array.get(i) == i);
}
@@ -375,8 +375,8 @@ test "PackedIntSlice" {
var data = P.init(&buffer, int_count);
//write values, counting up
- var i = usize(0);
- var count = I(0);
+ var i = @as(usize, 0);
+ var count = @as(I, 0);
while (i < data.len()) : (i += 1) {
data.set(i, count);
if (bits > 0) count +%= 1;
@@ -402,11 +402,11 @@ test "PackedIntSlice of PackedInt(Array/Slice)" {
const Int = @IntType(false, bits);
const PackedArray = PackedIntArray(Int, int_count);
- var packed_array = PackedArray(undefined);
+ var packed_array = @as(PackedArray, undefined);
const limit = (1 << bits);
- var i = usize(0);
+ var i = @as(usize, 0);
while (i < packed_array.len()) : (i += 1) {
packed_array.set(i, @intCast(Int, i % limit));
}
@@ -463,20 +463,20 @@ test "PackedIntSlice accumulating bit offsets" {
// anything
{
const PackedArray = PackedIntArray(u3, 16);
- var packed_array = PackedArray(undefined);
+ var packed_array = @as(PackedArray, undefined);
var packed_slice = packed_array.slice(0, packed_array.len());
- var i = usize(0);
+ var i = @as(usize, 0);
while (i < packed_array.len() - 1) : (i += 1) {
packed_slice = packed_slice.slice(1, packed_slice.len());
}
}
{
const PackedArray = PackedIntArray(u11, 88);
- var packed_array = PackedArray(undefined);
+ var packed_array = @as(PackedArray, undefined);
var packed_slice = packed_array.slice(0, packed_array.len());
- var i = usize(0);
+ var i = @as(usize, 0);
while (i < packed_array.len() - 1) : (i += 1) {
packed_slice = packed_slice.slice(1, packed_slice.len());
}
@@ -493,7 +493,7 @@ test "PackedInt(Array/Slice) sliceCast" {
var packed_slice_cast_9 = packed_array.slice(0, (packed_array.len() / 9) * 9).sliceCast(u9);
const packed_slice_cast_3 = packed_slice_cast_9.sliceCast(u3);
- var i = usize(0);
+ var i = @as(usize, 0);
while (i < packed_slice_cast_2.len()) : (i += 1) {
const val = switch (builtin.endian) {
.Big => 0b01,
@@ -518,8 +518,8 @@ test "PackedInt(Array/Slice) sliceCast" {
i = 0;
while (i < packed_slice_cast_3.len()) : (i += 1) {
const val = switch (builtin.endian) {
- .Big => if (i % 2 == 0) u3(0b111) else u3(0b000),
- .Little => if (i % 2 == 0) u3(0b111) else u3(0b000),
+ .Big => if (i % 2 == 0) @as(u3, 0b111) else @as(u3, 0b000),
+ .Little => if (i % 2 == 0) @as(u3, 0b111) else @as(u3, 0b000),
};
testing.expect(packed_slice_cast_3.get(i) == val);
}
@@ -541,7 +541,7 @@ test "PackedInt(Array/Slice)Endian" {
testing.expect(packed_array_be.bytes[0] == 0b00000001);
testing.expect(packed_array_be.bytes[1] == 0b00100011);
- var i = usize(0);
+ var i = @as(usize, 0);
while (i < packed_array_be.len()) : (i += 1) {
testing.expect(packed_array_be.get(i) == i);
}
@@ -579,7 +579,7 @@ test "PackedInt(Array/Slice)Endian" {
testing.expect(packed_array_be.bytes[3] == 0b00000001);
testing.expect(packed_array_be.bytes[4] == 0b00000000);
- var i = usize(0);
+ var i = @as(usize, 0);
while (i < packed_array_be.len()) : (i += 1) {
testing.expect(packed_array_be.get(i) == i);
}
diff --git a/lib/std/parker.zig b/lib/std/parker.zig
new file mode 100644
index 0000000000..4ba0100b9e
--- /dev/null
+++ b/lib/std/parker.zig
@@ -0,0 +1,180 @@
+const std = @import("std.zig");
+const builtin = @import("builtin");
+const time = std.time;
+const testing = std.testing;
+const assert = std.debug.assert;
+const SpinLock = std.SpinLock;
+const linux = std.os.linux;
+const windows = std.os.windows;
+
+pub const ThreadParker = switch (builtin.os) {
+ .linux => if (builtin.link_libc) PosixParker else LinuxParker,
+ .windows => WindowsParker,
+ else => if (builtin.link_libc) PosixParker else SpinParker,
+};
+
+const SpinParker = struct {
+ pub fn init() SpinParker {
+ return SpinParker{};
+ }
+ pub fn deinit(self: *SpinParker) void {}
+
+ pub fn unpark(self: *SpinParker, ptr: *const u32) void {}
+
+ pub fn park(self: *SpinParker, ptr: *const u32, expected: u32) void {
+ var backoff = SpinLock.Backoff.init();
+ while (@atomicLoad(u32, ptr, .Acquire) == expected)
+ backoff.yield();
+ }
+};
+
+const LinuxParker = struct {
+ pub fn init() LinuxParker {
+ return LinuxParker{};
+ }
+ pub fn deinit(self: *LinuxParker) void {}
+
+ pub fn unpark(self: *LinuxParker, ptr: *const u32) void {
+ const rc = linux.futex_wake(@ptrCast(*const i32, ptr), linux.FUTEX_WAKE | linux.FUTEX_PRIVATE_FLAG, 1);
+ assert(linux.getErrno(rc) == 0);
+ }
+
+ pub fn park(self: *LinuxParker, ptr: *const u32, expected: u32) void {
+ const value = @intCast(i32, expected);
+ while (@atomicLoad(u32, ptr, .Acquire) == expected) {
+ const rc = linux.futex_wait(@ptrCast(*const i32, ptr), linux.FUTEX_WAIT | linux.FUTEX_PRIVATE_FLAG, value, null);
+ switch (linux.getErrno(rc)) {
+ 0, linux.EAGAIN => return,
+ linux.EINTR => continue,
+ linux.EINVAL => unreachable,
+ else => continue,
+ }
+ }
+ }
+};
+
+const WindowsParker = struct {
+ waiters: u32,
+
+ pub fn init() WindowsParker {
+ return WindowsParker{ .waiters = 0 };
+ }
+ pub fn deinit(self: *WindowsParker) void {}
+
+ pub fn unpark(self: *WindowsParker, ptr: *const u32) void {
+ const key = @ptrCast(*const c_void, ptr);
+ const handle = getEventHandle() orelse return;
+
+ var waiting = @atomicLoad(u32, &self.waiters, .Monotonic);
+ while (waiting != 0) {
+ waiting = @cmpxchgWeak(u32, &self.waiters, waiting, waiting - 1, .Acquire, .Monotonic) orelse {
+ const rc = windows.ntdll.NtReleaseKeyedEvent(handle, key, windows.FALSE, null);
+ assert(rc == 0);
+ return;
+ };
+ }
+ }
+
+ pub fn park(self: *WindowsParker, ptr: *const u32, expected: u32) void {
+ var spin = SpinLock.Backoff.init();
+ const ev_handle = getEventHandle();
+ const key = @ptrCast(*const c_void, ptr);
+
+ while (@atomicLoad(u32, ptr, .Monotonic) == expected) {
+ if (ev_handle) |handle| {
+ _ = @atomicRmw(u32, &self.waiters, .Add, 1, .Release);
+ const rc = windows.ntdll.NtWaitForKeyedEvent(handle, key, windows.FALSE, null);
+ assert(rc == 0);
+ } else {
+ spin.yield();
+ }
+ }
+ }
+
+ var event_handle = std.lazyInit(windows.HANDLE);
+
+ fn getEventHandle() ?windows.HANDLE {
+ if (event_handle.get()) |handle_ptr|
+ return handle_ptr.*;
+ defer event_handle.resolve();
+
+ const access_mask = windows.GENERIC_READ | windows.GENERIC_WRITE;
+ if (windows.ntdll.NtCreateKeyedEvent(&event_handle.data, access_mask, null, 0) != 0)
+ return null;
+ return event_handle.data;
+ }
+};
+
+const PosixParker = struct {
+ cond: c.pthread_cond_t,
+ mutex: c.pthread_mutex_t,
+
+ const c = std.c;
+
+ pub fn init() PosixParker {
+ return PosixParker{
+ .cond = c.PTHREAD_COND_INITIALIZER,
+ .mutex = c.PTHREAD_MUTEX_INITIALIZER,
+ };
+ }
+
+ pub fn deinit(self: *PosixParker) void {
+ // On dragonfly, the destroy functions return EINVAL if they were initialized statically.
+ const retm = c.pthread_mutex_destroy(&self.mutex);
+ assert(retm == 0 or retm == (if (builtin.os == .dragonfly) os.EINVAL else 0));
+ const retc = c.pthread_cond_destroy(&self.cond);
+ assert(retc == 0 or retc == (if (builtin.os == .dragonfly) os.EINVAL else 0));
+ }
+
+ pub fn unpark(self: *PosixParker, ptr: *const u32) void {
+ assert(c.pthread_mutex_lock(&self.mutex) == 0);
+ defer assert(c.pthread_mutex_unlock(&self.mutex) == 0);
+ assert(c.pthread_cond_signal(&self.cond) == 0);
+ }
+
+ pub fn park(self: *PosixParker, ptr: *const u32, expected: u32) void {
+ assert(c.pthread_mutex_lock(&self.mutex) == 0);
+ defer assert(c.pthread_mutex_unlock(&self.mutex) == 0);
+ while (@atomicLoad(u32, ptr, .Acquire) == expected)
+ assert(c.pthread_cond_wait(&self.cond, &self.mutex) == 0);
+ }
+};
+
+test "std.ThreadParker" {
+ if (builtin.single_threaded)
+ return error.SkipZigTest;
+
+ const Context = struct {
+ parker: ThreadParker,
+ data: u32,
+
+ fn receiver(self: *@This()) void {
+ self.parker.park(&self.data, 0); // receives 1
+ assert(@atomicRmw(u32, &self.data, .Xchg, 2, .SeqCst) == 1); // sends 2
+ self.parker.unpark(&self.data); // wakes up waiters on 2
+ self.parker.park(&self.data, 2); // receives 3
+ assert(@atomicRmw(u32, &self.data, .Xchg, 4, .SeqCst) == 3); // sends 4
+ self.parker.unpark(&self.data); // wakes up waiters on 4
+ }
+
+ fn sender(self: *@This()) void {
+ assert(@atomicRmw(u32, &self.data, .Xchg, 1, .SeqCst) == 0); // sends 1
+ self.parker.unpark(&self.data); // wakes up waiters on 1
+ self.parker.park(&self.data, 1); // receives 2
+ assert(@atomicRmw(u32, &self.data, .Xchg, 3, .SeqCst) == 2); // sends 3
+ self.parker.unpark(&self.data); // wakes up waiters on 3
+ self.parker.park(&self.data, 3); // receives 4
+ }
+ };
+
+ var context = Context{
+ .parker = ThreadParker.init(),
+ .data = 0,
+ };
+ defer context.parker.deinit();
+
+ var receiver = try std.Thread.spawn(&context, Context.receiver);
+ defer receiver.wait();
+
+ context.sender();
+}
diff --git a/lib/std/pdb.zig b/lib/std/pdb.zig
index 7a2b2c6b6b..8e4a9b5d6a 100644
--- a/lib/std/pdb.zig
+++ b/lib/std/pdb.zig
@@ -532,7 +532,7 @@ const Msf = struct {
const stream_sizes = try allocator.alloc(u32, stream_count);
defer allocator.free(stream_sizes);
- // Microsoft's implementation uses u32(-1) for inexistant streams.
+ // Microsoft's implementation uses @as(u32, -1) for inexistant streams.
// These streams are not used, but still participate in the file
// and must be taken into account when resolving stream indices.
const Nil = 0xFFFFFFFF;
diff --git a/lib/std/priority_queue.zig b/lib/std/priority_queue.zig
index a081e03c5f..bf54f6937f 100644
--- a/lib/std/priority_queue.zig
+++ b/lib/std/priority_queue.zig
@@ -236,12 +236,12 @@ test "std.PriorityQueue: add and remove min heap" {
try queue.add(23);
try queue.add(25);
try queue.add(13);
- expectEqual(u32(7), queue.remove());
- expectEqual(u32(12), queue.remove());
- expectEqual(u32(13), queue.remove());
- expectEqual(u32(23), queue.remove());
- expectEqual(u32(25), queue.remove());
- expectEqual(u32(54), queue.remove());
+ expectEqual(@as(u32, 7), queue.remove());
+ expectEqual(@as(u32, 12), queue.remove());
+ expectEqual(@as(u32, 13), queue.remove());
+ expectEqual(@as(u32, 23), queue.remove());
+ expectEqual(@as(u32, 25), queue.remove());
+ expectEqual(@as(u32, 54), queue.remove());
}
test "std.PriorityQueue: add and remove same min heap" {
@@ -254,12 +254,12 @@ test "std.PriorityQueue: add and remove same min heap" {
try queue.add(2);
try queue.add(1);
try queue.add(1);
- expectEqual(u32(1), queue.remove());
- expectEqual(u32(1), queue.remove());
- expectEqual(u32(1), queue.remove());
- expectEqual(u32(1), queue.remove());
- expectEqual(u32(2), queue.remove());
- expectEqual(u32(2), queue.remove());
+ expectEqual(@as(u32, 1), queue.remove());
+ expectEqual(@as(u32, 1), queue.remove());
+ expectEqual(@as(u32, 1), queue.remove());
+ expectEqual(@as(u32, 1), queue.remove());
+ expectEqual(@as(u32, 2), queue.remove());
+ expectEqual(@as(u32, 2), queue.remove());
}
test "std.PriorityQueue: removeOrNull on empty" {
@@ -276,9 +276,9 @@ test "std.PriorityQueue: edge case 3 elements" {
try queue.add(9);
try queue.add(3);
try queue.add(2);
- expectEqual(u32(2), queue.remove());
- expectEqual(u32(3), queue.remove());
- expectEqual(u32(9), queue.remove());
+ expectEqual(@as(u32, 2), queue.remove());
+ expectEqual(@as(u32, 3), queue.remove());
+ expectEqual(@as(u32, 9), queue.remove());
}
test "std.PriorityQueue: peek" {
@@ -289,8 +289,8 @@ test "std.PriorityQueue: peek" {
try queue.add(9);
try queue.add(3);
try queue.add(2);
- expectEqual(u32(2), queue.peek().?);
- expectEqual(u32(2), queue.peek().?);
+ expectEqual(@as(u32, 2), queue.peek().?);
+ expectEqual(@as(u32, 2), queue.peek().?);
}
test "std.PriorityQueue: sift up with odd indices" {
@@ -341,12 +341,12 @@ test "std.PriorityQueue: add and remove max heap" {
try queue.add(23);
try queue.add(25);
try queue.add(13);
- expectEqual(u32(54), queue.remove());
- expectEqual(u32(25), queue.remove());
- expectEqual(u32(23), queue.remove());
- expectEqual(u32(13), queue.remove());
- expectEqual(u32(12), queue.remove());
- expectEqual(u32(7), queue.remove());
+ expectEqual(@as(u32, 54), queue.remove());
+ expectEqual(@as(u32, 25), queue.remove());
+ expectEqual(@as(u32, 23), queue.remove());
+ expectEqual(@as(u32, 13), queue.remove());
+ expectEqual(@as(u32, 12), queue.remove());
+ expectEqual(@as(u32, 7), queue.remove());
}
test "std.PriorityQueue: add and remove same max heap" {
@@ -359,12 +359,12 @@ test "std.PriorityQueue: add and remove same max heap" {
try queue.add(2);
try queue.add(1);
try queue.add(1);
- expectEqual(u32(2), queue.remove());
- expectEqual(u32(2), queue.remove());
- expectEqual(u32(1), queue.remove());
- expectEqual(u32(1), queue.remove());
- expectEqual(u32(1), queue.remove());
- expectEqual(u32(1), queue.remove());
+ expectEqual(@as(u32, 2), queue.remove());
+ expectEqual(@as(u32, 2), queue.remove());
+ expectEqual(@as(u32, 1), queue.remove());
+ expectEqual(@as(u32, 1), queue.remove());
+ expectEqual(@as(u32, 1), queue.remove());
+ expectEqual(@as(u32, 1), queue.remove());
}
test "std.PriorityQueue: iterator" {
@@ -386,5 +386,5 @@ test "std.PriorityQueue: iterator" {
_ = map.remove(e);
}
- expectEqual(usize(0), map.count());
+ expectEqual(@as(usize, 0), map.count());
}
diff --git a/lib/std/progress.zig b/lib/std/progress.zig
index fba77092b3..034d7ade26 100644
--- a/lib/std/progress.zig
+++ b/lib/std/progress.zig
@@ -98,11 +98,8 @@ pub const Progress = struct {
/// TODO solve https://github.com/ziglang/zig/issues/2765 and then change this
/// API to return Progress rather than accept it as a parameter.
pub fn start(self: *Progress, name: []const u8, estimated_total_items: ?usize) !*Node {
- if (std.io.getStdErr()) |stderr| {
- self.terminal = if (stderr.supportsAnsiEscapeCodes()) stderr else null;
- } else |_| {
- self.terminal = null;
- }
+ const stderr = std.io.getStdErr();
+ self.terminal = if (stderr.supportsAnsiEscapeCodes()) stderr else null;
self.root = Node{
.context = self,
.parent = null,
diff --git a/lib/std/rand.zig b/lib/std/rand.zig
index e14a60e2ae..1fea0526ed 100644
--- a/lib/std/rand.zig
+++ b/lib/std/rand.zig
@@ -93,13 +93,13 @@ pub const Random = struct {
// http://www.pcg-random.org/posts/bounded-rands.html
// "Lemire's (with an extra tweak from me)"
var x: Small = r.int(Small);
- var m: Large = Large(x) * Large(less_than);
+ var m: Large = @as(Large, x) * @as(Large, less_than);
var l: Small = @truncate(Small, m);
if (l < less_than) {
// TODO: workaround for https://github.com/ziglang/zig/issues/1770
// should be:
// var t: Small = -%less_than;
- var t: Small = @bitCast(Small, -%@bitCast(@IntType(true, Small.bit_count), Small(less_than)));
+ var t: Small = @bitCast(Small, -%@bitCast(@IntType(true, Small.bit_count), @as(Small, less_than)));
if (t >= less_than) {
t -= less_than;
@@ -109,7 +109,7 @@ pub const Random = struct {
}
while (l < t) {
x = r.int(Small);
- m = Large(x) * Large(less_than);
+ m = @as(Large, x) * @as(Large, less_than);
l = @truncate(Small, m);
}
}
@@ -286,7 +286,7 @@ pub fn limitRangeBiased(comptime T: type, random_int: T, less_than: T) T {
// adapted from:
// http://www.pcg-random.org/posts/bounded-rands.html
// "Integer Multiplication (Biased)"
- var m: T2 = T2(random_int) * T2(less_than);
+ var m: T2 = @as(T2, random_int) * @as(T2, less_than);
return @intCast(T, m >> T.bit_count);
}
@@ -633,8 +633,8 @@ pub const Xoroshiro128 = struct {
const r = s0 +% s1;
s1 ^= s0;
- self.s[0] = math.rotl(u64, s0, u8(55)) ^ s1 ^ (s1 << 14);
- self.s[1] = math.rotl(u64, s1, u8(36));
+ self.s[0] = math.rotl(u64, s0, @as(u8, 55)) ^ s1 ^ (s1 << 14);
+ self.s[1] = math.rotl(u64, s1, @as(u8, 36));
return r;
}
@@ -652,7 +652,7 @@ pub const Xoroshiro128 = struct {
inline for (table) |entry| {
var b: usize = 0;
while (b < 64) : (b += 1) {
- if ((entry & (u64(1) << @intCast(u6, b))) != 0) {
+ if ((entry & (@as(u64, 1) << @intCast(u6, b))) != 0) {
s0 ^= self.s[0];
s1 ^= self.s[1];
}
@@ -1090,7 +1090,7 @@ fn testRange(r: *Random, start: i8, end: i8) void {
testRangeBias(r, start, end, false);
}
fn testRangeBias(r: *Random, start: i8, end: i8, biased: bool) void {
- const count = @intCast(usize, i32(end) - i32(start));
+ const count = @intCast(usize, @as(i32, end) - @as(i32, start));
var values_buffer = [_]bool{false} ** 0x100;
const values = values_buffer[0..count];
var i: usize = 0;
diff --git a/lib/std/rand/ziggurat.zig b/lib/std/rand/ziggurat.zig
index 995248415b..c29d3eeb2b 100644
--- a/lib/std/rand/ziggurat.zig
+++ b/lib/std/rand/ziggurat.zig
@@ -17,7 +17,7 @@ pub fn next_f64(random: *Random, comptime tables: ZigTable) f64 {
// We manually construct a float from parts as we can avoid an extra random lookup here by
// using the unused exponent for the lookup table entry.
const bits = random.scalar(u64);
- const i = usize(bits & 0xff);
+ const i = @as(usize, bits & 0xff);
const u = blk: {
if (tables.is_symmetric) {
diff --git a/lib/std/segmented_list.zig b/lib/std/segmented_list.zig
index 3bbbde782e..7db1535755 100644
--- a/lib/std/segmented_list.zig
+++ b/lib/std/segmented_list.zig
@@ -162,7 +162,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
/// Grows or shrinks capacity to match usage.
pub fn setCapacity(self: *Self, new_capacity: usize) !void {
if (prealloc_item_count != 0) {
- if (new_capacity <= usize(1) << (prealloc_exp + @intCast(ShelfIndex, self.dynamic_segments.len))) {
+ if (new_capacity <= @as(usize, 1) << (prealloc_exp + @intCast(ShelfIndex, self.dynamic_segments.len))) {
return self.shrinkCapacity(new_capacity);
}
}
@@ -231,9 +231,9 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
fn shelfSize(shelf_index: ShelfIndex) usize {
if (prealloc_item_count == 0) {
- return usize(1) << shelf_index;
+ return @as(usize, 1) << shelf_index;
}
- return usize(1) << (shelf_index + (prealloc_exp + 1));
+ return @as(usize, 1) << (shelf_index + (prealloc_exp + 1));
}
fn shelfIndex(list_index: usize) ShelfIndex {
@@ -245,9 +245,9 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
fn boxIndex(list_index: usize, shelf_index: ShelfIndex) usize {
if (prealloc_item_count == 0) {
- return (list_index + 1) - (usize(1) << shelf_index);
+ return (list_index + 1) - (@as(usize, 1) << shelf_index);
}
- return list_index + prealloc_item_count - (usize(1) << ((prealloc_exp + 1) + shelf_index));
+ return list_index + prealloc_item_count - (@as(usize, 1) << ((prealloc_exp + 1) + shelf_index));
}
fn freeShelves(self: *Self, from_count: ShelfIndex, to_count: ShelfIndex) void {
diff --git a/lib/std/sort.zig b/lib/std/sort.zig
index 378a92992f..c5758dd6e7 100644
--- a/lib/std/sort.zig
+++ b/lib/std/sort.zig
@@ -813,7 +813,7 @@ fn blockSwap(comptime T: type, items: []T, start1: usize, start2: usize, block_s
// where have some idea as to how many unique values there are and where the next value might be
fn findFirstForward(comptime T: type, items: []T, value: T, range: Range, lessThan: fn (T, T) bool, unique: usize) usize {
if (range.length() == 0) return range.start;
- const skip = math.max(range.length() / unique, usize(1));
+ const skip = math.max(range.length() / unique, @as(usize, 1));
var index = range.start + skip;
while (lessThan(items[index - 1], value)) : (index += skip) {
@@ -827,7 +827,7 @@ fn findFirstForward(comptime T: type, items: []T, value: T, range: Range, lessTh
fn findFirstBackward(comptime T: type, items: []T, value: T, range: Range, lessThan: fn (T, T) bool, unique: usize) usize {
if (range.length() == 0) return range.start;
- const skip = math.max(range.length() / unique, usize(1));
+ const skip = math.max(range.length() / unique, @as(usize, 1));
var index = range.end - skip;
while (index > range.start and !lessThan(items[index - 1], value)) : (index -= skip) {
@@ -841,7 +841,7 @@ fn findFirstBackward(comptime T: type, items: []T, value: T, range: Range, lessT
fn findLastForward(comptime T: type, items: []T, value: T, range: Range, lessThan: fn (T, T) bool, unique: usize) usize {
if (range.length() == 0) return range.start;
- const skip = math.max(range.length() / unique, usize(1));
+ const skip = math.max(range.length() / unique, @as(usize, 1));
var index = range.start + skip;
while (!lessThan(value, items[index - 1])) : (index += skip) {
@@ -855,7 +855,7 @@ fn findLastForward(comptime T: type, items: []T, value: T, range: Range, lessTha
fn findLastBackward(comptime T: type, items: []T, value: T, range: Range, lessThan: fn (T, T) bool, unique: usize) usize {
if (range.length() == 0) return range.start;
- const skip = math.max(range.length() / unique, usize(1));
+ const skip = math.max(range.length() / unique, @as(usize, 1));
var index = range.end - skip;
while (index > range.start and lessThan(value, items[index - 1])) : (index -= skip) {
diff --git a/lib/std/special/build_runner.zig b/lib/std/special/build_runner.zig
index efe3275fe6..fdf5193c03 100644
--- a/lib/std/special/build_runner.zig
+++ b/lib/std/special/build_runner.zig
@@ -43,19 +43,8 @@ pub fn main() !void {
var targets = ArrayList([]const u8).init(allocator);
- var stderr_file = io.getStdErr();
- var stderr_file_stream: File.OutStream = undefined;
- var stderr_stream = if (stderr_file) |f| x: {
- stderr_file_stream = f.outStream();
- break :x &stderr_file_stream.stream;
- } else |err| err;
-
- var stdout_file = io.getStdOut();
- var stdout_file_stream: File.OutStream = undefined;
- var stdout_stream = if (stdout_file) |f| x: {
- stdout_file_stream = f.outStream();
- break :x &stdout_file_stream.stream;
- } else |err| err;
+ const stderr_stream = &io.getStdErr().outStream().stream;
+ const stdout_stream = &io.getStdOut().outStream().stream;
while (arg_it.next(allocator)) |err_or_arg| {
const arg = try unwrapArg(err_or_arg);
@@ -63,37 +52,37 @@ pub fn main() !void {
const option_contents = arg[2..];
if (option_contents.len == 0) {
warn("Expected option name after '-D'\n\n");
- return usageAndErr(builder, false, try stderr_stream);
+ return usageAndErr(builder, false, stderr_stream);
}
if (mem.indexOfScalar(u8, option_contents, '=')) |name_end| {
const option_name = option_contents[0..name_end];
const option_value = option_contents[name_end + 1 ..];
if (try builder.addUserInputOption(option_name, option_value))
- return usageAndErr(builder, false, try stderr_stream);
+ return usageAndErr(builder, false, stderr_stream);
} else {
if (try builder.addUserInputFlag(option_contents))
- return usageAndErr(builder, false, try stderr_stream);
+ return usageAndErr(builder, false, stderr_stream);
}
} else if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "--verbose")) {
builder.verbose = true;
} else if (mem.eql(u8, arg, "--help")) {
- return usage(builder, false, try stdout_stream);
+ return usage(builder, false, stdout_stream);
} else if (mem.eql(u8, arg, "--prefix")) {
builder.install_prefix = try unwrapArg(arg_it.next(allocator) orelse {
warn("Expected argument after --prefix\n\n");
- return usageAndErr(builder, false, try stderr_stream);
+ return usageAndErr(builder, false, stderr_stream);
});
} else if (mem.eql(u8, arg, "--search-prefix")) {
const search_prefix = try unwrapArg(arg_it.next(allocator) orelse {
warn("Expected argument after --search-prefix\n\n");
- return usageAndErr(builder, false, try stderr_stream);
+ return usageAndErr(builder, false, stderr_stream);
});
builder.addSearchPrefix(search_prefix);
} else if (mem.eql(u8, arg, "--override-lib-dir")) {
builder.override_lib_dir = try unwrapArg(arg_it.next(allocator) orelse {
warn("Expected argument after --override-lib-dir\n\n");
- return usageAndErr(builder, false, try stderr_stream);
+ return usageAndErr(builder, false, stderr_stream);
});
} else if (mem.eql(u8, arg, "--verbose-tokenize")) {
builder.verbose_tokenize = true;
@@ -111,7 +100,7 @@ pub fn main() !void {
builder.verbose_cc = true;
} else {
warn("Unrecognized argument: {}\n\n", arg);
- return usageAndErr(builder, false, try stderr_stream);
+ return usageAndErr(builder, false, stderr_stream);
}
} else {
try targets.append(arg);
@@ -122,12 +111,12 @@ pub fn main() !void {
try runBuild(builder);
if (builder.validateUserInputDidItFail())
- return usageAndErr(builder, true, try stderr_stream);
+ return usageAndErr(builder, true, stderr_stream);
builder.make(targets.toSliceConst()) catch |err| {
switch (err) {
error.InvalidStepName => {
- return usageAndErr(builder, true, try stderr_stream);
+ return usageAndErr(builder, true, stderr_stream);
},
error.UncleanExit => process.exit(1),
else => return err,
diff --git a/lib/std/special/c.zig b/lib/std/special/c.zig
index 473d2d4e33..145c8897d5 100644
--- a/lib/std/special/c.zig
+++ b/lib/std/special/c.zig
@@ -62,7 +62,7 @@ extern fn strncmp(_l: [*]const u8, _r: [*]const u8, _n: usize) c_int {
r += 1;
n -= 1;
}
- return c_int(l[0]) - c_int(r[0]);
+ return @as(c_int, l[0]) - @as(c_int, r[0]);
}
extern fn strerror(errnum: c_int) [*]const u8 {
@@ -540,7 +540,7 @@ fn generic_fmod(comptime T: type, x: T, y: T) T {
// scale result up
if (ex > 0) {
ux -%= 1 << digits;
- ux |= uint(@bitCast(u32, ex)) << digits;
+ ux |= @as(uint, @bitCast(u32, ex)) << digits;
} else {
ux >>= @intCast(log2uint, @bitCast(u32, -ex + 1));
}
@@ -687,7 +687,7 @@ export fn sqrt(x: f64) f64 {
export fn sqrtf(x: f32) f32 {
const tiny: f32 = 1.0e-30;
- const sign: i32 = @bitCast(i32, u32(0x80000000));
+ const sign: i32 = @bitCast(i32, @as(u32, 0x80000000));
var ix: i32 = @bitCast(i32, x);
if ((ix & 0x7F800000) == 0x7F800000) {
diff --git a/lib/std/special/compiler_rt.zig b/lib/std/special/compiler_rt.zig
index 0a09f616e9..1fbb618b1e 100644
--- a/lib/std/special/compiler_rt.zig
+++ b/lib/std/special/compiler_rt.zig
@@ -672,7 +672,7 @@ extern fn __udivsi3(n: u32, d: u32) u32 {
// special cases
if (d == 0) return 0; // ?!
if (n == 0) return 0;
- var sr = @bitCast(c_uint, c_int(@clz(u32, d)) - c_int(@clz(u32, n)));
+ var sr = @bitCast(c_uint, @as(c_int, @clz(u32, d)) - @as(c_int, @clz(u32, n)));
// 0 <= sr <= n_uword_bits - 1 or sr large
if (sr > n_uword_bits - 1) {
// d > r
@@ -1414,10 +1414,10 @@ test "test_divsi3" {
[_]i32{ -2, 1, -2 },
[_]i32{ -2, -1, 2 },
- [_]i32{ @bitCast(i32, u32(0x80000000)), 1, @bitCast(i32, u32(0x80000000)) },
- [_]i32{ @bitCast(i32, u32(0x80000000)), -1, @bitCast(i32, u32(0x80000000)) },
- [_]i32{ @bitCast(i32, u32(0x80000000)), -2, 0x40000000 },
- [_]i32{ @bitCast(i32, u32(0x80000000)), 2, @bitCast(i32, u32(0xC0000000)) },
+ [_]i32{ @bitCast(i32, @as(u32, 0x80000000)), 1, @bitCast(i32, @as(u32, 0x80000000)) },
+ [_]i32{ @bitCast(i32, @as(u32, 0x80000000)), -1, @bitCast(i32, @as(u32, 0x80000000)) },
+ [_]i32{ @bitCast(i32, @as(u32, 0x80000000)), -2, 0x40000000 },
+ [_]i32{ @bitCast(i32, @as(u32, 0x80000000)), 2, @bitCast(i32, @as(u32, 0xC0000000)) },
};
for (cases) |case| {
@@ -1443,8 +1443,8 @@ test "test_divmodsi4" {
[_]i32{ 19, 5, 3, 4 },
[_]i32{ 19, -5, -3, 4 },
- [_]i32{ @bitCast(i32, u32(0x80000000)), 8, @bitCast(i32, u32(0xf0000000)), 0 },
- [_]i32{ @bitCast(i32, u32(0x80000007)), 8, @bitCast(i32, u32(0xf0000001)), -1 },
+ [_]i32{ @bitCast(i32, @as(u32, 0x80000000)), 8, @bitCast(i32, @as(u32, 0xf0000000)), 0 },
+ [_]i32{ @bitCast(i32, @as(u32, 0x80000007)), 8, @bitCast(i32, @as(u32, 0xf0000001)), -1 },
};
for (cases) |case| {
@@ -1467,10 +1467,10 @@ test "test_divdi3" {
[_]i64{ -2, 1, -2 },
[_]i64{ -2, -1, 2 },
- [_]i64{ @bitCast(i64, u64(0x8000000000000000)), 1, @bitCast(i64, u64(0x8000000000000000)) },
- [_]i64{ @bitCast(i64, u64(0x8000000000000000)), -1, @bitCast(i64, u64(0x8000000000000000)) },
- [_]i64{ @bitCast(i64, u64(0x8000000000000000)), -2, 0x4000000000000000 },
- [_]i64{ @bitCast(i64, u64(0x8000000000000000)), 2, @bitCast(i64, u64(0xC000000000000000)) },
+ [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 1, @bitCast(i64, @as(u64, 0x8000000000000000)) },
+ [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -1, @bitCast(i64, @as(u64, 0x8000000000000000)) },
+ [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -2, 0x4000000000000000 },
+ [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 2, @bitCast(i64, @as(u64, 0xC000000000000000)) },
};
for (cases) |case| {
@@ -1492,12 +1492,12 @@ test "test_moddi3" {
[_]i64{ -5, 3, -2 },
[_]i64{ -5, -3, -2 },
- [_]i64{ @bitCast(i64, @intCast(u64, 0x8000000000000000)), 1, 0 },
- [_]i64{ @bitCast(i64, @intCast(u64, 0x8000000000000000)), -1, 0 },
- [_]i64{ @bitCast(i64, @intCast(u64, 0x8000000000000000)), 2, 0 },
- [_]i64{ @bitCast(i64, @intCast(u64, 0x8000000000000000)), -2, 0 },
- [_]i64{ @bitCast(i64, @intCast(u64, 0x8000000000000000)), 3, -2 },
- [_]i64{ @bitCast(i64, @intCast(u64, 0x8000000000000000)), -3, -2 },
+ [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 1, 0 },
+ [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -1, 0 },
+ [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 2, 0 },
+ [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -2, 0 },
+ [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 3, -2 },
+ [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -3, -2 },
};
for (cases) |case| {
diff --git a/lib/std/special/compiler_rt/addXf3.zig b/lib/std/special/compiler_rt/addXf3.zig
index 1654c1f08b..e3dd1819c3 100644
--- a/lib/std/special/compiler_rt/addXf3.zig
+++ b/lib/std/special/compiler_rt/addXf3.zig
@@ -19,26 +19,26 @@ pub extern fn __addtf3(a: f128, b: f128) f128 {
}
pub extern fn __subsf3(a: f32, b: f32) f32 {
- const neg_b = @bitCast(f32, @bitCast(u32, b) ^ (u32(1) << 31));
+ const neg_b = @bitCast(f32, @bitCast(u32, b) ^ (@as(u32, 1) << 31));
return addXf3(f32, a, neg_b);
}
pub extern fn __subdf3(a: f64, b: f64) f64 {
- const neg_b = @bitCast(f64, @bitCast(u64, b) ^ (u64(1) << 63));
+ const neg_b = @bitCast(f64, @bitCast(u64, b) ^ (@as(u64, 1) << 63));
return addXf3(f64, a, neg_b);
}
pub extern fn __subtf3(a: f128, b: f128) f128 {
- const neg_b = @bitCast(f128, @bitCast(u128, b) ^ (u128(1) << 127));
+ const neg_b = @bitCast(f128, @bitCast(u128, b) ^ (@as(u128, 1) << 127));
return addXf3(f128, a, neg_b);
}
// TODO: restore inline keyword, see: https://github.com/ziglang/zig/issues/2154
fn normalize(comptime T: type, significand: *@IntType(false, T.bit_count)) i32 {
const Z = @IntType(false, T.bit_count);
- const S = @IntType(false, T.bit_count - @clz(Z, Z(T.bit_count) - 1));
+ const S = @IntType(false, T.bit_count - @clz(Z, @as(Z, T.bit_count) - 1));
const significandBits = std.math.floatMantissaBits(T);
- const implicitBit = Z(1) << significandBits;
+ const implicitBit = @as(Z, 1) << significandBits;
const shift = @clz(@IntType(false, T.bit_count), significand.*) - @clz(Z, implicitBit);
significand.* <<= @intCast(S, shift);
@@ -48,17 +48,17 @@ fn normalize(comptime T: type, significand: *@IntType(false, T.bit_count)) i32 {
// TODO: restore inline keyword, see: https://github.com/ziglang/zig/issues/2154
fn addXf3(comptime T: type, a: T, b: T) T {
const Z = @IntType(false, T.bit_count);
- const S = @IntType(false, T.bit_count - @clz(Z, Z(T.bit_count) - 1));
+ const S = @IntType(false, T.bit_count - @clz(Z, @as(Z, T.bit_count) - 1));
const typeWidth = T.bit_count;
const significandBits = std.math.floatMantissaBits(T);
const exponentBits = std.math.floatExponentBits(T);
- const signBit = (Z(1) << (significandBits + exponentBits));
+ const signBit = (@as(Z, 1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const exponentBias = (maxExponent >> 1);
- const implicitBit = (Z(1) << significandBits);
+ const implicitBit = (@as(Z, 1) << significandBits);
const quietBit = implicitBit >> 1;
const significandMask = implicitBit - 1;
@@ -78,8 +78,8 @@ fn addXf3(comptime T: type, a: T, b: T) T {
const infRep = @bitCast(Z, std.math.inf(T));
// Detect if a or b is zero, infinity, or NaN.
- if (aAbs -% Z(1) >= infRep - Z(1) or
- bAbs -% Z(1) >= infRep - Z(1))
+ if (aAbs -% @as(Z, 1) >= infRep - @as(Z, 1) or
+ bAbs -% @as(Z, 1) >= infRep - @as(Z, 1))
{
// NaN + anything = qNaN
if (aAbs > infRep) return @bitCast(T, @bitCast(Z, a) | quietBit);
@@ -148,7 +148,7 @@ fn addXf3(comptime T: type, a: T, b: T) T {
const @"align" = @intCast(Z, aExponent - bExponent);
if (@"align" != 0) {
if (@"align" < typeWidth) {
- const sticky = if (bSignificand << @intCast(S, typeWidth - @"align") != 0) Z(1) else 0;
+ const sticky = if (bSignificand << @intCast(S, typeWidth - @"align") != 0) @as(Z, 1) else 0;
bSignificand = (bSignificand >> @truncate(S, @"align")) | sticky;
} else {
bSignificand = 1; // sticky; b is known to be non-zero.
@@ -157,7 +157,7 @@ fn addXf3(comptime T: type, a: T, b: T) T {
if (subtraction) {
aSignificand -= bSignificand;
// If a == -b, return +zero.
- if (aSignificand == 0) return @bitCast(T, Z(0));
+ if (aSignificand == 0) return @bitCast(T, @as(Z, 0));
// If partial cancellation occured, we need to left-shift the result
// and adjust the exponent:
@@ -185,7 +185,7 @@ fn addXf3(comptime T: type, a: T, b: T) T {
// Result is denormal before rounding; the exponent is zero and we
// need to shift the significand.
const shift = @intCast(Z, 1 - aExponent);
- const sticky = if (aSignificand << @intCast(S, typeWidth - shift) != 0) Z(1) else 0;
+ const sticky = if (aSignificand << @intCast(S, typeWidth - shift) != 0) @as(Z, 1) else 0;
aSignificand = aSignificand >> @intCast(S, shift | sticky);
aExponent = 0;
}
diff --git a/lib/std/special/compiler_rt/addXf3_test.zig b/lib/std/special/compiler_rt/addXf3_test.zig
index 099b737976..af991b37e9 100644
--- a/lib/std/special/compiler_rt/addXf3_test.zig
+++ b/lib/std/special/compiler_rt/addXf3_test.zig
@@ -3,8 +3,8 @@
// https://github.com/llvm/llvm-project/blob/02d85149a05cb1f6dc49f0ba7a2ceca53718ae17/compiler-rt/test/builtins/Unit/addtf3_test.c
// https://github.com/llvm/llvm-project/blob/02d85149a05cb1f6dc49f0ba7a2ceca53718ae17/compiler-rt/test/builtins/Unit/subtf3_test.c
-const qnan128 = @bitCast(f128, u128(0x7fff800000000000) << 64);
-const inf128 = @bitCast(f128, u128(0x7fff000000000000) << 64);
+const qnan128 = @bitCast(f128, @as(u128, 0x7fff800000000000) << 64);
+const inf128 = @bitCast(f128, @as(u128, 0x7fff000000000000) << 64);
const __addtf3 = @import("addXf3.zig").__addtf3;
@@ -34,7 +34,7 @@ test "addtf3" {
test__addtf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0);
// NaN + any = NaN
- test__addtf3(@bitCast(f128, (u128(0x7fff000000000000) << 64) | u128(0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0);
+ test__addtf3(@bitCast(f128, (@as(u128, 0x7fff000000000000) << 64) | @as(u128, 0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0);
// inf + inf = inf
test__addtf3(inf128, inf128, 0x7fff000000000000, 0x0);
@@ -75,7 +75,7 @@ test "subtf3" {
test__subtf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0);
// NaN + any = NaN
- test__subtf3(@bitCast(f128, (u128(0x7fff000000000000) << 64) | u128(0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0);
+ test__subtf3(@bitCast(f128, (@as(u128, 0x7fff000000000000) << 64) | @as(u128, 0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0);
// inf - any = inf
test__subtf3(inf128, 0x1.23456789abcdefp+5, 0x7fff000000000000, 0x0);
diff --git a/lib/std/special/compiler_rt/comparedf2.zig b/lib/std/special/compiler_rt/comparedf2.zig
index f97e2474be..95dc878630 100644
--- a/lib/std/special/compiler_rt/comparedf2.zig
+++ b/lib/std/special/compiler_rt/comparedf2.zig
@@ -13,19 +13,19 @@ const srep_t = i64;
const typeWidth = rep_t.bit_count;
const significandBits = std.math.floatMantissaBits(fp_t);
const exponentBits = std.math.floatExponentBits(fp_t);
-const signBit = (rep_t(1) << (significandBits + exponentBits));
+const signBit = (@as(rep_t, 1) << (significandBits + exponentBits));
const absMask = signBit - 1;
-const implicitBit = rep_t(1) << significandBits;
+const implicitBit = @as(rep_t, 1) << significandBits;
const significandMask = implicitBit - 1;
const exponentMask = absMask ^ significandMask;
const infRep = @bitCast(rep_t, std.math.inf(fp_t));
// TODO https://github.com/ziglang/zig/issues/641
// and then make the return types of some of these functions the enum instead of c_int
-const LE_LESS = c_int(-1);
-const LE_EQUAL = c_int(0);
-const LE_GREATER = c_int(1);
-const LE_UNORDERED = c_int(1);
+const LE_LESS = @as(c_int, -1);
+const LE_EQUAL = @as(c_int, 0);
+const LE_GREATER = @as(c_int, 1);
+const LE_UNORDERED = @as(c_int, 1);
pub extern fn __ledf2(a: fp_t, b: fp_t) c_int {
@setRuntimeSafety(is_test);
@@ -65,10 +65,10 @@ pub extern fn __ledf2(a: fp_t, b: fp_t) c_int {
// TODO https://github.com/ziglang/zig/issues/641
// and then make the return types of some of these functions the enum instead of c_int
-const GE_LESS = c_int(-1);
-const GE_EQUAL = c_int(0);
-const GE_GREATER = c_int(1);
-const GE_UNORDERED = c_int(-1); // Note: different from LE_UNORDERED
+const GE_LESS = @as(c_int, -1);
+const GE_EQUAL = @as(c_int, 0);
+const GE_GREATER = @as(c_int, 1);
+const GE_UNORDERED = @as(c_int, -1); // Note: different from LE_UNORDERED
pub extern fn __gedf2(a: fp_t, b: fp_t) c_int {
@setRuntimeSafety(is_test);
diff --git a/lib/std/special/compiler_rt/comparesf2.zig b/lib/std/special/compiler_rt/comparesf2.zig
index e99e0bb3dd..4468da4fbe 100644
--- a/lib/std/special/compiler_rt/comparesf2.zig
+++ b/lib/std/special/compiler_rt/comparesf2.zig
@@ -13,19 +13,19 @@ const srep_t = i32;
const typeWidth = rep_t.bit_count;
const significandBits = std.math.floatMantissaBits(fp_t);
const exponentBits = std.math.floatExponentBits(fp_t);
-const signBit = (rep_t(1) << (significandBits + exponentBits));
+const signBit = (@as(rep_t, 1) << (significandBits + exponentBits));
const absMask = signBit - 1;
-const implicitBit = rep_t(1) << significandBits;
+const implicitBit = @as(rep_t, 1) << significandBits;
const significandMask = implicitBit - 1;
const exponentMask = absMask ^ significandMask;
const infRep = @bitCast(rep_t, std.math.inf(fp_t));
// TODO https://github.com/ziglang/zig/issues/641
// and then make the return types of some of these functions the enum instead of c_int
-const LE_LESS = c_int(-1);
-const LE_EQUAL = c_int(0);
-const LE_GREATER = c_int(1);
-const LE_UNORDERED = c_int(1);
+const LE_LESS = @as(c_int, -1);
+const LE_EQUAL = @as(c_int, 0);
+const LE_GREATER = @as(c_int, 1);
+const LE_UNORDERED = @as(c_int, 1);
pub extern fn __lesf2(a: fp_t, b: fp_t) c_int {
@setRuntimeSafety(is_test);
@@ -65,10 +65,10 @@ pub extern fn __lesf2(a: fp_t, b: fp_t) c_int {
// TODO https://github.com/ziglang/zig/issues/641
// and then make the return types of some of these functions the enum instead of c_int
-const GE_LESS = c_int(-1);
-const GE_EQUAL = c_int(0);
-const GE_GREATER = c_int(1);
-const GE_UNORDERED = c_int(-1); // Note: different from LE_UNORDERED
+const GE_LESS = @as(c_int, -1);
+const GE_EQUAL = @as(c_int, 0);
+const GE_GREATER = @as(c_int, 1);
+const GE_UNORDERED = @as(c_int, -1); // Note: different from LE_UNORDERED
pub extern fn __gesf2(a: fp_t, b: fp_t) c_int {
@setRuntimeSafety(is_test);
diff --git a/lib/std/special/compiler_rt/comparetf2.zig b/lib/std/special/compiler_rt/comparetf2.zig
index 05e5974558..e973018455 100644
--- a/lib/std/special/compiler_rt/comparetf2.zig
+++ b/lib/std/special/compiler_rt/comparetf2.zig
@@ -1,9 +1,9 @@
// TODO https://github.com/ziglang/zig/issues/641
// and then make the return types of some of these functions the enum instead of c_int
-const LE_LESS = c_int(-1);
-const LE_EQUAL = c_int(0);
-const LE_GREATER = c_int(1);
-const LE_UNORDERED = c_int(1);
+const LE_LESS = @as(c_int, -1);
+const LE_EQUAL = @as(c_int, 0);
+const LE_GREATER = @as(c_int, 1);
+const LE_UNORDERED = @as(c_int, 1);
const rep_t = u128;
const srep_t = i128;
@@ -11,9 +11,9 @@ const srep_t = i128;
const typeWidth = rep_t.bit_count;
const significandBits = 112;
const exponentBits = (typeWidth - significandBits - 1);
-const signBit = (rep_t(1) << (significandBits + exponentBits));
+const signBit = (@as(rep_t, 1) << (significandBits + exponentBits));
const absMask = signBit - 1;
-const implicitBit = rep_t(1) << significandBits;
+const implicitBit = @as(rep_t, 1) << significandBits;
const significandMask = implicitBit - 1;
const exponentMask = absMask ^ significandMask;
const infRep = exponentMask;
@@ -60,10 +60,10 @@ pub extern fn __letf2(a: f128, b: f128) c_int {
// TODO https://github.com/ziglang/zig/issues/641
// and then make the return types of some of these functions the enum instead of c_int
-const GE_LESS = c_int(-1);
-const GE_EQUAL = c_int(0);
-const GE_GREATER = c_int(1);
-const GE_UNORDERED = c_int(-1); // Note: different from LE_UNORDERED
+const GE_LESS = @as(c_int, -1);
+const GE_EQUAL = @as(c_int, 0);
+const GE_GREATER = @as(c_int, 1);
+const GE_UNORDERED = @as(c_int, -1); // Note: different from LE_UNORDERED
pub extern fn __getf2(a: f128, b: f128) c_int {
@setRuntimeSafety(is_test);
diff --git a/lib/std/special/compiler_rt/divdf3.zig b/lib/std/special/compiler_rt/divdf3.zig
index 072feaec67..9937b09497 100644
--- a/lib/std/special/compiler_rt/divdf3.zig
+++ b/lib/std/special/compiler_rt/divdf3.zig
@@ -14,11 +14,11 @@ pub extern fn __divdf3(a: f64, b: f64) f64 {
const significandBits = std.math.floatMantissaBits(f64);
const exponentBits = std.math.floatExponentBits(f64);
- const signBit = (Z(1) << (significandBits + exponentBits));
+ const signBit = (@as(Z, 1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const exponentBias = (maxExponent >> 1);
- const implicitBit = (Z(1) << significandBits);
+ const implicitBit = (@as(Z, 1) << significandBits);
const quietBit = implicitBit >> 1;
const significandMask = implicitBit - 1;
@@ -91,7 +91,7 @@ pub extern fn __divdf3(a: f64, b: f64) f64 {
// polynomial approximation: reciprocal = 3/4 + 1/sqrt(2) - b/2. This
// is accurate to about 3.5 binary digits.
const q31b: u32 = @truncate(u32, bSignificand >> 21);
- var recip32 = u32(0x7504f333) -% q31b;
+ var recip32 = @as(u32, 0x7504f333) -% q31b;
// Now refine the reciprocal estimate using a Newton-Raphson iteration:
//
@@ -101,12 +101,12 @@ pub extern fn __divdf3(a: f64, b: f64) f64 {
// with each iteration, so after three iterations, we have about 28 binary
// digits of accuracy.
var correction32: u32 = undefined;
- correction32 = @truncate(u32, ~(u64(recip32) *% q31b >> 32) +% 1);
- recip32 = @truncate(u32, u64(recip32) *% correction32 >> 31);
- correction32 = @truncate(u32, ~(u64(recip32) *% q31b >> 32) +% 1);
- recip32 = @truncate(u32, u64(recip32) *% correction32 >> 31);
- correction32 = @truncate(u32, ~(u64(recip32) *% q31b >> 32) +% 1);
- recip32 = @truncate(u32, u64(recip32) *% correction32 >> 31);
+ correction32 = @truncate(u32, ~(@as(u64, recip32) *% q31b >> 32) +% 1);
+ recip32 = @truncate(u32, @as(u64, recip32) *% correction32 >> 31);
+ correction32 = @truncate(u32, ~(@as(u64, recip32) *% q31b >> 32) +% 1);
+ recip32 = @truncate(u32, @as(u64, recip32) *% correction32 >> 31);
+ correction32 = @truncate(u32, ~(@as(u64, recip32) *% q31b >> 32) +% 1);
+ recip32 = @truncate(u32, @as(u64, recip32) *% correction32 >> 31);
// recip32 might have overflowed to exactly zero in the preceding
// computation if the high word of b is exactly 1.0. This would sabotage
@@ -119,10 +119,10 @@ pub extern fn __divdf3(a: f64, b: f64) f64 {
const q63blo: u32 = @truncate(u32, bSignificand << 11);
var correction: u64 = undefined;
var reciprocal: u64 = undefined;
- correction = ~(u64(recip32) *% q31b +% (u64(recip32) *% q63blo >> 32)) +% 1;
+ correction = ~(@as(u64, recip32) *% q31b +% (@as(u64, recip32) *% q63blo >> 32)) +% 1;
const cHi = @truncate(u32, correction >> 32);
const cLo = @truncate(u32, correction);
- reciprocal = u64(recip32) *% cHi +% (u64(recip32) *% cLo >> 32);
+ reciprocal = @as(u64, recip32) *% cHi +% (@as(u64, recip32) *% cLo >> 32);
// We already adjusted the 32-bit estimate, now we need to adjust the final
// 64-bit reciprocal estimate downward to ensure that it is strictly smaller
@@ -195,7 +195,7 @@ pub extern fn __divdf3(a: f64, b: f64) f64 {
// Clear the implicit bit
var absResult = quotient & significandMask;
// Insert the exponent
- absResult |= @bitCast(Z, SignedZ(writtenExponent)) << significandBits;
+ absResult |= @bitCast(Z, @as(SignedZ, writtenExponent)) << significandBits;
// Round
absResult +%= round;
// Insert the sign and return
@@ -208,7 +208,7 @@ fn wideMultiply(comptime Z: type, a: Z, b: Z, hi: *Z, lo: *Z) void {
switch (Z) {
u32 => {
// 32x32 --> 64 bit multiply
- const product = u64(a) * u64(b);
+ const product = @as(u64, a) * @as(u64, b);
hi.* = @truncate(u32, product >> 32);
lo.* = @truncate(u32, product);
},
@@ -237,9 +237,9 @@ fn wideMultiply(comptime Z: type, a: Z, b: Z, hi: *Z, lo: *Z) void {
hi.* = S.hiWord(plohi) +% S.hiWord(philo) +% S.hiWord(r1) +% phihi;
},
u128 => {
- const Word_LoMask = u64(0x00000000ffffffff);
- const Word_HiMask = u64(0xffffffff00000000);
- const Word_FullMask = u64(0xffffffffffffffff);
+ const Word_LoMask = @as(u64, 0x00000000ffffffff);
+ const Word_HiMask = @as(u64, 0xffffffff00000000);
+ const Word_FullMask = @as(u64, 0xffffffffffffffff);
const S = struct {
fn Word_1(x: u128) u64 {
return @truncate(u32, x >> 96);
@@ -275,22 +275,22 @@ fn wideMultiply(comptime Z: type, a: Z, b: Z, hi: *Z, lo: *Z) void {
const product43: u64 = S.Word_4(a) * S.Word_3(b);
const product44: u64 = S.Word_4(a) * S.Word_4(b);
- const sum0: u128 = u128(product44);
- const sum1: u128 = u128(product34) +%
- u128(product43);
- const sum2: u128 = u128(product24) +%
- u128(product33) +%
- u128(product42);
- const sum3: u128 = u128(product14) +%
- u128(product23) +%
- u128(product32) +%
- u128(product41);
- const sum4: u128 = u128(product13) +%
- u128(product22) +%
- u128(product31);
- const sum5: u128 = u128(product12) +%
- u128(product21);
- const sum6: u128 = u128(product11);
+ const sum0: u128 = @as(u128, product44);
+ const sum1: u128 = @as(u128, product34) +%
+ @as(u128, product43);
+ const sum2: u128 = @as(u128, product24) +%
+ @as(u128, product33) +%
+ @as(u128, product42);
+ const sum3: u128 = @as(u128, product14) +%
+ @as(u128, product23) +%
+ @as(u128, product32) +%
+ @as(u128, product41);
+ const sum4: u128 = @as(u128, product13) +%
+ @as(u128, product22) +%
+ @as(u128, product31);
+ const sum5: u128 = @as(u128, product12) +%
+ @as(u128, product21);
+ const sum6: u128 = @as(u128, product11);
const r0: u128 = (sum0 & Word_FullMask) +%
((sum1 & Word_LoMask) << 32);
@@ -316,7 +316,7 @@ fn normalize(comptime T: type, significand: *@IntType(false, T.bit_count)) i32 {
@setRuntimeSafety(builtin.is_test);
const Z = @IntType(false, T.bit_count);
const significandBits = std.math.floatMantissaBits(T);
- const implicitBit = Z(1) << significandBits;
+ const implicitBit = @as(Z, 1) << significandBits;
const shift = @clz(Z, significand.*) - @clz(Z, implicitBit);
significand.* <<= @intCast(std.math.Log2Int(Z), shift);
diff --git a/lib/std/special/compiler_rt/divsf3.zig b/lib/std/special/compiler_rt/divsf3.zig
index 447653fbe1..4ee2eed36c 100644
--- a/lib/std/special/compiler_rt/divsf3.zig
+++ b/lib/std/special/compiler_rt/divsf3.zig
@@ -13,11 +13,11 @@ pub extern fn __divsf3(a: f32, b: f32) f32 {
const significandBits = std.math.floatMantissaBits(f32);
const exponentBits = std.math.floatExponentBits(f32);
- const signBit = (Z(1) << (significandBits + exponentBits));
+ const signBit = (@as(Z, 1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const exponentBias = (maxExponent >> 1);
- const implicitBit = (Z(1) << significandBits);
+ const implicitBit = (@as(Z, 1) << significandBits);
const quietBit = implicitBit >> 1;
const significandMask = implicitBit - 1;
@@ -90,7 +90,7 @@ pub extern fn __divsf3(a: f32, b: f32) f32 {
// polynomial approximation: reciprocal = 3/4 + 1/sqrt(2) - b/2. This
// is accurate to about 3.5 binary digits.
const q31b = bSignificand << 8;
- var reciprocal = u32(0x7504f333) -% q31b;
+ var reciprocal = @as(u32, 0x7504f333) -% q31b;
// Now refine the reciprocal estimate using a Newton-Raphson iteration:
//
@@ -100,12 +100,12 @@ pub extern fn __divsf3(a: f32, b: f32) f32 {
// with each iteration, so after three iterations, we have about 28 binary
// digits of accuracy.
var correction: u32 = undefined;
- correction = @truncate(u32, ~(u64(reciprocal) *% q31b >> 32) +% 1);
- reciprocal = @truncate(u32, u64(reciprocal) *% correction >> 31);
- correction = @truncate(u32, ~(u64(reciprocal) *% q31b >> 32) +% 1);
- reciprocal = @truncate(u32, u64(reciprocal) *% correction >> 31);
- correction = @truncate(u32, ~(u64(reciprocal) *% q31b >> 32) +% 1);
- reciprocal = @truncate(u32, u64(reciprocal) *% correction >> 31);
+ correction = @truncate(u32, ~(@as(u64, reciprocal) *% q31b >> 32) +% 1);
+ reciprocal = @truncate(u32, @as(u64, reciprocal) *% correction >> 31);
+ correction = @truncate(u32, ~(@as(u64, reciprocal) *% q31b >> 32) +% 1);
+ reciprocal = @truncate(u32, @as(u64, reciprocal) *% correction >> 31);
+ correction = @truncate(u32, ~(@as(u64, reciprocal) *% q31b >> 32) +% 1);
+ reciprocal = @truncate(u32, @as(u64, reciprocal) *% correction >> 31);
// Exhaustive testing shows that the error in reciprocal after three steps
// is in the interval [-0x1.f58108p-31, 0x1.d0e48cp-29], in line with our
@@ -127,7 +127,7 @@ pub extern fn __divsf3(a: f32, b: f32) f32 {
// is the error in the reciprocal of b scaled by the maximum
// possible value of a. As a consequence of this error bound,
// either q or nextafter(q) is the correctly rounded
- var quotient: Z = @truncate(u32, u64(reciprocal) *% (aSignificand << 1) >> 32);
+ var quotient: Z = @truncate(u32, @as(u64, reciprocal) *% (aSignificand << 1) >> 32);
// Two cases: quotient is in [0.5, 1.0) or quotient is in [1.0, 2.0).
// In either case, we are going to compute a residual of the form
@@ -189,7 +189,7 @@ fn normalize(comptime T: type, significand: *@IntType(false, T.bit_count)) i32 {
@setRuntimeSafety(builtin.is_test);
const Z = @IntType(false, T.bit_count);
const significandBits = std.math.floatMantissaBits(T);
- const implicitBit = Z(1) << significandBits;
+ const implicitBit = @as(Z, 1) << significandBits;
const shift = @clz(Z, significand.*) - @clz(Z, implicitBit);
significand.* <<= @intCast(std.math.Log2Int(Z), shift);
diff --git a/lib/std/special/compiler_rt/divti3_test.zig b/lib/std/special/compiler_rt/divti3_test.zig
index e1c1babae7..8601cfae03 100644
--- a/lib/std/special/compiler_rt/divti3_test.zig
+++ b/lib/std/special/compiler_rt/divti3_test.zig
@@ -14,8 +14,8 @@ test "divti3" {
test__divti3(-2, 1, -2);
test__divti3(-2, -1, 2);
- test__divti3(@bitCast(i128, u128(0x8 << 124)), 1, @bitCast(i128, u128(0x8 << 124)));
- test__divti3(@bitCast(i128, u128(0x8 << 124)), -1, @bitCast(i128, u128(0x8 << 124)));
- test__divti3(@bitCast(i128, u128(0x8 << 124)), -2, @bitCast(i128, u128(0x4 << 124)));
- test__divti3(@bitCast(i128, u128(0x8 << 124)), 2, @bitCast(i128, u128(0xc << 124)));
+ test__divti3(@bitCast(i128, @as(u128, 0x8 << 124)), 1, @bitCast(i128, @as(u128, 0x8 << 124)));
+ test__divti3(@bitCast(i128, @as(u128, 0x8 << 124)), -1, @bitCast(i128, @as(u128, 0x8 << 124)));
+ test__divti3(@bitCast(i128, @as(u128, 0x8 << 124)), -2, @bitCast(i128, @as(u128, 0x4 << 124)));
+ test__divti3(@bitCast(i128, @as(u128, 0x8 << 124)), 2, @bitCast(i128, @as(u128, 0xc << 124)));
}
diff --git a/lib/std/special/compiler_rt/extendXfYf2.zig b/lib/std/special/compiler_rt/extendXfYf2.zig
index e10667843f..3bdc5164e2 100644
--- a/lib/std/special/compiler_rt/extendXfYf2.zig
+++ b/lib/std/special/compiler_rt/extendXfYf2.zig
@@ -49,7 +49,7 @@ fn extendXfYf2(comptime dst_t: type, comptime src_t: type, a: @IntType(false, @t
const dstInfExp = (1 << dstExpBits) - 1;
const dstExpBias = dstInfExp >> 1;
- const dstMinNormal: dst_rep_t = dst_rep_t(1) << dstSigBits;
+ const dstMinNormal: dst_rep_t = @as(dst_rep_t, 1) << dstSigBits;
// Break a into a sign and representation of the absolute value
const aRep: src_rep_t = @bitCast(src_rep_t, a);
@@ -61,7 +61,7 @@ fn extendXfYf2(comptime dst_t: type, comptime src_t: type, a: @IntType(false, @t
// a is a normal number.
// Extend to the destination type by shifting the significand and
// exponent into the proper position and rebiasing the exponent.
- absResult = dst_rep_t(aAbs) << (dstSigBits - srcSigBits);
+ absResult = @as(dst_rep_t, aAbs) << (dstSigBits - srcSigBits);
absResult += (dstExpBias - srcExpBias) << dstSigBits;
} else if (aAbs >= srcInfinity) {
// a is NaN or infinity.
@@ -69,15 +69,15 @@ fn extendXfYf2(comptime dst_t: type, comptime src_t: type, a: @IntType(false, @t
// bit (if needed) and right-aligning the rest of the trailing NaN
// payload field.
absResult = dstInfExp << dstSigBits;
- absResult |= dst_rep_t(aAbs & srcQNaN) << (dstSigBits - srcSigBits);
- absResult |= dst_rep_t(aAbs & srcNaNCode) << (dstSigBits - srcSigBits);
+ absResult |= @as(dst_rep_t, aAbs & srcQNaN) << (dstSigBits - srcSigBits);
+ absResult |= @as(dst_rep_t, aAbs & srcNaNCode) << (dstSigBits - srcSigBits);
} else if (aAbs != 0) {
// a is denormal.
// renormalize the significand and clear the leading bit, then insert
// the correct adjusted exponent in the destination type.
const scale: u32 = @clz(src_rep_t, aAbs) -
- @clz(src_rep_t, src_rep_t(srcMinNormal));
- absResult = dst_rep_t(aAbs) << @intCast(DstShift, dstSigBits - srcSigBits + scale);
+ @clz(src_rep_t, @as(src_rep_t, srcMinNormal));
+ absResult = @as(dst_rep_t, aAbs) << @intCast(DstShift, dstSigBits - srcSigBits + scale);
absResult ^= dstMinNormal;
const resultExponent: u32 = dstExpBias - srcExpBias - scale + 1;
absResult |= @intCast(dst_rep_t, resultExponent) << dstSigBits;
@@ -87,7 +87,7 @@ fn extendXfYf2(comptime dst_t: type, comptime src_t: type, a: @IntType(false, @t
}
// Apply the signbit to (dst_t)abs(a).
- const result: dst_rep_t align(@alignOf(dst_t)) = absResult | dst_rep_t(sign) << (dstBits - srcBits);
+ const result: dst_rep_t align(@alignOf(dst_t)) = absResult | @as(dst_rep_t, sign) << (dstBits - srcBits);
return @bitCast(dst_t, result);
}
diff --git a/lib/std/special/compiler_rt/extendXfYf2_test.zig b/lib/std/special/compiler_rt/extendXfYf2_test.zig
index 6f8111c8fb..aa2faae901 100644
--- a/lib/std/special/compiler_rt/extendXfYf2_test.zig
+++ b/lib/std/special/compiler_rt/extendXfYf2_test.zig
@@ -134,11 +134,11 @@ test "extendsftf2" {
}
fn makeQNaN64() f64 {
- return @bitCast(f64, u64(0x7ff8000000000000));
+ return @bitCast(f64, @as(u64, 0x7ff8000000000000));
}
fn makeInf64() f64 {
- return @bitCast(f64, u64(0x7ff0000000000000));
+ return @bitCast(f64, @as(u64, 0x7ff0000000000000));
}
fn makeNaN64(rand: u64) f64 {
@@ -146,7 +146,7 @@ fn makeNaN64(rand: u64) f64 {
}
fn makeQNaN32() f32 {
- return @bitCast(f32, u32(0x7fc00000));
+ return @bitCast(f32, @as(u32, 0x7fc00000));
}
fn makeNaN32(rand: u32) f32 {
@@ -154,5 +154,5 @@ fn makeNaN32(rand: u32) f32 {
}
fn makeInf32() f32 {
- return @bitCast(f32, u32(0x7f800000));
+ return @bitCast(f32, @as(u32, 0x7f800000));
}
diff --git a/lib/std/special/compiler_rt/fixdfdi_test.zig b/lib/std/special/compiler_rt/fixdfdi_test.zig
index 1ba8a4f87d..e06d641824 100644
--- a/lib/std/special/compiler_rt/fixdfdi_test.zig
+++ b/lib/std/special/compiler_rt/fixdfdi_test.zig
@@ -6,7 +6,7 @@ const warn = std.debug.warn;
fn test__fixdfdi(a: f64, expected: i64) void {
const x = __fixdfdi(a);
- //warn("a={}:{x} x={}:{x} expected={}:{x}:u64({x})\n", a, @bitCast(u64, a), x, x, expected, expected, @bitCast(u64, expected));
+ //warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u64, {x})\n", a, @bitCast(u64, a), x, x, expected, expected, @bitCast(u64, expected));
testing.expect(x == expected);
}
diff --git a/lib/std/special/compiler_rt/fixdfsi_test.zig b/lib/std/special/compiler_rt/fixdfsi_test.zig
index fa5ff72e8f..da53468c7d 100644
--- a/lib/std/special/compiler_rt/fixdfsi_test.zig
+++ b/lib/std/special/compiler_rt/fixdfsi_test.zig
@@ -6,7 +6,7 @@ const warn = std.debug.warn;
fn test__fixdfsi(a: f64, expected: i32) void {
const x = __fixdfsi(a);
- //warn("a={}:{x} x={}:{x} expected={}:{x}:u64({x})\n", a, @bitCast(u64, a), x, x, expected, expected, @bitCast(u32, expected));
+ //warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u64, {x})\n", a, @bitCast(u64, a), x, x, expected, expected, @bitCast(u32, expected));
testing.expect(x == expected);
}
diff --git a/lib/std/special/compiler_rt/fixdfti_test.zig b/lib/std/special/compiler_rt/fixdfti_test.zig
index 4ab2c04cd1..b0c9049ba8 100644
--- a/lib/std/special/compiler_rt/fixdfti_test.zig
+++ b/lib/std/special/compiler_rt/fixdfti_test.zig
@@ -6,7 +6,7 @@ const warn = std.debug.warn;
fn test__fixdfti(a: f64, expected: i128) void {
const x = __fixdfti(a);
- //warn("a={}:{x} x={}:{x} expected={}:{x}:u64({x})\n", a, @bitCast(u64, a), x, x, expected, expected, @bitCast(u128, expected));
+ //warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u64, {x})\n", a, @bitCast(u64, a), x, x, expected, expected, @bitCast(u128, expected));
testing.expect(x == expected);
}
diff --git a/lib/std/special/compiler_rt/fixint.zig b/lib/std/special/compiler_rt/fixint.zig
index fd31798cc2..426ee1d58a 100644
--- a/lib/std/special/compiler_rt/fixint.zig
+++ b/lib/std/special/compiler_rt/fixint.zig
@@ -25,11 +25,11 @@ pub fn fixint(comptime fp_t: type, comptime fixint_t: type, a: fp_t) fixint_t {
const typeWidth = rep_t.bit_count;
const exponentBits = (typeWidth - significandBits - 1);
- const signBit = (rep_t(1) << (significandBits + exponentBits));
+ const signBit = (@as(rep_t, 1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const exponentBias = (maxExponent >> 1);
- const implicitBit = (rep_t(1) << significandBits);
+ const implicitBit = (@as(rep_t, 1) << significandBits);
const significandMask = (implicitBit - 1);
// Break a into sign, exponent, significand
@@ -51,7 +51,7 @@ pub fn fixint(comptime fp_t: type, comptime fixint_t: type, a: fp_t) fixint_t {
// If the value is too large for the integer type, saturate.
if (@intCast(usize, exponent) >= fixint_t.bit_count) {
- return if (negative) fixint_t(minInt(fixint_t)) else fixint_t(maxInt(fixint_t));
+ return if (negative) @as(fixint_t, minInt(fixint_t)) else @as(fixint_t, maxInt(fixint_t));
}
// If 0 <= exponent < significandBits, right shift else left shift
diff --git a/lib/std/special/compiler_rt/fixint_test.zig b/lib/std/special/compiler_rt/fixint_test.zig
index a876e17263..d5f7b3898d 100644
--- a/lib/std/special/compiler_rt/fixint_test.zig
+++ b/lib/std/special/compiler_rt/fixint_test.zig
@@ -81,8 +81,8 @@ test "fixint.i3" {
test "fixint.i32" {
test__fixint(f64, i32, -math.inf_f64, math.minInt(i32));
test__fixint(f64, i32, -math.f64_max, math.minInt(i32));
- test__fixint(f64, i32, f64(math.minInt(i32)), math.minInt(i32));
- test__fixint(f64, i32, f64(math.minInt(i32)) + 1, math.minInt(i32) + 1);
+ test__fixint(f64, i32, @as(f64, math.minInt(i32)), math.minInt(i32));
+ test__fixint(f64, i32, @as(f64, math.minInt(i32)) + 1, math.minInt(i32) + 1);
test__fixint(f64, i32, -2.0, -2);
test__fixint(f64, i32, -1.9, -1);
test__fixint(f64, i32, -1.1, -1);
@@ -96,8 +96,8 @@ test "fixint.i32" {
test__fixint(f64, i32, 0.1, 0);
test__fixint(f64, i32, 0.9, 0);
test__fixint(f64, i32, 1.0, 1);
- test__fixint(f64, i32, f64(math.maxInt(i32)) - 1, math.maxInt(i32) - 1);
- test__fixint(f64, i32, f64(math.maxInt(i32)), math.maxInt(i32));
+ test__fixint(f64, i32, @as(f64, math.maxInt(i32)) - 1, math.maxInt(i32) - 1);
+ test__fixint(f64, i32, @as(f64, math.maxInt(i32)), math.maxInt(i32));
test__fixint(f64, i32, math.f64_max, math.maxInt(i32));
test__fixint(f64, i32, math.inf_f64, math.maxInt(i32));
}
@@ -105,9 +105,9 @@ test "fixint.i32" {
test "fixint.i64" {
test__fixint(f64, i64, -math.inf_f64, math.minInt(i64));
test__fixint(f64, i64, -math.f64_max, math.minInt(i64));
- test__fixint(f64, i64, f64(math.minInt(i64)), math.minInt(i64));
- test__fixint(f64, i64, f64(math.minInt(i64)) + 1, math.minInt(i64));
- test__fixint(f64, i64, f64(math.minInt(i64) / 2), math.minInt(i64) / 2);
+ test__fixint(f64, i64, @as(f64, math.minInt(i64)), math.minInt(i64));
+ test__fixint(f64, i64, @as(f64, math.minInt(i64)) + 1, math.minInt(i64));
+ test__fixint(f64, i64, @as(f64, math.minInt(i64) / 2), math.minInt(i64) / 2);
test__fixint(f64, i64, -2.0, -2);
test__fixint(f64, i64, -1.9, -1);
test__fixint(f64, i64, -1.1, -1);
@@ -121,8 +121,8 @@ test "fixint.i64" {
test__fixint(f64, i64, 0.1, 0);
test__fixint(f64, i64, 0.9, 0);
test__fixint(f64, i64, 1.0, 1);
- test__fixint(f64, i64, f64(math.maxInt(i64)) - 1, math.maxInt(i64));
- test__fixint(f64, i64, f64(math.maxInt(i64)), math.maxInt(i64));
+ test__fixint(f64, i64, @as(f64, math.maxInt(i64)) - 1, math.maxInt(i64));
+ test__fixint(f64, i64, @as(f64, math.maxInt(i64)), math.maxInt(i64));
test__fixint(f64, i64, math.f64_max, math.maxInt(i64));
test__fixint(f64, i64, math.inf_f64, math.maxInt(i64));
}
@@ -130,8 +130,8 @@ test "fixint.i64" {
test "fixint.i128" {
test__fixint(f64, i128, -math.inf_f64, math.minInt(i128));
test__fixint(f64, i128, -math.f64_max, math.minInt(i128));
- test__fixint(f64, i128, f64(math.minInt(i128)), math.minInt(i128));
- test__fixint(f64, i128, f64(math.minInt(i128)) + 1, math.minInt(i128));
+ test__fixint(f64, i128, @as(f64, math.minInt(i128)), math.minInt(i128));
+ test__fixint(f64, i128, @as(f64, math.minInt(i128)) + 1, math.minInt(i128));
test__fixint(f64, i128, -2.0, -2);
test__fixint(f64, i128, -1.9, -1);
test__fixint(f64, i128, -1.1, -1);
@@ -145,8 +145,8 @@ test "fixint.i128" {
test__fixint(f64, i128, 0.1, 0);
test__fixint(f64, i128, 0.9, 0);
test__fixint(f64, i128, 1.0, 1);
- test__fixint(f64, i128, f64(math.maxInt(i128)) - 1, math.maxInt(i128));
- test__fixint(f64, i128, f64(math.maxInt(i128)), math.maxInt(i128));
+ test__fixint(f64, i128, @as(f64, math.maxInt(i128)) - 1, math.maxInt(i128));
+ test__fixint(f64, i128, @as(f64, math.maxInt(i128)), math.maxInt(i128));
test__fixint(f64, i128, math.f64_max, math.maxInt(i128));
test__fixint(f64, i128, math.inf_f64, math.maxInt(i128));
}
diff --git a/lib/std/special/compiler_rt/fixsfdi_test.zig b/lib/std/special/compiler_rt/fixsfdi_test.zig
index bfd715425c..02844946a7 100644
--- a/lib/std/special/compiler_rt/fixsfdi_test.zig
+++ b/lib/std/special/compiler_rt/fixsfdi_test.zig
@@ -6,7 +6,7 @@ const warn = std.debug.warn;
fn test__fixsfdi(a: f32, expected: i64) void {
const x = __fixsfdi(a);
- //warn("a={}:{x} x={}:{x} expected={}:{x}:u32({x})\n", a, @bitCast(u32, a), x, x, expected, expected, @bitCast(u64, expected));
+ //warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u32, {x})\n", a, @bitCast(u32, a), x, x, expected, expected, @bitCast(u64, expected));
testing.expect(x == expected);
}
diff --git a/lib/std/special/compiler_rt/fixsfsi_test.zig b/lib/std/special/compiler_rt/fixsfsi_test.zig
index 30406fea22..69d8309de0 100644
--- a/lib/std/special/compiler_rt/fixsfsi_test.zig
+++ b/lib/std/special/compiler_rt/fixsfsi_test.zig
@@ -6,7 +6,7 @@ const warn = std.debug.warn;
fn test__fixsfsi(a: f32, expected: i32) void {
const x = __fixsfsi(a);
- //warn("a={}:{x} x={}:{x} expected={}:{x}:u32({x})\n", a, @bitCast(u32, a), x, x, expected, expected, @bitCast(u32, expected));
+ //warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u32, {x})\n", a, @bitCast(u32, a), x, x, expected, expected, @bitCast(u32, expected));
testing.expect(x == expected);
}
diff --git a/lib/std/special/compiler_rt/fixsfti_test.zig b/lib/std/special/compiler_rt/fixsfti_test.zig
index 7136f7cfe8..cecfeda557 100644
--- a/lib/std/special/compiler_rt/fixsfti_test.zig
+++ b/lib/std/special/compiler_rt/fixsfti_test.zig
@@ -6,7 +6,7 @@ const warn = std.debug.warn;
fn test__fixsfti(a: f32, expected: i128) void {
const x = __fixsfti(a);
- //warn("a={}:{x} x={}:{x} expected={}:{x}:u128({x})\n", a, @bitCast(u32, a), x, x, expected, expected, @bitCast(u128, expected));
+ //warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u128, {x})\n", a, @bitCast(u32, a), x, x, expected, expected, @bitCast(u128, expected));
testing.expect(x == expected);
}
diff --git a/lib/std/special/compiler_rt/fixtfdi_test.zig b/lib/std/special/compiler_rt/fixtfdi_test.zig
index 7c63547642..b45001e18e 100644
--- a/lib/std/special/compiler_rt/fixtfdi_test.zig
+++ b/lib/std/special/compiler_rt/fixtfdi_test.zig
@@ -6,7 +6,7 @@ const warn = std.debug.warn;
fn test__fixtfdi(a: f128, expected: i64) void {
const x = __fixtfdi(a);
- //warn("a={}:{x} x={}:{x} expected={}:{x}:u64({x})\n", a, @bitCast(u128, a), x, x, expected, expected, @bitCast(u64, expected));
+ //warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u64, {x})\n", a, @bitCast(u128, a), x, x, expected, expected, @bitCast(u64, expected));
testing.expect(x == expected);
}
diff --git a/lib/std/special/compiler_rt/fixtfsi_test.zig b/lib/std/special/compiler_rt/fixtfsi_test.zig
index da769089df..c6f6623995 100644
--- a/lib/std/special/compiler_rt/fixtfsi_test.zig
+++ b/lib/std/special/compiler_rt/fixtfsi_test.zig
@@ -6,7 +6,7 @@ const warn = std.debug.warn;
fn test__fixtfsi(a: f128, expected: i32) void {
const x = __fixtfsi(a);
- //warn("a={}:{x} x={}:{x} expected={}:{x}:u32({x})\n", a, @bitCast(u128, a), x, x, expected, expected, @bitCast(u32, expected));
+ //warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u32, {x})\n", a, @bitCast(u128, a), x, x, expected, expected, @bitCast(u32, expected));
testing.expect(x == expected);
}
diff --git a/lib/std/special/compiler_rt/fixtfti_test.zig b/lib/std/special/compiler_rt/fixtfti_test.zig
index 02dba7fd61..b36c5beb4e 100644
--- a/lib/std/special/compiler_rt/fixtfti_test.zig
+++ b/lib/std/special/compiler_rt/fixtfti_test.zig
@@ -6,7 +6,7 @@ const warn = std.debug.warn;
fn test__fixtfti(a: f128, expected: i128) void {
const x = __fixtfti(a);
- //warn("a={}:{x} x={}:{x} expected={}:{x}:u128({x})\n", a, @bitCast(u128, a), x, x, expected, expected, @bitCast(u128, expected));
+ //warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u128, {x})\n", a, @bitCast(u128, a), x, x, expected, expected, @bitCast(u128, expected));
testing.expect(x == expected);
}
diff --git a/lib/std/special/compiler_rt/fixuint.zig b/lib/std/special/compiler_rt/fixuint.zig
index 55a113b368..977d3c16c9 100644
--- a/lib/std/special/compiler_rt/fixuint.zig
+++ b/lib/std/special/compiler_rt/fixuint.zig
@@ -19,11 +19,11 @@ pub fn fixuint(comptime fp_t: type, comptime fixuint_t: type, a: fp_t) fixuint_t
};
const typeWidth = rep_t.bit_count;
const exponentBits = (typeWidth - significandBits - 1);
- const signBit = (rep_t(1) << (significandBits + exponentBits));
+ const signBit = (@as(rep_t, 1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const exponentBias = (maxExponent >> 1);
- const implicitBit = (rep_t(1) << significandBits);
+ const implicitBit = (@as(rep_t, 1) << significandBits);
const significandMask = (implicitBit - 1);
// Break a into sign, exponent, significand
@@ -31,7 +31,7 @@ pub fn fixuint(comptime fp_t: type, comptime fixuint_t: type, a: fp_t) fixuint_t
const absMask = signBit - 1;
const aAbs: rep_t = aRep & absMask;
- const sign = if ((aRep & signBit) != 0) i32(-1) else i32(1);
+ const sign = if ((aRep & signBit) != 0) @as(i32, -1) else @as(i32, 1);
const exponent = @intCast(i32, aAbs >> significandBits) - exponentBias;
const significand: rep_t = (aAbs & significandMask) | implicitBit;
@@ -39,7 +39,7 @@ pub fn fixuint(comptime fp_t: type, comptime fixuint_t: type, a: fp_t) fixuint_t
if (sign == -1 or exponent < 0) return 0;
// If the value is too large for the integer type, saturate.
- if (@intCast(c_uint, exponent) >= fixuint_t.bit_count) return ~fixuint_t(0);
+ if (@intCast(c_uint, exponent) >= fixuint_t.bit_count) return ~@as(fixuint_t, 0);
// If 0 <= exponent < significandBits, right shift to get the result.
// Otherwise, shift left.
diff --git a/lib/std/special/compiler_rt/fixunstfsi_test.zig b/lib/std/special/compiler_rt/fixunstfsi_test.zig
index e709636912..286567629a 100644
--- a/lib/std/special/compiler_rt/fixunstfsi_test.zig
+++ b/lib/std/special/compiler_rt/fixunstfsi_test.zig
@@ -6,7 +6,7 @@ fn test__fixunstfsi(a: f128, expected: u32) void {
testing.expect(x == expected);
}
-const inf128 = @bitCast(f128, u128(0x7fff0000000000000000000000000000));
+const inf128 = @bitCast(f128, @as(u128, 0x7fff0000000000000000000000000000));
test "fixunstfsi" {
test__fixunstfsi(inf128, 0xffffffff);
diff --git a/lib/std/special/compiler_rt/fixunstfti_test.zig b/lib/std/special/compiler_rt/fixunstfti_test.zig
index 833e4779dd..62a9bbfecf 100644
--- a/lib/std/special/compiler_rt/fixunstfti_test.zig
+++ b/lib/std/special/compiler_rt/fixunstfti_test.zig
@@ -6,7 +6,7 @@ fn test__fixunstfti(a: f128, expected: u128) void {
testing.expect(x == expected);
}
-const inf128 = @bitCast(f128, u128(0x7fff0000000000000000000000000000));
+const inf128 = @bitCast(f128, @as(u128, 0x7fff0000000000000000000000000000));
test "fixunstfti" {
test__fixunstfti(inf128, 0xffffffffffffffffffffffffffffffff);
diff --git a/lib/std/special/compiler_rt/floatsiXf.zig b/lib/std/special/compiler_rt/floatsiXf.zig
index 7e05a3ebf7..714681834d 100644
--- a/lib/std/special/compiler_rt/floatsiXf.zig
+++ b/lib/std/special/compiler_rt/floatsiXf.zig
@@ -6,24 +6,24 @@ fn floatsiXf(comptime T: type, a: i32) T {
@setRuntimeSafety(builtin.is_test);
const Z = @IntType(false, T.bit_count);
- const S = @IntType(false, T.bit_count - @clz(Z, Z(T.bit_count) - 1));
+ const S = @IntType(false, T.bit_count - @clz(Z, @as(Z, T.bit_count) - 1));
if (a == 0) {
- return T(0.0);
+ return @as(T, 0.0);
}
const significandBits = std.math.floatMantissaBits(T);
const exponentBits = std.math.floatExponentBits(T);
const exponentBias = ((1 << exponentBits - 1) - 1);
- const implicitBit = Z(1) << significandBits;
- const signBit = Z(1 << Z.bit_count - 1);
+ const implicitBit = @as(Z, 1) << significandBits;
+ const signBit = @as(Z, 1 << Z.bit_count - 1);
const sign = a >> 31;
// Take absolute value of a via abs(x) = (x^(x >> 31)) - (x >> 31).
const abs_a = (a ^ sign) -% sign;
// The exponent is the width of abs(a)
- const exp = Z(31 - @clz(i32, abs_a));
+ const exp = @as(Z, 31 - @clz(i32, abs_a));
const sign_bit = if (sign < 0) signBit else 0;
diff --git a/lib/std/special/compiler_rt/floattidf.zig b/lib/std/special/compiler_rt/floattidf.zig
index 42ef6df7e4..1e83674598 100644
--- a/lib/std/special/compiler_rt/floattidf.zig
+++ b/lib/std/special/compiler_rt/floattidf.zig
@@ -47,7 +47,7 @@ pub extern fn __floattidf(arg: i128) f64 {
a += 1; // round - this step may add a significant bit
a >>= 2; // dump Q and R
// a is now rounded to DBL_MANT_DIG or DBL_MANT_DIG+1 bits
- if ((a & (u128(1) << DBL_MANT_DIG)) != 0) {
+ if ((a & (@as(u128, 1) << DBL_MANT_DIG)) != 0) {
a >>= 1;
e += 1;
}
diff --git a/lib/std/special/compiler_rt/floattisf.zig b/lib/std/special/compiler_rt/floattisf.zig
index f397d130ef..0c02bfff1f 100644
--- a/lib/std/special/compiler_rt/floattisf.zig
+++ b/lib/std/special/compiler_rt/floattisf.zig
@@ -48,7 +48,7 @@ pub extern fn __floattisf(arg: i128) f32 {
a += 1; // round - this step may add a significant bit
a >>= 2; // dump Q and R
// a is now rounded to FLT_MANT_DIG or FLT_MANT_DIG+1 bits
- if ((a & (u128(1) << FLT_MANT_DIG)) != 0) {
+ if ((a & (@as(u128, 1) << FLT_MANT_DIG)) != 0) {
a >>= 1;
e += 1;
}
diff --git a/lib/std/special/compiler_rt/floattitf.zig b/lib/std/special/compiler_rt/floattitf.zig
index b05282e293..aac22e36d0 100644
--- a/lib/std/special/compiler_rt/floattitf.zig
+++ b/lib/std/special/compiler_rt/floattitf.zig
@@ -47,7 +47,7 @@ pub extern fn __floattitf(arg: i128) f128 {
a += 1; // round - this step may add a significant bit
a >>= 2; // dump Q and R
// a is now rounded to LDBL_MANT_DIG or LDBL_MANT_DIG+1 bits
- if ((a & (u128(1) << LDBL_MANT_DIG)) != 0) {
+ if ((a & (@as(u128, 1) << LDBL_MANT_DIG)) != 0) {
a >>= 1;
e += 1;
}
diff --git a/lib/std/special/compiler_rt/floatunsidf.zig b/lib/std/special/compiler_rt/floatunsidf.zig
index efeb4c2672..d744009aea 100644
--- a/lib/std/special/compiler_rt/floatunsidf.zig
+++ b/lib/std/special/compiler_rt/floatunsidf.zig
@@ -2,7 +2,7 @@ const builtin = @import("builtin");
const std = @import("std");
const maxInt = std.math.maxInt;
-const implicitBit = u64(1) << 52;
+const implicitBit = @as(u64, 1) << 52;
pub extern fn __floatunsidf(arg: u32) f64 {
@setRuntimeSafety(builtin.is_test);
@@ -10,10 +10,10 @@ pub extern fn __floatunsidf(arg: u32) f64 {
if (arg == 0) return 0.0;
// The exponent is the width of abs(a)
- const exp = u64(31) - @clz(u32, arg);
+ const exp = @as(u64, 31) - @clz(u32, arg);
// Shift a into the significand field and clear the implicit bit
const shift = @intCast(u6, 52 - exp);
- const mant = u64(arg) << shift ^ implicitBit;
+ const mant = @as(u64, arg) << shift ^ implicitBit;
return @bitCast(f64, mant | (exp + 1023) << 52);
}
diff --git a/lib/std/special/compiler_rt/floatuntidf.zig b/lib/std/special/compiler_rt/floatuntidf.zig
index 2cd38c7308..5d3a201058 100644
--- a/lib/std/special/compiler_rt/floatuntidf.zig
+++ b/lib/std/special/compiler_rt/floatuntidf.zig
@@ -32,7 +32,7 @@ pub extern fn __floatuntidf(arg: u128) f64 {
const shift_amt = @bitCast(i32, N + (DBL_MANT_DIG + 2)) - sd;
const shift_amt_u7 = @intCast(u7, shift_amt);
a = (a >> @intCast(u7, sd - (DBL_MANT_DIG + 2))) |
- @boolToInt((a & (u128(maxInt(u128)) >> shift_amt_u7)) != 0);
+ @boolToInt((a & (@as(u128, maxInt(u128)) >> shift_amt_u7)) != 0);
},
}
// finish
@@ -40,7 +40,7 @@ pub extern fn __floatuntidf(arg: u128) f64 {
a += 1; // round - this step may add a significant bit
a >>= 2; // dump Q and R
// a is now rounded to DBL_MANT_DIG or DBL_MANT_DIG+1 bits
- if ((a & (u128(1) << DBL_MANT_DIG)) != 0) {
+ if ((a & (@as(u128, 1) << DBL_MANT_DIG)) != 0) {
a >>= 1;
e += 1;
}
diff --git a/lib/std/special/compiler_rt/floatuntisf.zig b/lib/std/special/compiler_rt/floatuntisf.zig
index 1b42b267d9..e450ad9a48 100644
--- a/lib/std/special/compiler_rt/floatuntisf.zig
+++ b/lib/std/special/compiler_rt/floatuntisf.zig
@@ -32,7 +32,7 @@ pub extern fn __floatuntisf(arg: u128) f32 {
const shift_amt = @bitCast(i32, N + (FLT_MANT_DIG + 2)) - sd;
const shift_amt_u7 = @intCast(u7, shift_amt);
a = (a >> @intCast(u7, sd - (FLT_MANT_DIG + 2))) |
- @boolToInt((a & (u128(maxInt(u128)) >> shift_amt_u7)) != 0);
+ @boolToInt((a & (@as(u128, maxInt(u128)) >> shift_amt_u7)) != 0);
},
}
// finish
@@ -40,7 +40,7 @@ pub extern fn __floatuntisf(arg: u128) f32 {
a += 1; // round - this step may add a significant bit
a >>= 2; // dump Q and R
// a is now rounded to FLT_MANT_DIG or FLT_MANT_DIG+1 bits
- if ((a & (u128(1) << FLT_MANT_DIG)) != 0) {
+ if ((a & (@as(u128, 1) << FLT_MANT_DIG)) != 0) {
a >>= 1;
e += 1;
}
diff --git a/lib/std/special/compiler_rt/floatuntitf.zig b/lib/std/special/compiler_rt/floatuntitf.zig
index eddcf92efd..f92942e034 100644
--- a/lib/std/special/compiler_rt/floatuntitf.zig
+++ b/lib/std/special/compiler_rt/floatuntitf.zig
@@ -32,7 +32,7 @@ pub extern fn __floatuntitf(arg: u128) f128 {
const shift_amt = @bitCast(i32, N + (LDBL_MANT_DIG + 2)) - sd;
const shift_amt_u7 = @intCast(u7, shift_amt);
a = (a >> @intCast(u7, sd - (LDBL_MANT_DIG + 2))) |
- @boolToInt((a & (u128(maxInt(u128)) >> shift_amt_u7)) != 0);
+ @boolToInt((a & (@as(u128, maxInt(u128)) >> shift_amt_u7)) != 0);
},
}
// finish
@@ -40,7 +40,7 @@ pub extern fn __floatuntitf(arg: u128) f128 {
a += 1; // round - this step may add a significant bit
a >>= 2; // dump Q and R
// a is now rounded to LDBL_MANT_DIG or LDBL_MANT_DIG+1 bits
- if ((a & (u128(1) << LDBL_MANT_DIG)) != 0) {
+ if ((a & (@as(u128, 1) << LDBL_MANT_DIG)) != 0) {
a >>= 1;
e += 1;
}
diff --git a/lib/std/special/compiler_rt/mulXf3.zig b/lib/std/special/compiler_rt/mulXf3.zig
index 51d40ad26f..11ee0b49a4 100644
--- a/lib/std/special/compiler_rt/mulXf3.zig
+++ b/lib/std/special/compiler_rt/mulXf3.zig
@@ -24,11 +24,11 @@ fn mulXf3(comptime T: type, a: T, b: T) T {
const significandBits = std.math.floatMantissaBits(T);
const exponentBits = std.math.floatExponentBits(T);
- const signBit = (Z(1) << (significandBits + exponentBits));
+ const signBit = (@as(Z, 1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const exponentBias = (maxExponent >> 1);
- const implicitBit = (Z(1) << significandBits);
+ const implicitBit = (@as(Z, 1) << significandBits);
const quietBit = implicitBit >> 1;
const significandMask = implicitBit - 1;
@@ -122,7 +122,7 @@ fn mulXf3(comptime T: type, a: T, b: T) T {
// a zero of the appropriate sign. Mathematically there is no need to
// handle this case separately, but we make it a special case to
// simplify the shift logic.
- const shift: u32 = @truncate(u32, Z(1) -% @bitCast(u32, productExponent));
+ const shift: u32 = @truncate(u32, @as(Z, 1) -% @bitCast(u32, productExponent));
if (shift >= typeWidth) return @bitCast(T, productSign);
// Otherwise, shift the significand of the result so that the round
@@ -131,7 +131,7 @@ fn mulXf3(comptime T: type, a: T, b: T) T {
} else {
// Result is normal before rounding; insert the exponent.
productHi &= significandMask;
- productHi |= Z(@bitCast(u32, productExponent)) << significandBits;
+ productHi |= @as(Z, @bitCast(u32, productExponent)) << significandBits;
}
// Insert the sign of the result:
@@ -150,7 +150,7 @@ fn wideMultiply(comptime Z: type, a: Z, b: Z, hi: *Z, lo: *Z) void {
switch (Z) {
u32 => {
// 32x32 --> 64 bit multiply
- const product = u64(a) * u64(b);
+ const product = @as(u64, a) * @as(u64, b);
hi.* = @truncate(u32, product >> 32);
lo.* = @truncate(u32, product);
},
@@ -179,9 +179,9 @@ fn wideMultiply(comptime Z: type, a: Z, b: Z, hi: *Z, lo: *Z) void {
hi.* = S.hiWord(plohi) +% S.hiWord(philo) +% S.hiWord(r1) +% phihi;
},
u128 => {
- const Word_LoMask = u64(0x00000000ffffffff);
- const Word_HiMask = u64(0xffffffff00000000);
- const Word_FullMask = u64(0xffffffffffffffff);
+ const Word_LoMask = @as(u64, 0x00000000ffffffff);
+ const Word_HiMask = @as(u64, 0xffffffff00000000);
+ const Word_FullMask = @as(u64, 0xffffffffffffffff);
const S = struct {
fn Word_1(x: u128) u64 {
return @truncate(u32, x >> 96);
@@ -217,22 +217,22 @@ fn wideMultiply(comptime Z: type, a: Z, b: Z, hi: *Z, lo: *Z) void {
const product43: u64 = S.Word_4(a) * S.Word_3(b);
const product44: u64 = S.Word_4(a) * S.Word_4(b);
- const sum0: u128 = u128(product44);
- const sum1: u128 = u128(product34) +%
- u128(product43);
- const sum2: u128 = u128(product24) +%
- u128(product33) +%
- u128(product42);
- const sum3: u128 = u128(product14) +%
- u128(product23) +%
- u128(product32) +%
- u128(product41);
- const sum4: u128 = u128(product13) +%
- u128(product22) +%
- u128(product31);
- const sum5: u128 = u128(product12) +%
- u128(product21);
- const sum6: u128 = u128(product11);
+ const sum0: u128 = @as(u128, product44);
+ const sum1: u128 = @as(u128, product34) +%
+ @as(u128, product43);
+ const sum2: u128 = @as(u128, product24) +%
+ @as(u128, product33) +%
+ @as(u128, product42);
+ const sum3: u128 = @as(u128, product14) +%
+ @as(u128, product23) +%
+ @as(u128, product32) +%
+ @as(u128, product41);
+ const sum4: u128 = @as(u128, product13) +%
+ @as(u128, product22) +%
+ @as(u128, product31);
+ const sum5: u128 = @as(u128, product12) +%
+ @as(u128, product21);
+ const sum6: u128 = @as(u128, product11);
const r0: u128 = (sum0 & Word_FullMask) +%
((sum1 & Word_LoMask) << 32);
@@ -258,7 +258,7 @@ fn normalize(comptime T: type, significand: *@IntType(false, T.bit_count)) i32 {
@setRuntimeSafety(builtin.is_test);
const Z = @IntType(false, T.bit_count);
const significandBits = std.math.floatMantissaBits(T);
- const implicitBit = Z(1) << significandBits;
+ const implicitBit = @as(Z, 1) << significandBits;
const shift = @clz(Z, significand.*) - @clz(Z, implicitBit);
significand.* <<= @intCast(std.math.Log2Int(Z), shift);
diff --git a/lib/std/special/compiler_rt/mulXf3_test.zig b/lib/std/special/compiler_rt/mulXf3_test.zig
index 1c0c0fc043..57dc385321 100644
--- a/lib/std/special/compiler_rt/mulXf3_test.zig
+++ b/lib/std/special/compiler_rt/mulXf3_test.zig
@@ -2,8 +2,8 @@
//
// https://github.com/llvm/llvm-project/blob/2ffb1b0413efa9a24eb3c49e710e36f92e2cb50b/compiler-rt/test/builtins/Unit/multf3_test.c
-const qnan128 = @bitCast(f128, u128(0x7fff800000000000) << 64);
-const inf128 = @bitCast(f128, u128(0x7fff000000000000) << 64);
+const qnan128 = @bitCast(f128, @as(u128, 0x7fff800000000000) << 64);
+const inf128 = @bitCast(f128, @as(u128, 0x7fff000000000000) << 64);
const __multf3 = @import("mulXf3.zig").__multf3;
@@ -39,7 +39,7 @@ fn test__multf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) void {
}
fn makeNaN128(rand: u64) f128 {
- const int_result = u128(0x7fff000000000000 | (rand & 0xffffffffffff)) << 64;
+ const int_result = @as(u128, 0x7fff000000000000 | (rand & 0xffffffffffff)) << 64;
const float_result = @bitCast(f128, int_result);
return float_result;
}
@@ -55,15 +55,15 @@ test "multf3" {
// any * any
test__multf3(
- @bitCast(f128, u128(0x40042eab345678439abcdefea5678234)),
- @bitCast(f128, u128(0x3ffeedcb34a235253948765432134675)),
+ @bitCast(f128, @as(u128, 0x40042eab345678439abcdefea5678234)),
+ @bitCast(f128, @as(u128, 0x3ffeedcb34a235253948765432134675)),
0x400423e7f9e3c9fc,
0xd906c2c2a85777c4,
);
test__multf3(
- @bitCast(f128, u128(0x3fcd353e45674d89abacc3a2ebf3ff50)),
- @bitCast(f128, u128(0x3ff6ed8764648369535adf4be3214568)),
+ @bitCast(f128, @as(u128, 0x3fcd353e45674d89abacc3a2ebf3ff50)),
+ @bitCast(f128, @as(u128, 0x3ff6ed8764648369535adf4be3214568)),
0x3fc52a163c6223fc,
0xc94c4bf0430768b4,
);
@@ -76,8 +76,8 @@ test "multf3" {
);
test__multf3(
- @bitCast(f128, u128(0x3f154356473c82a9fabf2d22ace345df)),
- @bitCast(f128, u128(0x3e38eda98765476743ab21da23d45679)),
+ @bitCast(f128, @as(u128, 0x3f154356473c82a9fabf2d22ace345df)),
+ @bitCast(f128, @as(u128, 0x3e38eda98765476743ab21da23d45679)),
0x3d4f37c1a3137cae,
0xfc6807048bc2836a,
);
diff --git a/lib/std/special/compiler_rt/muldi3.zig b/lib/std/special/compiler_rt/muldi3.zig
index 7700777c16..3efc5a9ac6 100644
--- a/lib/std/special/compiler_rt/muldi3.zig
+++ b/lib/std/special/compiler_rt/muldi3.zig
@@ -21,7 +21,7 @@ fn __muldsi3(a: u32, b: u32) i64 {
@setRuntimeSafety(builtin.is_test);
const bits_in_word_2 = @sizeOf(i32) * 8 / 2;
- const lower_mask = (~u32(0)) >> bits_in_word_2;
+ const lower_mask = (~@as(u32, 0)) >> bits_in_word_2;
var r: dwords = undefined;
r.s.low = (a & lower_mask) *% (b & lower_mask);
diff --git a/lib/std/special/compiler_rt/mulodi4.zig b/lib/std/special/compiler_rt/mulodi4.zig
index 82e9ef3253..21c7fd1f97 100644
--- a/lib/std/special/compiler_rt/mulodi4.zig
+++ b/lib/std/special/compiler_rt/mulodi4.zig
@@ -6,7 +6,7 @@ const minInt = std.math.minInt;
pub extern fn __mulodi4(a: i64, b: i64, overflow: *c_int) i64 {
@setRuntimeSafety(builtin.is_test);
- const min = @bitCast(i64, u64(1 << (i64.bit_count - 1)));
+ const min = @bitCast(i64, @as(u64, 1 << (i64.bit_count - 1)));
const max = ~min;
overflow.* = 0;
diff --git a/lib/std/special/compiler_rt/mulodi4_test.zig b/lib/std/special/compiler_rt/mulodi4_test.zig
index 7575c77044..803d60e8fa 100644
--- a/lib/std/special/compiler_rt/mulodi4_test.zig
+++ b/lib/std/special/compiler_rt/mulodi4_test.zig
@@ -52,34 +52,34 @@ test "mulodi4" {
test__mulodi4(0x7FFFFFFFFFFFFFFF, -2, 2, 1);
test__mulodi4(-2, 0x7FFFFFFFFFFFFFFF, 2, 1);
- test__mulodi4(0x7FFFFFFFFFFFFFFF, -1, @bitCast(i64, u64(0x8000000000000001)), 0);
- test__mulodi4(-1, 0x7FFFFFFFFFFFFFFF, @bitCast(i64, u64(0x8000000000000001)), 0);
+ test__mulodi4(0x7FFFFFFFFFFFFFFF, -1, @bitCast(i64, @as(u64, 0x8000000000000001)), 0);
+ test__mulodi4(-1, 0x7FFFFFFFFFFFFFFF, @bitCast(i64, @as(u64, 0x8000000000000001)), 0);
test__mulodi4(0x7FFFFFFFFFFFFFFF, 0, 0, 0);
test__mulodi4(0, 0x7FFFFFFFFFFFFFFF, 0, 0);
test__mulodi4(0x7FFFFFFFFFFFFFFF, 1, 0x7FFFFFFFFFFFFFFF, 0);
test__mulodi4(1, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0);
- test__mulodi4(0x7FFFFFFFFFFFFFFF, 2, @bitCast(i64, u64(0x8000000000000001)), 1);
- test__mulodi4(2, 0x7FFFFFFFFFFFFFFF, @bitCast(i64, u64(0x8000000000000001)), 1);
+ test__mulodi4(0x7FFFFFFFFFFFFFFF, 2, @bitCast(i64, @as(u64, 0x8000000000000001)), 1);
+ test__mulodi4(2, 0x7FFFFFFFFFFFFFFF, @bitCast(i64, @as(u64, 0x8000000000000001)), 1);
- test__mulodi4(@bitCast(i64, u64(0x8000000000000000)), -2, @bitCast(i64, u64(0x8000000000000000)), 1);
- test__mulodi4(-2, @bitCast(i64, u64(0x8000000000000000)), @bitCast(i64, u64(0x8000000000000000)), 1);
- test__mulodi4(@bitCast(i64, u64(0x8000000000000000)), -1, @bitCast(i64, u64(0x8000000000000000)), 1);
- test__mulodi4(-1, @bitCast(i64, u64(0x8000000000000000)), @bitCast(i64, u64(0x8000000000000000)), 1);
- test__mulodi4(@bitCast(i64, u64(0x8000000000000000)), 0, 0, 0);
- test__mulodi4(0, @bitCast(i64, u64(0x8000000000000000)), 0, 0);
- test__mulodi4(@bitCast(i64, u64(0x8000000000000000)), 1, @bitCast(i64, u64(0x8000000000000000)), 0);
- test__mulodi4(1, @bitCast(i64, u64(0x8000000000000000)), @bitCast(i64, u64(0x8000000000000000)), 0);
- test__mulodi4(@bitCast(i64, u64(0x8000000000000000)), 2, @bitCast(i64, u64(0x8000000000000000)), 1);
- test__mulodi4(2, @bitCast(i64, u64(0x8000000000000000)), @bitCast(i64, u64(0x8000000000000000)), 1);
+ test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000000)), -2, @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
+ test__mulodi4(-2, @bitCast(i64, @as(u64, 0x8000000000000000)), @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
+ test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000000)), -1, @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
+ test__mulodi4(-1, @bitCast(i64, @as(u64, 0x8000000000000000)), @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
+ test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000000)), 0, 0, 0);
+ test__mulodi4(0, @bitCast(i64, @as(u64, 0x8000000000000000)), 0, 0);
+ test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000000)), 1, @bitCast(i64, @as(u64, 0x8000000000000000)), 0);
+ test__mulodi4(1, @bitCast(i64, @as(u64, 0x8000000000000000)), @bitCast(i64, @as(u64, 0x8000000000000000)), 0);
+ test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000000)), 2, @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
+ test__mulodi4(2, @bitCast(i64, @as(u64, 0x8000000000000000)), @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
- test__mulodi4(@bitCast(i64, u64(0x8000000000000001)), -2, @bitCast(i64, u64(0x8000000000000001)), 1);
- test__mulodi4(-2, @bitCast(i64, u64(0x8000000000000001)), @bitCast(i64, u64(0x8000000000000001)), 1);
- test__mulodi4(@bitCast(i64, u64(0x8000000000000001)), -1, 0x7FFFFFFFFFFFFFFF, 0);
- test__mulodi4(-1, @bitCast(i64, u64(0x8000000000000001)), 0x7FFFFFFFFFFFFFFF, 0);
- test__mulodi4(@bitCast(i64, u64(0x8000000000000001)), 0, 0, 0);
- test__mulodi4(0, @bitCast(i64, u64(0x8000000000000001)), 0, 0);
- test__mulodi4(@bitCast(i64, u64(0x8000000000000001)), 1, @bitCast(i64, u64(0x8000000000000001)), 0);
- test__mulodi4(1, @bitCast(i64, u64(0x8000000000000001)), @bitCast(i64, u64(0x8000000000000001)), 0);
- test__mulodi4(@bitCast(i64, u64(0x8000000000000001)), 2, @bitCast(i64, u64(0x8000000000000000)), 1);
- test__mulodi4(2, @bitCast(i64, u64(0x8000000000000001)), @bitCast(i64, u64(0x8000000000000000)), 1);
+ test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000001)), -2, @bitCast(i64, @as(u64, 0x8000000000000001)), 1);
+ test__mulodi4(-2, @bitCast(i64, @as(u64, 0x8000000000000001)), @bitCast(i64, @as(u64, 0x8000000000000001)), 1);
+ test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000001)), -1, 0x7FFFFFFFFFFFFFFF, 0);
+ test__mulodi4(-1, @bitCast(i64, @as(u64, 0x8000000000000001)), 0x7FFFFFFFFFFFFFFF, 0);
+ test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000001)), 0, 0, 0);
+ test__mulodi4(0, @bitCast(i64, @as(u64, 0x8000000000000001)), 0, 0);
+ test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000001)), 1, @bitCast(i64, @as(u64, 0x8000000000000001)), 0);
+ test__mulodi4(1, @bitCast(i64, @as(u64, 0x8000000000000001)), @bitCast(i64, @as(u64, 0x8000000000000001)), 0);
+ test__mulodi4(@bitCast(i64, @as(u64, 0x8000000000000001)), 2, @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
+ test__mulodi4(2, @bitCast(i64, @as(u64, 0x8000000000000001)), @bitCast(i64, @as(u64, 0x8000000000000000)), 1);
}
diff --git a/lib/std/special/compiler_rt/muloti4.zig b/lib/std/special/compiler_rt/muloti4.zig
index ccde8e3e6c..ad6ad43808 100644
--- a/lib/std/special/compiler_rt/muloti4.zig
+++ b/lib/std/special/compiler_rt/muloti4.zig
@@ -4,7 +4,7 @@ const compiler_rt = @import("../compiler_rt.zig");
pub extern fn __muloti4(a: i128, b: i128, overflow: *c_int) i128 {
@setRuntimeSafety(builtin.is_test);
- const min = @bitCast(i128, u128(1 << (i128.bit_count - 1)));
+ const min = @bitCast(i128, @as(u128, 1 << (i128.bit_count - 1)));
const max = ~min;
overflow.* = 0;
diff --git a/lib/std/special/compiler_rt/muloti4_test.zig b/lib/std/special/compiler_rt/muloti4_test.zig
index 00144a8839..f94a13e04f 100644
--- a/lib/std/special/compiler_rt/muloti4_test.zig
+++ b/lib/std/special/compiler_rt/muloti4_test.zig
@@ -39,38 +39,38 @@ test "muloti4" {
test__muloti4(2097152, -4398046511103, -9223372036852678656, 0);
test__muloti4(-2097152, -4398046511103, 9223372036852678656, 0);
- test__muloti4(@bitCast(i128, u128(0x00000000000000B504F333F9DE5BE000)), @bitCast(i128, u128(0x000000000000000000B504F333F9DE5B)), @bitCast(i128, u128(0x7FFFFFFFFFFFF328DF915DA296E8A000)), 0);
- test__muloti4(@bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), -2, @bitCast(i128, u128(0x80000000000000000000000000000001)), 1);
- test__muloti4(-2, @bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, u128(0x80000000000000000000000000000001)), 1);
+ test__muloti4(@bitCast(i128, @as(u128, 0x00000000000000B504F333F9DE5BE000)), @bitCast(i128, @as(u128, 0x000000000000000000B504F333F9DE5B)), @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFF328DF915DA296E8A000)), 0);
+ test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), -2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1);
+ test__muloti4(-2, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1);
- test__muloti4(@bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), -1, @bitCast(i128, u128(0x80000000000000000000000000000001)), 0);
- test__muloti4(-1, @bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, u128(0x80000000000000000000000000000001)), 0);
- test__muloti4(@bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0, 0, 0);
- test__muloti4(0, @bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0, 0);
- test__muloti4(@bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 1, @bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0);
- test__muloti4(1, @bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0);
- test__muloti4(@bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 2, @bitCast(i128, u128(0x80000000000000000000000000000001)), 1);
- test__muloti4(2, @bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, u128(0x80000000000000000000000000000001)), 1);
+ test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), -1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0);
+ test__muloti4(-1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0);
+ test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0, 0, 0);
+ test__muloti4(0, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0, 0);
+ test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0);
+ test__muloti4(1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0);
+ test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1);
+ test__muloti4(2, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1);
- test__muloti4(@bitCast(i128, u128(0x80000000000000000000000000000000)), -2, @bitCast(i128, u128(0x80000000000000000000000000000000)), 1);
- test__muloti4(-2, @bitCast(i128, u128(0x80000000000000000000000000000000)), @bitCast(i128, u128(0x80000000000000000000000000000000)), 1);
- test__muloti4(@bitCast(i128, u128(0x80000000000000000000000000000000)), -1, @bitCast(i128, u128(0x80000000000000000000000000000000)), 1);
- test__muloti4(-1, @bitCast(i128, u128(0x80000000000000000000000000000000)), @bitCast(i128, u128(0x80000000000000000000000000000000)), 1);
- test__muloti4(@bitCast(i128, u128(0x80000000000000000000000000000000)), 0, 0, 0);
- test__muloti4(0, @bitCast(i128, u128(0x80000000000000000000000000000000)), 0, 0);
- test__muloti4(@bitCast(i128, u128(0x80000000000000000000000000000000)), 1, @bitCast(i128, u128(0x80000000000000000000000000000000)), 0);
- test__muloti4(1, @bitCast(i128, u128(0x80000000000000000000000000000000)), @bitCast(i128, u128(0x80000000000000000000000000000000)), 0);
- test__muloti4(@bitCast(i128, u128(0x80000000000000000000000000000000)), 2, @bitCast(i128, u128(0x80000000000000000000000000000000)), 1);
- test__muloti4(2, @bitCast(i128, u128(0x80000000000000000000000000000000)), @bitCast(i128, u128(0x80000000000000000000000000000000)), 1);
+ test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), -2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1);
+ test__muloti4(-2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1);
+ test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), -1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1);
+ test__muloti4(-1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1);
+ test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0, 0, 0);
+ test__muloti4(0, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0, 0);
+ test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0);
+ test__muloti4(1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0);
+ test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1);
+ test__muloti4(2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1);
- test__muloti4(@bitCast(i128, u128(0x80000000000000000000000000000001)), -2, @bitCast(i128, u128(0x80000000000000000000000000000001)), 1);
- test__muloti4(-2, @bitCast(i128, u128(0x80000000000000000000000000000001)), @bitCast(i128, u128(0x80000000000000000000000000000001)), 1);
- test__muloti4(@bitCast(i128, u128(0x80000000000000000000000000000001)), -1, @bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0);
- test__muloti4(-1, @bitCast(i128, u128(0x80000000000000000000000000000001)), @bitCast(i128, u128(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0);
- test__muloti4(@bitCast(i128, u128(0x80000000000000000000000000000001)), 0, 0, 0);
- test__muloti4(0, @bitCast(i128, u128(0x80000000000000000000000000000001)), 0, 0);
- test__muloti4(@bitCast(i128, u128(0x80000000000000000000000000000001)), 1, @bitCast(i128, u128(0x80000000000000000000000000000001)), 0);
- test__muloti4(1, @bitCast(i128, u128(0x80000000000000000000000000000001)), @bitCast(i128, u128(0x80000000000000000000000000000001)), 0);
- test__muloti4(@bitCast(i128, u128(0x80000000000000000000000000000001)), 2, @bitCast(i128, u128(0x80000000000000000000000000000000)), 1);
- test__muloti4(2, @bitCast(i128, u128(0x80000000000000000000000000000001)), @bitCast(i128, u128(0x80000000000000000000000000000000)), 1);
+ test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), -2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1);
+ test__muloti4(-2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1);
+ test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), -1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0);
+ test__muloti4(-1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0);
+ test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0, 0, 0);
+ test__muloti4(0, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0, 0);
+ test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0);
+ test__muloti4(1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0);
+ test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1);
+ test__muloti4(2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1);
}
diff --git a/lib/std/special/compiler_rt/multi3.zig b/lib/std/special/compiler_rt/multi3.zig
index 799b1f575d..f3b74b85d9 100644
--- a/lib/std/special/compiler_rt/multi3.zig
+++ b/lib/std/special/compiler_rt/multi3.zig
@@ -21,7 +21,7 @@ pub extern fn __multi3_windows_x86_64(a: v128, b: v128) v128 {
fn __mulddi3(a: u64, b: u64) i128 {
const bits_in_dword_2 = (@sizeOf(i64) * 8) / 2;
- const lower_mask = ~u64(0) >> bits_in_dword_2;
+ const lower_mask = ~@as(u64, 0) >> bits_in_dword_2;
var r: twords = undefined;
r.s.low = (a & lower_mask) *% (b & lower_mask);
var t: u64 = r.s.low >> bits_in_dword_2;
diff --git a/lib/std/special/compiler_rt/negXf2.zig b/lib/std/special/compiler_rt/negXf2.zig
index b71a503c1d..c4be085d62 100644
--- a/lib/std/special/compiler_rt/negXf2.zig
+++ b/lib/std/special/compiler_rt/negXf2.zig
@@ -15,7 +15,7 @@ fn negXf2(comptime T: type, a: T) T {
const significandBits = std.math.floatMantissaBits(T);
const exponentBits = std.math.floatExponentBits(T);
- const signBit = (Z(1) << (significandBits + exponentBits));
+ const signBit = (@as(Z, 1) << (significandBits + exponentBits));
return @bitCast(T, @bitCast(Z, a) ^ signBit);
}
diff --git a/lib/std/special/compiler_rt/popcountdi2_test.zig b/lib/std/special/compiler_rt/popcountdi2_test.zig
index bedcbcd1de..fe02786e15 100644
--- a/lib/std/special/compiler_rt/popcountdi2_test.zig
+++ b/lib/std/special/compiler_rt/popcountdi2_test.zig
@@ -20,8 +20,8 @@ test "popcountdi2" {
test__popcountdi2(0);
test__popcountdi2(1);
test__popcountdi2(2);
- test__popcountdi2(@bitCast(i64, u64(0xFFFFFFFFFFFFFFFD)));
- test__popcountdi2(@bitCast(i64, u64(0xFFFFFFFFFFFFFFFE)));
- test__popcountdi2(@bitCast(i64, u64(0xFFFFFFFFFFFFFFFF)));
+ test__popcountdi2(@bitCast(i64, @as(u64, 0xFFFFFFFFFFFFFFFD)));
+ test__popcountdi2(@bitCast(i64, @as(u64, 0xFFFFFFFFFFFFFFFE)));
+ test__popcountdi2(@bitCast(i64, @as(u64, 0xFFFFFFFFFFFFFFFF)));
// TODO some fuzz testing
}
diff --git a/lib/std/special/compiler_rt/truncXfYf2.zig b/lib/std/special/compiler_rt/truncXfYf2.zig
index e4c4aa38a7..d231c0d416 100644
--- a/lib/std/special/compiler_rt/truncXfYf2.zig
+++ b/lib/std/special/compiler_rt/truncXfYf2.zig
@@ -69,7 +69,7 @@ inline fn truncXfYf2(comptime dst_t: type, comptime src_t: type, a: src_t) dst_t
// destination format. We can convert by simply right-shifting with
// rounding and adjusting the exponent.
absResult = @truncate(dst_rep_t, aAbs >> (srcSigBits - dstSigBits));
- absResult -%= dst_rep_t(srcExpBias - dstExpBias) << dstSigBits;
+ absResult -%= @as(dst_rep_t, srcExpBias - dstExpBias) << dstSigBits;
const roundBits: src_rep_t = aAbs & roundMask;
if (roundBits > halfway) {
diff --git a/lib/std/special/compiler_rt/truncXfYf2_test.zig b/lib/std/special/compiler_rt/truncXfYf2_test.zig
index eccf7efb7e..d1dd837ddc 100644
--- a/lib/std/special/compiler_rt/truncXfYf2_test.zig
+++ b/lib/std/special/compiler_rt/truncXfYf2_test.zig
@@ -152,11 +152,11 @@ fn test__trunctfsf2(a: f128, expected: u32) void {
test "trunctfsf2" {
// qnan
- test__trunctfsf2(@bitCast(f128, u128(0x7fff800000000000 << 64)), 0x7fc00000);
+ test__trunctfsf2(@bitCast(f128, @as(u128, 0x7fff800000000000 << 64)), 0x7fc00000);
// nan
- test__trunctfsf2(@bitCast(f128, u128((0x7fff000000000000 | (0x810000000000 & 0xffffffffffff)) << 64)), 0x7fc08000);
+ test__trunctfsf2(@bitCast(f128, @as(u128, (0x7fff000000000000 | (0x810000000000 & 0xffffffffffff)) << 64)), 0x7fc08000);
// inf
- test__trunctfsf2(@bitCast(f128, u128(0x7fff000000000000 << 64)), 0x7f800000);
+ test__trunctfsf2(@bitCast(f128, @as(u128, 0x7fff000000000000 << 64)), 0x7f800000);
// zero
test__trunctfsf2(0.0, 0x0);
@@ -187,11 +187,11 @@ fn test__trunctfdf2(a: f128, expected: u64) void {
test "trunctfdf2" {
// qnan
- test__trunctfdf2(@bitCast(f128, u128(0x7fff800000000000 << 64)), 0x7ff8000000000000);
+ test__trunctfdf2(@bitCast(f128, @as(u128, 0x7fff800000000000 << 64)), 0x7ff8000000000000);
// nan
- test__trunctfdf2(@bitCast(f128, u128((0x7fff000000000000 | (0x810000000000 & 0xffffffffffff)) << 64)), 0x7ff8100000000000);
+ test__trunctfdf2(@bitCast(f128, @as(u128, (0x7fff000000000000 | (0x810000000000 & 0xffffffffffff)) << 64)), 0x7ff8100000000000);
// inf
- test__trunctfdf2(@bitCast(f128, u128(0x7fff000000000000 << 64)), 0x7ff0000000000000);
+ test__trunctfdf2(@bitCast(f128, @as(u128, 0x7fff000000000000 << 64)), 0x7ff0000000000000);
// zero
test__trunctfdf2(0.0, 0x0);
@@ -224,11 +224,11 @@ fn test__truncdfsf2(a: f64, expected: u32) void {
test "truncdfsf2" {
// nan & qnan
- test__truncdfsf2(@bitCast(f64, u64(0x7ff8000000000000)), 0x7fc00000);
- test__truncdfsf2(@bitCast(f64, u64(0x7ff0000000000001)), 0x7fc00000);
+ test__truncdfsf2(@bitCast(f64, @as(u64, 0x7ff8000000000000)), 0x7fc00000);
+ test__truncdfsf2(@bitCast(f64, @as(u64, 0x7ff0000000000001)), 0x7fc00000);
// inf
- test__truncdfsf2(@bitCast(f64, u64(0x7ff0000000000000)), 0x7f800000);
- test__truncdfsf2(@bitCast(f64, u64(0xfff0000000000000)), 0xff800000);
+ test__truncdfsf2(@bitCast(f64, @as(u64, 0x7ff0000000000000)), 0x7f800000);
+ test__truncdfsf2(@bitCast(f64, @as(u64, 0xfff0000000000000)), 0xff800000);
test__truncdfsf2(0.0, 0x0);
test__truncdfsf2(1.0, 0x3f800000);
diff --git a/lib/std/special/compiler_rt/udivmod.zig b/lib/std/special/compiler_rt/udivmod.zig
index c3066153f3..96fb7b3bdd 100644
--- a/lib/std/special/compiler_rt/udivmod.zig
+++ b/lib/std/special/compiler_rt/udivmod.zig
@@ -76,7 +76,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:
// K K
// ---
// K 0
- sr = @bitCast(c_uint, c_int(@clz(SingleInt, d[high])) - c_int(@clz(SingleInt, n[high])));
+ sr = @bitCast(c_uint, @as(c_int, @clz(SingleInt, d[high])) - @as(c_int, @clz(SingleInt, n[high])));
// 0 <= sr <= SingleInt.bit_count - 2 or sr large
if (sr > SingleInt.bit_count - 2) {
if (maybe_rem) |rem| {
@@ -114,7 +114,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:
// K X
// ---
// 0 K
- sr = 1 + SingleInt.bit_count + c_uint(@clz(SingleInt, d[low])) - c_uint(@clz(SingleInt, n[high]));
+ sr = 1 + SingleInt.bit_count + @as(c_uint, @clz(SingleInt, d[low])) - @as(c_uint, @clz(SingleInt, n[high]));
// 2 <= sr <= DoubleInt.bit_count - 1
// q.all = a << (DoubleInt.bit_count - sr);
// r.all = a >> sr;
@@ -140,7 +140,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:
// K X
// ---
// K K
- sr = @bitCast(c_uint, c_int(@clz(SingleInt, d[high])) - c_int(@clz(SingleInt, n[high])));
+ sr = @bitCast(c_uint, @as(c_int, @clz(SingleInt, d[high])) - @as(c_int, @clz(SingleInt, n[high])));
// 0 <= sr <= SingleInt.bit_count - 1 or sr large
if (sr > SingleInt.bit_count - 1) {
if (maybe_rem) |rem| {
diff --git a/lib/std/special/docs/index.html b/lib/std/special/docs/index.html
index 81df8f30f1..b170ad4a14 100644
--- a/lib/std/special/docs/index.html
+++ b/lib/std/special/docs/index.html
@@ -484,7 +484,7 @@
doc comments.
</p>
</div>
- <div id="fnDocs" class="hidden"></div>
+ <div id="tldDocs" class="hidden"></div>
<div id="sectFnErrors" class="hidden">
<h2>Errors</h2>
<div id="fnErrorsAnyError">
diff --git a/lib/std/special/docs/main.js b/lib/std/special/docs/main.js
index e0d6cdaf05..1812671227 100644
--- a/lib/std/special/docs/main.js
+++ b/lib/std/special/docs/main.js
@@ -20,7 +20,7 @@
var domListValues = document.getElementById("listValues");
var domFnProto = document.getElementById("fnProto");
var domFnProtoCode = document.getElementById("fnProtoCode");
- var domFnDocs = document.getElementById("fnDocs");
+ var domTldDocs = document.getElementById("tldDocs");
var domSectFnErrors = document.getElementById("sectFnErrors");
var domListFnErrors = document.getElementById("listFnErrors");
var domTableFnErrors = document.getElementById("tableFnErrors");
@@ -34,7 +34,6 @@
var domListSearchResults = document.getElementById("listSearchResults");
var domSectSearchNoResults = document.getElementById("sectSearchNoResults");
var domSectInfo = document.getElementById("sectInfo");
- var domListInfo = document.getElementById("listInfo");
var domTdTarget = document.getElementById("tdTarget");
var domTdZigVer = document.getElementById("tdZigVer");
var domHdrName = document.getElementById("hdrName");
@@ -102,7 +101,7 @@
function render() {
domStatus.classList.add("hidden");
domFnProto.classList.add("hidden");
- domFnDocs.classList.add("hidden");
+ domTldDocs.classList.add("hidden");
domSectPkgs.classList.add("hidden");
domSectTypes.classList.add("hidden");
domSectNamespaces.classList.add("hidden");
@@ -190,11 +189,11 @@
var docs = zigAnalysis.astNodes[decl.src].docs;
if (docs != null) {
- domFnDocs.innerHTML = markdown(docs);
+ domTldDocs.innerHTML = markdown(docs);
} else {
- domFnDocs.innerHTML = '<p>There are no doc comments for this declaration.</p>';
+ domTldDocs.innerHTML = '<p>There are no doc comments for this declaration.</p>';
}
- domFnDocs.classList.remove("hidden");
+ domTldDocs.classList.remove("hidden");
}
function typeIsErrSet(typeIndex) {
@@ -274,8 +273,8 @@
docsSource = protoSrcNode.docs;
}
if (docsSource != null) {
- domFnDocs.innerHTML = markdown(docsSource);
- domFnDocs.classList.remove("hidden");
+ domTldDocs.innerHTML = markdown(docsSource);
+ domTldDocs.classList.remove("hidden");
}
domFnProto.classList.remove("hidden");
}
@@ -893,8 +892,8 @@
var docs = zigAnalysis.astNodes[decl.src].docs;
if (docs != null) {
- domFnDocs.innerHTML = markdown(docs);
- domFnDocs.classList.remove("hidden");
+ domTldDocs.innerHTML = markdown(docs);
+ domTldDocs.classList.remove("hidden");
}
domFnProto.classList.remove("hidden");
@@ -906,8 +905,8 @@
var docs = zigAnalysis.astNodes[decl.src].docs;
if (docs != null) {
- domFnDocs.innerHTML = markdown(docs);
- domFnDocs.classList.remove("hidden");
+ domTldDocs.innerHTML = markdown(docs);
+ domTldDocs.classList.remove("hidden");
}
domFnProto.classList.remove("hidden");
@@ -957,6 +956,14 @@
varsList.sort(byNameProperty);
valsList.sort(byNameProperty);
+ if (container.src != null) {
+ var docs = zigAnalysis.astNodes[container.src].docs;
+ if (docs != null) {
+ domTldDocs.innerHTML = markdown(docs);
+ domTldDocs.classList.remove("hidden");
+ }
+ }
+
if (typesList.length !== 0) {
resizeDomList(domListTypes, typesList.length, '<li><a href="#"></a></li>');
for (var i = 0; i < typesList.length; i += 1) {
diff --git a/lib/std/special/start.zig b/lib/std/special/start.zig
index 5c4d77b694..c56d50d7c4 100644
--- a/lib/std/special/start.zig
+++ b/lib/std/special/start.zig
@@ -214,7 +214,7 @@ inline fn initEventLoopAndCallMain() u8 {
return @inlineCall(callMain);
}
-fn callMainAsync(loop: *std.event.Loop) u8 {
+async fn callMainAsync(loop: *std.event.Loop) u8 {
// This prevents the event loop from terminating at least until main() has returned.
loop.beginOneEvent();
defer loop.finishOneEvent();
diff --git a/lib/std/spinlock.zig b/lib/std/spinlock.zig
index 905460a2d0..bd811f709c 100644
--- a/lib/std/spinlock.zig
+++ b/lib/std/spinlock.zig
@@ -1,8 +1,8 @@
const std = @import("std.zig");
const builtin = @import("builtin");
-const AtomicOrder = builtin.AtomicOrder;
-const AtomicRmwOp = builtin.AtomicRmwOp;
const assert = std.debug.assert;
+const time = std.time;
+const os = std.os;
pub const SpinLock = struct {
lock: u8, // TODO use a bool or enum
@@ -11,7 +11,7 @@ pub const SpinLock = struct {
spinlock: *SpinLock,
pub fn release(self: Held) void {
- assert(@atomicRmw(u8, &self.spinlock.lock, builtin.AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst) == 1);
+ @atomicStore(u8, &self.spinlock.lock, 0, .Release);
}
};
@@ -20,9 +20,46 @@ pub const SpinLock = struct {
}
pub fn acquire(self: *SpinLock) Held {
- while (@atomicRmw(u8, &self.lock, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst) != 0) {}
+ var backoff = Backoff.init();
+ while (@atomicRmw(u8, &self.lock, .Xchg, 1, .Acquire) != 0)
+ backoff.yield();
return Held{ .spinlock = self };
}
+
+ pub fn yield(iterations: usize) void {
+ var i = iterations;
+ while (i != 0) : (i -= 1) {
+ switch (builtin.arch) {
+ .i386, .x86_64 => asm volatile ("pause"),
+ .arm, .aarch64 => asm volatile ("yield"),
+ else => time.sleep(0),
+ }
+ }
+ }
+
+ /// Provides a method to incrementally yield longer each time its called.
+ pub const Backoff = struct {
+ iteration: usize,
+
+ pub fn init() @This() {
+ return @This(){ .iteration = 0 };
+ }
+
+ /// Modified hybrid yielding from
+ /// http://www.1024cores.net/home/lock-free-algorithms/tricks/spinning
+ pub fn yield(self: *@This()) void {
+ defer self.iteration +%= 1;
+ if (self.iteration < 20) {
+ SpinLock.yield(self.iteration);
+ } else if (self.iteration < 24) {
+ os.sched_yield() catch time.sleep(1);
+ } else if (self.iteration < 26) {
+ time.sleep(1 * time.millisecond);
+ } else {
+ time.sleep(10 * time.millisecond);
+ }
+ }
+ };
};
test "spinlock" {
diff --git a/lib/std/statically_initialized_mutex.zig b/lib/std/statically_initialized_mutex.zig
deleted file mode 100644
index 2ad47b5d91..0000000000
--- a/lib/std/statically_initialized_mutex.zig
+++ /dev/null
@@ -1,105 +0,0 @@
-const std = @import("std.zig");
-const builtin = @import("builtin");
-const AtomicOrder = builtin.AtomicOrder;
-const AtomicRmwOp = builtin.AtomicRmwOp;
-const assert = std.debug.assert;
-const expect = std.testing.expect;
-const windows = std.os.windows;
-
-/// Lock may be held only once. If the same thread
-/// tries to acquire the same mutex twice, it deadlocks.
-/// This type is intended to be initialized statically. If you don't
-/// require static initialization, use std.Mutex.
-/// On Windows, this mutex allocates resources when it is
-/// first used, and the resources cannot be freed.
-/// On Linux, this is an alias of std.Mutex.
-pub const StaticallyInitializedMutex = switch (builtin.os) {
- builtin.Os.linux => std.Mutex,
- builtin.Os.windows => struct {
- lock: windows.CRITICAL_SECTION,
- init_once: windows.RTL_RUN_ONCE,
-
- pub const Held = struct {
- mutex: *StaticallyInitializedMutex,
-
- pub fn release(self: Held) void {
- windows.kernel32.LeaveCriticalSection(&self.mutex.lock);
- }
- };
-
- pub fn init() StaticallyInitializedMutex {
- return StaticallyInitializedMutex{
- .lock = undefined,
- .init_once = windows.INIT_ONCE_STATIC_INIT,
- };
- }
-
- extern fn initCriticalSection(
- InitOnce: *windows.RTL_RUN_ONCE,
- Parameter: ?*c_void,
- Context: ?*c_void,
- ) windows.BOOL {
- const lock = @ptrCast(*windows.CRITICAL_SECTION, @alignCast(@alignOf(windows.CRITICAL_SECTION), Parameter));
- windows.kernel32.InitializeCriticalSection(lock);
- return windows.TRUE;
- }
-
- /// TODO: once https://github.com/ziglang/zig/issues/287 is solved and std.Mutex has a better
- /// implementation of a runtime initialized mutex, remove this function.
- pub fn deinit(self: *StaticallyInitializedMutex) void {
- windows.InitOnceExecuteOnce(&self.init_once, initCriticalSection, &self.lock, null);
- windows.kernel32.DeleteCriticalSection(&self.lock);
- }
-
- pub fn acquire(self: *StaticallyInitializedMutex) Held {
- windows.InitOnceExecuteOnce(&self.init_once, initCriticalSection, &self.lock, null);
- windows.kernel32.EnterCriticalSection(&self.lock);
- return Held{ .mutex = self };
- }
- },
- else => std.Mutex,
-};
-
-test "std.StaticallyInitializedMutex" {
- const TestContext = struct {
- data: i128,
-
- const TestContext = @This();
- const incr_count = 10000;
-
- var mutex = StaticallyInitializedMutex.init();
-
- fn worker(ctx: *TestContext) void {
- var i: usize = 0;
- while (i != TestContext.incr_count) : (i += 1) {
- const held = mutex.acquire();
- defer held.release();
-
- ctx.data += 1;
- }
- }
- };
-
- var plenty_of_memory = try std.heap.direct_allocator.alloc(u8, 300 * 1024);
- defer std.heap.direct_allocator.free(plenty_of_memory);
-
- var fixed_buffer_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(plenty_of_memory);
- var a = &fixed_buffer_allocator.allocator;
-
- var context = TestContext{ .data = 0 };
-
- if (builtin.single_threaded) {
- TestContext.worker(&context);
- expect(context.data == TestContext.incr_count);
- } else {
- const thread_count = 10;
- var threads: [thread_count]*std.Thread = undefined;
- for (threads) |*t| {
- t.* = try std.Thread.spawn(&context, TestContext.worker);
- }
- for (threads) |t|
- t.wait();
-
- expect(context.data == thread_count * TestContext.incr_count);
- }
-}
diff --git a/lib/std/std.zig b/lib/std/std.zig
index bf2c5436fc..83b7ed6e94 100644
--- a/lib/std/std.zig
+++ b/lib/std/std.zig
@@ -19,11 +19,11 @@ pub const Progress = @import("progress.zig").Progress;
pub const SegmentedList = @import("segmented_list.zig").SegmentedList;
pub const SinglyLinkedList = @import("linked_list.zig").SinglyLinkedList;
pub const SpinLock = @import("spinlock.zig").SpinLock;
-pub const StaticallyInitializedMutex = @import("statically_initialized_mutex.zig").StaticallyInitializedMutex;
pub const StringHashMap = @import("hash_map.zig").StringHashMap;
pub const TailQueue = @import("linked_list.zig").TailQueue;
pub const Target = @import("target.zig").Target;
pub const Thread = @import("thread.zig").Thread;
+pub const ThreadParker = @import("parker.zig").ThreadParker;
pub const atomic = @import("atomic.zig");
pub const base64 = @import("base64.zig");
diff --git a/lib/std/target.zig b/lib/std/target.zig
index d297312b4e..5c0ac3d905 100644
--- a/lib/std/target.zig
+++ b/lib/std/target.zig
@@ -218,6 +218,40 @@ pub const Target = union(enum) {
);
}
+ /// Returned slice must be freed by the caller.
+ pub fn vcpkgTriplet(allocator: *mem.Allocator, target: Target, linkage: std.build.VcpkgLinkage) ![]const u8 {
+ const arch = switch (target.getArch()) {
+ .i386 => "x86",
+ .x86_64 => "x64",
+
+ .arm,
+ .armeb,
+ .thumb,
+ .thumbeb,
+ .aarch64_32,
+ => "arm",
+
+ .aarch64,
+ .aarch64_be,
+ => "arm64",
+
+ else => return error.VcpkgNoSuchArchitecture,
+ };
+
+ const os = switch (target.getOs()) {
+ .windows => "windows",
+ .linux => "linux",
+ .macosx => "macos",
+ else => return error.VcpkgNoSuchOs,
+ };
+
+ if (linkage == .Static) {
+ return try mem.join(allocator, "-", [_][]const u8{ arch, os, "static" });
+ } else {
+ return try mem.join(allocator, "-", [_][]const u8{ arch, os });
+ }
+ }
+
pub fn allocDescription(self: Target, allocator: *mem.Allocator) ![]u8 {
// TODO is there anything else worthy of the description that is not
// already captured in the triple?
@@ -319,7 +353,7 @@ pub const Target = union(enum) {
inline for (info.Union.fields) |field| {
if (mem.eql(u8, text, field.name)) {
if (field.field_type == void) {
- return (Arch)(@field(Arch, field.name));
+ return @as(Arch, @field(Arch, field.name));
} else {
const sub_info = @typeInfo(field.field_type);
inline for (sub_info.Enum.fields) |sub_field| {
@@ -581,7 +615,7 @@ pub const Target = union(enum) {
};
pub fn getExternalExecutor(self: Target) Executor {
- if (@TagType(Target)(self) == .Native) return .native;
+ if (@as(@TagType(Target), self) == .Native) return .native;
// If the target OS matches the host OS, we can use QEMU to emulate a foreign architecture.
if (self.getOs() == builtin.os) {
diff --git a/lib/std/testing.zig b/lib/std/testing.zig
index 7f347b0c24..09ab6e406d 100644
--- a/lib/std/testing.zig
+++ b/lib/std/testing.zig
@@ -62,7 +62,7 @@ pub fn expectEqual(expected: var, actual: @typeOf(expected)) void {
builtin.TypeInfo.Pointer.Size.C,
=> {
if (actual != expected) {
- std.debug.panic("expected {}, found {}", expected, actual);
+ std.debug.panic("expected {*}, found {*}", expected, actual);
}
},
diff --git a/lib/std/thread.zig b/lib/std/thread.zig
index fbfb1afd1e..4e15354055 100644
--- a/lib/std/thread.zig
+++ b/lib/std/thread.zig
@@ -344,7 +344,7 @@ pub const Thread = struct {
pub fn cpuCount() CpuCountError!usize {
if (builtin.os == .linux) {
const cpu_set = try os.sched_getaffinity(0);
- return usize(os.CPU_COUNT(cpu_set)); // TODO should not need this usize cast
+ return @as(usize, os.CPU_COUNT(cpu_set)); // TODO should not need this usize cast
}
if (builtin.os == .windows) {
var system_info: windows.SYSTEM_INFO = undefined;
diff --git a/lib/std/time.zig b/lib/std/time.zig
index 04dbb908e2..716c999577 100644
--- a/lib/std/time.zig
+++ b/lib/std/time.zig
@@ -38,7 +38,7 @@ pub fn milliTimestamp() u64 {
const hns_per_ms = (ns_per_s / 100) / ms_per_s;
const epoch_adj = epoch.windows * ms_per_s;
- const ft64 = (u64(ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+ const ft64 = (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
return @divFloor(ft64, hns_per_ms) - -epoch_adj;
}
if (builtin.os == .wasi and !builtin.link_libc) {
@@ -142,10 +142,10 @@ pub const Timer = struct {
// seccomp is going to block us it will at least do so consistently
var ts: os.timespec = undefined;
os.clock_getres(monotonic_clock_id, &ts) catch return error.TimerUnsupported;
- self.resolution = @intCast(u64, ts.tv_sec) * u64(ns_per_s) + @intCast(u64, ts.tv_nsec);
+ self.resolution = @intCast(u64, ts.tv_sec) * @as(u64, ns_per_s) + @intCast(u64, ts.tv_nsec);
os.clock_gettime(monotonic_clock_id, &ts) catch return error.TimerUnsupported;
- self.start_time = @intCast(u64, ts.tv_sec) * u64(ns_per_s) + @intCast(u64, ts.tv_nsec);
+ self.start_time = @intCast(u64, ts.tv_sec) * @as(u64, ns_per_s) + @intCast(u64, ts.tv_nsec);
}
return self;
@@ -185,7 +185,7 @@ pub const Timer = struct {
}
var ts: os.timespec = undefined;
os.clock_gettime(monotonic_clock_id, &ts) catch unreachable;
- return @intCast(u64, ts.tv_sec) * u64(ns_per_s) + @intCast(u64, ts.tv_nsec);
+ return @intCast(u64, ts.tv_sec) * @as(u64, ns_per_s) + @intCast(u64, ts.tv_nsec);
}
};
diff --git a/lib/std/unicode.zig b/lib/std/unicode.zig
index 2e96147166..726b84f125 100644
--- a/lib/std/unicode.zig
+++ b/lib/std/unicode.zig
@@ -7,10 +7,10 @@ const mem = std.mem;
/// Returns how many bytes the UTF-8 representation would require
/// for the given codepoint.
pub fn utf8CodepointSequenceLength(c: u32) !u3 {
- if (c < 0x80) return u3(1);
- if (c < 0x800) return u3(2);
- if (c < 0x10000) return u3(3);
- if (c < 0x110000) return u3(4);
+ if (c < 0x80) return @as(u3, 1);
+ if (c < 0x800) return @as(u3, 2);
+ if (c < 0x10000) return @as(u3, 3);
+ if (c < 0x110000) return @as(u3, 4);
return error.CodepointTooLarge;
}
@@ -18,10 +18,10 @@ pub fn utf8CodepointSequenceLength(c: u32) !u3 {
/// returns a number 1-4 indicating the total length of the codepoint in bytes.
/// If this byte does not match the form of a UTF-8 start byte, returns Utf8InvalidStartByte.
pub fn utf8ByteSequenceLength(first_byte: u8) !u3 {
- if (first_byte < 0b10000000) return u3(1);
- if (first_byte & 0b11100000 == 0b11000000) return u3(2);
- if (first_byte & 0b11110000 == 0b11100000) return u3(3);
- if (first_byte & 0b11111000 == 0b11110000) return u3(4);
+ if (first_byte < 0b10000000) return @as(u3, 1);
+ if (first_byte & 0b11100000 == 0b11000000) return @as(u3, 2);
+ if (first_byte & 0b11110000 == 0b11100000) return @as(u3, 3);
+ if (first_byte & 0b11111000 == 0b11110000) return @as(u3, 4);
return error.Utf8InvalidStartByte;
}
@@ -68,7 +68,7 @@ const Utf8DecodeError = Utf8Decode2Error || Utf8Decode3Error || Utf8Decode4Error
/// utf8Decode2,utf8Decode3,utf8Decode4 directly instead of this function.
pub fn utf8Decode(bytes: []const u8) Utf8DecodeError!u32 {
return switch (bytes.len) {
- 1 => u32(bytes[0]),
+ 1 => @as(u32, bytes[0]),
2 => utf8Decode2(bytes),
3 => utf8Decode3(bytes),
4 => utf8Decode4(bytes),
@@ -226,7 +226,7 @@ pub const Utf8Iterator = struct {
const slice = it.nextCodepointSlice() orelse return null;
switch (slice.len) {
- 1 => return u32(slice[0]),
+ 1 => return @as(u32, slice[0]),
2 => return utf8Decode2(slice) catch unreachable,
3 => return utf8Decode3(slice) catch unreachable,
4 => return utf8Decode4(slice) catch unreachable,
@@ -250,15 +250,15 @@ pub const Utf16LeIterator = struct {
assert(it.i <= it.bytes.len);
if (it.i == it.bytes.len) return null;
const c0: u32 = mem.readIntSliceLittle(u16, it.bytes[it.i .. it.i + 2]);
- if (c0 & ~u32(0x03ff) == 0xd800) {
+ if (c0 & ~@as(u32, 0x03ff) == 0xd800) {
// surrogate pair
it.i += 2;
if (it.i >= it.bytes.len) return error.DanglingSurrogateHalf;
const c1: u32 = mem.readIntSliceLittle(u16, it.bytes[it.i .. it.i + 2]);
- if (c1 & ~u32(0x03ff) != 0xdc00) return error.ExpectedSecondSurrogateHalf;
+ if (c1 & ~@as(u32, 0x03ff) != 0xdc00) return error.ExpectedSecondSurrogateHalf;
it.i += 2;
return 0x10000 + (((c0 & 0x03ff) << 10) | (c1 & 0x03ff));
- } else if (c0 & ~u32(0x03ff) == 0xdc00) {
+ } else if (c0 & ~@as(u32, 0x03ff) == 0xdc00) {
return error.UnexpectedSecondSurrogateHalf;
} else {
it.i += 2;
diff --git a/lib/std/unicode/throughput_test.zig b/lib/std/unicode/throughput_test.zig
index f8b18af734..8122e537ed 100644
--- a/lib/std/unicode/throughput_test.zig
+++ b/lib/std/unicode/throughput_test.zig
@@ -2,9 +2,7 @@ const builtin = @import("builtin");
const std = @import("std");
pub fn main() !void {
- var stdout_file = try std.io.getStdOut();
- var stdout_out_stream = stdout_file.outStream();
- const stdout = &stdout_out_stream.stream;
+ const stdout = &std.io.getStdOut().outStream().stream;
const args = try std.process.argsAlloc(std.heap.direct_allocator);
diff --git a/lib/std/valgrind.zig b/lib/std/valgrind.zig
index 0d7f79dfa2..ffdce1b729 100644
--- a/lib/std/valgrind.zig
+++ b/lib/std/valgrind.zig
@@ -1,5 +1,6 @@
const builtin = @import("builtin");
-const math = @import("index.zig").math;
+const std = @import("std.zig");
+const math = std.math;
pub fn doClientRequest(default: usize, request: usize, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) usize {
if (!builtin.valgrind_support) {
@@ -13,7 +14,7 @@ pub fn doClientRequest(default: usize, request: usize, a1: usize, a2: usize, a3:
\\ roll $29, %%edi ; roll $19, %%edi
\\ xchgl %%ebx,%%ebx
: [_] "={edx}" (-> usize)
- : [_] "{eax}" (&[]usize{ request, a1, a2, a3, a4, a5 }),
+ : [_] "{eax}" (&[_]usize{ request, a1, a2, a3, a4, a5 }),
[_] "0" (default)
: "cc", "memory"
);
@@ -24,7 +25,7 @@ pub fn doClientRequest(default: usize, request: usize, a1: usize, a2: usize, a3:
\\ rolq $61, %%rdi ; rolq $51, %%rdi
\\ xchgq %%rbx,%%rbx
: [_] "={rdx}" (-> usize)
- : [_] "{rax}" (&[]usize{ request, a1, a2, a3, a4, a5 }),
+ : [_] "{rax}" (&[_]usize{ request, a1, a2, a3, a4, a5 }),
[_] "0" (default)
: "cc", "memory"
);
@@ -76,7 +77,7 @@ pub const ClientRequest = extern enum {
InnerThreads = 6402,
};
pub fn ToolBase(base: [2]u8) u32 {
- return (u32(base[0] & 0xff) << 24) | (u32(base[1] & 0xff) << 16);
+ return (@as(u32, base[0] & 0xff) << 24) | (@as(u32, base[1] & 0xff) << 16);
}
pub fn IsTool(base: [2]u8, code: usize) bool {
return ToolBase(base) == (code & 0xffff0000);
@@ -95,48 +96,52 @@ fn doClientRequestStmt(request: ClientRequest, a1: usize, a2: usize, a3: usize,
/// running under Valgrind which is running under another Valgrind,
/// etc.
pub fn runningOnValgrind() usize {
- return doClientRequestExpr(0, ClientRequest.RunningOnValgrind, 0, 0, 0, 0, 0);
+ return doClientRequestExpr(0, .RunningOnValgrind, 0, 0, 0, 0, 0);
+}
+
+test "works whether running on valgrind or not" {
+ _ = runningOnValgrind();
}
/// Discard translation of code in the slice qzz. Useful if you are debugging
/// a JITter or some such, since it provides a way to make sure valgrind will
/// retranslate the invalidated area. Returns no value.
pub fn discardTranslations(qzz: []const u8) void {
- doClientRequestStmt(ClientRequest.DiscardTranslations, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
+ doClientRequestStmt(.DiscardTranslations, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
}
pub fn innerThreads(qzz: [*]u8) void {
- doClientRequestStmt(ClientRequest.InnerThreads, qzz, 0, 0, 0, 0);
+ doClientRequestStmt(.InnerThreads, qzz, 0, 0, 0, 0);
}
//pub fn printf(format: [*]const u8, args: ...) usize {
// return doClientRequestExpr(0,
-// ClientRequest.PrintfValistByRef,
+// .PrintfValistByRef,
// @ptrToInt(format), @ptrToInt(args),
// 0, 0, 0);
//}
//pub fn printfBacktrace(format: [*]const u8, args: ...) usize {
// return doClientRequestExpr(0,
-// ClientRequest.PrintfBacktraceValistByRef,
+// .PrintfBacktraceValistByRef,
// @ptrToInt(format), @ptrToInt(args),
// 0, 0, 0);
//}
pub fn nonSIMDCall0(func: fn (usize) usize) usize {
- return doClientRequestExpr(0, ClientRequest.ClientCall0, @ptrToInt(func), 0, 0, 0, 0);
+ return doClientRequestExpr(0, .ClientCall0, @ptrToInt(func), 0, 0, 0, 0);
}
pub fn nonSIMDCall1(func: fn (usize, usize) usize, a1: usize) usize {
- return doClientRequestExpr(0, ClientRequest.ClientCall1, @ptrToInt(func), a1, 0, 0, 0);
+ return doClientRequestExpr(0, .ClientCall1, @ptrToInt(func), a1, 0, 0, 0);
}
pub fn nonSIMDCall2(func: fn (usize, usize, usize) usize, a1: usize, a2: usize) usize {
- return doClientRequestExpr(0, ClientRequest.ClientCall2, @ptrToInt(func), a1, a2, 0, 0);
+ return doClientRequestExpr(0, .ClientCall2, @ptrToInt(func), a1, a2, 0, 0);
}
pub fn nonSIMDCall3(func: fn (usize, usize, usize, usize) usize, a1: usize, a2: usize, a3: usize) usize {
- return doClientRequestExpr(0, ClientRequest.ClientCall3, @ptrToInt(func), a1, a2, a3, 0);
+ return doClientRequestExpr(0, .ClientCall3, @ptrToInt(func), a1, a2, a3, 0);
}
/// Counts the number of errors that have been recorded by a tool. Nb:
@@ -144,19 +149,19 @@ pub fn nonSIMDCall3(func: fn (usize, usize, usize, usize) usize, a1: usize, a2:
/// VG_(unique_error)() for them to be counted.
pub fn countErrors() usize {
return doClientRequestExpr(0, // default return
- ClientRequest.CountErrors, 0, 0, 0, 0, 0);
+ .CountErrors, 0, 0, 0, 0, 0);
}
pub fn mallocLikeBlock(mem: []u8, rzB: usize, is_zeroed: bool) void {
- doClientRequestStmt(ClientRequest.MalloclikeBlock, @ptrToInt(mem.ptr), mem.len, rzB, @boolToInt(is_zeroed), 0);
+ doClientRequestStmt(.MalloclikeBlock, @ptrToInt(mem.ptr), mem.len, rzB, @boolToInt(is_zeroed), 0);
}
pub fn resizeInPlaceBlock(oldmem: []u8, newsize: usize, rzB: usize) void {
- doClientRequestStmt(ClientRequest.ResizeinplaceBlock, @ptrToInt(oldmem.ptr), oldmem.len, newsize, rzB, 0);
+ doClientRequestStmt(.ResizeinplaceBlock, @ptrToInt(oldmem.ptr), oldmem.len, newsize, rzB, 0);
}
pub fn freeLikeBlock(addr: [*]u8, rzB: usize) void {
- doClientRequestStmt(ClientRequest.FreelikeBlock, @ptrToInt(addr), rzB, 0, 0, 0);
+ doClientRequestStmt(.FreelikeBlock, @ptrToInt(addr), rzB, 0, 0, 0);
}
/// Create a memory pool.
@@ -165,66 +170,66 @@ pub const MempoolFlags = extern enum {
MetaPool = 2,
};
pub fn createMempool(pool: [*]u8, rzB: usize, is_zeroed: bool, flags: usize) void {
- doClientRequestStmt(ClientRequest.CreateMempool, @ptrToInt(pool), rzB, @boolToInt(is_zeroed), flags, 0);
+ doClientRequestStmt(.CreateMempool, @ptrToInt(pool), rzB, @boolToInt(is_zeroed), flags, 0);
}
/// Destroy a memory pool.
pub fn destroyMempool(pool: [*]u8) void {
- doClientRequestStmt(ClientRequest.DestroyMempool, pool, 0, 0, 0, 0);
+ doClientRequestStmt(.DestroyMempool, pool, 0, 0, 0, 0);
}
/// Associate a piece of memory with a memory pool.
pub fn mempoolAlloc(pool: [*]u8, mem: []u8) void {
- doClientRequestStmt(ClientRequest.MempoolAlloc, @ptrToInt(pool), @ptrToInt(mem.ptr), mem.len, 0, 0);
+ doClientRequestStmt(.MempoolAlloc, @ptrToInt(pool), @ptrToInt(mem.ptr), mem.len, 0, 0);
}
/// Disassociate a piece of memory from a memory pool.
pub fn mempoolFree(pool: [*]u8, addr: [*]u8) void {
- doClientRequestStmt(ClientRequest.MempoolFree, @ptrToInt(pool), @ptrToInt(addr), 0, 0, 0);
+ doClientRequestStmt(.MempoolFree, @ptrToInt(pool), @ptrToInt(addr), 0, 0, 0);
}
/// Disassociate any pieces outside a particular range.
pub fn mempoolTrim(pool: [*]u8, mem: []u8) void {
- doClientRequestStmt(ClientRequest.MempoolTrim, @ptrToInt(pool), @ptrToInt(mem.ptr), mem.len, 0, 0);
+ doClientRequestStmt(.MempoolTrim, @ptrToInt(pool), @ptrToInt(mem.ptr), mem.len, 0, 0);
}
/// Resize and/or move a piece associated with a memory pool.
pub fn moveMempool(poolA: [*]u8, poolB: [*]u8) void {
- doClientRequestStmt(ClientRequest.MoveMempool, @ptrToInt(poolA), @ptrToInt(poolB), 0, 0, 0);
+ doClientRequestStmt(.MoveMempool, @ptrToInt(poolA), @ptrToInt(poolB), 0, 0, 0);
}
/// Resize and/or move a piece associated with a memory pool.
pub fn mempoolChange(pool: [*]u8, addrA: [*]u8, mem: []u8) void {
- doClientRequestStmt(ClientRequest.MempoolChange, @ptrToInt(pool), @ptrToInt(addrA), @ptrToInt(mem.ptr), mem.len, 0);
+ doClientRequestStmt(.MempoolChange, @ptrToInt(pool), @ptrToInt(addrA), @ptrToInt(mem.ptr), mem.len, 0);
}
/// Return if a mempool exists.
pub fn mempoolExists(pool: [*]u8) bool {
- return doClientRequestExpr(0, ClientRequest.MempoolExists, @ptrToInt(pool), 0, 0, 0, 0) != 0;
+ return doClientRequestExpr(0, .MempoolExists, @ptrToInt(pool), 0, 0, 0, 0) != 0;
}
/// Mark a piece of memory as being a stack. Returns a stack id.
/// start is the lowest addressable stack byte, end is the highest
/// addressable stack byte.
pub fn stackRegister(stack: []u8) usize {
- return doClientRequestExpr(0, ClientRequest.StackRegister, @ptrToInt(stack.ptr), @ptrToInt(stack.ptr) + stack.len, 0, 0, 0);
+ return doClientRequestExpr(0, .StackRegister, @ptrToInt(stack.ptr), @ptrToInt(stack.ptr) + stack.len, 0, 0, 0);
}
/// Unmark the piece of memory associated with a stack id as being a stack.
pub fn stackDeregister(id: usize) void {
- doClientRequestStmt(ClientRequest.StackDeregister, id, 0, 0, 0, 0);
+ doClientRequestStmt(.StackDeregister, id, 0, 0, 0, 0);
}
/// Change the start and end address of the stack id.
/// start is the new lowest addressable stack byte, end is the new highest
/// addressable stack byte.
pub fn stackChange(id: usize, newstack: []u8) void {
- doClientRequestStmt(ClientRequest.StackChange, id, @ptrToInt(newstack.ptr), @ptrToInt(newstack.ptr) + newstack.len, 0, 0);
+ doClientRequestStmt(.StackChange, id, @ptrToInt(newstack.ptr), @ptrToInt(newstack.ptr) + newstack.len, 0, 0);
}
// Load PDB debug info for Wine PE image_map.
// pub fn loadPdbDebuginfo(fd, ptr, total_size, delta) void {
-// doClientRequestStmt(ClientRequest.LoadPdbDebuginfo,
+// doClientRequestStmt(.LoadPdbDebuginfo,
// fd, ptr, total_size, delta,
// 0);
// }
@@ -234,7 +239,7 @@ pub fn stackChange(id: usize, newstack: []u8) void {
/// result will be dumped in there and is guaranteed to be zero
/// terminated. If no info is found, the first byte is set to zero.
pub fn mapIpToSrcloc(addr: *const u8, buf64: [64]u8) usize {
- return doClientRequestExpr(0, ClientRequest.MapIpToSrcloc, @ptrToInt(addr), @ptrToInt(&buf64[0]), 0, 0, 0);
+ return doClientRequestExpr(0, .MapIpToSrcloc, @ptrToInt(addr), @ptrToInt(&buf64[0]), 0, 0, 0);
}
/// Disable error reporting for this thread. Behaves in a stack like
@@ -246,12 +251,12 @@ pub fn mapIpToSrcloc(addr: *const u8, buf64: [64]u8) usize {
/// reporting. Child threads do not inherit this setting from their
/// parents -- they are always created with reporting enabled.
pub fn disableErrorReporting() void {
- doClientRequestStmt(ClientRequest.ChangeErrDisablement, 1, 0, 0, 0, 0);
+ doClientRequestStmt(.ChangeErrDisablement, 1, 0, 0, 0, 0);
}
/// Re-enable error reporting, (see disableErrorReporting())
pub fn enableErrorReporting() void {
- doClientRequestStmt(ClientRequest.ChangeErrDisablement, math.maxInt(usize), 0, 0, 0, 0);
+ doClientRequestStmt(.ChangeErrDisablement, math.maxInt(usize), 0, 0, 0, 0);
}
/// Execute a monitor command from the client program.
@@ -260,8 +265,13 @@ pub fn enableErrorReporting() void {
/// If no connection is opened, output will go to the log output.
/// Returns 1 if command not recognised, 0 otherwise.
pub fn monitorCommand(command: [*]u8) bool {
- return doClientRequestExpr(0, ClientRequest.GdbMonitorCommand, @ptrToInt(command.ptr), 0, 0, 0, 0) != 0;
+ return doClientRequestExpr(0, .GdbMonitorCommand, @ptrToInt(command.ptr), 0, 0, 0, 0) != 0;
}
-pub const memcheck = @import("memcheck.zig");
-pub const callgrind = @import("callgrind.zig");
+pub const memcheck = @import("valgrind/memcheck.zig");
+pub const callgrind = @import("valgrind/callgrind.zig");
+
+test "" {
+ _ = @import("valgrind/memcheck.zig");
+ _ = @import("valgrind/callgrind.zig");
+}
diff --git a/lib/std/valgrind/callgrind.zig b/lib/std/valgrind/callgrind.zig
index d008294870..82725e9103 100644
--- a/lib/std/valgrind/callgrind.zig
+++ b/lib/std/valgrind/callgrind.zig
@@ -1,4 +1,4 @@
-const std = @import("../index.zig");
+const std = @import("../std.zig");
const valgrind = std.valgrind;
pub const CallgrindClientRequest = extern enum {
@@ -20,7 +20,7 @@ fn doCallgrindClientRequestStmt(request: CallgrindClientRequest, a1: usize, a2:
/// Dump current state of cost centers, and zero them afterwards
pub fn dumpStats() void {
- doCallgrindClientRequestStmt(CallgrindClientRequest.DumpStats, 0, 0, 0, 0, 0);
+ doCallgrindClientRequestStmt(.DumpStats, 0, 0, 0, 0, 0);
}
/// Dump current state of cost centers, and zero them afterwards.
@@ -28,12 +28,12 @@ pub fn dumpStats() void {
/// the dump. This string is written as a description field into the
/// profile data dump.
pub fn dumpStatsAt(pos_str: [*]u8) void {
- doCallgrindClientRequestStmt(CallgrindClientRequest.DumpStatsAt, @ptrToInt(pos_str), 0, 0, 0, 0);
+ doCallgrindClientRequestStmt(.DumpStatsAt, @ptrToInt(pos_str), 0, 0, 0, 0);
}
/// Zero cost centers
pub fn zeroStats() void {
- doCallgrindClientRequestStmt(CallgrindClientRequest.ZeroStats, 0, 0, 0, 0, 0);
+ doCallgrindClientRequestStmt(.ZeroStats, 0, 0, 0, 0, 0);
}
/// Toggles collection state.
@@ -41,7 +41,7 @@ pub fn zeroStats() void {
/// should be noted or if they are to be ignored. Events are noted
/// by increment of counters in a cost center
pub fn toggleCollect() void {
- doCallgrindClientRequestStmt(CallgrindClientRequest.ToggleCollect, 0, 0, 0, 0, 0);
+ doCallgrindClientRequestStmt(.ToggleCollect, 0, 0, 0, 0, 0);
}
/// Start full callgrind instrumentation if not already switched on.
@@ -49,7 +49,7 @@ pub fn toggleCollect() void {
/// this will lead to an artificial cache warmup phase afterwards with
/// cache misses which would not have happened in reality.
pub fn startInstrumentation() void {
- doCallgrindClientRequestStmt(CallgrindClientRequest.StartInstrumentation, 0, 0, 0, 0, 0);
+ doCallgrindClientRequestStmt(.StartInstrumentation, 0, 0, 0, 0, 0);
}
/// Stop full callgrind instrumentation if not already switched off.
@@ -60,5 +60,5 @@ pub fn startInstrumentation() void {
/// To start Callgrind in this mode to ignore the setup phase, use
/// the option "--instr-atstart=no".
pub fn stopInstrumentation() void {
- doCallgrindClientRequestStmt(CallgrindClientRequest.StopInstrumentation, 0, 0, 0, 0, 0);
+ doCallgrindClientRequestStmt(.StopInstrumentation, 0, 0, 0, 0, 0);
}
diff --git a/lib/std/valgrind/memcheck.zig b/lib/std/valgrind/memcheck.zig
index 2830f58dbd..a15a6cca0e 100644
--- a/lib/std/valgrind/memcheck.zig
+++ b/lib/std/valgrind/memcheck.zig
@@ -1,4 +1,5 @@
-const std = @import("../index.zig");
+const std = @import("../std.zig");
+const testing = std.testing;
const valgrind = std.valgrind;
pub const MemCheckClientRequest = extern enum {
@@ -31,7 +32,7 @@ fn doMemCheckClientRequestStmt(request: MemCheckClientRequest, a1: usize, a2: us
/// This returns -1 when run on Valgrind and 0 otherwise.
pub fn makeMemNoAccess(qzz: []u8) i1 {
return @intCast(i1, doMemCheckClientRequestExpr(0, // default return
- MemCheckClientRequest.MakeMemNoAccess, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0));
+ .MakeMemNoAccess, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0));
}
/// Similarly, mark memory at qzz.ptr as addressable but undefined
@@ -39,7 +40,7 @@ pub fn makeMemNoAccess(qzz: []u8) i1 {
/// This returns -1 when run on Valgrind and 0 otherwise.
pub fn makeMemUndefined(qzz: []u8) i1 {
return @intCast(i1, doMemCheckClientRequestExpr(0, // default return
- MemCheckClientRequest.MakeMemUndefined, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0));
+ .MakeMemUndefined, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0));
}
/// Similarly, mark memory at qzz.ptr as addressable and defined
@@ -47,7 +48,7 @@ pub fn makeMemUndefined(qzz: []u8) i1 {
pub fn makeMemDefined(qzz: []u8) i1 {
// This returns -1 when run on Valgrind and 0 otherwise.
return @intCast(i1, doMemCheckClientRequestExpr(0, // default return
- MemCheckClientRequest.MakeMemDefined, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0));
+ .MakeMemDefined, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0));
}
/// Similar to makeMemDefined except that addressability is
@@ -56,7 +57,7 @@ pub fn makeMemDefined(qzz: []u8) i1 {
/// This returns -1 when run on Valgrind and 0 otherwise.
pub fn makeMemDefinedIfAddressable(qzz: []u8) i1 {
return @intCast(i1, doMemCheckClientRequestExpr(0, // default return
- MemCheckClientRequest.MakeMemDefinedIfAddressable, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0));
+ .MakeMemDefinedIfAddressable, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0));
}
/// Create a block-description handle. The description is an ascii
@@ -65,14 +66,14 @@ pub fn makeMemDefinedIfAddressable(qzz: []u8) i1 {
/// properties of the memory range.
pub fn createBlock(qzz: []u8, desc: [*]u8) usize {
return doMemCheckClientRequestExpr(0, // default return
- MemCheckClientRequest.CreateBlock, @ptrToInt(qzz.ptr), qzz.len, @ptrToInt(desc), 0, 0);
+ .CreateBlock, @ptrToInt(qzz.ptr), qzz.len, @ptrToInt(desc), 0, 0);
}
/// Discard a block-description-handle. Returns 1 for an
/// invalid handle, 0 for a valid handle.
pub fn discard(blkindex) bool {
return doMemCheckClientRequestExpr(0, // default return
- MemCheckClientRequest.Discard, 0, blkindex, 0, 0, 0) != 0;
+ .Discard, 0, blkindex, 0, 0, 0) != 0;
}
/// Check that memory at qzz.ptr is addressable for qzz.len bytes.
@@ -80,7 +81,7 @@ pub fn discard(blkindex) bool {
/// error message and returns the address of the first offending byte.
/// Otherwise it returns zero.
pub fn checkMemIsAddressable(qzz: []u8) usize {
- return doMemCheckClientRequestExpr(0, MemCheckClientRequest.CheckMemIsAddressable, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
+ return doMemCheckClientRequestExpr(0, .CheckMemIsAddressable, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
}
/// Check that memory at qzz.ptr is addressable and defined for
@@ -88,31 +89,31 @@ pub fn checkMemIsAddressable(qzz: []u8) usize {
/// established, Valgrind prints an error message and returns the
/// address of the first offending byte. Otherwise it returns zero.
pub fn checkMemIsDefined(qzz: []u8) usize {
- return doMemCheckClientRequestExpr(0, MemCheckClientRequest.CheckMemIsDefined, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
+ return doMemCheckClientRequestExpr(0, .CheckMemIsDefined, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
}
/// Do a full memory leak check (like --leak-check=full) mid-execution.
pub fn doLeakCheck() void {
- doMemCheckClientRequestStmt(MemCheckClientRequest.DO_LEAK_CHECK, 0, 0, 0, 0, 0);
+ doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 0, 0, 0, 0, 0);
}
/// Same as doLeakCheck() but only showing the entries for
/// which there was an increase in leaked bytes or leaked nr of blocks
/// since the previous leak search.
pub fn doAddedLeakCheck() void {
- doMemCheckClientRequestStmt(MemCheckClientRequest.DO_LEAK_CHECK, 0, 1, 0, 0, 0);
+ doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 0, 1, 0, 0, 0);
}
/// Same as doAddedLeakCheck() but showing entries with
/// increased or decreased leaked bytes/blocks since previous leak
/// search.
pub fn doChangedLeakCheck() void {
- doMemCheckClientRequestStmt(MemCheckClientRequest.DO_LEAK_CHECK, 0, 2, 0, 0, 0);
+ doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 0, 2, 0, 0, 0);
}
/// Do a summary memory leak check (like --leak-check=summary) mid-execution.
pub fn doQuickLeakCheck() void {
- doMemCheckClientRequestStmt(MemCheckClientRequest.DO_LEAK_CHECK, 1, 0, 0, 0, 0);
+ doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 1, 0, 0, 0, 0);
}
/// Return number of leaked, dubious, reachable and suppressed bytes found by
@@ -125,27 +126,65 @@ const CountResult = struct {
};
pub fn countLeaks() CountResult {
- var res = CountResult{
+ var res: CountResult = .{
.leaked = 0,
.dubious = 0,
.reachable = 0,
.suppressed = 0,
};
- doMemCheckClientRequestStmt(MemCheckClientRequest.CountLeaks, &res.leaked, &res.dubious, &res.reachable, &res.suppressed, 0);
+ doMemCheckClientRequestStmt(
+ .CountLeaks,
+ @ptrToInt(&res.leaked),
+ @ptrToInt(&res.dubious),
+ @ptrToInt(&res.reachable),
+ @ptrToInt(&res.suppressed),
+ 0,
+ );
return res;
}
+test "countLeaks" {
+ testing.expectEqual(
+ @as(CountResult, .{
+ .leaked = 0,
+ .dubious = 0,
+ .reachable = 0,
+ .suppressed = 0,
+ }),
+ countLeaks(),
+ );
+}
+
pub fn countLeakBlocks() CountResult {
- var res = CountResult{
+ var res: CountResult = .{
.leaked = 0,
.dubious = 0,
.reachable = 0,
.suppressed = 0,
};
- doMemCheckClientRequestStmt(MemCheckClientRequest.CountLeakBlocks, &res.leaked, &res.dubious, &res.reachable, &res.suppressed, 0);
+ doMemCheckClientRequestStmt(
+ .CountLeakBlocks,
+ @ptrToInt(&res.leaked),
+ @ptrToInt(&res.dubious),
+ @ptrToInt(&res.reachable),
+ @ptrToInt(&res.suppressed),
+ 0,
+ );
return res;
}
+test "countLeakBlocks" {
+ testing.expectEqual(
+ @as(CountResult, .{
+ .leaked = 0,
+ .dubious = 0,
+ .reachable = 0,
+ .suppressed = 0,
+ }),
+ countLeakBlocks(),
+ );
+}
+
/// Get the validity data for addresses zza and copy it
/// into the provided zzvbits array. Return values:
/// 0 if not running on valgrind
@@ -156,7 +195,7 @@ pub fn countLeakBlocks() CountResult {
/// impossible to segfault your system by using this call.
pub fn getVbits(zza: []u8, zzvbits: []u8) u2 {
std.debug.assert(zzvbits.len >= zza.len / 8);
- return @intCast(u2, doMemCheckClientRequestExpr(0, MemCheckClientRequest.GetVbits, @ptrToInt(zza.ptr), @ptrToInt(zzvbits), zza.len, 0, 0));
+ return @intCast(u2, doMemCheckClientRequestExpr(0, .GetVbits, @ptrToInt(zza.ptr), @ptrToInt(zzvbits), zza.len, 0, 0));
}
/// Set the validity data for addresses zza, copying it
@@ -169,17 +208,17 @@ pub fn getVbits(zza: []u8, zzvbits: []u8) u2 {
/// impossible to segfault your system by using this call.
pub fn setVbits(zzvbits: []u8, zza: []u8) u2 {
std.debug.assert(zzvbits.len >= zza.len / 8);
- return @intCast(u2, doMemCheckClientRequestExpr(0, MemCheckClientRequest.SetVbits, @ptrToInt(zza.ptr), @ptrToInt(zzvbits), zza.len, 0, 0));
+ return @intCast(u2, doMemCheckClientRequestExpr(0, .SetVbits, @ptrToInt(zza.ptr), @ptrToInt(zzvbits), zza.len, 0, 0));
}
/// Disable and re-enable reporting of addressing errors in the
/// specified address range.
pub fn disableAddrErrorReportingInRange(qzz: []u8) usize {
return doMemCheckClientRequestExpr(0, // default return
- MemCheckClientRequest.DisableAddrErrorReportingInRange, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
+ .DisableAddrErrorReportingInRange, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
}
pub fn enableAddrErrorReportingInRange(qzz: []u8) usize {
return doMemCheckClientRequestExpr(0, // default return
- MemCheckClientRequest.EnableAddrErrorReportingInRange, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
+ .EnableAddrErrorReportingInRange, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
}
diff --git a/lib/std/zig/ast.zig b/lib/std/zig/ast.zig
index 9f32c6e54b..0a7bfe2f56 100644
--- a/lib/std/zig/ast.zig
+++ b/lib/std/zig/ast.zig
@@ -576,7 +576,6 @@ pub const Node = struct {
pub const Root = struct {
base: Node,
- doc_comments: ?*DocComment,
decls: DeclList,
eof_token: TokenIndex,
@@ -1648,10 +1647,15 @@ pub const Node = struct {
pub const SuffixOp = struct {
base: Node,
- lhs: *Node,
+ lhs: Lhs,
op: Op,
rtoken: TokenIndex,
+ pub const Lhs = union(enum) {
+ node: *Node,
+ dot: TokenIndex,
+ };
+
pub const Op = union(enum) {
Call: Call,
ArrayAccess: *Node,
@@ -1679,8 +1683,13 @@ pub const Node = struct {
pub fn iterate(self: *SuffixOp, index: usize) ?*Node {
var i = index;
- if (i < 1) return self.lhs;
- i -= 1;
+ switch (self.lhs) {
+ .node => |node| {
+ if (i == 0) return node;
+ i -= 1;
+ },
+ .dot => {},
+ }
switch (self.op) {
.Call => |*call_info| {
@@ -1721,7 +1730,10 @@ pub const Node = struct {
.Call => |*call_info| if (call_info.async_token) |async_token| return async_token,
else => {},
}
- return self.lhs.firstToken();
+ switch (self.lhs) {
+ .node => |node| return node.firstToken(),
+ .dot => |dot| return dot,
+ }
}
pub fn lastToken(self: *const SuffixOp) TokenIndex {
@@ -2241,7 +2253,6 @@ pub const Node = struct {
test "iterate" {
var root = Node.Root{
.base = Node{ .id = Node.Id.Root },
- .doc_comments = null,
.decls = Node.Root.DeclList.init(std.debug.global_allocator),
.eof_token = 0,
};
diff --git a/lib/std/zig/parse.zig b/lib/std/zig/parse.zig
index 4c6c461c01..42dff71b2a 100644
--- a/lib/std/zig/parse.zig
+++ b/lib/std/zig/parse.zig
@@ -58,13 +58,6 @@ fn parseRoot(arena: *Allocator, it: *TokenIterator, tree: *Tree) Allocator.Error
node.* = Node.Root{
.base = Node{ .id = .Root },
.decls = undefined,
- // TODO: Because zig fmt collapses consecutive comments separated by blank lines into
- // a single multi-line comment, it is currently impossible to have a container-level
- // doc comment and NO doc comment on the first decl. For now, simply
- // ignore the problem and assume that there will be no container-level
- // doc comments.
- // See: https://github.com/ziglang/zig/issues/2288
- .doc_comments = null,
.eof_token = undefined,
};
node.decls = parseContainerMembers(arena, it, tree) catch |err| {
@@ -94,6 +87,11 @@ fn parseContainerMembers(arena: *Allocator, it: *TokenIterator, tree: *Tree) !No
var list = Node.Root.DeclList.init(arena);
while (true) {
+ if (try parseContainerDocComments(arena, it, tree)) |node| {
+ try list.push(node);
+ continue;
+ }
+
const doc_comments = try parseDocComment(arena, it, tree);
if (try parseTestDecl(arena, it, tree)) |node| {
@@ -155,12 +153,35 @@ fn parseContainerMembers(arena: *Allocator, it: *TokenIterator, tree: *Tree) !No
continue;
}
+ // Dangling doc comment
+ if (doc_comments != null) {
+ try tree.errors.push(AstError{
+ .UnattachedDocComment = AstError.UnattachedDocComment{ .token = doc_comments.?.firstToken() },
+ });
+ }
break;
}
return list;
}
+/// Eat a multiline container doc comment
+fn parseContainerDocComments(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
+ var lines = Node.DocComment.LineList.init(arena);
+ while (eatToken(it, .ContainerDocComment)) |line| {
+ try lines.push(line);
+ }
+
+ if (lines.len == 0) return null;
+
+ const node = try arena.create(Node.DocComment);
+ node.* = Node.DocComment{
+ .base = Node{ .id = .DocComment },
+ .lines = lines,
+ };
+ return &node.base;
+}
+
/// TestDecl <- KEYWORD_test STRINGLITERAL Block
fn parseTestDecl(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
const test_token = eatToken(it, .Keyword_test) orelse return null;
@@ -1026,16 +1047,16 @@ fn parseWhileExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
/// CurlySuffixExpr <- TypeExpr InitList?
fn parseCurlySuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
const type_expr = (try parseTypeExpr(arena, it, tree)) orelse return null;
- const init_list = (try parseInitList(arena, it, tree)) orelse return type_expr;
- init_list.cast(Node.SuffixOp).?.lhs = type_expr;
- return init_list;
+ const suffix_op = (try parseInitList(arena, it, tree)) orelse return type_expr;
+ suffix_op.lhs.node = type_expr;
+ return &suffix_op.base;
}
/// InitList
/// <- LBRACE FieldInit (COMMA FieldInit)* COMMA? RBRACE
/// / LBRACE Expr (COMMA Expr)* COMMA? RBRACE
/// / LBRACE RBRACE
-fn parseInitList(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
+fn parseInitList(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node.SuffixOp {
const lbrace = eatToken(it, .LBrace) orelse return null;
var init_list = Node.SuffixOp.Op.InitList.init(arena);
@@ -1064,11 +1085,11 @@ fn parseInitList(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
const node = try arena.create(Node.SuffixOp);
node.* = Node.SuffixOp{
.base = Node{ .id = .SuffixOp },
- .lhs = undefined, // set by caller
+ .lhs = .{.node = undefined}, // set by caller
.op = op,
.rtoken = try expectToken(it, tree, .RBrace),
};
- return &node.base;
+ return node;
}
/// TypeExpr <- PrefixTypeOp* ErrorUnionExpr
@@ -1117,7 +1138,7 @@ fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
while (try parseSuffixOp(arena, it, tree)) |node| {
switch (node.id) {
- .SuffixOp => node.cast(Node.SuffixOp).?.lhs = res,
+ .SuffixOp => node.cast(Node.SuffixOp).?.lhs = .{.node = res},
.InfixOp => node.cast(Node.InfixOp).?.lhs = res,
else => unreachable,
}
@@ -1133,7 +1154,7 @@ fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
const node = try arena.create(Node.SuffixOp);
node.* = Node.SuffixOp{
.base = Node{ .id = .SuffixOp },
- .lhs = res,
+ .lhs = .{.node = res},
.op = Node.SuffixOp.Op{
.Call = Node.SuffixOp.Op.Call{
.params = params.list,
@@ -1150,7 +1171,7 @@ fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
while (true) {
if (try parseSuffixOp(arena, it, tree)) |node| {
switch (node.id) {
- .SuffixOp => node.cast(Node.SuffixOp).?.lhs = res,
+ .SuffixOp => node.cast(Node.SuffixOp).?.lhs = .{.node = res},
.InfixOp => node.cast(Node.InfixOp).?.lhs = res,
else => unreachable,
}
@@ -1161,7 +1182,7 @@ fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
const call = try arena.create(Node.SuffixOp);
call.* = Node.SuffixOp{
.base = Node{ .id = .SuffixOp },
- .lhs = res,
+ .lhs = .{.node = res},
.op = Node.SuffixOp.Op{
.Call = Node.SuffixOp.Op.Call{
.params = params.list,
@@ -1215,7 +1236,7 @@ fn parsePrimaryTypeExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*N
return &node.base;
}
if (try parseContainerDecl(arena, it, tree)) |node| return node;
- if (try parseEnumLiteral(arena, it, tree)) |node| return node;
+ if (try parseAnonLiteral(arena, it, tree)) |node| return node;
if (try parseErrorSetDecl(arena, it, tree)) |node| return node;
if (try parseFloatLiteral(arena, it, tree)) |node| return node;
if (try parseFnProto(arena, it, tree)) |node| return node;
@@ -1494,16 +1515,28 @@ fn parseAsmExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
}
/// DOT IDENTIFIER
-fn parseEnumLiteral(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
+fn parseAnonLiteral(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
const dot = eatToken(it, .Period) orelse return null;
- const name = try expectToken(it, tree, .Identifier);
- const node = try arena.create(Node.EnumLiteral);
- node.* = Node.EnumLiteral{
- .base = Node{ .id = .EnumLiteral },
- .dot = dot,
- .name = name,
- };
- return &node.base;
+
+ // anon enum literal
+ if (eatToken(it, .Identifier)) |name| {
+ const node = try arena.create(Node.EnumLiteral);
+ node.* = Node.EnumLiteral{
+ .base = Node{ .id = .EnumLiteral },
+ .dot = dot,
+ .name = name,
+ };
+ return &node.base;
+ }
+
+ // anon container literal
+ if (try parseInitList(arena, it, tree)) |node| {
+ node.lhs = .{.dot = dot};
+ return &node.base;
+ }
+
+ putBackToken(it, dot);
+ return null;
}
/// AsmOutput <- COLON AsmOutputList AsmInput?
@@ -1618,7 +1651,11 @@ fn parseBlockLabel(arena: *Allocator, it: *TokenIterator, tree: *Tree) ?TokenInd
/// FieldInit <- DOT IDENTIFIER EQUAL Expr
fn parseFieldInit(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
const period_token = eatToken(it, .Period) orelse return null;
- const name_token = try expectToken(it, tree, .Identifier);
+ const name_token = eatToken(it, .Identifier) orelse {
+ // Because of anon literals `.{` is also valid.
+ putBackToken(it, period_token);
+ return null;
+ };
const eq_token = eatToken(it, .Equal) orelse {
// `.Name` may also be an enum literal, which is a later rule.
putBackToken(it, name_token);
diff --git a/lib/std/zig/parse_string_literal.zig b/lib/std/zig/parse_string_literal.zig
index acae0b64c7..a6bdff4a02 100644
--- a/lib/std/zig/parse_string_literal.zig
+++ b/lib/std/zig/parse_string_literal.zig
@@ -19,7 +19,7 @@ pub fn parseStringLiteral(
bytes: []const u8,
bad_index: *usize, // populated if error.InvalidCharacter is returned
) ParseStringLiteralError![]u8 {
- const first_index = if (bytes[0] == 'c') usize(2) else usize(1);
+ const first_index = if (bytes[0] == 'c') @as(usize, 2) else @as(usize, 1);
assert(bytes[bytes.len - 1] == '"');
var list = std.ArrayList(u8).init(allocator);
diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig
index 28bd287c8a..2f420768bf 100644
--- a/lib/std/zig/parser_test.zig
+++ b/lib/std/zig/parser_test.zig
@@ -1,9 +1,26 @@
-// TODO remove `use` keyword eventually: https://github.com/ziglang/zig/issues/2591
-test "zig fmt: change use to usingnamespace" {
- try testTransform(
- \\use @import("std");
- ,
- \\usingnamespace @import("std");
+test "zig fmt: anon literal in array" {
+ try testCanonical(
+ \\var arr: [2]Foo = .{
+ \\ .{ .a = 2 },
+ \\ .{ .b = 3 },
+ \\};
+ \\
+ );
+}
+
+test "zig fmt: anon struct literal syntax" {
+ try testCanonical(
+ \\const x = .{
+ \\ .a = b,
+ \\ .c = d,
+ \\};
+ \\
+ );
+}
+
+test "zig fmt: anon list literal syntax" {
+ try testCanonical(
+ \\const x = .{ a, b, c };
\\
);
}
@@ -37,7 +54,7 @@ test "zig fmt: while else err prong with no block" {
\\test "" {
\\ const result = while (returnError()) |value| {
\\ break value;
- \\ } else |err| i32(2);
+ \\ } else |err| @as(i32, 2);
\\ expect(result == 2);
\\}
\\
@@ -1444,11 +1461,11 @@ test "zig fmt: preserve spacing" {
\\const std = @import("std");
\\
\\pub fn main() !void {
- \\ var stdout_file = try std.io.getStdOut;
- \\ var stdout_file = try std.io.getStdOut;
+ \\ var stdout_file = std.io.getStdOut;
+ \\ var stdout_file = std.io.getStdOut;
\\
- \\ var stdout_file = try std.io.getStdOut;
- \\ var stdout_file = try std.io.getStdOut;
+ \\ var stdout_file = std.io.getStdOut;
+ \\ var stdout_file = std.io.getStdOut;
\\}
\\
);
@@ -2549,6 +2566,62 @@ test "zig fmt: comments at several places in struct init" {
);
}
+test "zig fmt: top level doc comments" {
+ try testCanonical(
+ \\//! tld 1
+ \\//! tld 2
+ \\//! tld 3
+ \\
+ \\// comment
+ \\
+ \\/// A doc
+ \\const A = struct {
+ \\ //! A tld 1
+ \\ //! A tld 2
+ \\ //! A tld 3
+ \\};
+ \\
+ \\/// B doc
+ \\const B = struct {
+ \\ //! B tld 1
+ \\ //! B tld 2
+ \\ //! B tld 3
+ \\
+ \\ /// b doc
+ \\ b: u32,
+ \\};
+ \\
+ \\/// C doc
+ \\const C = struct {
+ \\ //! C tld 1
+ \\ //! C tld 2
+ \\ //! C tld 3
+ \\
+ \\ /// c1 doc
+ \\ c1: u32,
+ \\
+ \\ //! C tld 4
+ \\ //! C tld 5
+ \\ //! C tld 6
+ \\
+ \\ /// c2 doc
+ \\ c2: u32,
+ \\};
+ \\
+ );
+ try testCanonical(
+ \\//! Top-level documentation.
+ \\
+ \\/// This is A
+ \\pub const A = usize;
+ \\
+ );
+ try testCanonical(
+ \\//! Nothing here
+ \\
+ );
+}
+
const std = @import("std");
const mem = std.mem;
const warn = std.debug.warn;
@@ -2558,8 +2631,7 @@ const maxInt = std.math.maxInt;
var fixed_buffer_mem: [100 * 1024]u8 = undefined;
fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *bool) ![]u8 {
- var stderr_file = try io.getStdErr();
- var stderr = &stderr_file.outStream().stream;
+ const stderr = &io.getStdErr().outStream().stream;
const tree = try std.zig.parse(allocator, source);
defer tree.deinit();
diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig
index 996cfc29e4..258a5493de 100644
--- a/lib/std/zig/render.zig
+++ b/lib/std/zig/render.zig
@@ -226,9 +226,7 @@ fn renderTopLevelDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, i
if (use_decl.visib_token) |visib_token| {
try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub
}
- // TODO after depracating use, go back to this:
- //try renderToken(tree, stream, use_decl.use_token, indent, start_col, Space.Space); // usingnamespace
- try stream.write("usingnamespace ");
+ try renderToken(tree, stream, use_decl.use_token, indent, start_col, Space.Space); // usingnamespace
try renderExpression(allocator, stream, tree, indent, start_col, use_decl.expr, Space.None);
try renderToken(tree, stream, use_decl.semicolon_token, indent, start_col, Space.Newline); // ;
},
@@ -301,6 +299,17 @@ fn renderTopLevelDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, i
assert(!decl.requireSemiColon());
try renderExpression(allocator, stream, tree, indent, start_col, decl, Space.Newline);
},
+
+ ast.Node.Id.DocComment => {
+ const comment = @fieldParentPtr(ast.Node.DocComment, "base", decl);
+ var it = comment.lines.iterator(0);
+ while (it.next()) |line_token_index| {
+ try renderToken(tree, stream, line_token_index.*, indent, start_col, Space.Newline);
+ if (it.peek()) |_| {
+ try stream.writeByteNTimes(' ', indent);
+ }
+ }
+ },
else => unreachable,
}
}
@@ -410,8 +419,8 @@ fn renderExpression(
switch (prefix_op_node.op) {
ast.Node.PrefixOp.Op.PtrType => |ptr_info| {
const star_offset = switch (tree.tokens.at(prefix_op_node.op_token).id) {
- Token.Id.AsteriskAsterisk => usize(1),
- else => usize(0),
+ Token.Id.AsteriskAsterisk => @as(usize, 1),
+ else => @as(usize, 0),
};
try renderTokenOffset(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None, star_offset); // *
if (ptr_info.allowzero_token) |allowzero_token| {
@@ -540,9 +549,9 @@ fn renderExpression(
try renderToken(tree, stream, async_token, indent, start_col, Space.Space);
}
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs.node, Space.None);
- const lparen = tree.nextToken(suffix_op.lhs.lastToken());
+ const lparen = tree.nextToken(suffix_op.lhs.node.lastToken());
if (call_info.params.len == 0) {
try renderToken(tree, stream, lparen, indent, start_col, Space.None);
@@ -600,7 +609,7 @@ fn renderExpression(
const lbracket = tree.prevToken(index_expr.firstToken());
const rbracket = tree.nextToken(index_expr.lastToken());
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs.node, Space.None);
try renderToken(tree, stream, lbracket, indent, start_col, Space.None); // [
const starts_with_comment = tree.tokens.at(lbracket + 1).id == .LineComment;
@@ -618,18 +627,18 @@ fn renderExpression(
},
ast.Node.SuffixOp.Op.Deref => {
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs.node, Space.None);
return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); // .*
},
ast.Node.SuffixOp.Op.UnwrapOptional => {
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs.node, Space.None);
try renderToken(tree, stream, tree.prevToken(suffix_op.rtoken), indent, start_col, Space.None); // .
return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); // ?
},
@TagType(ast.Node.SuffixOp.Op).Slice => |range| {
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs.node, Space.None);
const lbracket = tree.prevToken(range.start.firstToken());
const dotdot = tree.nextToken(range.start.lastToken());
@@ -649,10 +658,16 @@ fn renderExpression(
},
ast.Node.SuffixOp.Op.StructInitializer => |*field_inits| {
- const lbrace = tree.nextToken(suffix_op.lhs.lastToken());
+ const lbrace = switch (suffix_op.lhs) {
+ .dot => |dot| tree.nextToken(dot),
+ .node => |node| tree.nextToken(node.lastToken()),
+ };
if (field_inits.len == 0) {
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ switch (suffix_op.lhs) {
+ .dot => |dot| try renderToken(tree, stream, dot, indent, start_col, Space.None),
+ .node => |node| try renderExpression(allocator, stream, tree, indent, start_col, node, Space.None),
+ }
try renderToken(tree, stream, lbrace, indent + indent_delta, start_col, Space.None);
return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space);
}
@@ -693,7 +708,10 @@ fn renderExpression(
break :blk;
}
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ switch (suffix_op.lhs) {
+ .dot => |dot| try renderToken(tree, stream, dot, indent, start_col, Space.None),
+ .node => |node| try renderExpression(allocator, stream, tree, indent, start_col, node, Space.None),
+ }
try renderToken(tree, stream, lbrace, indent, start_col, Space.Space);
try renderExpression(allocator, stream, tree, indent, start_col, &field_init.base, Space.Space);
return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space);
@@ -701,7 +719,10 @@ fn renderExpression(
if (!src_has_trailing_comma and src_same_line and expr_outputs_one_line) {
// render all on one line, no trailing comma
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ switch (suffix_op.lhs) {
+ .dot => |dot| try renderToken(tree, stream, dot, indent, start_col, Space.None),
+ .node => |node| try renderExpression(allocator, stream, tree, indent, start_col, node, Space.None),
+ }
try renderToken(tree, stream, lbrace, indent, start_col, Space.Space);
var it = field_inits.iterator(0);
@@ -721,7 +742,10 @@ fn renderExpression(
const new_indent = indent + indent_delta;
- try renderExpression(allocator, stream, tree, new_indent, start_col, suffix_op.lhs, Space.None);
+ switch (suffix_op.lhs) {
+ .dot => |dot| try renderToken(tree, stream, dot, new_indent, start_col, Space.None),
+ .node => |node| try renderExpression(allocator, stream, tree, new_indent, start_col, node, Space.None),
+ }
try renderToken(tree, stream, lbrace, new_indent, start_col, Space.Newline);
var it = field_inits.iterator(0);
@@ -745,23 +769,35 @@ fn renderExpression(
},
ast.Node.SuffixOp.Op.ArrayInitializer => |*exprs| {
- const lbrace = tree.nextToken(suffix_op.lhs.lastToken());
+ const lbrace = switch (suffix_op.lhs) {
+ .dot => |dot| tree.nextToken(dot),
+ .node => |node| tree.nextToken(node.lastToken()),
+ };
if (exprs.len == 0) {
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ switch (suffix_op.lhs) {
+ .dot => |dot| try renderToken(tree, stream, dot, indent, start_col, Space.None),
+ .node => |node| try renderExpression(allocator, stream, tree, indent, start_col, node, Space.None),
+ }
try renderToken(tree, stream, lbrace, indent, start_col, Space.None);
return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space);
}
if (exprs.len == 1 and tree.tokens.at(exprs.at(0).*.lastToken() + 1).id == .RBrace) {
const expr = exprs.at(0).*;
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ switch (suffix_op.lhs) {
+ .dot => |dot| try renderToken(tree, stream, dot, indent, start_col, Space.None),
+ .node => |node| try renderExpression(allocator, stream, tree, indent, start_col, node, Space.None),
+ }
try renderToken(tree, stream, lbrace, indent, start_col, Space.None);
try renderExpression(allocator, stream, tree, indent, start_col, expr, Space.None);
return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space);
}
- try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None);
+ switch (suffix_op.lhs) {
+ .dot => |dot| try renderToken(tree, stream, dot, indent, start_col, Space.None),
+ .node => |node| try renderExpression(allocator, stream, tree, indent, start_col, node, Space.None),
+ }
// scan to find row size
const maybe_row_size: ?usize = blk: {
@@ -2097,7 +2133,7 @@ fn renderTokenOffset(
while (true) {
assert(loc.line != 0);
- const newline_count = if (loc.line == 1) u8(1) else u8(2);
+ const newline_count = if (loc.line == 1) @as(u8, 1) else @as(u8, 2);
try stream.writeByteNTimes('\n', newline_count);
try stream.writeByteNTimes(' ', indent);
try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(next_token), " "));
diff --git a/lib/std/zig/tokenizer.zig b/lib/std/zig/tokenizer.zig
index 672bd482da..f17adae648 100644
--- a/lib/std/zig/tokenizer.zig
+++ b/lib/std/zig/tokenizer.zig
@@ -59,7 +59,6 @@ pub const Token = struct {
Keyword{ .bytes = "undefined", .id = Id.Keyword_undefined },
Keyword{ .bytes = "union", .id = Id.Keyword_union },
Keyword{ .bytes = "unreachable", .id = Id.Keyword_unreachable },
- Keyword{ .bytes = "use", .id = Id.Keyword_usingnamespace },
Keyword{ .bytes = "usingnamespace", .id = Id.Keyword_usingnamespace },
Keyword{ .bytes = "var", .id = Id.Keyword_var },
Keyword{ .bytes = "volatile", .id = Id.Keyword_volatile },
@@ -143,6 +142,7 @@ pub const Token = struct {
FloatLiteral,
LineComment,
DocComment,
+ ContainerDocComment,
BracketStarBracket,
BracketStarCBracket,
ShebangLine,
@@ -212,6 +212,7 @@ pub const Token = struct {
.FloatLiteral => "FloatLiteral",
.LineComment => "LineComment",
.DocComment => "DocComment",
+ .ContainerDocComment => "ContainerDocComment",
.ShebangLine => "ShebangLine",
.Bang => "!",
@@ -337,26 +338,13 @@ pub const Tokenizer = struct {
}
pub fn init(buffer: []const u8) Tokenizer {
- if (mem.startsWith(u8, buffer, "#!")) {
- const src_start = if (mem.indexOfScalar(u8, buffer, '\n')) |i| i + 1 else buffer.len;
- return Tokenizer{
- .buffer = buffer,
- .index = src_start,
- .pending_invalid_token = Token{
- .id = Token.Id.ShebangLine,
- .start = 0,
- .end = src_start,
- },
- };
- } else {
- // Skip the UTF-8 BOM if present
- const src_start = if (mem.startsWith(u8, buffer, "\xEF\xBB\xBF")) 3 else usize(0);
- return Tokenizer{
- .buffer = buffer,
- .index = src_start,
- .pending_invalid_token = null,
- };
- }
+ // Skip the UTF-8 BOM if present
+ const src_start = if (mem.startsWith(u8, buffer, "\xEF\xBB\xBF")) 3 else @as(usize, 0);
+ return Tokenizer{
+ .buffer = buffer,
+ .index = src_start,
+ .pending_invalid_token = null,
+ };
}
const State = enum {
@@ -388,6 +376,7 @@ pub const Tokenizer = struct {
LineComment,
DocCommentStart,
DocComment,
+ ContainerDocComment,
Zero,
IntegerLiteral,
IntegerLiteralWithRadix,
@@ -763,12 +752,12 @@ pub const Tokenizer = struct {
self.index += 1;
break;
},
- '\n' => break, // Look for this error later.
+ '\n', '\r' => break, // Look for this error later.
else => self.checkLiteralCharacter(),
},
State.StringLiteralBackslash => switch (c) {
- '\n' => break, // Look for this error later.
+ '\n', '\r' => break, // Look for this error later.
else => {
state = State.StringLiteral;
},
@@ -1077,6 +1066,10 @@ pub const Tokenizer = struct {
'/' => {
state = State.DocCommentStart;
},
+ '!' => {
+ result.id = Token.Id.ContainerDocComment;
+ state = State.ContainerDocComment;
+ },
'\n' => break,
else => {
state = State.LineComment;
@@ -1097,7 +1090,7 @@ pub const Tokenizer = struct {
self.checkLiteralCharacter();
},
},
- State.LineComment, State.DocComment => switch (c) {
+ State.LineComment, State.DocComment, State.ContainerDocComment => switch (c) {
'\n' => break,
else => self.checkLiteralCharacter(),
},
@@ -1235,6 +1228,9 @@ pub const Tokenizer = struct {
State.DocComment, State.DocCommentStart => {
result.id = Token.Id.DocComment;
},
+ State.ContainerDocComment => {
+ result.id = Token.Id.ContainerDocComment;
+ },
State.NumberDot,
State.NumberDotHex,
@@ -1602,6 +1598,8 @@ test "tokenizer - line comment and doc comment" {
testTokenize("/// a", [_]Token.Id{Token.Id.DocComment});
testTokenize("///", [_]Token.Id{Token.Id.DocComment});
testTokenize("////", [_]Token.Id{Token.Id.LineComment});
+ testTokenize("//!", [_]Token.Id{Token.Id.ContainerDocComment});
+ testTokenize("//!!", [_]Token.Id{Token.Id.ContainerDocComment});
}
test "tokenizer - line comment followed by identifier" {
@@ -1625,6 +1623,16 @@ test "tokenizer - UTF-8 BOM is recognized and skipped" {
});
}
+test "correctly parse pointer assignment" {
+ testTokenize("b.*=3;\n", [_]Token.Id{
+ Token.Id.Identifier,
+ Token.Id.PeriodAsterisk,
+ Token.Id.Equal,
+ Token.Id.IntegerLiteral,
+ Token.Id.Semicolon,
+ });
+}
+
fn testTokenize(source: []const u8, expected_tokens: []const Token.Id) void {
var tokenizer = Tokenizer.init(source);
for (expected_tokens) |expected_token_id| {