From d890e817610dd75feef55c1f7983190852c622a5 Mon Sep 17 00:00:00 2001 From: Jacob Young Date: Tue, 31 Oct 2023 04:26:57 -0400 Subject: [PATCH] mem: fix ub in writeInt Use inline to vastly simplify the exposed API. This allows a comptime-known endian parameter to be propogated, making extra functions for a specific endianness completely unnecessary. --- lib/std/Build/Step/CheckObject.zig | 4 +- lib/std/base64.zig | 8 +- lib/std/child_process.zig | 4 +- lib/std/coff.zig | 40 +- lib/std/compress/gzip.zig | 10 +- lib/std/compress/lzma/decode.zig | 6 +- lib/std/compress/lzma/decode/rangecoder.zig | 2 +- lib/std/compress/lzma2/decode.zig | 6 +- lib/std/compress/xz.zig | 8 +- lib/std/compress/xz/block.zig | 6 +- lib/std/compress/zlib.zig | 8 +- lib/std/compress/zstandard.zig | 2 +- lib/std/compress/zstandard/decode/block.zig | 8 +- lib/std/compress/zstandard/decompress.zig | 27 +- lib/std/crypto/25519/field.zig | 20 +- lib/std/crypto/25519/scalar.zig | 12 +- lib/std/crypto/Certificate/Bundle/macos.zig | 4 +- lib/std/crypto/aegis.zig | 8 +- lib/std/crypto/aes/soft.zig | 36 +- lib/std/crypto/aes_gcm.zig | 16 +- lib/std/crypto/aes_ocb.zig | 8 +- lib/std/crypto/argon2.zig | 34 +- lib/std/crypto/ascon.zig | 13 +- lib/std/crypto/bcrypt.zig | 4 +- lib/std/crypto/blake2.zig | 20 +- lib/std/crypto/blake3.zig | 4 +- lib/std/crypto/chacha20.zig | 146 ++--- lib/std/crypto/cmac.zig | 4 +- lib/std/crypto/isap.zig | 22 +- lib/std/crypto/keccak_p.zig | 24 +- lib/std/crypto/md5.zig | 4 +- lib/std/crypto/pcurves/common.zig | 6 +- lib/std/crypto/pcurves/secp256k1.zig | 10 +- lib/std/crypto/poly1305.zig | 16 +- lib/std/crypto/salsa20.zig | 68 +-- lib/std/crypto/scrypt.zig | 8 +- lib/std/crypto/sha1.zig | 4 +- lib/std/crypto/sha2.zig | 8 +- lib/std/crypto/siphash.zig | 8 +- lib/std/crypto/tls.zig | 2 +- lib/std/crypto/tls/Client.zig | 6 +- lib/std/debug.zig | 10 +- lib/std/dwarf.zig | 7 +- lib/std/dwarf/call_frame.zig | 9 +- lib/std/dwarf/expressions.zig | 33 +- lib/std/fmt/parse_float/FloatStream.zig | 2 +- lib/std/fmt/parse_float/decimal.zig | 2 +- lib/std/hash/cityhash.zig | 4 +- lib/std/hash/crc.zig | 2 +- lib/std/hash/verify.zig | 2 +- lib/std/hash/wyhash.zig | 2 +- lib/std/hash/xxhash.zig | 22 +- lib/std/io.zig | 16 - lib/std/io/Reader.zig | 26 +- lib/std/io/writer.zig | 30 +- lib/std/mem.zig | 643 ++++++++------------ lib/std/net.zig | 6 +- lib/std/os/test.zig | 6 +- lib/std/pdb.zig | 26 +- lib/std/rand.zig | 9 +- lib/std/rand/Isaac64.zig | 2 +- lib/std/rand/Pcg.zig | 4 +- lib/std/rand/RomuTrio.zig | 2 +- lib/std/rand/Sfc64.zig | 2 +- lib/std/rand/Xoroshiro128.zig | 2 +- lib/std/rand/Xoshiro256.zig | 2 +- lib/std/rand/test.zig | 2 +- lib/std/tz.zig | 8 +- lib/std/unicode.zig | 49 +- lib/std/zig/Server.zig | 4 +- lib/test_runner.zig | 4 +- src/Package/Fetch/git.zig | 24 +- src/arch/wasm/CodeGen.zig | 2 +- src/arch/wasm/Emit.zig | 4 +- src/arch/x86_64/Emit.zig | 2 +- src/arch/x86_64/encoder.zig | 8 +- src/glibc.zig | 10 +- src/link/Coff.zig | 18 +- src/link/Coff/Relocation.zig | 21 +- src/link/Elf/Atom.zig | 84 +-- src/link/Elf/eh_frame.zig | 28 +- src/link/Elf/synthetic_sections.zig | 30 +- src/link/MachO.zig | 14 +- src/link/MachO/Archive.zig | 8 +- src/link/MachO/Atom.zig | 52 +- src/link/MachO/CodeSignature.zig | 58 +- src/link/MachO/DwarfInfo.zig | 34 +- src/link/MachO/Relocation.zig | 18 +- src/link/MachO/UnwindInfo.zig | 2 +- src/link/MachO/eh_frame.zig | 52 +- src/link/MachO/stubs.zig | 38 +- src/link/MachO/thunks.zig | 6 +- src/link/MachO/zld.zig | 4 +- src/link/Plan9.zig | 14 +- src/link/Plan9/aout.zig | 2 +- src/link/Wasm.zig | 10 +- src/link/Wasm/Archive.zig | 4 +- src/link/Wasm/Atom.zig | 4 +- src/link/Wasm/Object.zig | 2 +- src/resinator/ani.zig | 4 +- src/resinator/bmp.zig | 14 +- src/resinator/compile.zig | 189 +++--- src/resinator/errors.zig | 12 +- src/resinator/ico.zig | 66 +- src/resinator/res.zig | 32 +- test/behavior/bugs/1851.zig | 1 + test/behavior/struct.zig | 3 +- 107 files changed, 1129 insertions(+), 1337 deletions(-) diff --git a/lib/std/Build/Step/CheckObject.zig b/lib/std/Build/Step/CheckObject.zig index 2534298854..45a5ea541f 100644 --- a/lib/std/Build/Step/CheckObject.zig +++ b/lib/std/Build/Step/CheckObject.zig @@ -1624,8 +1624,8 @@ const WasmDumper = struct { switch (opcode) { .i32_const => try writer.print("i32.const {x}\n", .{try std.leb.readILEB128(i32, reader)}), .i64_const => try writer.print("i64.const {x}\n", .{try std.leb.readILEB128(i64, reader)}), - .f32_const => try writer.print("f32.const {x}\n", .{@as(f32, @bitCast(try reader.readIntLittle(u32)))}), - .f64_const => try writer.print("f64.const {x}\n", .{@as(f64, @bitCast(try reader.readIntLittle(u64)))}), + .f32_const => try writer.print("f32.const {x}\n", .{@as(f32, @bitCast(try reader.readInt(u32, .Little)))}), + .f64_const => try writer.print("f64.const {x}\n", .{@as(f64, @bitCast(try reader.readInt(u64, .Little)))}), .global_get => try writer.print("global.get {x}\n", .{try std.leb.readULEB128(u32, reader)}), else => unreachable, } diff --git a/lib/std/base64.zig b/lib/std/base64.zig index 2ec8fb5678..f0ad1d97bc 100644 --- a/lib/std/base64.zig +++ b/lib/std/base64.zig @@ -104,14 +104,14 @@ pub const Base64Encoder = struct { var idx: usize = 0; var out_idx: usize = 0; while (idx + 15 < source.len) : (idx += 12) { - const bits = std.mem.readIntBig(u128, source[idx..][0..16]); + const bits = std.mem.readInt(u128, source[idx..][0..16], .Big); inline for (0..16) |i| { dest[out_idx + i] = encoder.alphabet_chars[@truncate((bits >> (122 - i * 6)) & 0x3f)]; } out_idx += 16; } while (idx + 3 < source.len) : (idx += 3) { - const bits = std.mem.readIntBig(u32, source[idx..][0..4]); + const bits = std.mem.readInt(u32, source[idx..][0..4], .Big); dest[out_idx] = encoder.alphabet_chars[(bits >> 26) & 0x3f]; dest[out_idx + 1] = encoder.alphabet_chars[(bits >> 20) & 0x3f]; dest[out_idx + 2] = encoder.alphabet_chars[(bits >> 14) & 0x3f]; @@ -226,7 +226,7 @@ pub const Base64Decoder = struct { if ((new_bits & invalid_char_tst) != 0) return error.InvalidCharacter; bits |= (new_bits << (24 * i)); } - std.mem.writeIntLittle(u128, dest[dest_idx..][0..16], bits); + std.mem.writeInt(u128, dest[dest_idx..][0..16], bits, .Little); } while (fast_src_idx + 4 < source.len and dest_idx + 3 < dest.len) : ({ fast_src_idx += 4; @@ -237,7 +237,7 @@ pub const Base64Decoder = struct { bits |= decoder.fast_char_to_index[2][source[fast_src_idx + 2]]; bits |= decoder.fast_char_to_index[3][source[fast_src_idx + 3]]; if ((bits & invalid_char_tst) != 0) return error.InvalidCharacter; - std.mem.writeIntLittle(u32, dest[dest_idx..][0..4], bits); + std.mem.writeInt(u32, dest[dest_idx..][0..4], bits, .Little); } var remaining = source[fast_src_idx..]; for (remaining, fast_src_idx..) |c, src_idx| { diff --git a/lib/std/child_process.zig b/lib/std/child_process.zig index 81c5bc1e03..ca1191398a 100644 --- a/lib/std/child_process.zig +++ b/lib/std/child_process.zig @@ -1376,7 +1376,7 @@ fn writeIntFd(fd: i32, value: ErrInt) !void { .capable_io_mode = .blocking, .intended_io_mode = .blocking, }; - file.writer().writeIntNative(u64, @as(u64, @intCast(value))) catch return error.SystemResources; + file.writer().writeInt(u64, @intCast(value), .Little) catch return error.SystemResources; } fn readIntFd(fd: i32) !ErrInt { @@ -1385,7 +1385,7 @@ fn readIntFd(fd: i32) !ErrInt { .capable_io_mode = .blocking, .intended_io_mode = .blocking, }; - return @as(ErrInt, @intCast(file.reader().readIntNative(u64) catch return error.SystemResources)); + return @as(ErrInt, @intCast(file.reader().readInt(u64, .Little) catch return error.SystemResources)); } /// Caller must free result. diff --git a/lib/std/coff.zig b/lib/std/coff.zig index 13e420308e..0a2f9c5210 100644 --- a/lib/std/coff.zig +++ b/lib/std/coff.zig @@ -663,7 +663,7 @@ pub const Symbol = struct { pub fn getNameOffset(self: Symbol) ?u32 { if (!std.mem.eql(u8, self.name[0..4], "\x00\x00\x00\x00")) return null; - const offset = std.mem.readIntLittle(u32, self.name[4..8]); + const offset = std.mem.readInt(u32, self.name[4..8], .Little); return offset; } }; @@ -1075,7 +1075,7 @@ pub const Coff = struct { var stream = std.io.fixedBufferStream(data); const reader = stream.reader(); try stream.seekTo(pe_pointer_offset); - var coff_header_offset = try reader.readIntLittle(u32); + var coff_header_offset = try reader.readInt(u32, .Little); try stream.seekTo(coff_header_offset); var buf: [4]u8 = undefined; try reader.readNoEof(&buf); @@ -1142,7 +1142,7 @@ pub const Coff = struct { if (!mem.eql(u8, &cv_signature, "RSDS")) return error.InvalidPEMagic; try reader.readNoEof(self.guid[0..]); - self.age = try reader.readIntLittle(u32); + self.age = try reader.readInt(u32, .Little); // Finally read the null-terminated string. var byte = try reader.readByte(); @@ -1223,7 +1223,7 @@ pub const Coff = struct { if (coff_header.pointer_to_symbol_table == 0) return null; const offset = coff_header.pointer_to_symbol_table + Symbol.sizeOf() * coff_header.number_of_symbols; - const size = mem.readIntLittle(u32, self.data[offset..][0..4]); + const size = mem.readInt(u32, self.data[offset..][0..4], .Little); if ((offset + size) > self.data.len) return error.InvalidStrtabSize; return Strtab{ .buffer = self.data[offset..][0..size] }; @@ -1324,9 +1324,9 @@ pub const Symtab = struct { fn asSymbol(raw: []const u8) Symbol { return .{ .name = raw[0..8].*, - .value = mem.readIntLittle(u32, raw[8..12]), - .section_number = @as(SectionNumber, @enumFromInt(mem.readIntLittle(u16, raw[12..14]))), - .type = @as(SymType, @bitCast(mem.readIntLittle(u16, raw[14..16]))), + .value = mem.readInt(u32, raw[8..12], .Little), + .section_number = @as(SectionNumber, @enumFromInt(mem.readInt(u16, raw[12..14], .Little))), + .type = @as(SymType, @bitCast(mem.readInt(u16, raw[14..16], .Little))), .storage_class = @as(StorageClass, @enumFromInt(raw[16])), .number_of_aux_symbols = raw[17], }; @@ -1335,27 +1335,27 @@ pub const Symtab = struct { fn asDebugInfo(raw: []const u8) DebugInfoDefinition { return .{ .unused_1 = raw[0..4].*, - .linenumber = mem.readIntLittle(u16, raw[4..6]), + .linenumber = mem.readInt(u16, raw[4..6], .Little), .unused_2 = raw[6..12].*, - .pointer_to_next_function = mem.readIntLittle(u32, raw[12..16]), + .pointer_to_next_function = mem.readInt(u32, raw[12..16], .Little), .unused_3 = raw[16..18].*, }; } fn asFuncDef(raw: []const u8) FunctionDefinition { return .{ - .tag_index = mem.readIntLittle(u32, raw[0..4]), - .total_size = mem.readIntLittle(u32, raw[4..8]), - .pointer_to_linenumber = mem.readIntLittle(u32, raw[8..12]), - .pointer_to_next_function = mem.readIntLittle(u32, raw[12..16]), + .tag_index = mem.readInt(u32, raw[0..4], .Little), + .total_size = mem.readInt(u32, raw[4..8], .Little), + .pointer_to_linenumber = mem.readInt(u32, raw[8..12], .Little), + .pointer_to_next_function = mem.readInt(u32, raw[12..16], .Little), .unused = raw[16..18].*, }; } fn asWeakExtDef(raw: []const u8) WeakExternalDefinition { return .{ - .tag_index = mem.readIntLittle(u32, raw[0..4]), - .flag = @as(WeakExternalFlag, @enumFromInt(mem.readIntLittle(u32, raw[4..8]))), + .tag_index = mem.readInt(u32, raw[0..4], .Little), + .flag = @as(WeakExternalFlag, @enumFromInt(mem.readInt(u32, raw[4..8], .Little))), .unused = raw[8..18].*, }; } @@ -1368,11 +1368,11 @@ pub const Symtab = struct { fn asSectDef(raw: []const u8) SectionDefinition { return .{ - .length = mem.readIntLittle(u32, raw[0..4]), - .number_of_relocations = mem.readIntLittle(u16, raw[4..6]), - .number_of_linenumbers = mem.readIntLittle(u16, raw[6..8]), - .checksum = mem.readIntLittle(u32, raw[8..12]), - .number = mem.readIntLittle(u16, raw[12..14]), + .length = mem.readInt(u32, raw[0..4], .Little), + .number_of_relocations = mem.readInt(u16, raw[4..6], .Little), + .number_of_linenumbers = mem.readInt(u16, raw[6..8], .Little), + .checksum = mem.readInt(u32, raw[8..12], .Little), + .number = mem.readInt(u16, raw[12..14], .Little), .selection = @as(ComdatSelection, @enumFromInt(raw[14])), .unused = raw[15..18].*, }; diff --git a/lib/std/compress/gzip.zig b/lib/std/compress/gzip.zig index f6fb038ae3..0b87411798 100644 --- a/lib/std/compress/gzip.zig +++ b/lib/std/compress/gzip.zig @@ -58,7 +58,7 @@ pub fn Decompress(comptime ReaderType: type) type { const FLG = header[3]; // Modification time, as a Unix timestamp. // If zero there's no timestamp available. - const MTIME = mem.readIntLittle(u32, header[4..8]); + const MTIME = mem.readInt(u32, header[4..8], .Little); // Extra flags const XFL = header[8]; // Operating system where the compression took place @@ -66,7 +66,7 @@ pub fn Decompress(comptime ReaderType: type) type { _ = XFL; const extra = if (FLG & FEXTRA != 0) blk: { - const len = try hashed_reader.readIntLittle(u16); + const len = try hashed_reader.readInt(u16, .Little); const tmp_buf = try allocator.alloc(u8, len); errdefer allocator.free(tmp_buf); @@ -88,7 +88,7 @@ pub fn Decompress(comptime ReaderType: type) type { errdefer if (comment) |p| allocator.free(p); if (FLG & FHCRC != 0) { - const hash = try source.readIntLittle(u16); + const hash = try source.readInt(u16, .Little); if (hash != @as(u16, @truncate(hasher.hasher.final()))) return error.WrongChecksum; } @@ -133,12 +133,12 @@ pub fn Decompress(comptime ReaderType: type) type { } // We've reached the end of stream, check if the checksum matches - const hash = try self.in_reader.readIntLittle(u32); + const hash = try self.in_reader.readInt(u32, .Little); if (hash != self.hasher.final()) return error.WrongChecksum; // The ISIZE field is the size of the uncompressed input modulo 2^32 - const input_size = try self.in_reader.readIntLittle(u32); + const input_size = try self.in_reader.readInt(u32, .Little); if (self.read_amt & 0xffffffff != input_size) return error.CorruptedData; diff --git a/lib/std/compress/lzma/decode.zig b/lib/std/compress/lzma/decode.zig index 0dae9281e8..e8062cc6d2 100644 --- a/lib/std/compress/lzma/decode.zig +++ b/lib/std/compress/lzma/decode.zig @@ -58,12 +58,12 @@ pub const Params = struct { props /= 5; const pb = @as(u3, @intCast(props)); - const dict_size_provided = try reader.readIntLittle(u32); + const dict_size_provided = try reader.readInt(u32, .Little); const dict_size = @max(0x1000, dict_size_provided); const unpacked_size = switch (options.unpacked_size) { .read_from_header => blk: { - const unpacked_size_provided = try reader.readIntLittle(u64); + const unpacked_size_provided = try reader.readInt(u64, .Little); const marker_mandatory = unpacked_size_provided == 0xFFFF_FFFF_FFFF_FFFF; break :blk if (marker_mandatory) null @@ -71,7 +71,7 @@ pub const Params = struct { unpacked_size_provided; }, .read_header_but_use_provided => |x| blk: { - _ = try reader.readIntLittle(u64); + _ = try reader.readInt(u64, .Little); break :blk x; }, .use_provided => |x| x, diff --git a/lib/std/compress/lzma/decode/rangecoder.zig b/lib/std/compress/lzma/decode/rangecoder.zig index 54d2195e33..b102639be0 100644 --- a/lib/std/compress/lzma/decode/rangecoder.zig +++ b/lib/std/compress/lzma/decode/rangecoder.zig @@ -12,7 +12,7 @@ pub const RangeDecoder = struct { } return RangeDecoder{ .range = 0xFFFF_FFFF, - .code = try reader.readIntBig(u32), + .code = try reader.readInt(u32, .Big), }; } diff --git a/lib/std/compress/lzma2/decode.zig b/lib/std/compress/lzma2/decode.zig index a23007d42a..ba67782d86 100644 --- a/lib/std/compress/lzma2/decode.zig +++ b/lib/std/compress/lzma2/decode.zig @@ -97,12 +97,12 @@ pub const Decoder = struct { const unpacked_size = blk: { var tmp: u64 = status & 0x1F; tmp <<= 16; - tmp |= try reader.readIntBig(u16); + tmp |= try reader.readInt(u16, .Big); break :blk tmp + 1; }; const packed_size = blk: { - const tmp: u17 = try reader.readIntBig(u16); + const tmp: u17 = try reader.readInt(u16, .Big); break :blk tmp + 1; }; @@ -155,7 +155,7 @@ pub const Decoder = struct { accum: *LzAccumBuffer, reset_dict: bool, ) !void { - const unpacked_size = @as(u17, try reader.readIntBig(u16)) + 1; + const unpacked_size = @as(u17, try reader.readInt(u16, .Big)) + 1; if (reset_dict) { try accum.reset(writer); diff --git a/lib/std/compress/xz.zig b/lib/std/compress/xz.zig index 3ceec90a7a..4515ed89dc 100644 --- a/lib/std/compress/xz.zig +++ b/lib/std/compress/xz.zig @@ -52,7 +52,7 @@ pub fn Decompress(comptime ReaderType: type) type { break :blk hasher.hasher.final(); }; - const hash_b = try source.readIntLittle(u32); + const hash_b = try source.readInt(u32, .Little); if (hash_a != hash_b) return error.WrongChecksum; @@ -105,20 +105,20 @@ pub fn Decompress(comptime ReaderType: type) type { } const hash_a = hasher.hasher.final(); - const hash_b = try counting_reader.readIntLittle(u32); + const hash_b = try counting_reader.readInt(u32, .Little); if (hash_a != hash_b) return error.WrongChecksum; break :blk counter.bytes_read; }; - const hash_a = try self.in_reader.readIntLittle(u32); + const hash_a = try self.in_reader.readInt(u32, .Little); const hash_b = blk: { var hasher = std.compress.hashedReader(self.in_reader, Crc32.init()); const hashed_reader = hasher.reader(); - const backward_size = (@as(u64, try hashed_reader.readIntLittle(u32)) + 1) * 4; + const backward_size = (@as(u64, try hashed_reader.readInt(u32, .Little)) + 1) * 4; if (backward_size != index_size) return error.CorruptInput; diff --git a/lib/std/compress/xz/block.zig b/lib/std/compress/xz/block.zig index 6f4fad1c7f..640375988f 100644 --- a/lib/std/compress/xz/block.zig +++ b/lib/std/compress/xz/block.zig @@ -148,7 +148,7 @@ pub fn Decoder(comptime ReaderType: type) type { } const hash_a = header_hasher.hasher.final(); - const hash_b = try header_reader.readIntLittle(u32); + const hash_b = try header_reader.readInt(u32, .Little); if (hash_a != hash_b) return error.WrongChecksum; } @@ -182,13 +182,13 @@ pub fn Decoder(comptime ReaderType: type) type { .none => {}, .crc32 => { const hash_a = Crc32.hash(unpacked_bytes); - const hash_b = try self.inner_reader.readIntLittle(u32); + const hash_b = try self.inner_reader.readInt(u32, .Little); if (hash_a != hash_b) return error.WrongChecksum; }, .crc64 => { const hash_a = Crc64.hash(unpacked_bytes); - const hash_b = try self.inner_reader.readIntLittle(u64); + const hash_b = try self.inner_reader.readInt(u64, .Little); if (hash_a != hash_b) return error.WrongChecksum; }, diff --git a/lib/std/compress/zlib.zig b/lib/std/compress/zlib.zig index 5580192537..a39c8bc3c3 100644 --- a/lib/std/compress/zlib.zig +++ b/lib/std/compress/zlib.zig @@ -36,7 +36,7 @@ pub fn DecompressStream(comptime ReaderType: type) type { fn init(allocator: mem.Allocator, source: ReaderType) !Self { // Zlib header format is specified in RFC1950 - const header_u16 = try source.readIntBig(u16); + const header_u16 = try source.readInt(u16, .Big); // verify the header checksum if (header_u16 % 31 != 0) @@ -81,7 +81,7 @@ pub fn DecompressStream(comptime ReaderType: type) type { } // We've reached the end of stream, check if the checksum matches - const hash = try self.in_reader.readIntBig(u32); + const hash = try self.in_reader.readInt(u32, .Big); if (hash != self.hasher.final()) return error.WrongChecksum; @@ -132,7 +132,7 @@ pub fn CompressStream(comptime WriterType: type) type { }; header.checksum = @as(u5, @truncate(31 - @as(u16, @bitCast(header)) % 31)); - try dest.writeIntBig(u16, @as(u16, @bitCast(header))); + try dest.writeInt(u16, @as(u16, @bitCast(header)), .Big); const compression_level: deflate.Compression = switch (options.level) { .no_compression => .no_compression, @@ -171,7 +171,7 @@ pub fn CompressStream(comptime WriterType: type) type { pub fn finish(self: *Self) !void { const hash = self.hasher.final(); try self.deflator.close(); - try self.in_writer.writeIntBig(u32, hash); + try self.in_writer.writeInt(u32, hash, .Big); } }; } diff --git a/lib/std/compress/zstandard.zig b/lib/std/compress/zstandard.zig index ef2ccc2f1c..7376373adc 100644 --- a/lib/std/compress/zstandard.zig +++ b/lib/std/compress/zstandard.zig @@ -201,7 +201,7 @@ pub fn DecompressStream( if (block_header.last_block) { self.state = .LastBlock; if (self.frame_context.has_checksum) { - const checksum = source_reader.readIntLittle(u32) catch + const checksum = source_reader.readInt(u32, .Little) catch return error.MalformedFrame; if (comptime options.verify_checksum) { if (self.frame_context.hasher_opt) |*hasher| { diff --git a/lib/std/compress/zstandard/decode/block.zig b/lib/std/compress/zstandard/decode/block.zig index 4a035fb543..184f453de4 100644 --- a/lib/std/compress/zstandard/decode/block.zig +++ b/lib/std/compress/zstandard/decode/block.zig @@ -13,8 +13,6 @@ const readers = @import("../readers.zig"); const decodeFseTable = @import("fse.zig").decodeFseTable; -const readInt = std.mem.readIntLittle; - pub const Error = error{ BlockSizeOverMaximum, MalformedBlockSize, @@ -1031,9 +1029,9 @@ fn decodeStreams(size_format: u2, stream_data: []const u8) !LiteralsSection.Stre if (stream_data.len < 6) return error.MalformedLiteralsSection; - const stream_1_length = @as(usize, readInt(u16, stream_data[0..2])); - const stream_2_length = @as(usize, readInt(u16, stream_data[2..4])); - const stream_3_length = @as(usize, readInt(u16, stream_data[4..6])); + const stream_1_length: usize = std.mem.readInt(u16, stream_data[0..2], .Little); + const stream_2_length: usize = std.mem.readInt(u16, stream_data[2..4], .Little); + const stream_3_length: usize = std.mem.readInt(u16, stream_data[4..6], .Little); const stream_1_start = 6; const stream_2_start = stream_1_start + stream_1_length; diff --git a/lib/std/compress/zstandard/decompress.zig b/lib/std/compress/zstandard/decompress.zig index bc977d1fba..65e0593ea7 100644 --- a/lib/std/compress/zstandard/decompress.zig +++ b/lib/std/compress/zstandard/decompress.zig @@ -15,9 +15,6 @@ pub const block = @import("decode/block.zig"); const readers = @import("readers.zig"); -const readInt = std.mem.readIntLittle; -const readIntSlice = std.mem.readIntSliceLittle; - /// Returns `true` is `magic` is a valid magic number for a skippable frame pub fn isSkippableMagic(magic: u32) bool { return frame.Skippable.magic_number_min <= magic and magic <= frame.Skippable.magic_number_max; @@ -31,7 +28,7 @@ pub fn isSkippableMagic(magic: u32) bool { /// skippable frames. /// - `error.EndOfStream` if `source` contains fewer than 4 bytes pub fn decodeFrameType(source: anytype) error{ BadMagic, EndOfStream }!frame.Kind { - const magic = try source.readIntLittle(u32); + const magic = try source.readInt(u32, .Little); return frameType(magic); } @@ -65,14 +62,14 @@ pub const HeaderError = error{ BadMagic, EndOfStream, ReservedBitSet }; /// - `error.ReservedBitSet` if the frame is a Zstandard frame and any of the /// reserved bits are set pub fn decodeFrameHeader(source: anytype) (@TypeOf(source).Error || HeaderError)!FrameHeader { - const magic = try source.readIntLittle(u32); + const magic = try source.readInt(u32, .Little); const frame_type = try frameType(magic); switch (frame_type) { .zstandard => return FrameHeader{ .zstandard = try decodeZstandardHeader(source) }, .skippable => return FrameHeader{ .skippable = .{ .magic_number = magic, - .frame_size = try source.readIntLittle(u32), + .frame_size = try source.readInt(u32, .Little), }, }, } @@ -193,7 +190,7 @@ pub fn decodeFrame( switch (try decodeFrameType(fbs.reader())) { .zstandard => return decodeZstandardFrame(dest, src, verify_checksum), .skippable => { - const content_size = try fbs.reader().readIntLittle(u32); + const content_size = try fbs.reader().readInt(u32, .Little); if (content_size > std.math.maxInt(usize) - 8) return error.SkippableSizeTooLarge; const read_count = @as(usize, content_size) + 8; if (read_count > src.len) return error.SkippableSizeTooLarge; @@ -238,7 +235,7 @@ pub fn decodeFrameArrayList( ) (error{ BadMagic, OutOfMemory, SkippableSizeTooLarge } || FrameContext.Error || FrameError)!usize { var fbs = std.io.fixedBufferStream(src); const reader = fbs.reader(); - const magic = try reader.readIntLittle(u32); + const magic = try reader.readInt(u32, .Little); switch (try frameType(magic)) { .zstandard => return decodeZstandardFrameArrayList( allocator, @@ -248,7 +245,7 @@ pub fn decodeFrameArrayList( window_size_max, ), .skippable => { - const content_size = try fbs.reader().readIntLittle(u32); + const content_size = try fbs.reader().readInt(u32, .Little); if (content_size > std.math.maxInt(usize) - 8) return error.SkippableSizeTooLarge; const read_count = @as(usize, content_size) + 8; if (read_count > src.len) return error.SkippableSizeTooLarge; @@ -302,7 +299,7 @@ pub fn decodeZstandardFrame( WindowSizeUnknown, DictionaryIdFlagUnsupported, } || FrameError)!ReadWriteCount { - assert(readInt(u32, src[0..4]) == frame.Zstandard.magic_number); + assert(std.mem.readInt(u32, src[0..4], .Little) == frame.Zstandard.magic_number); var consumed_count: usize = 4; var frame_context = context: { @@ -354,7 +351,7 @@ pub fn decodeZStandardFrameBlocks( if (written_count != content_size) return error.BadContentSize; if (frame_context.has_checksum) { if (src.len < consumed_count + 4) return error.EndOfStream; - const checksum = readIntSlice(u32, src[consumed_count .. consumed_count + 4]); + const checksum = std.mem.readInt(u32, src[consumed_count..][0..4], .Little); consumed_count += 4; if (frame_context.hasher_opt) |*hasher| { if (checksum != computeChecksum(hasher)) return error.ChecksumFailure; @@ -445,7 +442,7 @@ pub fn decodeZstandardFrameArrayList( verify_checksum: bool, window_size_max: usize, ) (error{OutOfMemory} || FrameContext.Error || FrameError)!usize { - assert(readInt(u32, src[0..4]) == frame.Zstandard.magic_number); + assert(std.mem.readInt(u32, src[0..4], .Little) == frame.Zstandard.magic_number); var consumed_count: usize = 4; var frame_context = context: { @@ -520,7 +517,7 @@ pub fn decodeZstandardFrameBlocksArrayList( if (frame_context.has_checksum) { if (src.len < consumed_count + 4) return error.EndOfStream; - const checksum = readIntSlice(u32, src[consumed_count .. consumed_count + 4]); + const checksum = std.mem.readInt(u32, src[consumed_count..][0..4], .Little); consumed_count += 4; if (frame_context.hasher_opt) |*hasher| { if (checksum != computeChecksum(hasher)) return error.ChecksumFailure; @@ -569,9 +566,9 @@ fn decodeFrameBlocksInner( /// Decode the header of a skippable frame. The first four bytes of `src` must /// be a valid magic number for a skippable frame. pub fn decodeSkippableHeader(src: *const [8]u8) SkippableHeader { - const magic = readInt(u32, src[0..4]); + const magic = std.mem.readInt(u32, src[0..4], .Little); assert(isSkippableMagic(magic)); - const frame_size = readInt(u32, src[4..8]); + const frame_size = std.mem.readInt(u32, src[4..8], .Little); return .{ .magic_number = magic, .frame_size = frame_size, diff --git a/lib/std/crypto/25519/field.zig b/lib/std/crypto/25519/field.zig index 627df9d4cb..389a8084cd 100644 --- a/lib/std/crypto/25519/field.zig +++ b/lib/std/crypto/25519/field.zig @@ -1,8 +1,6 @@ const std = @import("std"); const builtin = @import("builtin"); const crypto = std.crypto; -const readIntLittle = std.mem.readIntLittle; -const writeIntLittle = std.mem.writeIntLittle; const NonCanonicalError = crypto.errors.NonCanonicalError; const NotSquareError = crypto.errors.NotSquareError; @@ -73,11 +71,11 @@ pub const Fe = struct { /// Unpack a field element pub fn fromBytes(s: [32]u8) Fe { var fe: Fe = undefined; - fe.limbs[0] = readIntLittle(u64, s[0..8]) & MASK51; - fe.limbs[1] = (readIntLittle(u64, s[6..14]) >> 3) & MASK51; - fe.limbs[2] = (readIntLittle(u64, s[12..20]) >> 6) & MASK51; - fe.limbs[3] = (readIntLittle(u64, s[19..27]) >> 1) & MASK51; - fe.limbs[4] = (readIntLittle(u64, s[24..32]) >> 12) & MASK51; + fe.limbs[0] = std.mem.readInt(u64, s[0..8], .Little) & MASK51; + fe.limbs[1] = (std.mem.readInt(u64, s[6..14], .Little) >> 3) & MASK51; + fe.limbs[2] = (std.mem.readInt(u64, s[12..20], .Little) >> 6) & MASK51; + fe.limbs[3] = (std.mem.readInt(u64, s[19..27], .Little) >> 1) & MASK51; + fe.limbs[4] = (std.mem.readInt(u64, s[24..32], .Little) >> 12) & MASK51; return fe; } @@ -87,10 +85,10 @@ pub const Fe = struct { var reduced = fe; reduced.reduce(); var s: [32]u8 = undefined; - writeIntLittle(u64, s[0..8], reduced.limbs[0] | (reduced.limbs[1] << 51)); - writeIntLittle(u64, s[8..16], (reduced.limbs[1] >> 13) | (reduced.limbs[2] << 38)); - writeIntLittle(u64, s[16..24], (reduced.limbs[2] >> 26) | (reduced.limbs[3] << 25)); - writeIntLittle(u64, s[24..32], (reduced.limbs[3] >> 39) | (reduced.limbs[4] << 12)); + std.mem.writeInt(u64, s[0..8], reduced.limbs[0] | (reduced.limbs[1] << 51), .Little); + std.mem.writeInt(u64, s[8..16], (reduced.limbs[1] >> 13) | (reduced.limbs[2] << 38), .Little); + std.mem.writeInt(u64, s[16..24], (reduced.limbs[2] >> 26) | (reduced.limbs[3] << 25), .Little); + std.mem.writeInt(u64, s[24..32], (reduced.limbs[3] >> 39) | (reduced.limbs[4] << 12), .Little); return s; } diff --git a/lib/std/crypto/25519/scalar.zig b/lib/std/crypto/25519/scalar.zig index 1699c68e12..cf18c7cedd 100644 --- a/lib/std/crypto/25519/scalar.zig +++ b/lib/std/crypto/25519/scalar.zig @@ -15,7 +15,7 @@ pub const zero = [_]u8{0} ** 32; const field_order_s = s: { var s: [32]u8 = undefined; - mem.writeIntLittle(u256, &s, field_order); + mem.writeInt(u256, &s, field_order, .Little); break :s s; }; @@ -127,9 +127,9 @@ pub const Scalar = struct { var bytes: CompressedScalar = undefined; var i: usize = 0; while (i < 4) : (i += 1) { - mem.writeIntLittle(u64, bytes[i * 7 ..][0..8], expanded.limbs[i]); + mem.writeInt(u64, bytes[i * 7 ..][0..8], expanded.limbs[i], .Little); } - mem.writeIntLittle(u32, bytes[i * 7 ..][0..4], @as(u32, @intCast(expanded.limbs[i]))); + mem.writeInt(u32, bytes[i * 7 ..][0..4], @intCast(expanded.limbs[i]), .Little); return bytes; } @@ -580,7 +580,7 @@ const ScalarDouble = struct { var limbs: Limbs = undefined; var i: usize = 0; while (i < 9) : (i += 1) { - limbs[i] = mem.readIntLittle(u64, bytes[i * 7 ..][0..8]) & 0xffffffffffffff; + limbs[i] = mem.readInt(u64, bytes[i * 7 ..][0..8], .Little) & 0xffffffffffffff; } limbs[i] = @as(u64, bytes[i * 7]); return ScalarDouble{ .limbs = limbs }; @@ -590,9 +590,9 @@ const ScalarDouble = struct { var limbs: Limbs = undefined; var i: usize = 0; while (i < 4) : (i += 1) { - limbs[i] = mem.readIntLittle(u64, bytes[i * 7 ..][0..8]) & 0xffffffffffffff; + limbs[i] = mem.readInt(u64, bytes[i * 7 ..][0..8], .Little) & 0xffffffffffffff; } - limbs[i] = @as(u64, mem.readIntLittle(u32, bytes[i * 7 ..][0..4])); + limbs[i] = @as(u64, mem.readInt(u32, bytes[i * 7 ..][0..4], .Little)); @memset(limbs[5..], 0); return ScalarDouble{ .limbs = limbs }; } diff --git a/lib/std/crypto/Certificate/Bundle/macos.zig b/lib/std/crypto/Certificate/Bundle/macos.zig index 028275a06b..3814fd421f 100644 --- a/lib/std/crypto/Certificate/Bundle/macos.zig +++ b/lib/std/crypto/Certificate/Bundle/macos.zig @@ -32,7 +32,7 @@ pub fn rescanMac(cb: *Bundle, gpa: Allocator) RescanMacError!void { var table_idx: u32 = 0; while (table_idx < table_list.len) : (table_idx += 1) { - table_list[table_idx] = try reader.readIntBig(u32); + table_list[table_idx] = try reader.readInt(u32, .Big); } const now_sec = std.time.timestamp(); @@ -51,7 +51,7 @@ pub fn rescanMac(cb: *Bundle, gpa: Allocator) RescanMacError!void { var record_idx: u32 = 0; while (record_idx < record_list.len) : (record_idx += 1) { - record_list[record_idx] = try reader.readIntBig(u32); + record_list[record_idx] = try reader.readInt(u32, .Big); } for (record_list) |record_offset| { diff --git a/lib/std/crypto/aegis.zig b/lib/std/crypto/aegis.zig index 18047a13b5..f6b6864936 100644 --- a/lib/std/crypto/aegis.zig +++ b/lib/std/crypto/aegis.zig @@ -106,8 +106,8 @@ const State128L = struct { fn mac(state: *State128L, comptime tag_bits: u9, adlen: usize, mlen: usize) [tag_bits / 8]u8 { const blocks = &state.blocks; var sizes: [16]u8 = undefined; - mem.writeIntLittle(u64, sizes[0..8], adlen * 8); - mem.writeIntLittle(u64, sizes[8..16], mlen * 8); + mem.writeInt(u64, sizes[0..8], adlen * 8, .Little); + mem.writeInt(u64, sizes[8..16], mlen * 8, .Little); const tmp = AesBlock.fromBytes(&sizes).xorBlocks(blocks[2]); var i: usize = 0; while (i < 7) : (i += 1) { @@ -284,8 +284,8 @@ const State256 = struct { fn mac(state: *State256, comptime tag_bits: u9, adlen: usize, mlen: usize) [tag_bits / 8]u8 { const blocks = &state.blocks; var sizes: [16]u8 = undefined; - mem.writeIntLittle(u64, sizes[0..8], adlen * 8); - mem.writeIntLittle(u64, sizes[8..16], mlen * 8); + mem.writeInt(u64, sizes[0..8], adlen * 8, .Little); + mem.writeInt(u64, sizes[8..16], mlen * 8, .Little); const tmp = AesBlock.fromBytes(&sizes).xorBlocks(blocks[3]); var i: usize = 0; while (i < 7) : (i += 1) { diff --git a/lib/std/crypto/aes/soft.zig b/lib/std/crypto/aes/soft.zig index 68a661a93a..e1fa201c9c 100644 --- a/lib/std/crypto/aes/soft.zig +++ b/lib/std/crypto/aes/soft.zig @@ -15,20 +15,20 @@ pub const Block = struct { /// Convert a byte sequence into an internal representation. pub inline fn fromBytes(bytes: *const [16]u8) Block { - const s0 = mem.readIntLittle(u32, bytes[0..4]); - const s1 = mem.readIntLittle(u32, bytes[4..8]); - const s2 = mem.readIntLittle(u32, bytes[8..12]); - const s3 = mem.readIntLittle(u32, bytes[12..16]); + const s0 = mem.readInt(u32, bytes[0..4], .Little); + const s1 = mem.readInt(u32, bytes[4..8], .Little); + const s2 = mem.readInt(u32, bytes[8..12], .Little); + const s3 = mem.readInt(u32, bytes[12..16], .Little); return Block{ .repr = BlockVec{ s0, s1, s2, s3 } }; } /// Convert the internal representation of a block into a byte sequence. pub inline fn toBytes(block: Block) [16]u8 { var bytes: [16]u8 = undefined; - mem.writeIntLittle(u32, bytes[0..4], block.repr[0]); - mem.writeIntLittle(u32, bytes[4..8], block.repr[1]); - mem.writeIntLittle(u32, bytes[8..12], block.repr[2]); - mem.writeIntLittle(u32, bytes[12..16], block.repr[3]); + mem.writeInt(u32, bytes[0..4], block.repr[0], .Little); + mem.writeInt(u32, bytes[4..8], block.repr[1], .Little); + mem.writeInt(u32, bytes[8..12], block.repr[2], .Little); + mem.writeInt(u32, bytes[12..16], block.repr[3], .Little); return bytes; } @@ -123,13 +123,13 @@ pub const Block = struct { // Last round uses s-box directly and XORs to produce output. var x: [4]u8 = undefined; x = sbox_lookup(&sbox_encrypt, @as(u8, @truncate(s0)), @as(u8, @truncate(s1 >> 8)), @as(u8, @truncate(s2 >> 16)), @as(u8, @truncate(s3 >> 24))); - var t0 = mem.readIntLittle(u32, &x); + var t0 = mem.readInt(u32, &x, .Little); x = sbox_lookup(&sbox_encrypt, @as(u8, @truncate(s1)), @as(u8, @truncate(s2 >> 8)), @as(u8, @truncate(s3 >> 16)), @as(u8, @truncate(s0 >> 24))); - var t1 = mem.readIntLittle(u32, &x); + var t1 = mem.readInt(u32, &x, .Little); x = sbox_lookup(&sbox_encrypt, @as(u8, @truncate(s2)), @as(u8, @truncate(s3 >> 8)), @as(u8, @truncate(s0 >> 16)), @as(u8, @truncate(s1 >> 24))); - var t2 = mem.readIntLittle(u32, &x); + var t2 = mem.readInt(u32, &x, .Little); x = sbox_lookup(&sbox_encrypt, @as(u8, @truncate(s3)), @as(u8, @truncate(s0 >> 8)), @as(u8, @truncate(s1 >> 16)), @as(u8, @truncate(s2 >> 24))); - var t3 = mem.readIntLittle(u32, &x); + var t3 = mem.readInt(u32, &x, .Little); t0 ^= round_key.repr[0]; t1 ^= round_key.repr[1]; @@ -219,13 +219,13 @@ pub const Block = struct { // Last round uses s-box directly and XORs to produce output. var x: [4]u8 = undefined; x = sbox_lookup(&sbox_decrypt, @as(u8, @truncate(s0)), @as(u8, @truncate(s3 >> 8)), @as(u8, @truncate(s2 >> 16)), @as(u8, @truncate(s1 >> 24))); - var t0 = mem.readIntLittle(u32, &x); + var t0 = mem.readInt(u32, &x, .Little); x = sbox_lookup(&sbox_decrypt, @as(u8, @truncate(s1)), @as(u8, @truncate(s0 >> 8)), @as(u8, @truncate(s3 >> 16)), @as(u8, @truncate(s2 >> 24))); - var t1 = mem.readIntLittle(u32, &x); + var t1 = mem.readInt(u32, &x, .Little); x = sbox_lookup(&sbox_decrypt, @as(u8, @truncate(s2)), @as(u8, @truncate(s1 >> 8)), @as(u8, @truncate(s0 >> 16)), @as(u8, @truncate(s3 >> 24))); - var t2 = mem.readIntLittle(u32, &x); + var t2 = mem.readInt(u32, &x, .Little); x = sbox_lookup(&sbox_decrypt, @as(u8, @truncate(s3)), @as(u8, @truncate(s2 >> 8)), @as(u8, @truncate(s1 >> 16)), @as(u8, @truncate(s0 >> 24))); - var t3 = mem.readIntLittle(u32, &x); + var t3 = mem.readInt(u32, &x, .Little); t0 ^= round_key.repr[0]; t1 ^= round_key.repr[1]; @@ -349,14 +349,14 @@ fn KeySchedule(comptime Aes: type) type { // Apply sbox_encrypt to each byte in w. fn func(w: u32) u32 { const x = sbox_lookup(&sbox_key_schedule, @as(u8, @truncate(w)), @as(u8, @truncate(w >> 8)), @as(u8, @truncate(w >> 16)), @as(u8, @truncate(w >> 24))); - return mem.readIntLittle(u32, &x); + return mem.readInt(u32, &x, .Little); } }.func; var round_keys: [rounds + 1]Block = undefined; comptime var i: usize = 0; inline while (i < words_in_key) : (i += 1) { - round_keys[i / 4].repr[i % 4] = mem.readIntBig(u32, key[4 * i ..][0..4]); + round_keys[i / 4].repr[i % 4] = mem.readInt(u32, key[4 * i ..][0..4], .Big); } inline while (i < round_keys.len * 4) : (i += 1) { var t = round_keys[(i - 1) / 4].repr[(i - 1) % 4]; diff --git a/lib/std/crypto/aes_gcm.zig b/lib/std/crypto/aes_gcm.zig index 1715636bed..5545d1c0e8 100644 --- a/lib/std/crypto/aes_gcm.zig +++ b/lib/std/crypto/aes_gcm.zig @@ -33,7 +33,7 @@ fn AesGcm(comptime Aes: anytype) type { var t: [16]u8 = undefined; var j: [16]u8 = undefined; j[0..nonce_length].* = npub; - mem.writeIntBig(u32, j[nonce_length..][0..4], 1); + mem.writeInt(u32, j[nonce_length..][0..4], 1, .Big); aes.encrypt(&t, &j); const block_count = (math.divCeil(usize, ad.len, Ghash.block_length) catch unreachable) + (math.divCeil(usize, c.len, Ghash.block_length) catch unreachable) + 1; @@ -41,14 +41,14 @@ fn AesGcm(comptime Aes: anytype) type { mac.update(ad); mac.pad(); - mem.writeIntBig(u32, j[nonce_length..][0..4], 2); + mem.writeInt(u32, j[nonce_length..][0..4], 2, .Big); modes.ctr(@TypeOf(aes), aes, c, m, j, std.builtin.Endian.Big); mac.update(c[0..m.len][0..]); mac.pad(); var final_block = h; - mem.writeIntBig(u64, final_block[0..8], ad.len * 8); - mem.writeIntBig(u64, final_block[8..16], m.len * 8); + mem.writeInt(u64, final_block[0..8], ad.len * 8, .Big); + mem.writeInt(u64, final_block[8..16], m.len * 8, .Big); mac.update(&final_block); mac.final(tag); for (t, 0..) |x, i| { @@ -75,7 +75,7 @@ fn AesGcm(comptime Aes: anytype) type { var t: [16]u8 = undefined; var j: [16]u8 = undefined; j[0..nonce_length].* = npub; - mem.writeIntBig(u32, j[nonce_length..][0..4], 1); + mem.writeInt(u32, j[nonce_length..][0..4], 1, .Big); aes.encrypt(&t, &j); const block_count = (math.divCeil(usize, ad.len, Ghash.block_length) catch unreachable) + (math.divCeil(usize, c.len, Ghash.block_length) catch unreachable) + 1; @@ -87,8 +87,8 @@ fn AesGcm(comptime Aes: anytype) type { mac.pad(); var final_block = h; - mem.writeIntBig(u64, final_block[0..8], ad.len * 8); - mem.writeIntBig(u64, final_block[8..16], m.len * 8); + mem.writeInt(u64, final_block[0..8], ad.len * 8, .Big); + mem.writeInt(u64, final_block[8..16], m.len * 8, .Big); mac.update(&final_block); var computed_tag: [Ghash.mac_length]u8 = undefined; mac.final(&computed_tag); @@ -103,7 +103,7 @@ fn AesGcm(comptime Aes: anytype) type { return error.AuthenticationFailed; } - mem.writeIntBig(u32, j[nonce_length..][0..4], 2); + mem.writeInt(u32, j[nonce_length..][0..4], 2, .Big); modes.ctr(@TypeOf(aes), aes, m, c, j, std.builtin.Endian.Big); } }; diff --git a/lib/std/crypto/aes_ocb.zig b/lib/std/crypto/aes_ocb.zig index 26f98ff362..65162c01ee 100644 --- a/lib/std/crypto/aes_ocb.zig +++ b/lib/std/crypto/aes_ocb.zig @@ -29,10 +29,10 @@ fn AesOcb(comptime Aes: anytype) type { upto: usize, inline fn double(l: Block) Block { - const l_ = mem.readIntBig(u128, &l); + const l_ = mem.readInt(u128, &l, .Big); const l_2 = (l_ << 1) ^ (0x87 & -%(l_ >> 127)); var l2: Block = undefined; - mem.writeIntBig(u128, &l2, l_2); + mem.writeInt(u128, &l2, l_2, .Big); return l2; } @@ -94,10 +94,10 @@ fn AesOcb(comptime Aes: anytype) type { nx[15] &= 0xc0; var ktop_: Block = undefined; aes_enc_ctx.encrypt(&ktop_, &nx); - const ktop = mem.readIntBig(u128, &ktop_); + const ktop = mem.readInt(u128, &ktop_, .Big); var stretch = (@as(u192, ktop) << 64) | @as(u192, @as(u64, @truncate(ktop >> 64)) ^ @as(u64, @truncate(ktop >> 56))); var offset: Block = undefined; - mem.writeIntBig(u128, &offset, @as(u128, @truncate(stretch >> (64 - @as(u7, bottom))))); + mem.writeInt(u128, &offset, @as(u128, @truncate(stretch >> (64 - @as(u7, bottom)))), .Big); return offset; } diff --git a/lib/std/crypto/argon2.zig b/lib/std/crypto/argon2.zig index 3625bb39fd..09835011c7 100644 --- a/lib/std/crypto/argon2.zig +++ b/lib/std/crypto/argon2.zig @@ -110,27 +110,27 @@ fn initHash( var parameters: [24]u8 = undefined; var tmp: [4]u8 = undefined; var b2 = Blake2b512.init(.{}); - mem.writeIntLittle(u32, parameters[0..4], params.p); - mem.writeIntLittle(u32, parameters[4..8], @as(u32, @intCast(dk_len))); - mem.writeIntLittle(u32, parameters[8..12], params.m); - mem.writeIntLittle(u32, parameters[12..16], params.t); - mem.writeIntLittle(u32, parameters[16..20], version); - mem.writeIntLittle(u32, parameters[20..24], @intFromEnum(mode)); + mem.writeInt(u32, parameters[0..4], params.p, .Little); + mem.writeInt(u32, parameters[4..8], @as(u32, @intCast(dk_len)), .Little); + mem.writeInt(u32, parameters[8..12], params.m, .Little); + mem.writeInt(u32, parameters[12..16], params.t, .Little); + mem.writeInt(u32, parameters[16..20], version, .Little); + mem.writeInt(u32, parameters[20..24], @intFromEnum(mode), .Little); b2.update(¶meters); - mem.writeIntLittle(u32, &tmp, @as(u32, @intCast(password.len))); + mem.writeInt(u32, &tmp, @as(u32, @intCast(password.len)), .Little); b2.update(&tmp); b2.update(password); - mem.writeIntLittle(u32, &tmp, @as(u32, @intCast(salt.len))); + mem.writeInt(u32, &tmp, @as(u32, @intCast(salt.len)), .Little); b2.update(&tmp); b2.update(salt); const secret = params.secret orelse ""; std.debug.assert(secret.len <= max_int); - mem.writeIntLittle(u32, &tmp, @as(u32, @intCast(secret.len))); + mem.writeInt(u32, &tmp, @as(u32, @intCast(secret.len)), .Little); b2.update(&tmp); b2.update(secret); const ad = params.ad orelse ""; std.debug.assert(ad.len <= max_int); - mem.writeIntLittle(u32, &tmp, @as(u32, @intCast(ad.len))); + mem.writeInt(u32, &tmp, @as(u32, @intCast(ad.len)), .Little); b2.update(&tmp); b2.update(ad); b2.final(h0[0..Blake2b512.digest_length]); @@ -140,7 +140,7 @@ fn initHash( fn blake2bLong(out: []u8, in: []const u8) void { const H = Blake2b512; var outlen_bytes: [4]u8 = undefined; - mem.writeIntLittle(u32, &outlen_bytes, @as(u32, @intCast(out.len))); + mem.writeInt(u32, &outlen_bytes, @as(u32, @intCast(out.len)), .Little); var out_buf: [H.digest_length]u8 = undefined; @@ -183,18 +183,18 @@ fn initBlocks( var lane: u24 = 0; while (lane < threads) : (lane += 1) { const j = lane * (memory / threads); - mem.writeIntLittle(u32, h0[Blake2b512.digest_length + 4 ..][0..4], lane); + mem.writeInt(u32, h0[Blake2b512.digest_length + 4 ..][0..4], lane, .Little); - mem.writeIntLittle(u32, h0[Blake2b512.digest_length..][0..4], 0); + mem.writeInt(u32, h0[Blake2b512.digest_length..][0..4], 0, .Little); blake2bLong(&block0, h0); for (&blocks.items[j + 0], 0..) |*v, i| { - v.* = mem.readIntLittle(u64, block0[i * 8 ..][0..8]); + v.* = mem.readInt(u64, block0[i * 8 ..][0..8], .Little); } - mem.writeIntLittle(u32, h0[Blake2b512.digest_length..][0..4], 1); + mem.writeInt(u32, h0[Blake2b512.digest_length..][0..4], 1, .Little); blake2bLong(&block0, h0); for (&blocks.items[j + 1], 0..) |*v, i| { - v.* = mem.readIntLittle(u64, block0[i * 8 ..][0..8]); + v.* = mem.readInt(u64, block0[i * 8 ..][0..8], .Little); } } } @@ -433,7 +433,7 @@ fn finalize( } var block: [1024]u8 = undefined; for (blocks.items[memory - 1], 0..) |v, i| { - mem.writeIntLittle(u64, block[i * 8 ..][0..8], v); + mem.writeInt(u64, block[i * 8 ..][0..8], v, .Little); } blake2bLong(out, &block); } diff --git a/lib/std/crypto/ascon.zig b/lib/std/crypto/ascon.zig index 8aa0b109f2..673359ad80 100644 --- a/lib/std/crypto/ascon.zig +++ b/lib/std/crypto/ascon.zig @@ -8,11 +8,12 @@ //! It is not meant to be used directly, but as a building block for symmetric cryptography. const std = @import("std"); -const builtin = std.builtin; +const builtin = @import("builtin"); const debug = std.debug; const mem = std.mem; const testing = std.testing; const rotr = std.math.rotr; +const native_endian = builtin.cpu.arch.endian(); /// An Ascon state. /// @@ -20,7 +21,7 @@ const rotr = std.math.rotr; /// /// The NIST submission (v1.2) serializes these words as big-endian, /// but software implementations are free to use native endianness. -pub fn State(comptime endian: builtin.Endian) type { +pub fn State(comptime endian: std.builtin.Endian) type { return struct { const Self = @This(); @@ -133,14 +134,14 @@ pub fn State(comptime endian: builtin.Endian) type { var i: usize = 0; while (i + 8 <= in.len) : (i += 8) { - const x = mem.readIntNative(u64, in[i..][0..8]) ^ mem.nativeTo(u64, self.st[i / 8], endian); - mem.writeIntNative(u64, out[i..][0..8], x); + const x = mem.readInt(u64, in[i..][0..8], native_endian) ^ mem.nativeTo(u64, self.st[i / 8], endian); + mem.writeInt(u64, out[i..][0..8], x, native_endian); } if (i < in.len) { var padded = [_]u8{0} ** 8; @memcpy(padded[0 .. in.len - i], in[i..]); - const x = mem.readIntNative(u64, &padded) ^ mem.nativeTo(u64, self.st[i / 8], endian); - mem.writeIntNative(u64, &padded, x); + const x = mem.readInt(u64, &padded, native_endian) ^ mem.nativeTo(u64, self.st[i / 8], endian); + mem.writeInt(u64, &padded, x, native_endian); @memcpy(out[i..], padded[0 .. in.len - i]); } } diff --git a/lib/std/crypto/bcrypt.zig b/lib/std/crypto/bcrypt.zig index ce3a5aec79..8da09ff5c9 100644 --- a/lib/std/crypto/bcrypt.zig +++ b/lib/std/crypto/bcrypt.zig @@ -451,7 +451,7 @@ pub fn bcrypt( var ct: [ct_length]u8 = undefined; for (cdata, 0..) |c, i| { - mem.writeIntBig(u32, ct[i * 4 ..][0..4], c); + mem.writeInt(u32, ct[i * 4 ..][0..4], c, .Big); } return ct[0..dk_length].*; } @@ -547,7 +547,7 @@ const pbkdf_prf = struct { // copy out var out: [32]u8 = undefined; for (cdata, 0..) |v, i| { - std.mem.writeIntLittle(u32, out[4 * i ..][0..4], v); + std.mem.writeInt(u32, out[4 * i ..][0..4], v, .Little); } // zap diff --git a/lib/std/crypto/blake2.zig b/lib/std/crypto/blake2.zig index ba07226d08..b17fdbc36e 100644 --- a/lib/std/crypto/blake2.zig +++ b/lib/std/crypto/blake2.zig @@ -85,12 +85,12 @@ pub fn Blake2s(comptime out_bits: usize) type { d.buf_len = 0; if (options.salt) |salt| { - d.h[4] ^= mem.readIntLittle(u32, salt[0..4]); - d.h[5] ^= mem.readIntLittle(u32, salt[4..8]); + d.h[4] ^= mem.readInt(u32, salt[0..4], .Little); + d.h[5] ^= mem.readInt(u32, salt[4..8], .Little); } if (options.context) |context| { - d.h[6] ^= mem.readIntLittle(u32, context[0..4]); - d.h[7] ^= mem.readIntLittle(u32, context[4..8]); + d.h[6] ^= mem.readInt(u32, context[0..4], .Little); + d.h[7] ^= mem.readInt(u32, context[4..8], .Little); } if (key_len > 0) { @memset(d.buf[key_len..], 0); @@ -143,7 +143,7 @@ pub fn Blake2s(comptime out_bits: usize) type { var v: [16]u32 = undefined; for (&m, 0..) |*r, i| { - r.* = mem.readIntLittle(u32, b[4 * i ..][0..4]); + r.* = mem.readInt(u32, b[4 * i ..][0..4], .Little); } var k: usize = 0; @@ -521,12 +521,12 @@ pub fn Blake2b(comptime out_bits: usize) type { d.buf_len = 0; if (options.salt) |salt| { - d.h[4] ^= mem.readIntLittle(u64, salt[0..8]); - d.h[5] ^= mem.readIntLittle(u64, salt[8..16]); + d.h[4] ^= mem.readInt(u64, salt[0..8], .Little); + d.h[5] ^= mem.readInt(u64, salt[8..16], .Little); } if (options.context) |context| { - d.h[6] ^= mem.readIntLittle(u64, context[0..8]); - d.h[7] ^= mem.readIntLittle(u64, context[8..16]); + d.h[6] ^= mem.readInt(u64, context[0..8], .Little); + d.h[7] ^= mem.readInt(u64, context[8..16], .Little); } if (key_len > 0) { @memset(d.buf[key_len..], 0); @@ -579,7 +579,7 @@ pub fn Blake2b(comptime out_bits: usize) type { var v: [16]u64 = undefined; for (&m, 0..) |*r, i| { - r.* = mem.readIntLittle(u64, b[8 * i ..][0..8]); + r.* = mem.readInt(u64, b[8 * i ..][0..8], .Little); } var k: usize = 0; diff --git a/lib/std/crypto/blake3.zig b/lib/std/crypto/blake3.zig index 6923ec378d..d33ab6aac1 100644 --- a/lib/std/crypto/blake3.zig +++ b/lib/std/crypto/blake3.zig @@ -212,7 +212,7 @@ fn first8Words(words: [16]u32) [8]u32 { fn wordsFromLittleEndianBytes(comptime count: usize, bytes: [count * 4]u8) [count]u32 { var words: [count]u32 = undefined; for (&words, 0..) |*word, i| { - word.* = mem.readIntSliceLittle(u32, bytes[4 * i ..]); + word.* = mem.readInt(u32, bytes[4 * i ..][0..4], .Little); } return words; } @@ -252,7 +252,7 @@ const Output = struct { var word_counter: usize = 0; while (out_word_it.next()) |out_word| { var word_bytes: [4]u8 = undefined; - mem.writeIntLittle(u32, &word_bytes, words[word_counter]); + mem.writeInt(u32, &word_bytes, words[word_counter], .Little); @memcpy(out_word, word_bytes[0..out_word.len]); word_counter += 1; } diff --git a/lib/std/crypto/chacha20.zig b/lib/std/crypto/chacha20.zig index 26743232cb..941bfefe48 100644 --- a/lib/std/crypto/chacha20.zig +++ b/lib/std/crypto/chacha20.zig @@ -87,10 +87,10 @@ fn ChaChaVecImpl(comptime rounds_nb: usize, comptime degree: comptime_int) type switch (degree) { 1 => { const constant_le = Lane{ - mem.readIntLittle(u32, c[0..4]), - mem.readIntLittle(u32, c[4..8]), - mem.readIntLittle(u32, c[8..12]), - mem.readIntLittle(u32, c[12..16]), + mem.readInt(u32, c[0..4], .Little), + mem.readInt(u32, c[4..8], .Little), + mem.readInt(u32, c[8..12], .Little), + mem.readInt(u32, c[12..16], .Little), }; return BlockVec{ constant_le, @@ -101,14 +101,14 @@ fn ChaChaVecImpl(comptime rounds_nb: usize, comptime degree: comptime_int) type }, 2 => { const constant_le = Lane{ - mem.readIntLittle(u32, c[0..4]), - mem.readIntLittle(u32, c[4..8]), - mem.readIntLittle(u32, c[8..12]), - mem.readIntLittle(u32, c[12..16]), - mem.readIntLittle(u32, c[0..4]), - mem.readIntLittle(u32, c[4..8]), - mem.readIntLittle(u32, c[8..12]), - mem.readIntLittle(u32, c[12..16]), + mem.readInt(u32, c[0..4], .Little), + mem.readInt(u32, c[4..8], .Little), + mem.readInt(u32, c[8..12], .Little), + mem.readInt(u32, c[12..16], .Little), + mem.readInt(u32, c[0..4], .Little), + mem.readInt(u32, c[4..8], .Little), + mem.readInt(u32, c[8..12], .Little), + mem.readInt(u32, c[12..16], .Little), }; const n1 = @addWithOverflow(d[0], 1); return BlockVec{ @@ -123,22 +123,22 @@ fn ChaChaVecImpl(comptime rounds_nb: usize, comptime degree: comptime_int) type const n2 = @addWithOverflow(d[0], 2); const n3 = @addWithOverflow(d[0], 3); const constant_le = Lane{ - mem.readIntLittle(u32, c[0..4]), - mem.readIntLittle(u32, c[4..8]), - mem.readIntLittle(u32, c[8..12]), - mem.readIntLittle(u32, c[12..16]), - mem.readIntLittle(u32, c[0..4]), - mem.readIntLittle(u32, c[4..8]), - mem.readIntLittle(u32, c[8..12]), - mem.readIntLittle(u32, c[12..16]), - mem.readIntLittle(u32, c[0..4]), - mem.readIntLittle(u32, c[4..8]), - mem.readIntLittle(u32, c[8..12]), - mem.readIntLittle(u32, c[12..16]), - mem.readIntLittle(u32, c[0..4]), - mem.readIntLittle(u32, c[4..8]), - mem.readIntLittle(u32, c[8..12]), - mem.readIntLittle(u32, c[12..16]), + mem.readInt(u32, c[0..4], .Little), + mem.readInt(u32, c[4..8], .Little), + mem.readInt(u32, c[8..12], .Little), + mem.readInt(u32, c[12..16], .Little), + mem.readInt(u32, c[0..4], .Little), + mem.readInt(u32, c[4..8], .Little), + mem.readInt(u32, c[8..12], .Little), + mem.readInt(u32, c[12..16], .Little), + mem.readInt(u32, c[0..4], .Little), + mem.readInt(u32, c[4..8], .Little), + mem.readInt(u32, c[8..12], .Little), + mem.readInt(u32, c[12..16], .Little), + mem.readInt(u32, c[0..4], .Little), + mem.readInt(u32, c[4..8], .Little), + mem.readInt(u32, c[8..12], .Little), + mem.readInt(u32, c[12..16], .Little), }; return BlockVec{ constant_le, @@ -218,10 +218,10 @@ fn ChaChaVecImpl(comptime rounds_nb: usize, comptime degree: comptime_int) type inline fn hashToBytes(comptime dm: usize, out: *[64 * dm]u8, x: BlockVec) void { for (0..dm) |d| { for (0..4) |i| { - mem.writeIntLittle(u32, out[64 * d + 16 * i + 0 ..][0..4], x[i][0 + 4 * d]); - mem.writeIntLittle(u32, out[64 * d + 16 * i + 4 ..][0..4], x[i][1 + 4 * d]); - mem.writeIntLittle(u32, out[64 * d + 16 * i + 8 ..][0..4], x[i][2 + 4 * d]); - mem.writeIntLittle(u32, out[64 * d + 16 * i + 12 ..][0..4], x[i][3 + 4 * d]); + mem.writeInt(u32, out[64 * d + 16 * i + 0 ..][0..4], x[i][0 + 4 * d], .Little); + mem.writeInt(u32, out[64 * d + 16 * i + 4 ..][0..4], x[i][1 + 4 * d], .Little); + mem.writeInt(u32, out[64 * d + 16 * i + 8 ..][0..4], x[i][2 + 4 * d], .Little); + mem.writeInt(u32, out[64 * d + 16 * i + 12 ..][0..4], x[i][3 + 4 * d], .Little); } } } @@ -309,20 +309,20 @@ fn ChaChaVecImpl(comptime rounds_nb: usize, comptime degree: comptime_int) type fn hchacha20(input: [16]u8, key: [32]u8) [32]u8 { var c: [4]u32 = undefined; for (c, 0..) |_, i| { - c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]); + c[i] = mem.readInt(u32, input[4 * i ..][0..4], .Little); } const ctx = initContext(keyToWords(key), c); var x: BlockVec = undefined; chacha20Core(x[0..], ctx); var out: [32]u8 = undefined; - mem.writeIntLittle(u32, out[0..4], x[0][0]); - mem.writeIntLittle(u32, out[4..8], x[0][1]); - mem.writeIntLittle(u32, out[8..12], x[0][2]); - mem.writeIntLittle(u32, out[12..16], x[0][3]); - mem.writeIntLittle(u32, out[16..20], x[3][0]); - mem.writeIntLittle(u32, out[20..24], x[3][1]); - mem.writeIntLittle(u32, out[24..28], x[3][2]); - mem.writeIntLittle(u32, out[28..32], x[3][3]); + mem.writeInt(u32, out[0..4], x[0][0], .Little); + mem.writeInt(u32, out[4..8], x[0][1], .Little); + mem.writeInt(u32, out[8..12], x[0][2], .Little); + mem.writeInt(u32, out[12..16], x[0][3], .Little); + mem.writeInt(u32, out[16..20], x[3][0], .Little); + mem.writeInt(u32, out[20..24], x[3][1], .Little); + mem.writeInt(u32, out[24..28], x[3][2], .Little); + mem.writeInt(u32, out[28..32], x[3][3], .Little); return out; } }; @@ -336,10 +336,10 @@ fn ChaChaNonVecImpl(comptime rounds_nb: usize) type { fn initContext(key: [8]u32, d: [4]u32) BlockVec { const c = "expand 32-byte k"; const constant_le = comptime [4]u32{ - mem.readIntLittle(u32, c[0..4]), - mem.readIntLittle(u32, c[4..8]), - mem.readIntLittle(u32, c[8..12]), - mem.readIntLittle(u32, c[12..16]), + mem.readInt(u32, c[0..4], .Little), + mem.readInt(u32, c[4..8], .Little), + mem.readInt(u32, c[8..12], .Little), + mem.readInt(u32, c[12..16], .Little), }; return BlockVec{ constant_le[0], constant_le[1], constant_le[2], constant_le[3], @@ -396,10 +396,10 @@ fn ChaChaNonVecImpl(comptime rounds_nb: usize) type { inline fn hashToBytes(out: *[64]u8, x: BlockVec) void { for (0..4) |i| { - mem.writeIntLittle(u32, out[16 * i + 0 ..][0..4], x[i * 4 + 0]); - mem.writeIntLittle(u32, out[16 * i + 4 ..][0..4], x[i * 4 + 1]); - mem.writeIntLittle(u32, out[16 * i + 8 ..][0..4], x[i * 4 + 2]); - mem.writeIntLittle(u32, out[16 * i + 12 ..][0..4], x[i * 4 + 3]); + mem.writeInt(u32, out[16 * i + 0 ..][0..4], x[i * 4 + 0], .Little); + mem.writeInt(u32, out[16 * i + 4 ..][0..4], x[i * 4 + 1], .Little); + mem.writeInt(u32, out[16 * i + 8 ..][0..4], x[i * 4 + 2], .Little); + mem.writeInt(u32, out[16 * i + 12 ..][0..4], x[i * 4 + 3], .Little); } } @@ -477,20 +477,20 @@ fn ChaChaNonVecImpl(comptime rounds_nb: usize) type { fn hchacha20(input: [16]u8, key: [32]u8) [32]u8 { var c: [4]u32 = undefined; for (c, 0..) |_, i| { - c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]); + c[i] = mem.readInt(u32, input[4 * i ..][0..4], .Little); } const ctx = initContext(keyToWords(key), c); var x: BlockVec = undefined; chacha20Core(x[0..], ctx); var out: [32]u8 = undefined; - mem.writeIntLittle(u32, out[0..4], x[0]); - mem.writeIntLittle(u32, out[4..8], x[1]); - mem.writeIntLittle(u32, out[8..12], x[2]); - mem.writeIntLittle(u32, out[12..16], x[3]); - mem.writeIntLittle(u32, out[16..20], x[12]); - mem.writeIntLittle(u32, out[20..24], x[13]); - mem.writeIntLittle(u32, out[24..28], x[14]); - mem.writeIntLittle(u32, out[28..32], x[15]); + mem.writeInt(u32, out[0..4], x[0], .Little); + mem.writeInt(u32, out[4..8], x[1], .Little); + mem.writeInt(u32, out[8..12], x[2], .Little); + mem.writeInt(u32, out[12..16], x[3], .Little); + mem.writeInt(u32, out[16..20], x[12], .Little); + mem.writeInt(u32, out[20..24], x[13], .Little); + mem.writeInt(u32, out[24..28], x[14], .Little); + mem.writeInt(u32, out[28..32], x[15], .Little); return out; } }; @@ -519,7 +519,7 @@ fn ChaChaImpl(comptime rounds_nb: usize) type { fn keyToWords(key: [32]u8) [8]u32 { var k: [8]u32 = undefined; for (0..8) |i| { - k[i] = mem.readIntLittle(u32, key[i * 4 ..][0..4]); + k[i] = mem.readInt(u32, key[i * 4 ..][0..4], .Little); } return k; } @@ -552,9 +552,9 @@ fn ChaChaIETF(comptime rounds_nb: usize) type { var d: [4]u32 = undefined; d[0] = counter; - d[1] = mem.readIntLittle(u32, nonce[0..4]); - d[2] = mem.readIntLittle(u32, nonce[4..8]); - d[3] = mem.readIntLittle(u32, nonce[8..12]); + d[1] = mem.readInt(u32, nonce[0..4], .Little); + d[2] = mem.readInt(u32, nonce[4..8], .Little); + d[3] = mem.readInt(u32, nonce[8..12], .Little); ChaChaImpl(rounds_nb).chacha20Xor(out, in, keyToWords(key), d, false); } @@ -564,9 +564,9 @@ fn ChaChaIETF(comptime rounds_nb: usize) type { var d: [4]u32 = undefined; d[0] = counter; - d[1] = mem.readIntLittle(u32, nonce[0..4]); - d[2] = mem.readIntLittle(u32, nonce[4..8]); - d[3] = mem.readIntLittle(u32, nonce[8..12]); + d[1] = mem.readInt(u32, nonce[0..4], .Little); + d[2] = mem.readInt(u32, nonce[4..8], .Little); + d[3] = mem.readInt(u32, nonce[8..12], .Little); ChaChaImpl(rounds_nb).chacha20Stream(out, keyToWords(key), d, false); } }; @@ -592,8 +592,8 @@ fn ChaChaWith64BitNonce(comptime rounds_nb: usize) type { var c: [4]u32 = undefined; c[0] = @as(u32, @truncate(counter)); c[1] = @as(u32, @truncate(counter >> 32)); - c[2] = mem.readIntLittle(u32, nonce[0..4]); - c[3] = mem.readIntLittle(u32, nonce[4..8]); + c[2] = mem.readInt(u32, nonce[0..4], .Little); + c[3] = mem.readInt(u32, nonce[4..8], .Little); ChaChaImpl(rounds_nb).chacha20Xor(out, in, k, c, true); } @@ -605,8 +605,8 @@ fn ChaChaWith64BitNonce(comptime rounds_nb: usize) type { var c: [4]u32 = undefined; c[0] = @as(u32, @truncate(counter)); c[1] = @as(u32, @truncate(counter >> 32)); - c[2] = mem.readIntLittle(u32, nonce[0..4]); - c[3] = mem.readIntLittle(u32, nonce[4..8]); + c[2] = mem.readInt(u32, nonce[0..4], .Little); + c[3] = mem.readInt(u32, nonce[4..8], .Little); ChaChaImpl(rounds_nb).chacha20Stream(out, k, c, true); } }; @@ -672,8 +672,8 @@ fn ChaChaPoly1305(comptime rounds_nb: usize) type { mac.update(zeros[0..padding]); } var lens: [16]u8 = undefined; - mem.writeIntLittle(u64, lens[0..8], ad.len); - mem.writeIntLittle(u64, lens[8..16], m.len); + mem.writeInt(u64, lens[0..8], ad.len, .Little); + mem.writeInt(u64, lens[8..16], m.len, .Little); mac.update(lens[0..]); mac.final(tag); } @@ -708,8 +708,8 @@ fn ChaChaPoly1305(comptime rounds_nb: usize) type { mac.update(zeros[0..padding]); } var lens: [16]u8 = undefined; - mem.writeIntLittle(u64, lens[0..8], ad.len); - mem.writeIntLittle(u64, lens[8..16], c.len); + mem.writeInt(u64, lens[0..8], ad.len, .Little); + mem.writeInt(u64, lens[8..16], c.len, .Little); mac.update(lens[0..]); var computed_tag: [16]u8 = undefined; mac.final(computed_tag[0..]); diff --git a/lib/std/crypto/cmac.zig b/lib/std/crypto/cmac.zig index 5f2d332c01..e28853de51 100644 --- a/lib/std/crypto/cmac.zig +++ b/lib/std/crypto/cmac.zig @@ -76,7 +76,7 @@ pub fn Cmac(comptime BlockCipher: type) type { fn double(l: Block) Block { const Int = std.meta.Int(.unsigned, block_length * 8); - const l_ = mem.readIntBig(Int, &l); + const l_ = mem.readInt(Int, &l, .Big); const l_2 = switch (block_length) { 8 => (l_ << 1) ^ (0x1b & -%(l_ >> 63)), // mod x^64 + x^4 + x^3 + x + 1 16 => (l_ << 1) ^ (0x87 & -%(l_ >> 127)), // mod x^128 + x^7 + x^2 + x + 1 @@ -85,7 +85,7 @@ pub fn Cmac(comptime BlockCipher: type) type { else => @compileError("unsupported block length"), }; var l2: Block = undefined; - mem.writeIntBig(Int, &l2, l_2); + mem.writeInt(Int, &l2, l_2, .Big); return l2; } }; diff --git a/lib/std/crypto/isap.zig b/lib/std/crypto/isap.zig index 0f27625a30..3555ae2467 100644 --- a/lib/std/crypto/isap.zig +++ b/lib/std/crypto/isap.zig @@ -55,9 +55,9 @@ pub const IsapA128A = struct { fn trickle(k: [16]u8, iv: [8]u8, y: []const u8, comptime out_len: usize) [out_len]u8 { var isap = IsapA128A{ .st = Ascon.initFromWords(.{ - mem.readIntBig(u64, k[0..8]), - mem.readIntBig(u64, k[8..16]), - mem.readIntBig(u64, iv[0..8]), + mem.readInt(u64, k[0..8], .Big), + mem.readInt(u64, k[8..16], .Big), + mem.readInt(u64, iv[0..8], .Big), 0, 0, }), @@ -85,9 +85,9 @@ pub const IsapA128A = struct { fn mac(c: []const u8, ad: []const u8, npub: [16]u8, key: [16]u8) [16]u8 { var isap = IsapA128A{ .st = Ascon.initFromWords(.{ - mem.readIntBig(u64, npub[0..8]), - mem.readIntBig(u64, npub[8..16]), - mem.readIntBig(u64, iv1[0..]), + mem.readInt(u64, npub[0..8], .Big), + mem.readInt(u64, npub[8..16], .Big), + mem.readInt(u64, iv1[0..], .Big), 0, 0, }), @@ -116,11 +116,11 @@ pub const IsapA128A = struct { const nb = trickle(key, iv3, npub[0..], 24); var isap = IsapA128A{ .st = Ascon.initFromWords(.{ - mem.readIntBig(u64, nb[0..8]), - mem.readIntBig(u64, nb[8..16]), - mem.readIntBig(u64, nb[16..24]), - mem.readIntBig(u64, npub[0..8]), - mem.readIntBig(u64, npub[8..16]), + mem.readInt(u64, nb[0..8], .Big), + mem.readInt(u64, nb[8..16], .Big), + mem.readInt(u64, nb[16..24], .Big), + mem.readInt(u64, npub[0..8], .Big), + mem.readInt(u64, npub[8..16], .Big), }), }; isap.st.permuteR(6); diff --git a/lib/std/crypto/keccak_p.zig b/lib/std/crypto/keccak_p.zig index f877a5f135..46d4f85ef9 100644 --- a/lib/std/crypto/keccak_p.zig +++ b/lib/std/crypto/keccak_p.zig @@ -1,7 +1,9 @@ const std = @import("std"); +const builtin = @import("builtin"); const assert = std.debug.assert; const math = std.math; const mem = std.mem; +const native_endian = builtin.cpu.arch.endian(); /// The Keccak-f permutation. pub fn KeccakF(comptime f: u11) type { @@ -43,7 +45,7 @@ pub fn KeccakF(comptime f: u11) type { pub fn init(bytes: [block_bytes]u8) Self { var self: Self = undefined; inline for (&self.st, 0..) |*r, i| { - r.* = mem.readIntLittle(T, bytes[@sizeOf(T) * i ..][0..@sizeOf(T)]); + r.* = mem.readInt(T, bytes[@sizeOf(T) * i ..][0..@sizeOf(T)], .Little); } return self; } @@ -64,12 +66,12 @@ pub fn KeccakF(comptime f: u11) type { pub fn setBytes(self: *Self, bytes: []const u8) void { var i: usize = 0; while (i + @sizeOf(T) <= bytes.len) : (i += @sizeOf(T)) { - self.st[i / @sizeOf(T)] = mem.readIntLittle(T, bytes[i..][0..@sizeOf(T)]); + self.st[i / @sizeOf(T)] = mem.readInt(T, bytes[i..][0..@sizeOf(T)], .Little); } if (i < bytes.len) { var padded = [_]u8{0} ** @sizeOf(T); @memcpy(padded[0 .. bytes.len - i], bytes[i..]); - self.st[i / @sizeOf(T)] = mem.readIntLittle(T, padded[0..]); + self.st[i / @sizeOf(T)] = mem.readInt(T, padded[0..], .Little); } } @@ -83,12 +85,12 @@ pub fn KeccakF(comptime f: u11) type { pub fn addBytes(self: *Self, bytes: []const u8) void { var i: usize = 0; while (i + @sizeOf(T) <= bytes.len) : (i += @sizeOf(T)) { - self.st[i / @sizeOf(T)] ^= mem.readIntLittle(T, bytes[i..][0..@sizeOf(T)]); + self.st[i / @sizeOf(T)] ^= mem.readInt(T, bytes[i..][0..@sizeOf(T)], .Little); } if (i < bytes.len) { var padded = [_]u8{0} ** @sizeOf(T); @memcpy(padded[0 .. bytes.len - i], bytes[i..]); - self.st[i / @sizeOf(T)] ^= mem.readIntLittle(T, padded[0..]); + self.st[i / @sizeOf(T)] ^= mem.readInt(T, padded[0..], .Little); } } @@ -96,11 +98,11 @@ pub fn KeccakF(comptime f: u11) type { pub fn extractBytes(self: *Self, out: []u8) void { var i: usize = 0; while (i + @sizeOf(T) <= out.len) : (i += @sizeOf(T)) { - mem.writeIntLittle(T, out[i..][0..@sizeOf(T)], self.st[i / @sizeOf(T)]); + mem.writeInt(T, out[i..][0..@sizeOf(T)], self.st[i / @sizeOf(T)], .Little); } if (i < out.len) { var padded = [_]u8{0} ** @sizeOf(T); - mem.writeIntLittle(T, padded[0..], self.st[i / @sizeOf(T)]); + mem.writeInt(T, padded[0..], self.st[i / @sizeOf(T)], .Little); @memcpy(out[i..], padded[0 .. out.len - i]); } } @@ -111,14 +113,14 @@ pub fn KeccakF(comptime f: u11) type { var i: usize = 0; while (i + @sizeOf(T) <= in.len) : (i += @sizeOf(T)) { - const x = mem.readIntNative(T, in[i..][0..@sizeOf(T)]) ^ mem.nativeToLittle(T, self.st[i / @sizeOf(T)]); - mem.writeIntNative(T, out[i..][0..@sizeOf(T)], x); + const x = mem.readInt(T, in[i..][0..@sizeOf(T)], native_endian) ^ mem.nativeToLittle(T, self.st[i / @sizeOf(T)]); + mem.writeInt(T, out[i..][0..@sizeOf(T)], x, native_endian); } if (i < in.len) { var padded = [_]u8{0} ** @sizeOf(T); @memcpy(padded[0 .. in.len - i], in[i..]); - const x = mem.readIntNative(T, &padded) ^ mem.nativeToLittle(T, self.st[i / @sizeOf(T)]); - mem.writeIntNative(T, &padded, x); + const x = mem.readInt(T, &padded, native_endian) ^ mem.nativeToLittle(T, self.st[i / @sizeOf(T)]); + mem.writeInt(T, &padded, x, native_endian); @memcpy(out[i..], padded[0 .. in.len - i]); } } diff --git a/lib/std/crypto/md5.zig b/lib/std/crypto/md5.zig index 839c7b5ed8..3c6d04ceaf 100644 --- a/lib/std/crypto/md5.zig +++ b/lib/std/crypto/md5.zig @@ -112,7 +112,7 @@ pub const Md5 = struct { d.round(d.buf[0..]); for (d.s, 0..) |s, j| { - mem.writeIntLittle(u32, out[4 * j ..][0..4], s); + mem.writeInt(u32, out[4 * j ..][0..4], s, .Little); } } @@ -121,7 +121,7 @@ pub const Md5 = struct { var i: usize = 0; while (i < 16) : (i += 1) { - s[i] = mem.readIntLittle(u32, b[i * 4 ..][0..4]); + s[i] = mem.readInt(u32, b[i * 4 ..][0..4], .Little); } var v: [4]u32 = [_]u32{ diff --git a/lib/std/crypto/pcurves/common.zig b/lib/std/crypto/pcurves/common.zig index edc437517c..6c775e3c1c 100644 --- a/lib/std/crypto/pcurves/common.zig +++ b/lib/std/crypto/pcurves/common.zig @@ -54,7 +54,7 @@ pub fn Field(comptime params: FieldParams) type { var s = if (endian == .Little) s_ else orderSwap(s_); const field_order_s = comptime fos: { var fos: [encoded_length]u8 = undefined; - mem.writeIntLittle(std.meta.Int(.unsigned, encoded_length * 8), &fos, field_order); + mem.writeInt(std.meta.Int(.unsigned, encoded_length * 8), &fos, field_order, .Little); break :fos fos; }; if (crypto.utils.timingSafeCompare(u8, &s, &field_order_s, .Little) != .lt) { @@ -95,14 +95,14 @@ pub fn Field(comptime params: FieldParams) type { /// Create a field element from an integer. pub fn fromInt(comptime x: IntRepr) NonCanonicalError!Fe { var s: [encoded_length]u8 = undefined; - mem.writeIntLittle(IntRepr, &s, x); + mem.writeInt(IntRepr, &s, x, .Little); return fromBytes(s, .Little); } /// Return the field element as an integer. pub fn toInt(fe: Fe) IntRepr { const s = fe.toBytes(.Little); - return mem.readIntLittle(IntRepr, &s); + return mem.readInt(IntRepr, &s, .Little); } /// Return true if the field element is zero. diff --git a/lib/std/crypto/pcurves/secp256k1.zig b/lib/std/crypto/pcurves/secp256k1.zig index b871306ade..926f3114aa 100644 --- a/lib/std/crypto/pcurves/secp256k1.zig +++ b/lib/std/crypto/pcurves/secp256k1.zig @@ -41,7 +41,7 @@ pub const Secp256k1 = struct { const lambda_s = s: { var buf: [32]u8 = undefined; - mem.writeIntLittle(u256, &buf, Endormorphism.lambda); + mem.writeInt(u256, &buf, Endormorphism.lambda, .Little); break :s buf; }; @@ -54,12 +54,12 @@ pub const Secp256k1 = struct { pub fn splitScalar(s: [32]u8, endian: std.builtin.Endian) NonCanonicalError!SplitScalar { const b1_neg_s = comptime s: { var buf: [32]u8 = undefined; - mem.writeIntLittle(u256, &buf, 303414439467246543595250775667605759171); + mem.writeInt(u256, &buf, 303414439467246543595250775667605759171, .Little); break :s buf; }; const b2_neg_s = comptime s: { var buf: [32]u8 = undefined; - mem.writeIntLittle(u256, &buf, scalar.field_order - 64502973549206556628585045361533709077); + mem.writeInt(u256, &buf, scalar.field_order - 64502973549206556628585045361533709077, .Little); break :s buf; }; const k = mem.readInt(u256, &s, endian); @@ -72,10 +72,10 @@ pub const Secp256k1 = struct { var buf: [32]u8 = undefined; - mem.writeIntLittle(u256, &buf, c1); + mem.writeInt(u256, &buf, c1, .Little); const c1x = try scalar.mul(buf, b1_neg_s, .Little); - mem.writeIntLittle(u256, &buf, c2); + mem.writeInt(u256, &buf, c2, .Little); const c2x = try scalar.mul(buf, b2_neg_s, .Little); const r2 = try scalar.add(c1x, c2x, .Little); diff --git a/lib/std/crypto/poly1305.zig b/lib/std/crypto/poly1305.zig index 5bcb75169d..f8764e1f22 100644 --- a/lib/std/crypto/poly1305.zig +++ b/lib/std/crypto/poly1305.zig @@ -22,12 +22,12 @@ pub const Poly1305 = struct { pub fn init(key: *const [key_length]u8) Poly1305 { return Poly1305{ .r = [_]u64{ - mem.readIntLittle(u64, key[0..8]) & 0x0ffffffc0fffffff, - mem.readIntLittle(u64, key[8..16]) & 0x0ffffffc0ffffffc, + mem.readInt(u64, key[0..8], .Little) & 0x0ffffffc0fffffff, + mem.readInt(u64, key[8..16], .Little) & 0x0ffffffc0ffffffc, }, .pad = [_]u64{ - mem.readIntLittle(u64, key[16..24]), - mem.readIntLittle(u64, key[24..32]), + mem.readInt(u64, key[16..24], .Little), + mem.readInt(u64, key[24..32], .Little), }, }; } @@ -56,8 +56,8 @@ pub const Poly1305 = struct { var i: usize = 0; while (i + block_length <= m.len) : (i += block_length) { - const in0 = mem.readIntLittle(u64, m[i..][0..8]); - const in1 = mem.readIntLittle(u64, m[i + 8 ..][0..8]); + const in0 = mem.readInt(u64, m[i..][0..8], .Little); + const in1 = mem.readInt(u64, m[i + 8 ..][0..8], .Little); // Add the input message to H var v = @addWithOverflow(h0, in0); @@ -182,8 +182,8 @@ pub const Poly1305 = struct { const c = ((h0 & st.pad[0]) | ((h0 | st.pad[0]) & ~st.h[0])) >> 63; st.h[1] = h1 +% st.pad[1] +% c; - mem.writeIntLittle(u64, out[0..8], st.h[0]); - mem.writeIntLittle(u64, out[8..16], st.h[1]); + mem.writeInt(u64, out[0..8], st.h[0], .Little); + mem.writeInt(u64, out[8..16], st.h[1], .Little); utils.secureZero(u8, @as([*]u8, @ptrCast(st))[0..@sizeOf(Poly1305)]); } diff --git a/lib/std/crypto/salsa20.zig b/lib/std/crypto/salsa20.zig index a2368fc3b6..6e170eb037 100644 --- a/lib/std/crypto/salsa20.zig +++ b/lib/std/crypto/salsa20.zig @@ -29,10 +29,10 @@ fn SalsaVecImpl(comptime rounds: comptime_int) type { fn initContext(key: [8]u32, d: [4]u32) BlockVec { const c = "expand 32-byte k"; const constant_le = comptime [4]u32{ - mem.readIntLittle(u32, c[0..4]), - mem.readIntLittle(u32, c[4..8]), - mem.readIntLittle(u32, c[8..12]), - mem.readIntLittle(u32, c[12..16]), + mem.readInt(u32, c[0..4], .Little), + mem.readInt(u32, c[4..8], .Little), + mem.readInt(u32, c[8..12], .Little), + mem.readInt(u32, c[12..16], .Little), }; return BlockVec{ Lane{ key[0], key[1], key[2], key[3] }, @@ -112,10 +112,10 @@ fn SalsaVecImpl(comptime rounds: comptime_int) type { fn hashToBytes(out: *[64]u8, x: BlockVec) void { var i: usize = 0; while (i < 4) : (i += 1) { - mem.writeIntLittle(u32, out[16 * i + 0 ..][0..4], x[i][0]); - mem.writeIntLittle(u32, out[16 * i + 4 ..][0..4], x[i][1]); - mem.writeIntLittle(u32, out[16 * i + 8 ..][0..4], x[i][2]); - mem.writeIntLittle(u32, out[16 * i + 12 ..][0..4], x[i][3]); + mem.writeInt(u32, out[16 * i + 0 ..][0..4], x[i][0], .Little); + mem.writeInt(u32, out[16 * i + 4 ..][0..4], x[i][1], .Little); + mem.writeInt(u32, out[16 * i + 8 ..][0..4], x[i][2], .Little); + mem.writeInt(u32, out[16 * i + 12 ..][0..4], x[i][3], .Little); } } @@ -158,20 +158,20 @@ fn SalsaVecImpl(comptime rounds: comptime_int) type { fn hsalsa(input: [16]u8, key: [32]u8) [32]u8 { var c: [4]u32 = undefined; for (c, 0..) |_, i| { - c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]); + c[i] = mem.readInt(u32, input[4 * i ..][0..4], .Little); } const ctx = initContext(keyToWords(key), c); var x: BlockVec = undefined; salsaCore(x[0..], ctx, false); var out: [32]u8 = undefined; - mem.writeIntLittle(u32, out[0..4], x[0][0]); - mem.writeIntLittle(u32, out[4..8], x[1][1]); - mem.writeIntLittle(u32, out[8..12], x[2][2]); - mem.writeIntLittle(u32, out[12..16], x[3][3]); - mem.writeIntLittle(u32, out[16..20], x[1][2]); - mem.writeIntLittle(u32, out[20..24], x[1][3]); - mem.writeIntLittle(u32, out[24..28], x[2][0]); - mem.writeIntLittle(u32, out[28..32], x[2][1]); + mem.writeInt(u32, out[0..4], x[0][0], .Little); + mem.writeInt(u32, out[4..8], x[1][1], .Little); + mem.writeInt(u32, out[8..12], x[2][2], .Little); + mem.writeInt(u32, out[12..16], x[3][3], .Little); + mem.writeInt(u32, out[16..20], x[1][2], .Little); + mem.writeInt(u32, out[20..24], x[1][3], .Little); + mem.writeInt(u32, out[24..28], x[2][0], .Little); + mem.writeInt(u32, out[28..32], x[2][1], .Little); return out; } }; @@ -184,10 +184,10 @@ fn SalsaNonVecImpl(comptime rounds: comptime_int) type { fn initContext(key: [8]u32, d: [4]u32) BlockVec { const c = "expand 32-byte k"; const constant_le = comptime [4]u32{ - mem.readIntLittle(u32, c[0..4]), - mem.readIntLittle(u32, c[4..8]), - mem.readIntLittle(u32, c[8..12]), - mem.readIntLittle(u32, c[12..16]), + mem.readInt(u32, c[0..4], .Little), + mem.readInt(u32, c[4..8], .Little), + mem.readInt(u32, c[8..12], .Little), + mem.readInt(u32, c[12..16], .Little), }; return BlockVec{ constant_le[0], key[0], key[1], key[2], @@ -241,7 +241,7 @@ fn SalsaNonVecImpl(comptime rounds: comptime_int) type { fn hashToBytes(out: *[64]u8, x: BlockVec) void { for (x, 0..) |w, i| { - mem.writeIntLittle(u32, out[i * 4 ..][0..4], w); + mem.writeInt(u32, out[i * 4 ..][0..4], w, .Little); } } @@ -283,20 +283,20 @@ fn SalsaNonVecImpl(comptime rounds: comptime_int) type { fn hsalsa(input: [16]u8, key: [32]u8) [32]u8 { var c: [4]u32 = undefined; for (c, 0..) |_, i| { - c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]); + c[i] = mem.readInt(u32, input[4 * i ..][0..4], .Little); } const ctx = initContext(keyToWords(key), c); var x: BlockVec = undefined; salsaCore(x[0..], ctx, false); var out: [32]u8 = undefined; - mem.writeIntLittle(u32, out[0..4], x[0]); - mem.writeIntLittle(u32, out[4..8], x[5]); - mem.writeIntLittle(u32, out[8..12], x[10]); - mem.writeIntLittle(u32, out[12..16], x[15]); - mem.writeIntLittle(u32, out[16..20], x[6]); - mem.writeIntLittle(u32, out[20..24], x[7]); - mem.writeIntLittle(u32, out[24..28], x[8]); - mem.writeIntLittle(u32, out[28..32], x[9]); + mem.writeInt(u32, out[0..4], x[0], .Little); + mem.writeInt(u32, out[4..8], x[5], .Little); + mem.writeInt(u32, out[8..12], x[10], .Little); + mem.writeInt(u32, out[12..16], x[15], .Little); + mem.writeInt(u32, out[16..20], x[6], .Little); + mem.writeInt(u32, out[20..24], x[7], .Little); + mem.writeInt(u32, out[24..28], x[8], .Little); + mem.writeInt(u32, out[28..32], x[9], .Little); return out; } }; @@ -308,7 +308,7 @@ fn keyToWords(key: [32]u8) [8]u32 { var k: [8]u32 = undefined; var i: usize = 0; while (i < 8) : (i += 1) { - k[i] = mem.readIntLittle(u32, key[i * 4 ..][0..4]); + k[i] = mem.readInt(u32, key[i * 4 ..][0..4], .Little); } return k; } @@ -335,8 +335,8 @@ pub fn Salsa(comptime rounds: comptime_int) type { debug.assert(in.len == out.len); var d: [4]u32 = undefined; - d[0] = mem.readIntLittle(u32, nonce[0..4]); - d[1] = mem.readIntLittle(u32, nonce[4..8]); + d[0] = mem.readInt(u32, nonce[0..4], .Little); + d[1] = mem.readInt(u32, nonce[4..8], .Little); d[2] = @as(u32, @truncate(counter)); d[3] = @as(u32, @truncate(counter >> 32)); SalsaImpl(rounds).salsaXor(out, in, keyToWords(key), d); diff --git a/lib/std/crypto/scrypt.zig b/lib/std/crypto/scrypt.zig index 8745a3b34e..4589902aaf 100644 --- a/lib/std/crypto/scrypt.zig +++ b/lib/std/crypto/scrypt.zig @@ -91,7 +91,7 @@ fn smix(b: []align(16) u8, r: u30, n: usize, v: []align(16) u32, xy: []align(16) var y: []align(16) u32 = @alignCast(xy[32 * r ..]); for (x, 0..) |*v1, j| { - v1.* = mem.readIntSliceLittle(u32, b[4 * j ..]); + v1.* = mem.readInt(u32, b[4 * j ..][0..4], .Little); } var tmp: [16]u32 align(16) = undefined; @@ -116,7 +116,7 @@ fn smix(b: []align(16) u8, r: u30, n: usize, v: []align(16) u32, xy: []align(16) } for (x, 0..) |v1, j| { - mem.writeIntLittle(u32, b[4 * j ..][0..4], v1); + mem.writeInt(u32, b[4 * j ..][0..4], v1, .Little); } } @@ -361,7 +361,7 @@ const crypt_format = struct { std.debug.assert(dst.len == decodedLen(src.len)); var i: usize = 0; while (i < src.len / 4) : (i += 1) { - mem.writeIntSliceLittle(u24, dst[i * 3 ..], try intDecode(u24, src[i * 4 ..][0..4])); + mem.writeInt(u24, dst[i * 3 ..][0..3], try intDecode(u24, src[i * 4 ..][0..4]), .Little); } const leftover = src[i * 4 ..]; var v: u24 = 0; @@ -377,7 +377,7 @@ const crypt_format = struct { std.debug.assert(dst.len == encodedLen(src.len)); var i: usize = 0; while (i < src.len / 3) : (i += 1) { - intEncode(dst[i * 4 ..][0..4], mem.readIntSliceLittle(u24, src[i * 3 ..])); + intEncode(dst[i * 4 ..][0..4], mem.readInt(u24, src[i * 3 ..][0..3], .Little)); } const leftover = src[i * 3 ..]; var v: u24 = 0; diff --git a/lib/std/crypto/sha1.zig b/lib/std/crypto/sha1.zig index ee892237a7..88a0a33262 100644 --- a/lib/std/crypto/sha1.zig +++ b/lib/std/crypto/sha1.zig @@ -111,7 +111,7 @@ pub const Sha1 = struct { d.round(d.buf[0..]); for (d.s, 0..) |s, j| { - mem.writeIntBig(u32, out[4 * j ..][0..4], s); + mem.writeInt(u32, out[4 * j ..][0..4], s, .Big); } } @@ -151,7 +151,7 @@ pub const Sha1 = struct { roundParam(0, 1, 2, 3, 4, 15), }; inline for (round0a) |r| { - s[r.i] = mem.readIntBig(u32, b[r.i * 4 ..][0..4]); + s[r.i] = mem.readInt(u32, b[r.i * 4 ..][0..4], .Big); 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)); diff --git a/lib/std/crypto/sha2.zig b/lib/std/crypto/sha2.zig index f87ea90d92..2beed0549b 100644 --- a/lib/std/crypto/sha2.zig +++ b/lib/std/crypto/sha2.zig @@ -171,7 +171,7 @@ fn Sha2x32(comptime params: Sha2Params32) type { const rr = d.s[0 .. params.digest_bits / 32]; for (rr, 0..) |s, j| { - mem.writeIntBig(u32, out[4 * j ..][0..4], s); + mem.writeInt(u32, out[4 * j ..][0..4], s, .Big); } } @@ -195,7 +195,7 @@ fn Sha2x32(comptime params: Sha2Params32) type { fn round(d: *Self, b: *const [64]u8) void { var s: [64]u32 align(16) = undefined; for (@as(*align(1) const [16]u32, @ptrCast(b)), 0..) |*elem, i| { - s[i] = mem.readIntBig(u32, mem.asBytes(elem)); + s[i] = mem.readInt(u32, mem.asBytes(elem), .Big); } if (!@inComptime()) { @@ -663,7 +663,7 @@ fn Sha2x64(comptime params: Sha2Params64) type { const rr = d.s[0 .. params.digest_bits / 64]; for (rr, 0..) |s, j| { - mem.writeIntBig(u64, out[8 * j ..][0..8], s); + mem.writeInt(u64, out[8 * j ..][0..8], s, .Big); } } @@ -678,7 +678,7 @@ fn Sha2x64(comptime params: Sha2Params64) type { var i: usize = 0; while (i < 16) : (i += 1) { - s[i] = mem.readIntBig(u64, b[i * 8 ..][0..8]); + s[i] = mem.readInt(u64, b[i * 8 ..][0..8], .Big); } while (i < 80) : (i += 1) { s[i] = s[i - 16] +% s[i - 7] +% diff --git a/lib/std/crypto/siphash.zig b/lib/std/crypto/siphash.zig index 4399587397..905fb2c383 100644 --- a/lib/std/crypto/siphash.zig +++ b/lib/std/crypto/siphash.zig @@ -56,8 +56,8 @@ fn SipHashStateless(comptime T: type, comptime c_rounds: usize, comptime d_round msg_len: u8, fn init(key: *const [key_length]u8) Self { - const k0 = mem.readIntLittle(u64, key[0..8]); - const k1 = mem.readIntLittle(u64, key[8..16]); + const k0 = mem.readInt(u64, key[0..8], .Little); + const k1 = mem.readInt(u64, key[8..16], .Little); var d = Self{ .v0 = k0 ^ 0x736f6d6570736575, @@ -124,7 +124,7 @@ fn SipHashStateless(comptime T: type, comptime c_rounds: usize, comptime d_round } fn round(self: *Self, b: [8]u8) void { - const m = mem.readIntLittle(u64, &b); + const m = mem.readInt(u64, &b, .Little); self.v3 ^= m; comptime var i: usize = 0; @@ -213,7 +213,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) /// Return an authentication tag for the current state /// Assumes `out` is less than or equal to `mac_length`. pub fn final(self: *Self, out: *[mac_length]u8) void { - mem.writeIntLittle(T, out, self.state.final(self.buf[0..self.buf_len])); + mem.writeInt(T, out, self.state.final(self.buf[0..self.buf_len]), .Little); } pub fn finalResult(self: *Self) [mac_length]u8 { diff --git a/lib/std/crypto/tls.zig b/lib/std/crypto/tls.zig index eb5a6b4c1a..35c49d500e 100644 --- a/lib/std/crypto/tls.zig +++ b/lib/std/crypto/tls.zig @@ -370,7 +370,7 @@ pub fn hkdfExpandLabel( const max_context_len = 255; const tls13 = "tls13 "; var buf: [2 + 1 + tls13.len + max_label_len + 1 + max_context_len]u8 = undefined; - mem.writeIntBig(u16, buf[0..2], len); + mem.writeInt(u16, buf[0..2], len, .Big); buf[2] = @as(u8, @intCast(tls13.len + label.len)); buf[3..][0..tls13.len].* = tls13.*; var i: usize = 3 + tls13.len; diff --git a/lib/std/crypto/tls/Client.zig b/lib/std/crypto/tls/Client.zig index 7671d06469..60c525ba70 100644 --- a/lib/std/crypto/tls/Client.zig +++ b/lib/std/crypto/tls/Client.zig @@ -1049,10 +1049,10 @@ pub fn readvAdvanced(c: *Client, stream: anytype, iovecs: []const std.os.iovec) } const ct: tls.ContentType = @enumFromInt(frag[in]); in += 1; - const legacy_version = mem.readIntBig(u16, frag[in..][0..2]); + const legacy_version = mem.readInt(u16, frag[in..][0..2], .Big); in += 2; _ = legacy_version; - const record_len = mem.readIntBig(u16, frag[in..][0..2]); + const record_len = mem.readInt(u16, frag[in..][0..2], .Big); if (record_len > max_ciphertext_len) return error.TlsRecordOverflow; in += 2; const end = in + record_len; @@ -1136,7 +1136,7 @@ pub fn readvAdvanced(c: *Client, stream: anytype, iovecs: []const std.os.iovec) while (true) { const handshake_type: tls.HandshakeType = @enumFromInt(cleartext[ct_i]); ct_i += 1; - const handshake_len = mem.readIntBig(u24, cleartext[ct_i..][0..3]); + const handshake_len = mem.readInt(u24, cleartext[ct_i..][0..3], .Big); ct_i += 3; const next_handshake_i = ct_i + handshake_len; if (next_handshake_i > cleartext.len - 1) diff --git a/lib/std/debug.zig b/lib/std/debug.zig index 5302105fe9..1bf1f7307c 100644 --- a/lib/std/debug.zig +++ b/lib/std/debug.zig @@ -1135,8 +1135,8 @@ pub fn readElfDebugInfo( const gnu_debuglink = try chopSlice(mapped_mem, shdr.sh_offset, shdr.sh_size); const debug_filename = mem.sliceTo(@as([*:0]const u8, @ptrCast(gnu_debuglink.ptr)), 0); const crc_offset = mem.alignForward(usize, @intFromPtr(&debug_filename[debug_filename.len]) + 1, 4) - @intFromPtr(gnu_debuglink.ptr); - const crc_bytes = gnu_debuglink[crc_offset .. crc_offset + 4]; - separate_debug_crc = mem.readIntSliceNative(u32, crc_bytes); + const crc_bytes = gnu_debuglink[crc_offset..][0..4]; + separate_debug_crc = mem.readInt(u32, crc_bytes, native_endian); separate_debug_filename = debug_filename; continue; } @@ -1868,10 +1868,10 @@ pub const DebugInfo = struct { elf.PT_NOTE => { // Look for .note.gnu.build-id const note_bytes = @as([*]const u8, @ptrFromInt(info.dlpi_addr + phdr.p_vaddr))[0..phdr.p_memsz]; - const name_size = mem.readIntSliceNative(u32, note_bytes[0..4]); + const name_size = mem.readInt(u32, note_bytes[0..4], native_endian); if (name_size != 4) continue; - const desc_size = mem.readIntSliceNative(u32, note_bytes[4..8]); - const note_type = mem.readIntSliceNative(u32, note_bytes[8..12]); + const desc_size = mem.readInt(u32, note_bytes[4..8], native_endian); + const note_type = mem.readInt(u32, note_bytes[8..12], native_endian); if (note_type != elf.NT_GNU_BUILD_ID) continue; if (!mem.eql(u8, "GNU\x00", note_bytes[12..16])) continue; context.build_id = note_bytes[16..][0..desc_size]; diff --git a/lib/std/dwarf.zig b/lib/std/dwarf.zig index 9a296d3d98..7b4aa0fdec 100644 --- a/lib/std/dwarf.zig +++ b/lib/std/dwarf.zig @@ -7,6 +7,7 @@ const mem = std.mem; const math = std.math; const leb = @import("leb128.zig"); const assert = std.debug.assert; +const native_endian = builtin.cpu.arch.endian(); pub const TAG = @import("dwarf/TAG.zig"); pub const AT = @import("dwarf/AT.zig"); @@ -1741,7 +1742,7 @@ pub const DwarfInfo = struct { context.cfa = switch (row.cfa.rule) { .val_offset => |offset| blk: { const register = row.cfa.register orelse return error.InvalidCFARule; - const value = mem.readIntSliceNative(usize, try abi.regBytes(context.thread_context, register, context.reg_context)); + const value = mem.readInt(usize, (try abi.regBytes(context.thread_context, register, context.reg_context))[0..@sizeOf(usize)], native_endian); break :blk try call_frame.applyOffset(value, offset); }, .expression => |expression| blk: { @@ -1814,11 +1815,11 @@ pub const DwarfInfo = struct { } if (has_return_address) { - context.pc = abi.stripInstructionPtrAuthCode(mem.readIntSliceNative(usize, try abi.regBytes( + context.pc = abi.stripInstructionPtrAuthCode(mem.readInt(usize, (try abi.regBytes( context.thread_context, cie.return_address_register, context.reg_context, - ))); + ))[0..@sizeOf(usize)], native_endian)); } else { context.pc = 0; } diff --git a/lib/std/dwarf/call_frame.zig b/lib/std/dwarf/call_frame.zig index f238fd178e..3b9c940aed 100644 --- a/lib/std/dwarf/call_frame.zig +++ b/lib/std/dwarf/call_frame.zig @@ -7,6 +7,7 @@ const dwarf = std.dwarf; const abi = dwarf.abi; const expressions = dwarf.expressions; const assert = std.debug.assert; +const native_endian = builtin.cpu.arch.endian(); const Opcode = enum(u8) { advance_loc = 0x1 << 6, @@ -386,12 +387,12 @@ pub const VirtualMachine = struct { const addr = try applyOffset(cfa, offset); if (expression_context.isValidMemory) |isValidMemory| if (!isValidMemory(addr)) return error.InvalidAddress; const ptr: *const usize = @ptrFromInt(addr); - mem.writeIntSliceNative(usize, out, ptr.*); + mem.writeInt(usize, out[0..@sizeOf(usize)], ptr.*, native_endian); } else return error.InvalidCFA; }, .val_offset => |offset| { if (context.cfa) |cfa| { - mem.writeIntSliceNative(usize, out, try applyOffset(cfa, offset)); + mem.writeInt(usize, out[0..@sizeOf(usize)], try applyOffset(cfa, offset), native_endian); } else return error.InvalidCFA; }, .register => |register| { @@ -409,14 +410,14 @@ pub const VirtualMachine = struct { if (!context.isValidMemory(addr)) return error.InvalidExpressionAddress; const ptr: *usize = @ptrFromInt(addr); - mem.writeIntSliceNative(usize, out, ptr.*); + mem.writeInt(usize, out[0..@sizeOf(usize)], ptr.*, native_endian); }, .val_expression => |expression| { context.stack_machine.reset(); const value = try context.stack_machine.run(expression, context.allocator, expression_context, context.cfa.?); if (value) |v| { if (v != .generic) return error.InvalidExpressionValue; - mem.writeIntSliceNative(usize, out, v.generic); + mem.writeInt(usize, out[0..@sizeOf(usize)], v.generic, native_endian); } else return error.NoExpressionValue; }, .architectural => return error.UnimplementedRegisterRule, diff --git a/lib/std/dwarf/expressions.zig b/lib/std/dwarf/expressions.zig index f89edc08a1..729ff0de9b 100644 --- a/lib/std/dwarf/expressions.zig +++ b/lib/std/dwarf/expressions.zig @@ -6,6 +6,7 @@ const dwarf = std.dwarf; const abi = dwarf.abi; const mem = std.mem; const assert = std.debug.assert; +const native_endian = builtin.cpu.arch.endian(); /// Expressions can be evaluated in different contexts, each requiring its own set of inputs. /// Callers should specify all the fields relevant to their context. If a field is required @@ -147,10 +148,10 @@ pub fn StackMachine(comptime options: ExpressionOptions) type { .regval_type => |regval_type| regval_type.value, .const_type => |const_type| { const value: u64 = switch (const_type.value_bytes.len) { - 1 => mem.readIntSliceNative(u8, const_type.value_bytes), - 2 => mem.readIntSliceNative(u16, const_type.value_bytes), - 4 => mem.readIntSliceNative(u32, const_type.value_bytes), - 8 => mem.readIntSliceNative(u64, const_type.value_bytes), + 1 => mem.readInt(u8, const_type.value_bytes[0..1], native_endian), + 2 => mem.readInt(u16, const_type.value_bytes[0..2], native_endian), + 4 => mem.readInt(u32, const_type.value_bytes[0..4], native_endian), + 8 => mem.readInt(u64, const_type.value_bytes[0..8], native_endian), else => return error.InvalidIntegralTypeSize, }; @@ -352,7 +353,7 @@ pub fn StackMachine(comptime options: ExpressionOptions) type { const debug_addr_index = operand.?.generic; const offset = context.compile_unit.?.addr_base + debug_addr_index; if (offset >= context.debug_addr.?.len) return error.InvalidExpression; - const value = mem.readIntSliceNative(usize, context.debug_addr.?[offset..][0..@sizeOf(usize)]); + const value = mem.readInt(usize, context.debug_addr.?[offset..][0..@sizeOf(usize)], native_endian); try self.stack.append(allocator, .{ .generic = value }); }, @@ -386,21 +387,21 @@ pub fn StackMachine(comptime options: ExpressionOptions) type { if (context.thread_context == null) return error.IncompleteExpressionContext; const base_register = operand.?.base_register; - var value: i64 = @intCast(mem.readIntSliceNative(usize, try abi.regBytes( + var value: i64 = @intCast(mem.readInt(usize, (try abi.regBytes( context.thread_context.?, base_register.base_register, context.reg_context, - ))); + ))[0..@sizeOf(usize)], native_endian)); value += base_register.offset; try self.stack.append(allocator, .{ .generic = @intCast(value) }); }, OP.regval_type => { const register_type = operand.?.register_type; - const value = mem.readIntSliceNative(usize, try abi.regBytes( + const value = mem.readInt(usize, (try abi.regBytes( context.thread_context.?, register_type.register, context.reg_context, - )); + ))[0..@sizeOf(usize)], native_endian); try self.stack.append(allocator, .{ .regval_type = .{ .type_offset = register_type.type_offset, @@ -756,7 +757,7 @@ pub fn StackMachine(comptime options: ExpressionOptions) type { var block_stream = std.io.fixedBufferStream(block); const register = (try readOperand(&block_stream, block[0], context)).?.register; - const value = mem.readIntSliceNative(usize, try abi.regBytes(context.thread_context.?, register, context.reg_context)); + const value = mem.readInt(usize, (try abi.regBytes(context.thread_context.?, register, context.reg_context))[0..@sizeOf(usize)], native_endian); try self.stack.append(allocator, .{ .generic = value }); } else { var stack_machine: Self = .{}; @@ -1121,9 +1122,9 @@ test "DWARF expressions" { var mock_debug_addr = std.ArrayList(u8).init(allocator); defer mock_debug_addr.deinit(); - try mock_debug_addr.writer().writeIntNative(u16, 0); - try mock_debug_addr.writer().writeIntNative(usize, input[11]); - try mock_debug_addr.writer().writeIntNative(usize, input[12]); + try mock_debug_addr.writer().writeInt(u16, 0, native_endian); + try mock_debug_addr.writer().writeInt(usize, input[11], native_endian); + try mock_debug_addr.writer().writeInt(usize, input[12], native_endian); const context = ExpressionContext{ .compile_unit = &mock_compile_unit, @@ -1185,7 +1186,7 @@ test "DWARF expressions" { // TODO: Test fbreg (once implemented): mock a DIE and point compile_unit.frame_base at it - mem.writeIntSliceNative(usize, reg_bytes, 0xee); + mem.writeInt(usize, reg_bytes[0..@sizeOf(usize)], 0xee, native_endian); (try abi.regValueNative(usize, &thread_context, abi.fpRegNum(reg_context), reg_context)).* = 1; (try abi.regValueNative(usize, &thread_context, abi.spRegNum(reg_context), reg_context)).* = 2; (try abi.regValueNative(usize, &thread_context, abi.ipRegNum(), reg_context)).* = 3; @@ -1538,7 +1539,7 @@ test "DWARF expressions" { const value: usize = @truncate(0xffeeffee_ffeeffee); var value_bytes: [options.addr_size]u8 = undefined; - mem.writeIntSliceNative(usize, &value_bytes, value); + mem.writeInt(usize, &value_bytes, value, native_endian); // Convert to generic type stack_machine.reset(); @@ -1613,7 +1614,7 @@ test "DWARF expressions" { }; if (abi.regBytes(&thread_context, 0, reg_context)) |reg_bytes| { - mem.writeIntSliceNative(usize, reg_bytes, 0xee); + mem.writeInt(usize, reg_bytes[0..@sizeOf(usize)], 0xee, native_endian); var sub_program = std.ArrayList(u8).init(allocator); defer sub_program.deinit(); diff --git a/lib/std/fmt/parse_float/FloatStream.zig b/lib/std/fmt/parse_float/FloatStream.zig index 803ac65e6d..3b1a33df3a 100644 --- a/lib/std/fmt/parse_float/FloatStream.zig +++ b/lib/std/fmt/parse_float/FloatStream.zig @@ -98,7 +98,7 @@ pub fn skipChars2(self: *FloatStream, c1: u8, c2: u8) void { } pub fn readU64Unchecked(self: FloatStream) u64 { - return std.mem.readIntSliceLittle(u64, self.slice[self.offset..]); + return std.mem.readInt(u64, self.slice[self.offset..][0..8], .Little); } pub fn readU64(self: FloatStream) ?u64 { diff --git a/lib/std/fmt/parse_float/decimal.zig b/lib/std/fmt/parse_float/decimal.zig index f8d736a065..57751903ab 100644 --- a/lib/std/fmt/parse_float/decimal.zig +++ b/lib/std/fmt/parse_float/decimal.zig @@ -260,7 +260,7 @@ pub fn Decimal(comptime T: type) type { if (!isEightDigits(v)) { break; } - std.mem.writeIntSliceLittle(u64, d.digits[d.num_digits..], v - 0x3030_3030_3030_3030); + std.mem.writeInt(u64, d.digits[d.num_digits..][0..8], v - 0x3030_3030_3030_3030, .Little); d.num_digits += 8; stream.advance(8); } diff --git a/lib/std/hash/cityhash.zig b/lib/std/hash/cityhash.zig index 2fab089095..5c6139fe5e 100644 --- a/lib/std/hash/cityhash.zig +++ b/lib/std/hash/cityhash.zig @@ -6,11 +6,11 @@ inline fn offsetPtr(ptr: [*]const u8, offset: usize) [*]const u8 { } fn fetch32(ptr: [*]const u8, offset: usize) u32 { - return std.mem.readIntLittle(u32, offsetPtr(ptr, offset)[0..4]); + return std.mem.readInt(u32, offsetPtr(ptr, offset)[0..4], .Little); } fn fetch64(ptr: [*]const u8, offset: usize) u64 { - return std.mem.readIntLittle(u64, offsetPtr(ptr, offset)[0..8]); + return std.mem.readInt(u64, offsetPtr(ptr, offset)[0..8], .Little); } pub const CityHash32 = struct { diff --git a/lib/std/hash/crc.zig b/lib/std/hash/crc.zig index cbd3c75d4d..56376ef675 100644 --- a/lib/std/hash/crc.zig +++ b/lib/std/hash/crc.zig @@ -163,7 +163,7 @@ pub fn Crc32WithPoly(comptime poly: Polynomial) type { const p = input[i..][0..8]; // Unrolling this way gives ~50Mb/s increase - self.crc ^= std.mem.readIntLittle(u32, p[0..4]); + self.crc ^= std.mem.readInt(u32, p[0..4], .Little); self.crc = lookup_tables[0][p[7]] ^ diff --git a/lib/std/hash/verify.zig b/lib/std/hash/verify.zig index 1a20d8d1a3..c3aae0bcd8 100644 --- a/lib/std/hash/verify.zig +++ b/lib/std/hash/verify.zig @@ -37,7 +37,7 @@ pub fn smhasher(comptime hash_fn: anytype) u32 { for (0..256) |i| { buf[i] = @intCast(i); const h = hashMaybeSeed(hash_fn, 256 - i, buf[0..i]); - std.mem.writeIntLittle(HashResult, buf_all[i * hash_size ..][0..hash_size], h); + std.mem.writeInt(HashResult, buf_all[i * hash_size ..][0..hash_size], h, .Little); } return @truncate(hashMaybeSeed(hash_fn, 0, buf_all[0..])); diff --git a/lib/std/hash/wyhash.zig b/lib/std/hash/wyhash.zig index 91cdf5007f..d5c96fefbb 100644 --- a/lib/std/hash/wyhash.zig +++ b/lib/std/hash/wyhash.zig @@ -131,7 +131,7 @@ pub const Wyhash = struct { inline fn read(comptime bytes: usize, data: []const u8) u64 { std.debug.assert(bytes <= 8); const T = std.meta.Int(.unsigned, 8 * bytes); - return @as(u64, std.mem.readIntLittle(T, data[0..bytes])); + return @as(u64, std.mem.readInt(T, data[0..bytes], .Little)); } inline fn mum(a: *u64, b: *u64) void { diff --git a/lib/std/hash/xxhash.zig b/lib/std/hash/xxhash.zig index 6ca57973a1..9e49c7c086 100644 --- a/lib/std/hash/xxhash.zig +++ b/lib/std/hash/xxhash.zig @@ -53,10 +53,10 @@ pub const XxHash64 = struct { } fn processStripe(self: *Accumulator, buf: *const [32]u8) void { - self.acc1 = round(self.acc1, mem.readIntLittle(u64, buf[0..8])); - self.acc2 = round(self.acc2, mem.readIntLittle(u64, buf[8..16])); - self.acc3 = round(self.acc3, mem.readIntLittle(u64, buf[16..24])); - self.acc4 = round(self.acc4, mem.readIntLittle(u64, buf[24..32])); + self.acc1 = round(self.acc1, mem.readInt(u64, buf[0..8], .Little)); + self.acc2 = round(self.acc2, mem.readInt(u64, buf[8..16], .Little)); + self.acc3 = round(self.acc3, mem.readInt(u64, buf[16..24], .Little)); + self.acc4 = round(self.acc4, mem.readInt(u64, buf[24..32], .Little)); } fn merge(self: Accumulator) u64 { @@ -139,7 +139,7 @@ pub const XxHash64 = struct { fn finalize8(v: u64, bytes: *const [8]u8) u64 { var acc = v; - const lane = mem.readIntLittle(u64, bytes); + const lane = mem.readInt(u64, bytes, .Little); acc ^= round(0, lane); acc = rotl(u64, acc, 27) *% prime_1; acc +%= prime_4; @@ -148,7 +148,7 @@ pub const XxHash64 = struct { fn finalize4(v: u64, bytes: *const [4]u8) u64 { var acc = v; - const lane = @as(u64, mem.readIntLittle(u32, bytes)); + const lane = @as(u64, mem.readInt(u32, bytes, .Little)); acc ^= lane *% prime_1; acc = rotl(u64, acc, 23) *% prime_2; acc +%= prime_3; @@ -291,10 +291,10 @@ pub const XxHash32 = struct { } fn processStripe(self: *Accumulator, buf: *const [16]u8) void { - self.acc1 = round(self.acc1, mem.readIntLittle(u32, buf[0..4])); - self.acc2 = round(self.acc2, mem.readIntLittle(u32, buf[4..8])); - self.acc3 = round(self.acc3, mem.readIntLittle(u32, buf[8..12])); - self.acc4 = round(self.acc4, mem.readIntLittle(u32, buf[12..16])); + self.acc1 = round(self.acc1, mem.readInt(u32, buf[0..4], .Little)); + self.acc2 = round(self.acc2, mem.readInt(u32, buf[4..8], .Little)); + self.acc3 = round(self.acc3, mem.readInt(u32, buf[8..12], .Little)); + self.acc4 = round(self.acc4, mem.readInt(u32, buf[12..16], .Little)); } fn merge(self: Accumulator) u32 { @@ -390,7 +390,7 @@ pub const XxHash32 = struct { fn finalize4(v: u32, bytes: *const [4]u8) u32 { var acc = v; - const lane = mem.readIntLittle(u32, bytes); + const lane = mem.readInt(u32, bytes, .Little); acc +%= lane *% prime_3; acc = rotl(u32, acc, 17) *% prime_4; return acc; diff --git a/lib/std/io.zig b/lib/std/io.zig index 8bbc8d6150..e19b2e0e16 100644 --- a/lib/std/io.zig +++ b/lib/std/io.zig @@ -269,22 +269,6 @@ pub fn GenericReader( return @errorCast(self.any().readBoundedBytes(num_bytes)); } - pub inline fn readIntNative(self: Self, comptime T: type) NoEofError!T { - return @errorCast(self.any().readIntNative(T)); - } - - pub inline fn readIntForeign(self: Self, comptime T: type) NoEofError!T { - return @errorCast(self.any().readIntForeign(T)); - } - - pub inline fn readIntLittle(self: Self, comptime T: type) NoEofError!T { - return @errorCast(self.any().readIntLittle(T)); - } - - pub inline fn readIntBig(self: Self, comptime T: type) NoEofError!T { - return @errorCast(self.any().readIntBig(T)); - } - pub inline fn readInt(self: Self, comptime T: type, endian: std.builtin.Endian) NoEofError!T { return @errorCast(self.any().readInt(T, endian)); } diff --git a/lib/std/io/Reader.zig b/lib/std/io/Reader.zig index 4a03eb0b54..4da04a3339 100644 --- a/lib/std/io/Reader.zig +++ b/lib/std/io/Reader.zig @@ -276,30 +276,8 @@ pub fn readBoundedBytes(self: Self, comptime num_bytes: usize) anyerror!std.Boun return result; } -/// Reads a native-endian integer -pub fn readIntNative(self: Self, comptime T: type) anyerror!T { - const bytes = try self.readBytesNoEof(@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))); - return mem.readIntNative(T, &bytes); -} - -/// Reads a foreign-endian integer -pub fn readIntForeign(self: Self, comptime T: type) anyerror!T { - const bytes = try self.readBytesNoEof(@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))); - return mem.readIntForeign(T, &bytes); -} - -pub fn readIntLittle(self: Self, comptime T: type) anyerror!T { - const bytes = try self.readBytesNoEof(@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))); - return mem.readIntLittle(T, &bytes); -} - -pub fn readIntBig(self: Self, comptime T: type) anyerror!T { - const bytes = try self.readBytesNoEof(@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))); - return mem.readIntBig(T, &bytes); -} - -pub fn readInt(self: Self, comptime T: type, endian: std.builtin.Endian) anyerror!T { - const bytes = try self.readBytesNoEof(@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))); +pub inline fn readInt(self: Self, comptime T: type, endian: std.builtin.Endian) anyerror!T { + const bytes = try self.readBytesNoEof(@divExact(@typeInfo(T).Int.bits, 8)); return mem.readInt(T, &bytes, endian); } diff --git a/lib/std/io/writer.zig b/lib/std/io/writer.zig index 41dcf9b6e7..f1c0efda90 100644 --- a/lib/std/io/writer.zig +++ b/lib/std/io/writer.zig @@ -45,34 +45,8 @@ pub fn Writer( } } - /// Write a native-endian integer. - pub fn writeIntNative(self: Self, comptime T: type, value: T) Error!void { - var bytes: [@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))]u8 = undefined; - mem.writeIntNative(std.math.ByteAlignedInt(@TypeOf(value)), &bytes, value); - return self.writeAll(&bytes); - } - - /// Write a foreign-endian integer. - pub fn writeIntForeign(self: Self, comptime T: type, value: T) Error!void { - var bytes: [@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))]u8 = undefined; - mem.writeIntForeign(std.math.ByteAlignedInt(@TypeOf(value)), &bytes, value); - return self.writeAll(&bytes); - } - - pub fn writeIntLittle(self: Self, comptime T: type, value: T) Error!void { - var bytes: [@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))]u8 = undefined; - mem.writeIntLittle(std.math.ByteAlignedInt(@TypeOf(value)), &bytes, value); - return self.writeAll(&bytes); - } - - pub fn writeIntBig(self: Self, comptime T: type, value: T) Error!void { - var bytes: [@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))]u8 = undefined; - mem.writeIntBig(std.math.ByteAlignedInt(@TypeOf(value)), &bytes, value); - return self.writeAll(&bytes); - } - - pub fn writeInt(self: Self, comptime T: type, value: T, endian: std.builtin.Endian) Error!void { - var bytes: [@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))]u8 = undefined; + pub inline fn writeInt(self: Self, comptime T: type, value: T, endian: std.builtin.Endian) Error!void { + var bytes: [@divExact(@typeInfo(T).Int.bits, 8)]u8 = undefined; mem.writeInt(std.math.ByteAlignedInt(@TypeOf(value)), &bytes, value, endian); return self.writeAll(&bytes); } diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 9d769d465b..fcc02b920d 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -1587,68 +1587,40 @@ pub fn readVarPackedInt( /// Reads an integer from memory with bit count specified by T. /// The bit count of T must be evenly divisible by 8. /// This function cannot fail and cannot cause undefined behavior. -/// Assumes the endianness of memory is native. This means the function can -/// simply pointer cast memory. -pub fn readIntNative(comptime T: type, bytes: *const [@divExact(@typeInfo(T).Int.bits, 8)]u8) T { - return @as(*align(1) const T, @ptrCast(bytes)).*; +pub inline fn readInt(comptime T: type, buffer: *const [@divExact(@typeInfo(T).Int.bits, 8)]u8, endian: Endian) T { + const value: T = @bitCast(buffer.*); + return if (endian == native_endian) value else @byteSwap(value); } -/// Reads an integer from memory with bit count specified by T. -/// The bit count of T must be evenly divisible by 8. -/// This function cannot fail and cannot cause undefined behavior. -/// Assumes the endianness of memory is foreign, so it must byte-swap. -pub fn readIntForeign(comptime T: type, bytes: *const [@divExact(@typeInfo(T).Int.bits, 8)]u8) T { - return @byteSwap(readIntNative(T, bytes)); +test readInt { + try testing.expect(readInt(u0, &[_]u8{}, .Big) == 0x0); + try testing.expect(readInt(u0, &[_]u8{}, .Little) == 0x0); + + try testing.expect(readInt(u8, &[_]u8{0x32}, .Big) == 0x32); + try testing.expect(readInt(u8, &[_]u8{0x12}, .Little) == 0x12); + + try testing.expect(readInt(u16, &[_]u8{ 0x12, 0x34 }, .Big) == 0x1234); + try testing.expect(readInt(u16, &[_]u8{ 0x12, 0x34 }, .Little) == 0x3412); + + try testing.expect(readInt(u72, &[_]u8{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x24 }, .Big) == 0x123456789abcdef024); + try testing.expect(readInt(u72, &[_]u8{ 0xec, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe }, .Little) == 0xfedcba9876543210ec); + + try testing.expect(readInt(i8, &[_]u8{0xff}, .Big) == -1); + try testing.expect(readInt(i8, &[_]u8{0xfe}, .Little) == -2); + + try testing.expect(readInt(i16, &[_]u8{ 0xff, 0xfd }, .Big) == -3); + try testing.expect(readInt(i16, &[_]u8{ 0xfc, 0xff }, .Little) == -4); } -pub const readIntLittle = switch (native_endian) { - .Little => readIntNative, - .Big => readIntForeign, -}; - -pub const readIntBig = switch (native_endian) { - .Little => readIntForeign, - .Big => readIntNative, -}; - -/// Asserts that bytes.len >= @typeInfo(T).Int.bits / 8. Reads the integer starting from index 0 +/// Asserts that buffer.len >= @typeInfo(T).Int.bits / 8. Reads the integer starting from index 0 /// and ignores extra bytes. /// The bit count of T must be evenly divisible by 8. -/// Assumes the endianness of memory is native. This means the function can -/// simply pointer cast memory. -pub fn readIntSliceNative(comptime T: type, bytes: []const u8) T { - const n = @divExact(@typeInfo(T).Int.bits, 8); - assert(bytes.len >= n); - return readIntNative(T, bytes[0..n]); -} - -/// Asserts that bytes.len >= @typeInfo(T).Int.bits / 8. Reads the integer starting from index 0 -/// and ignores extra bytes. -/// The bit count of T must be evenly divisible by 8. -/// Assumes the endianness of memory is foreign, so it must byte-swap. -pub fn readIntSliceForeign(comptime T: type, bytes: []const u8) T { - return @byteSwap(readIntSliceNative(T, bytes)); -} - -pub const readIntSliceLittle = switch (native_endian) { - .Little => readIntSliceNative, - .Big => readIntSliceForeign, -}; - -pub const readIntSliceBig = switch (native_endian) { - .Little => readIntSliceForeign, - .Big => readIntSliceNative, -}; - -/// Reads an integer from memory with bit count specified by T. -/// The bit count of T must be evenly divisible by 8. -/// This function cannot fail and cannot cause undefined behavior. -pub fn readInt(comptime T: type, bytes: *const [@divExact(@typeInfo(T).Int.bits, 8)]u8, endian: Endian) T { - if (endian == native_endian) { - return readIntNative(T, bytes); - } else { - return readIntForeign(T, bytes); - } +pub inline fn readIntSlice(comptime T: type, buffer: []const u8, endian: Endian) T { + const byte_len = @divExact(@typeInfo(T).Int.bits, 8); + return switch (endian) { + .Little => readInt(T, buffer[0..byte_len], endian), + .Big => readInt(T, buffer[buffer.len - byte_len ..], endian), + }; } fn readPackedIntLittle(comptime T: type, bytes: []const u8, bit_offset: usize) T { @@ -1668,7 +1640,7 @@ fn readPackedIntLittle(comptime T: type, bytes: []const u8, bit_offset: usize) T // Read by loading a LoadInt, and then follow it up with a 1-byte read // of the tail if bit_offset pushed us over a byte boundary. const read_bytes = bytes[bit_offset / 8 ..]; - const val = @as(uN, @truncate(readIntLittle(LoadInt, read_bytes[0..load_size]) >> bit_shift)); + const val = @as(uN, @truncate(readInt(LoadInt, read_bytes[0..load_size], .Little) >> bit_shift)); if (bit_shift > load_tail_bits) { const tail_bits = @as(Log2N, @intCast(bit_shift - load_tail_bits)); const tail_byte = read_bytes[load_size]; @@ -1696,7 +1668,7 @@ fn readPackedIntBig(comptime T: type, bytes: []const u8, bit_offset: usize) T { // of the tail if bit_offset pushed us over a byte boundary. const end = bytes.len - (bit_offset / 8); const read_bytes = bytes[(end - byte_count)..end]; - const val = @as(uN, @truncate(readIntBig(LoadInt, bytes[(end - load_size)..end][0..load_size]) >> bit_shift)); + const val = @as(uN, @truncate(readInt(LoadInt, bytes[(end - load_size)..end][0..load_size], .Big) >> bit_shift)); if (bit_shift > load_tail_bits) { const tail_bits = @as(Log2N, @intCast(bit_shift - load_tail_bits)); const tail_byte = if (bit_count < 8) @as(uN, @truncate(read_bytes[0])) else @as(uN, read_bytes[0]); @@ -1729,91 +1701,225 @@ pub fn readPackedInt(comptime T: type, bytes: []const u8, bit_offset: usize, end } } -/// Asserts that bytes.len >= @typeInfo(T).Int.bits / 8. Reads the integer starting from index 0 -/// and ignores extra bytes. -/// The bit count of T must be evenly divisible by 8. -pub fn readIntSlice(comptime T: type, bytes: []const u8, endian: Endian) T { - const n = @divExact(@typeInfo(T).Int.bits, 8); - assert(bytes.len >= n); - return readInt(T, bytes[0..n], endian); -} - test "comptime read/write int" { comptime { var bytes: [2]u8 = undefined; - writeIntLittle(u16, &bytes, 0x1234); - const result = readIntBig(u16, &bytes); + writeInt(u16, &bytes, 0x1234, .Little); + const result = readInt(u16, &bytes, .Big); try testing.expect(result == 0x3412); } comptime { var bytes: [2]u8 = undefined; - writeIntBig(u16, &bytes, 0x1234); - const result = readIntLittle(u16, &bytes); + writeInt(u16, &bytes, 0x1234, .Big); + const result = readInt(u16, &bytes, .Little); try testing.expect(result == 0x3412); } } -test "readIntBig and readIntLittle" { - if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; - if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; - - try testing.expect(readIntSliceBig(u0, &[_]u8{}) == 0x0); - try testing.expect(readIntSliceLittle(u0, &[_]u8{}) == 0x0); - - try testing.expect(readIntSliceBig(u8, &[_]u8{0x32}) == 0x32); - try testing.expect(readIntSliceLittle(u8, &[_]u8{0x12}) == 0x12); - - try testing.expect(readIntSliceBig(u16, &[_]u8{ 0x12, 0x34 }) == 0x1234); - try testing.expect(readIntSliceLittle(u16, &[_]u8{ 0x12, 0x34 }) == 0x3412); - - try testing.expect(readIntSliceBig(u72, &[_]u8{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x24 }) == 0x123456789abcdef024); - try testing.expect(readIntSliceLittle(u72, &[_]u8{ 0xec, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe }) == 0xfedcba9876543210ec); - - try testing.expect(readIntSliceBig(i8, &[_]u8{0xff}) == -1); - try testing.expect(readIntSliceLittle(i8, &[_]u8{0xfe}) == -2); - - try testing.expect(readIntSliceBig(i16, &[_]u8{ 0xff, 0xfd }) == -3); - try testing.expect(readIntSliceLittle(i16, &[_]u8{ 0xfc, 0xff }) == -4); -} - -/// Writes an integer to memory, storing it in twos-complement. -/// This function always succeeds, has defined behavior for all inputs, and -/// accepts any integer bit width. -/// This function stores in native endian, which means it is implemented as a simple -/// memory store. -pub fn writeIntNative(comptime T: type, buf: *[@as(u16, @intCast((@as(u17, @typeInfo(T).Int.bits) + 7) / 8))]u8, value: T) void { - @as(*align(1) T, @ptrCast(buf)).* = value; -} - /// Writes an integer to memory, storing it in twos-complement. /// This function always succeeds, has defined behavior for all inputs, but /// the integer bit width must be divisible by 8. -/// This function stores in foreign endian, which means it does a @byteSwap first. -pub fn writeIntForeign(comptime T: type, buf: *[@divExact(@typeInfo(T).Int.bits, 8)]u8, value: T) void { - writeIntNative(T, buf, @byteSwap(value)); +pub inline fn writeInt(comptime T: type, buffer: *[@divExact(@typeInfo(T).Int.bits, 8)]u8, value: T, endian: Endian) void { + buffer.* = @bitCast(if (endian == native_endian) value else @byteSwap(value)); } -pub const writeIntLittle = switch (native_endian) { - .Little => writeIntNative, - .Big => writeIntForeign, -}; +test writeInt { + var buf0: [0]u8 = undefined; + var buf1: [1]u8 = undefined; + var buf2: [2]u8 = undefined; + var buf9: [9]u8 = undefined; -pub const writeIntBig = switch (native_endian) { - .Little => writeIntForeign, - .Big => writeIntNative, -}; + writeInt(u0, &buf0, 0x0, .Big); + try testing.expect(eql(u8, buf0[0..], &[_]u8{})); + writeInt(u0, &buf0, 0x0, .Little); + try testing.expect(eql(u8, buf0[0..], &[_]u8{})); -/// Writes an integer to memory, storing it in twos-complement. -/// This function always succeeds, has defined behavior for all inputs, but -/// the integer bit width must be divisible by 8. -pub fn writeInt(comptime T: type, buffer: *[@divExact(@typeInfo(T).Int.bits, 8)]u8, value: T, endian: Endian) void { - if (endian == native_endian) { - return writeIntNative(T, buffer, value); - } else { - return writeIntForeign(T, buffer, value); + writeInt(u8, &buf1, 0x12, .Big); + try testing.expect(eql(u8, buf1[0..], &[_]u8{0x12})); + writeInt(u8, &buf1, 0x34, .Little); + try testing.expect(eql(u8, buf1[0..], &[_]u8{0x34})); + + writeInt(u16, &buf2, 0x1234, .Big); + try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0x12, 0x34 })); + writeInt(u16, &buf2, 0x5678, .Little); + try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0x78, 0x56 })); + + writeInt(u72, &buf9, 0x123456789abcdef024, .Big); + try testing.expect(eql(u8, buf9[0..], &[_]u8{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x24 })); + writeInt(u72, &buf9, 0xfedcba9876543210ec, .Little); + try testing.expect(eql(u8, buf9[0..], &[_]u8{ 0xec, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe })); + + writeInt(i8, &buf1, -1, .Big); + try testing.expect(eql(u8, buf1[0..], &[_]u8{0xff})); + writeInt(i8, &buf1, -2, .Little); + try testing.expect(eql(u8, buf1[0..], &[_]u8{0xfe})); + + writeInt(i16, &buf2, -3, .Big); + try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0xff, 0xfd })); + writeInt(i16, &buf2, -4, .Little); + try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0xfc, 0xff })); +} + +/// Writes a twos-complement integer to memory, with the specified endianness. +/// Asserts that buf.len >= @typeInfo(T).Int.bits / 8. +/// The bit count of T must be evenly divisible by 8. +/// Any extra bytes in buffer not part of the integer are set to zero, with +/// respect to endianness. To avoid the branch to check for extra buffer bytes, +/// use writeInt instead. +pub inline fn writeIntSlice(comptime T: type, buffer: []u8, value: T, endian: Endian) void { + const byte_len = @divExact(@typeInfo(T).Int.bits, 8); + switch (endian) { + .Little => { + writeInt(T, buffer[0..byte_len], value, endian); + @memset(buffer[byte_len..], 0); + }, + .Big => { + @memset(buffer[0 .. buffer.len - byte_len], 0); + writeInt(T, buffer[buffer.len - byte_len ..][0..byte_len], value, endian); + }, } } +test writeIntSlice { + try testWriteIntImpl(); + try comptime testWriteIntImpl(); +} +fn testWriteIntImpl() !void { + var bytes: [8]u8 = undefined; + + writeIntSlice(u0, bytes[0..], 0, .Big); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + })); + + writeIntSlice(u0, bytes[0..], 0, .Little); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + })); + + writeIntSlice(u64, bytes[0..], 0x12345678CAFEBABE, .Big); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x12, + 0x34, + 0x56, + 0x78, + 0xCA, + 0xFE, + 0xBA, + 0xBE, + })); + + writeIntSlice(u64, bytes[0..], 0xBEBAFECA78563412, .Little); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x12, + 0x34, + 0x56, + 0x78, + 0xCA, + 0xFE, + 0xBA, + 0xBE, + })); + + writeIntSlice(u32, bytes[0..], 0x12345678, .Big); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x00, + 0x00, + 0x00, + 0x00, + 0x12, + 0x34, + 0x56, + 0x78, + })); + + writeIntSlice(u32, bytes[0..], 0x78563412, .Little); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x12, + 0x34, + 0x56, + 0x78, + 0x00, + 0x00, + 0x00, + 0x00, + })); + + writeIntSlice(u16, bytes[0..], 0x1234, .Big); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x12, + 0x34, + })); + + writeIntSlice(u16, bytes[0..], 0x1234, .Little); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x34, + 0x12, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + })); + + writeIntSlice(i16, bytes[0..], @as(i16, -21555), .Little); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0xCD, + 0xAB, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + })); + + writeIntSlice(i16, bytes[0..], @as(i16, -21555), .Big); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xAB, + 0xCD, + })); + + writeIntSlice(u8, bytes[0..], 0x12, .Big); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x12, + })); + + writeIntSlice(u8, bytes[0..], 0x12, .Little); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x12, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + })); + + writeIntSlice(i8, bytes[0..], -1, .Big); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xff, + })); + + writeIntSlice(i8, bytes[0..], -1, .Little); + try testing.expect(eql(u8, &bytes, &[_]u8{ + 0xff, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + })); +} + fn writePackedIntLittle(comptime T: type, bytes: []u8, bit_offset: usize, value: T) void { const uN = std.meta.Int(.unsigned, @bitSizeOf(T)); const Log2N = std.math.Log2Int(T); @@ -1844,7 +1950,7 @@ fn writePackedIntLittle(comptime T: type, bytes: []u8, bit_offset: usize, value: write_value |= @as(StoreInt, tail) << (8 * (store_size - 1)); } - writeIntLittle(StoreInt, write_bytes[0..store_size], write_value); + writeInt(StoreInt, write_bytes[0..store_size], write_value, .Little); } fn writePackedIntBig(comptime T: type, bytes: []u8, bit_offset: usize, value: T) void { @@ -1879,7 +1985,7 @@ fn writePackedIntBig(comptime T: type, bytes: []u8, bit_offset: usize, value: T) write_value |= @as(StoreInt, tail) << (8 * (store_size - 1)); } - writeIntBig(StoreInt, write_bytes[(byte_count - store_size)..][0..store_size], write_value); + writeInt(StoreInt, write_bytes[(byte_count - store_size)..][0..store_size], write_value, .Big); } pub const writePackedIntNative = switch (native_endian) { @@ -1908,91 +2014,6 @@ pub fn writePackedInt(comptime T: type, bytes: []u8, bit_offset: usize, value: T } } -/// Writes a twos-complement little-endian integer to memory. -/// Asserts that buf.len >= @typeInfo(T).Int.bits / 8. -/// The bit count of T must be divisible by 8. -/// Any extra bytes in buffer after writing the integer are set to zero. To -/// avoid the branch to check for extra buffer bytes, use writeIntLittle -/// instead. -fn writeIntSliceLittleNative(comptime T: type, buffer: []u8, value: T) void { - assert(buffer.len >= @divExact(@typeInfo(T).Int.bits, 8)); - - if (@typeInfo(T).Int.bits == 0) { - return @memset(buffer, 0); - } else if (@typeInfo(T).Int.bits == 8) { - @memset(buffer, 0); - buffer[0] = @as(u8, @bitCast(value)); - return; - } - - const write_end = @divExact(@typeInfo(T).Int.bits, 8); - @as(*align(1) T, @ptrCast(buffer)).* = value; - @memset(buffer[write_end..], 0); -} - -fn writeIntSliceLittleForeign(comptime T: type, buffer: []u8, value: T) void { - return writeIntSliceLittleNative(T, buffer, @byteSwap(value)); -} - -pub const writeIntSliceLittle = switch (native_endian) { - .Little => writeIntSliceLittleNative, - .Big => writeIntSliceLittleForeign, -}; - -/// Writes a twos-complement big-endian integer to memory. -/// Asserts that buffer.len >= @typeInfo(T).Int.bits / 8. -/// The bit count of T must be divisible by 8. -/// Any extra bytes in buffer before writing the integer are set to zero. To -/// avoid the branch to check for extra buffer bytes, use writeIntBig instead. -fn writeIntSliceBigNative(comptime T: type, buffer: []u8, value: T) void { - assert(buffer.len >= @divExact(@typeInfo(T).Int.bits, 8)); - - if (@typeInfo(T).Int.bits == 0) { - return @memset(buffer, 0); - } else if (@typeInfo(T).Int.bits == 8) { - @memset(buffer, 0); - buffer[buffer.len - 1] = @as(u8, @bitCast(value)); - return; - } - - const write_start = buffer.len - @divExact(@typeInfo(T).Int.bits, 8); - @memset(buffer[0..write_start], 0); - @as(*align(1) T, @ptrCast(buffer[write_start..])).* = value; -} - -fn writeIntSliceBigForeign(comptime T: type, buffer: []u8, value: T) void { - return writeIntSliceBigNative(T, buffer, @byteSwap(value)); -} - -pub const writeIntSliceBig = switch (native_endian) { - .Little => writeIntSliceBigForeign, - .Big => writeIntSliceBigNative, -}; - -pub const writeIntSliceNative = switch (native_endian) { - .Little => writeIntSliceLittleNative, - .Big => writeIntSliceBigNative, -}; - -pub const writeIntSliceForeign = switch (native_endian) { - .Little => writeIntSliceBigForeign, - .Big => writeIntSliceLittleForeign, -}; - -/// Writes a twos-complement integer to memory, with the specified endianness. -/// Asserts that buf.len >= @typeInfo(T).Int.bits / 8. -/// The bit count of T must be evenly divisible by 8. -/// Any extra bytes in buffer not part of the integer are set to zero, with -/// respect to endianness. To avoid the branch to check for extra buffer bytes, -/// use writeInt instead. -pub fn writeIntSlice(comptime T: type, buffer: []u8, value: T, endian: Endian) void { - comptime assert(@typeInfo(T).Int.bits % 8 == 0); - return switch (endian) { - .Little => writeIntSliceLittle(T, buffer, value), - .Big => writeIntSliceBig(T, buffer, value), - }; -} - /// Stores an integer to packed memory with provided bit_count, bit_offset, and signedness. /// If negative, the written value is sign-extended. /// @@ -2055,45 +2076,6 @@ pub fn writeVarPackedInt(bytes: []u8, bit_offset: usize, bit_count: usize, value write_bytes[@as(usize, @intCast(i))] |= @as(u8, @intCast(@as(uN, @bitCast(remaining)) & tail_mask)); } -test "writeIntBig and writeIntLittle" { - if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; - - var buf0: [0]u8 = undefined; - var buf1: [1]u8 = undefined; - var buf2: [2]u8 = undefined; - var buf9: [9]u8 = undefined; - - writeIntBig(u0, &buf0, 0x0); - try testing.expect(eql(u8, buf0[0..], &[_]u8{})); - writeIntLittle(u0, &buf0, 0x0); - try testing.expect(eql(u8, buf0[0..], &[_]u8{})); - - writeIntBig(u8, &buf1, 0x12); - try testing.expect(eql(u8, buf1[0..], &[_]u8{0x12})); - writeIntLittle(u8, &buf1, 0x34); - try testing.expect(eql(u8, buf1[0..], &[_]u8{0x34})); - - writeIntBig(u16, &buf2, 0x1234); - try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0x12, 0x34 })); - writeIntLittle(u16, &buf2, 0x5678); - try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0x78, 0x56 })); - - writeIntBig(u72, &buf9, 0x123456789abcdef024); - try testing.expect(eql(u8, buf9[0..], &[_]u8{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x24 })); - writeIntLittle(u72, &buf9, 0xfedcba9876543210ec); - try testing.expect(eql(u8, buf9[0..], &[_]u8{ 0xec, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe })); - - writeIntBig(i8, &buf1, -1); - try testing.expect(eql(u8, buf1[0..], &[_]u8{0xff})); - writeIntLittle(i8, &buf1, -2); - try testing.expect(eql(u8, buf1[0..], &[_]u8{0xfe})); - - writeIntBig(i16, &buf2, -3); - try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0xff, 0xfd })); - writeIntLittle(i16, &buf2, -4); - try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0xfc, 0xff })); -} - /// Swap the byte order of all the members of the fields of a struct /// (Changing their endianness) pub fn byteSwapAllFields(comptime S: type, ptr: *S) void { @@ -3311,12 +3293,12 @@ fn testReadIntImpl() !void { 0x56, 0x78, }; - try testing.expect(readInt(u32, &bytes, Endian.Big) == 0x12345678); - try testing.expect(readIntBig(u32, &bytes) == 0x12345678); - try testing.expect(readIntBig(i32, &bytes) == 0x12345678); - try testing.expect(readInt(u32, &bytes, Endian.Little) == 0x78563412); - try testing.expect(readIntLittle(u32, &bytes) == 0x78563412); - try testing.expect(readIntLittle(i32, &bytes) == 0x78563412); + try testing.expect(readInt(u32, &bytes, .Big) == 0x12345678); + try testing.expect(readInt(u32, &bytes, .Big) == 0x12345678); + try testing.expect(readInt(i32, &bytes, .Big) == 0x12345678); + try testing.expect(readInt(u32, &bytes, .Little) == 0x78563412); + try testing.expect(readInt(u32, &bytes, .Little) == 0x78563412); + try testing.expect(readInt(i32, &bytes, .Little) == 0x78563412); } { const buf = [_]u8{ @@ -3325,7 +3307,7 @@ fn testReadIntImpl() !void { 0x12, 0x34, }; - const answer = readInt(u32, &buf, Endian.Big); + const answer = readInt(u32, &buf, .Big); try testing.expect(answer == 0x00001234); } { @@ -3335,7 +3317,7 @@ fn testReadIntImpl() !void { 0x00, 0x00, }; - const answer = readInt(u32, &buf, Endian.Little); + const answer = readInt(u32, &buf, .Little); try testing.expect(answer == 0x00003412); } { @@ -3343,153 +3325,13 @@ fn testReadIntImpl() !void { 0xff, 0xfe, }; - try testing.expect(readIntBig(u16, &bytes) == 0xfffe); - try testing.expect(readIntBig(i16, &bytes) == -0x0002); - try testing.expect(readIntLittle(u16, &bytes) == 0xfeff); - try testing.expect(readIntLittle(i16, &bytes) == -0x0101); + try testing.expect(readInt(u16, &bytes, .Big) == 0xfffe); + try testing.expect(readInt(i16, &bytes, .Big) == -0x0002); + try testing.expect(readInt(u16, &bytes, .Little) == 0xfeff); + try testing.expect(readInt(i16, &bytes, .Little) == -0x0101); } } -test writeIntSlice { - try testWriteIntImpl(); - try comptime testWriteIntImpl(); -} -fn testWriteIntImpl() !void { - var bytes: [8]u8 = undefined; - - writeIntSlice(u0, bytes[0..], 0, Endian.Big); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, - })); - - writeIntSlice(u0, bytes[0..], 0, Endian.Little); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, - })); - - writeIntSlice(u64, bytes[0..], 0x12345678CAFEBABE, Endian.Big); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x12, - 0x34, - 0x56, - 0x78, - 0xCA, - 0xFE, - 0xBA, - 0xBE, - })); - - writeIntSlice(u64, bytes[0..], 0xBEBAFECA78563412, Endian.Little); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x12, - 0x34, - 0x56, - 0x78, - 0xCA, - 0xFE, - 0xBA, - 0xBE, - })); - - writeIntSlice(u32, bytes[0..], 0x12345678, Endian.Big); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x00, - 0x00, - 0x00, - 0x00, - 0x12, - 0x34, - 0x56, - 0x78, - })); - - writeIntSlice(u32, bytes[0..], 0x78563412, Endian.Little); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x12, - 0x34, - 0x56, - 0x78, - 0x00, - 0x00, - 0x00, - 0x00, - })); - - writeIntSlice(u16, bytes[0..], 0x1234, Endian.Big); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x12, - 0x34, - })); - - writeIntSlice(u16, bytes[0..], 0x1234, Endian.Little); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x34, - 0x12, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - })); - - writeIntSlice(i16, bytes[0..], @as(i16, -21555), Endian.Little); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0xCD, - 0xAB, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - })); - - writeIntSlice(i16, bytes[0..], @as(i16, -21555), Endian.Big); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xAB, - 0xCD, - })); - - writeIntSlice(u8, bytes[0..], 0x12, Endian.Big); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x12, - })); - - writeIntSlice(u8, bytes[0..], 0x12, Endian.Little); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x12, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, - })); - - writeIntSlice(i8, bytes[0..], -1, Endian.Big); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0xff, - })); - - writeIntSlice(i8, bytes[0..], -1, Endian.Little); - try testing.expect(eql(u8, &bytes, &[_]u8{ - 0xff, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, - })); -} - /// Returns the smallest number in a slice. O(n). /// `slice` must not be empty. pub fn min(comptime T: type, slice: []const T) T { @@ -4671,7 +4513,6 @@ pub fn alignInSlice(slice: anytype, comptime new_alignment: usize) ?AlignedSlice } test "read/write(Var)PackedInt" { - if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; switch (builtin.cpu.arch) { diff --git a/lib/std/net.zig b/lib/std/net.zig index b6f0f20f2c..1badada19e 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -1052,7 +1052,7 @@ fn linuxLookupName( } else { sa6.addr[0..12].* = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff".*; da6.addr[0..12].* = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff".*; - mem.writeIntNative(u32, da6.addr[12..], addr.addr.in.sa.addr); + mem.writeInt(u32, da6.addr[12..], addr.addr.in.sa.addr, native_endian); da4.addr = addr.addr.in.sa.addr; da = @ptrCast(&da4); dalen = @sizeOf(os.sockaddr.in); @@ -1073,7 +1073,7 @@ fn linuxLookupName( os.getsockname(fd, sa, &salen) catch break :syscalls; if (addr.addr.any.family == os.AF.INET) { // TODO sa6.addr[12..16] should return *[4]u8, making this cast unnecessary. - mem.writeIntNative(u32, @as(*[4]u8, @ptrCast(&sa6.addr[12])), sa4.addr); + mem.writeInt(u32, @as(*[4]u8, @ptrCast(&sa6.addr[12])), sa4.addr, native_endian); } if (dscope == @as(i32, scopeOf(sa6.addr))) key |= DAS_MATCHINGSCOPE; if (dlabel == labelOf(sa6.addr)) key |= DAS_MATCHINGLABEL; @@ -1569,7 +1569,7 @@ fn resMSendRc( ); for (0..ns.len) |i| { if (ns[i].any.family != os.AF.INET) continue; - mem.writeIntNative(u32, ns[i].in6.sa.addr[12..], ns[i].in.sa.addr); + mem.writeInt(u32, ns[i].in6.sa.addr[12..], ns[i].in.sa.addr, native_endian); ns[i].in6.sa.addr[0..12].* = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff".*; ns[i].any.family = os.AF.INET6; ns[i].in6.sa.flowinfo = 0; diff --git a/lib/std/os/test.zig b/lib/std/os/test.zig index 734f56490f..1fa629e5ae 100644 --- a/lib/std/os/test.zig +++ b/lib/std/os/test.zig @@ -609,7 +609,7 @@ test "mmap" { var i: u32 = 0; while (i < alloc_size / @sizeOf(u32)) : (i += 1) { - try stream.writeIntNative(u32, i); + try stream.writeInt(u32, i, .Little); } } @@ -633,7 +633,7 @@ test "mmap" { var i: u32 = 0; while (i < alloc_size / @sizeOf(u32)) : (i += 1) { - try testing.expectEqual(i, try stream.readIntNative(u32)); + try testing.expectEqual(i, try stream.readInt(u32, .Little)); } } @@ -657,7 +657,7 @@ test "mmap" { var i: u32 = alloc_size / 2 / @sizeOf(u32); while (i < alloc_size / @sizeOf(u32)) : (i += 1) { - try testing.expectEqual(i, try stream.readIntNative(u32)); + try testing.expectEqual(i, try stream.readInt(u32, .Little)); } } diff --git a/lib/std/pdb.zig b/lib/std/pdb.zig index 0f77279677..3632adc138 100644 --- a/lib/std/pdb.zig +++ b/lib/std/pdb.zig @@ -464,12 +464,12 @@ pub const PDBStringTableHeader = extern struct { }; fn readSparseBitVector(stream: anytype, allocator: mem.Allocator) ![]u32 { - const num_words = try stream.readIntLittle(u32); + const num_words = try stream.readInt(u32, .Little); var list = ArrayList(u32).init(allocator); errdefer list.deinit(); var word_i: u32 = 0; while (word_i != num_words) : (word_i += 1) { - const word = try stream.readIntLittle(u32); + const word = try stream.readInt(u32, .Little); var bit_i: u5 = 0; while (true) : (bit_i += 1) { if (word & (@as(u32, 1) << bit_i) != 0) { @@ -625,10 +625,10 @@ pub const Pdb = struct { const reader = stream.reader(); // Parse the InfoStreamHeader. - const version = try reader.readIntLittle(u32); - const signature = try reader.readIntLittle(u32); + const version = try reader.readInt(u32, .Little); + const signature = try reader.readInt(u32, .Little); _ = signature; - const age = try reader.readIntLittle(u32); + const age = try reader.readInt(u32, .Little); const guid = try reader.readBytesNoEof(16); if (version != 20000404) // VC70, only value observed by LLVM team @@ -639,7 +639,7 @@ pub const Pdb = struct { // Find the string table. const string_table_index = str_tab_index: { - const name_bytes_len = try reader.readIntLittle(u32); + const name_bytes_len = try reader.readInt(u32, .Little); const name_bytes = try self.allocator.alloc(u8, name_bytes_len); defer self.allocator.free(name_bytes); try reader.readNoEof(name_bytes); @@ -667,8 +667,8 @@ pub const Pdb = struct { defer self.allocator.free(deleted); for (present) |_| { - const name_offset = try reader.readIntLittle(u32); - const name_index = try reader.readIntLittle(u32); + const name_offset = try reader.readInt(u32, .Little); + const name_index = try reader.readInt(u32, .Little); if (name_offset > name_bytes.len) return error.InvalidDebugInfo; const name = mem.sliceTo(name_bytes[name_offset..], 0); @@ -821,7 +821,7 @@ pub const Pdb = struct { return error.MissingDebugInfo; const reader = stream.reader(); - const signature = try reader.readIntLittle(u32); + const signature = try reader.readInt(u32, .Little); if (signature != 4) return error.InvalidDebugInfo; @@ -899,7 +899,7 @@ const Msf = struct { try file.seekTo(superblock.BlockSize * superblock.BlockMapAddr); var dir_blocks = try allocator.alloc(u32, dir_block_count); for (dir_blocks) |*b| { - b.* = try in.readIntLittle(u32); + b.* = try in.readInt(u32, .Little); } var directory = MsfStream.init( superblock.BlockSize, @@ -908,7 +908,7 @@ const Msf = struct { ); const begin = directory.pos; - const stream_count = try directory.reader().readIntLittle(u32); + const stream_count = try directory.reader().readInt(u32, .Little); const stream_sizes = try allocator.alloc(u32, stream_count); defer allocator.free(stream_sizes); @@ -917,7 +917,7 @@ const Msf = struct { // and must be taken into account when resolving stream indices. const Nil = 0xFFFFFFFF; for (stream_sizes) |*s| { - const size = try directory.reader().readIntLittle(u32); + const size = try directory.reader().readInt(u32, .Little); s.* = if (size == Nil) 0 else blockCountFromSize(size, superblock.BlockSize); } @@ -932,7 +932,7 @@ const Msf = struct { var blocks = try allocator.alloc(u32, size); var j: u32 = 0; while (j < size) : (j += 1) { - const block_id = try directory.reader().readIntLittle(u32); + const block_id = try directory.reader().readInt(u32, .Little); const n = (block_id % superblock.BlockSize); // 0 is for SuperBlock, 1 and 2 for FPMs. if (block_id == 0 or n == 1 or n == 2 or block_id * superblock.BlockSize > file_len) diff --git a/lib/std/rand.zig b/lib/std/rand.zig index c573a94d61..bca8289c85 100644 --- a/lib/std/rand.zig +++ b/lib/std/rand.zig @@ -104,15 +104,16 @@ pub const Random = struct { pub fn int(r: Random, comptime T: type) T { const bits = @typeInfo(T).Int.bits; const UnsignedT = std.meta.Int(.unsigned, bits); - const ByteAlignedT = std.meta.Int(.unsigned, @divTrunc(bits + 7, 8) * 8); + const ceil_bytes = comptime std.math.divCeil(u16, bits, 8) catch unreachable; + const ByteAlignedT = std.meta.Int(.unsigned, ceil_bytes * 8); - var rand_bytes: [@sizeOf(ByteAlignedT)]u8 = undefined; - r.bytes(rand_bytes[0..]); + var rand_bytes: [ceil_bytes]u8 = undefined; + r.bytes(&rand_bytes); // use LE instead of native endian for better portability maybe? // TODO: endian portability is pointless if the underlying prng isn't endian portable. // TODO: document the endian portability of this library. - const byte_aligned_result = mem.readIntSliceLittle(ByteAlignedT, &rand_bytes); + const byte_aligned_result = mem.readInt(ByteAlignedT, &rand_bytes, .Little); const unsigned_result: UnsignedT = @truncate(byte_aligned_result); return @bitCast(unsigned_result); } diff --git a/lib/std/rand/Isaac64.zig b/lib/std/rand/Isaac64.zig index 785c551dfd..d3a6a19b5b 100644 --- a/lib/std/rand/Isaac64.zig +++ b/lib/std/rand/Isaac64.zig @@ -228,7 +228,7 @@ test "isaac64 fill" { for (seq) |s| { var buf0: [8]u8 = undefined; var buf1: [7]u8 = undefined; - std.mem.writeIntLittle(u64, &buf0, s); + std.mem.writeInt(u64, &buf0, s, .Little); r.fill(&buf1); try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..])); } diff --git a/lib/std/rand/Pcg.zig b/lib/std/rand/Pcg.zig index b682197b23..6219954713 100644 --- a/lib/std/rand/Pcg.zig +++ b/lib/std/rand/Pcg.zig @@ -111,8 +111,8 @@ test "pcg fill" { var i: u32 = 0; while (i < seq.len) : (i += 2) { var buf0: [8]u8 = undefined; - std.mem.writeIntLittle(u32, buf0[0..4], seq[i]); - std.mem.writeIntLittle(u32, buf0[4..8], seq[i + 1]); + std.mem.writeInt(u32, buf0[0..4], seq[i], .Little); + std.mem.writeInt(u32, buf0[4..8], seq[i + 1], .Little); var buf1: [7]u8 = undefined; r.fill(&buf1); diff --git a/lib/std/rand/RomuTrio.zig b/lib/std/rand/RomuTrio.zig index 4ce2b7af01..9864b03327 100644 --- a/lib/std/rand/RomuTrio.zig +++ b/lib/std/rand/RomuTrio.zig @@ -115,7 +115,7 @@ test "RomuTrio fill" { for (seq) |s| { var buf0: [8]u8 = undefined; var buf1: [7]u8 = undefined; - std.mem.writeIntLittle(u64, &buf0, s); + std.mem.writeInt(u64, &buf0, s, .Little); r.fill(&buf1); try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..])); } diff --git a/lib/std/rand/Sfc64.zig b/lib/std/rand/Sfc64.zig index af439b115b..e3197cc3ec 100644 --- a/lib/std/rand/Sfc64.zig +++ b/lib/std/rand/Sfc64.zig @@ -125,7 +125,7 @@ test "Sfc64 fill" { for (seq) |s| { var buf0: [8]u8 = undefined; var buf1: [7]u8 = undefined; - std.mem.writeIntLittle(u64, &buf0, s); + std.mem.writeInt(u64, &buf0, s, .Little); r.fill(&buf1); try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..])); } diff --git a/lib/std/rand/Xoroshiro128.zig b/lib/std/rand/Xoroshiro128.zig index 56c4980e6d..2b215fdc0c 100644 --- a/lib/std/rand/Xoroshiro128.zig +++ b/lib/std/rand/Xoroshiro128.zig @@ -140,7 +140,7 @@ test "xoroshiro fill" { for (seq) |s| { var buf0: [8]u8 = undefined; var buf1: [7]u8 = undefined; - std.mem.writeIntLittle(u64, &buf0, s); + std.mem.writeInt(u64, &buf0, s, .Little); r.fill(&buf1); try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..])); } diff --git a/lib/std/rand/Xoshiro256.zig b/lib/std/rand/Xoshiro256.zig index 5c30dc3fa7..c1cc897a05 100644 --- a/lib/std/rand/Xoshiro256.zig +++ b/lib/std/rand/Xoshiro256.zig @@ -139,7 +139,7 @@ test "xoroshiro fill" { for (seq) |s| { var buf0: [8]u8 = undefined; var buf1: [7]u8 = undefined; - std.mem.writeIntLittle(u64, &buf0, s); + std.mem.writeInt(u64, &buf0, s, .Little); r.fill(&buf1); try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..])); } diff --git a/lib/std/rand/test.zig b/lib/std/rand/test.zig index 2f4995b3fe..6746a05773 100644 --- a/lib/std/rand/test.zig +++ b/lib/std/rand/test.zig @@ -71,7 +71,7 @@ const Dilbert = struct { for (seq) |s| { var buf0: [8]u8 = undefined; var buf1: [8]u8 = undefined; - std.mem.writeIntBig(u64, &buf0, s); + std.mem.writeInt(u64, &buf0, s, .Big); r.fill(&buf1); try std.testing.expect(std.mem.eql(u8, buf0[0..], buf1[0..])); } diff --git a/lib/std/tz.zig b/lib/std/tz.zig index 16288bd4ce..a17756a7bb 100644 --- a/lib/std/tz.zig +++ b/lib/std/tz.zig @@ -98,7 +98,7 @@ pub const Tz = struct { // Parse transition types var i: usize = 0; while (i < header.counts.timecnt) : (i += 1) { - transitions[i].ts = if (legacy) try reader.readIntBig(i32) else try reader.readIntBig(i64); + transitions[i].ts = if (legacy) try reader.readInt(i32, .Big) else try reader.readInt(i64, .Big); } i = 0; @@ -111,7 +111,7 @@ pub const Tz = struct { // Parse time types i = 0; while (i < header.counts.typecnt) : (i += 1) { - const offset = try reader.readIntBig(i32); + const offset = try reader.readInt(i32, .Big); if (offset < -2147483648) return error.Malformed; // rfc8536: utoff [...] MUST NOT be -2**31 const dst = try reader.readByte(); if (dst != 0 and dst != 1) return error.Malformed; // rfc8536: (is)dst [...] The value MUST be 0 or 1. @@ -144,12 +144,12 @@ pub const Tz = struct { // Parse leap seconds i = 0; while (i < header.counts.leapcnt) : (i += 1) { - const occur: i64 = if (legacy) try reader.readIntBig(i32) else try reader.readIntBig(i64); + const occur: i64 = if (legacy) try reader.readInt(i32, .Big) else try reader.readInt(i64, .Big); if (occur < 0) return error.Malformed; // rfc8536: occur [...] MUST be nonnegative if (i > 0 and leapseconds[i - 1].occurrence + 2419199 > occur) return error.Malformed; // rfc8536: occur [...] each later value MUST be at least 2419199 greater than the previous value if (occur > std.math.maxInt(i48)) return error.Malformed; // Unreasonably far into the future - const corr = try reader.readIntBig(i32); + const corr = try reader.readInt(i32, .Big); if (i == 0 and corr != -1 and corr != 1) return error.Malformed; // rfc8536: The correction value in the first leap-second record, if present, MUST be either one (1) or minus one (-1) if (i > 0 and leapseconds[i - 1].correction != corr + 1 and leapseconds[i - 1].correction != corr - 1) return error.Malformed; // rfc8536: The correction values in adjacent leap-second records MUST differ by exactly one (1) if (corr > std.math.maxInt(i16)) return error.Malformed; // Unreasonably large correction diff --git a/lib/std/unicode.zig b/lib/std/unicode.zig index 4a4a1b10d1..9336e6bbe8 100644 --- a/lib/std/unicode.zig +++ b/lib/std/unicode.zig @@ -1,8 +1,9 @@ const std = @import("./std.zig"); +const builtin = @import("builtin"); const assert = std.debug.assert; const testing = std.testing; const mem = std.mem; -const builtin = @import("builtin"); +const native_endian = builtin.cpu.arch.endian(); /// Use this to replace an unknown, unrecognized, or unrepresentable character. /// @@ -175,7 +176,7 @@ pub fn utf8CountCodepoints(s: []const u8) !usize { while (i < s.len) { // Fast path for ASCII sequences while (i + N <= s.len) : (i += N) { - const v = mem.readIntNative(usize, s[i..][0..N]); + const v = mem.readInt(usize, s[i..][0..N], native_endian); if (v & MASK != 0) break; len += N; } @@ -451,12 +452,12 @@ pub const Utf16LeIterator = struct { assert(it.i <= it.bytes.len); if (it.i == it.bytes.len) return null; var code_units: [2]u16 = undefined; - code_units[0] = mem.readIntLittle(u16, it.bytes[it.i..][0..2]); + code_units[0] = mem.readInt(u16, it.bytes[it.i..][0..2], .Little); it.i += 2; if (utf16IsHighSurrogate(code_units[0])) { // surrogate pair if (it.i >= it.bytes.len) return error.DanglingSurrogateHalf; - code_units[1] = mem.readIntLittle(u16, it.bytes[it.i..][0..2]); + code_units[1] = mem.readInt(u16, it.bytes[it.i..][0..2], .Little); const codepoint = try utf16DecodeSurrogatePair(&code_units); it.i += 2; return codepoint; @@ -877,16 +878,16 @@ test "utf16leToUtf8" { const utf16le_as_bytes = mem.sliceAsBytes(utf16le[0..]); { - mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 'A'); - mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 'a'); + mem.writeInt(u16, utf16le_as_bytes[0..2], 'A', .Little); + mem.writeInt(u16, utf16le_as_bytes[2..4], 'a', .Little); const utf8 = try utf16leToUtf8Alloc(std.testing.allocator, &utf16le); defer std.testing.allocator.free(utf8); try testing.expect(mem.eql(u8, utf8, "Aa")); } { - mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0x80); - mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xffff); + mem.writeInt(u16, utf16le_as_bytes[0..2], 0x80, .Little); + mem.writeInt(u16, utf16le_as_bytes[2..4], 0xffff, .Little); const utf8 = try utf16leToUtf8Alloc(std.testing.allocator, &utf16le); defer std.testing.allocator.free(utf8); try testing.expect(mem.eql(u8, utf8, "\xc2\x80" ++ "\xef\xbf\xbf")); @@ -894,8 +895,8 @@ test "utf16leToUtf8" { { // the values just outside the surrogate half range - mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0xd7ff); - mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xe000); + mem.writeInt(u16, utf16le_as_bytes[0..2], 0xd7ff, .Little); + mem.writeInt(u16, utf16le_as_bytes[2..4], 0xe000, .Little); const utf8 = try utf16leToUtf8Alloc(std.testing.allocator, &utf16le); defer std.testing.allocator.free(utf8); try testing.expect(mem.eql(u8, utf8, "\xed\x9f\xbf" ++ "\xee\x80\x80")); @@ -903,8 +904,8 @@ test "utf16leToUtf8" { { // smallest surrogate pair - mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0xd800); - mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xdc00); + mem.writeInt(u16, utf16le_as_bytes[0..2], 0xd800, .Little); + mem.writeInt(u16, utf16le_as_bytes[2..4], 0xdc00, .Little); const utf8 = try utf16leToUtf8Alloc(std.testing.allocator, &utf16le); defer std.testing.allocator.free(utf8); try testing.expect(mem.eql(u8, utf8, "\xf0\x90\x80\x80")); @@ -912,24 +913,24 @@ test "utf16leToUtf8" { { // largest surrogate pair - mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0xdbff); - mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xdfff); + mem.writeInt(u16, utf16le_as_bytes[0..2], 0xdbff, .Little); + mem.writeInt(u16, utf16le_as_bytes[2..4], 0xdfff, .Little); const utf8 = try utf16leToUtf8Alloc(std.testing.allocator, &utf16le); defer std.testing.allocator.free(utf8); try testing.expect(mem.eql(u8, utf8, "\xf4\x8f\xbf\xbf")); } { - mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0xdbff); - mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xdc00); + mem.writeInt(u16, utf16le_as_bytes[0..2], 0xdbff, .Little); + mem.writeInt(u16, utf16le_as_bytes[2..4], 0xdc00, .Little); const utf8 = try utf16leToUtf8Alloc(std.testing.allocator, &utf16le); defer std.testing.allocator.free(utf8); try testing.expect(mem.eql(u8, utf8, "\xf4\x8f\xb0\x80")); } { - mem.writeIntSliceLittle(u16, utf16le_as_bytes[0..], 0xdcdc); - mem.writeIntSliceLittle(u16, utf16le_as_bytes[2..], 0xdcdc); + mem.writeInt(u16, utf16le_as_bytes[0..2], 0xdcdc, .Little); + mem.writeInt(u16, utf16le_as_bytes[2..4], 0xdcdc, .Little); const result = utf16leToUtf8Alloc(std.testing.allocator, &utf16le); try std.testing.expectError(error.UnexpectedSecondSurrogateHalf, result); } @@ -1140,12 +1141,12 @@ test "fmtUtf16le" { try expectFmt("", "{}", .{fmtUtf16le(utf8ToUtf16LeStringLiteral(""))}); try expectFmt("foo", "{}", .{fmtUtf16le(utf8ToUtf16LeStringLiteral("foo"))}); try expectFmt("𐐷", "{}", .{fmtUtf16le(utf8ToUtf16LeStringLiteral("𐐷"))}); - try expectFmt("퟿", "{}", .{fmtUtf16le(&[_]u16{std.mem.readIntNative(u16, "\xff\xd7")})}); - try expectFmt("�", "{}", .{fmtUtf16le(&[_]u16{std.mem.readIntNative(u16, "\x00\xd8")})}); - try expectFmt("�", "{}", .{fmtUtf16le(&[_]u16{std.mem.readIntNative(u16, "\xff\xdb")})}); - try expectFmt("�", "{}", .{fmtUtf16le(&[_]u16{std.mem.readIntNative(u16, "\x00\xdc")})}); - try expectFmt("�", "{}", .{fmtUtf16le(&[_]u16{std.mem.readIntNative(u16, "\xff\xdf")})}); - try expectFmt("", "{}", .{fmtUtf16le(&[_]u16{std.mem.readIntNative(u16, "\x00\xe0")})}); + try expectFmt("퟿", "{}", .{fmtUtf16le(&[_]u16{std.mem.readInt(u16, "\xff\xd7", native_endian)})}); + try expectFmt("�", "{}", .{fmtUtf16le(&[_]u16{std.mem.readInt(u16, "\x00\xd8", native_endian)})}); + try expectFmt("�", "{}", .{fmtUtf16le(&[_]u16{std.mem.readInt(u16, "\xff\xdb", native_endian)})}); + try expectFmt("�", "{}", .{fmtUtf16le(&[_]u16{std.mem.readInt(u16, "\x00\xdc", native_endian)})}); + try expectFmt("�", "{}", .{fmtUtf16le(&[_]u16{std.mem.readInt(u16, "\xff\xdf", native_endian)})}); + try expectFmt("", "{}", .{fmtUtf16le(&[_]u16{std.mem.readInt(u16, "\x00\xe0", native_endian)})}); } test "utf8ToUtf16LeStringLiteral" { diff --git a/lib/std/zig/Server.zig b/lib/std/zig/Server.zig index 15795176a0..d15020dcc0 100644 --- a/lib/std/zig/Server.zig +++ b/lib/std/zig/Server.zig @@ -279,12 +279,12 @@ fn bswap_u32_array(slice: []u32) void { /// workaround for https://github.com/ziglang/zig/issues/14904 fn bswap_and_workaround_u32(bytes_ptr: *const [4]u8) u32 { - return std.mem.readIntLittle(u32, bytes_ptr); + return std.mem.readInt(u32, bytes_ptr, .Little); } /// workaround for https://github.com/ziglang/zig/issues/14904 fn bswap_and_workaround_tag(bytes_ptr: *const [4]u8) InMessage.Tag { - const int = std.mem.readIntLittle(u32, bytes_ptr); + const int = std.mem.readInt(u32, bytes_ptr, .Little); return @as(InMessage.Tag, @enumFromInt(int)); } diff --git a/lib/test_runner.zig b/lib/test_runner.zig index 18608d298a..7ed29ebfb1 100644 --- a/lib/test_runner.zig +++ b/lib/test_runner.zig @@ -13,7 +13,9 @@ var cmdline_buffer: [4096]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&cmdline_buffer); pub fn main() void { - if (builtin.zig_backend == .stage2_aarch64) { + if (builtin.zig_backend == .stage2_aarch64 or + builtin.zig_backend == .stage2_wasm) + { return mainSimple() catch @panic("test failure"); } diff --git a/src/Package/Fetch/git.zig b/src/Package/Fetch/git.zig index 9a2e682300..b584a9b64e 100644 --- a/src/Package/Fetch/git.zig +++ b/src/Package/Fetch/git.zig @@ -305,12 +305,12 @@ const Odb = struct { const n_objects = odb.index_header.fan_out_table[255]; const offset_values_start = IndexHeader.size + n_objects * (oid_length + 4); try odb.index_file.seekTo(offset_values_start + found_index * 4); - const l1_offset: packed struct { value: u31, big: bool } = @bitCast(try odb.index_file.reader().readIntBig(u32)); + const l1_offset: packed struct { value: u31, big: bool } = @bitCast(try odb.index_file.reader().readInt(u32, .Big)); const pack_offset = pack_offset: { if (l1_offset.big) { const l2_offset_values_start = offset_values_start + n_objects * 4; try odb.index_file.seekTo(l2_offset_values_start + l1_offset.value * 4); - break :pack_offset try odb.index_file.reader().readIntBig(u64); + break :pack_offset try odb.index_file.reader().readInt(u64, .Big); } else { break :pack_offset l1_offset.value; } @@ -845,12 +845,12 @@ const PackHeader = struct { else => |other| return other, }; if (!mem.eql(u8, &actual_signature, signature)) return error.InvalidHeader; - const version = reader.readIntBig(u32) catch |e| switch (e) { + const version = reader.readInt(u32, .Big) catch |e| switch (e) { error.EndOfStream => return error.InvalidHeader, else => |other| return other, }; if (version != supported_version) return error.UnsupportedVersion; - const total_objects = reader.readIntBig(u32) catch |e| switch (e) { + const total_objects = reader.readInt(u32, .Big) catch |e| switch (e) { error.EndOfStream => return error.InvalidHeader, else => |other| return other, }; @@ -966,14 +966,14 @@ const IndexHeader = struct { fn read(reader: anytype) !IndexHeader { var header_bytes = try reader.readBytesNoEof(size); if (!mem.eql(u8, header_bytes[0..4], signature)) return error.InvalidHeader; - const version = mem.readIntBig(u32, header_bytes[4..8]); + const version = mem.readInt(u32, header_bytes[4..8], .Big); if (version != supported_version) return error.UnsupportedVersion; var fan_out_table: [256]u32 = undefined; var fan_out_table_stream = std.io.fixedBufferStream(header_bytes[8..]); const fan_out_table_reader = fan_out_table_stream.reader(); for (&fan_out_table) |*entry| { - entry.* = fan_out_table_reader.readIntBig(u32) catch unreachable; + entry.* = fan_out_table_reader.readInt(u32, .Big) catch unreachable; } return .{ .fan_out_table = fan_out_table }; } @@ -1041,9 +1041,9 @@ pub fn indexPack(allocator: Allocator, pack: std.fs.File, index_writer: anytype) var index_hashed_writer = hashedWriter(index_writer, Sha1.init(.{})); const writer = index_hashed_writer.writer(); try writer.writeAll(IndexHeader.signature); - try writer.writeIntBig(u32, IndexHeader.supported_version); + try writer.writeInt(u32, IndexHeader.supported_version, .Big); for (fan_out_table) |fan_out_entry| { - try writer.writeIntBig(u32, fan_out_entry); + try writer.writeInt(u32, fan_out_entry, .Big); } for (oids.items) |oid| { @@ -1051,7 +1051,7 @@ pub fn indexPack(allocator: Allocator, pack: std.fs.File, index_writer: anytype) } for (oids.items) |oid| { - try writer.writeIntBig(u32, index_entries.get(oid).?.crc32); + try writer.writeInt(u32, index_entries.get(oid).?.crc32, .Big); } var big_offsets = std.ArrayListUnmanaged(u64){}; @@ -1059,15 +1059,15 @@ pub fn indexPack(allocator: Allocator, pack: std.fs.File, index_writer: anytype) for (oids.items) |oid| { const offset = index_entries.get(oid).?.offset; if (offset <= std.math.maxInt(u31)) { - try writer.writeIntBig(u32, @intCast(offset)); + try writer.writeInt(u32, @intCast(offset), .Big); } else { const index = big_offsets.items.len; try big_offsets.append(allocator, offset); - try writer.writeIntBig(u32, @as(u32, @intCast(index)) | (1 << 31)); + try writer.writeInt(u32, @as(u32, @intCast(index)) | (1 << 31), .Big); } } for (big_offsets.items) |offset| { - try writer.writeIntBig(u64, offset); + try writer.writeInt(u64, offset, .Big); } try writer.writeAll(&pack_checksum); diff --git a/src/arch/wasm/CodeGen.zig b/src/arch/wasm/CodeGen.zig index 9588ec65fd..3d12a015ed 100644 --- a/src/arch/wasm/CodeGen.zig +++ b/src/arch/wasm/CodeGen.zig @@ -3364,7 +3364,7 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue { const backing_int_ty = struct_type.backingIntType(ip).toType(); const int_val = try mod.intValue( backing_int_ty, - mem.readIntLittle(u64, &buf), + mem.readInt(u64, &buf, .Little), ); return func.lowerConstant(int_val, backing_int_ty); }, diff --git a/src/arch/wasm/Emit.zig b/src/arch/wasm/Emit.zig index 3b1911b895..80f44d8ce2 100644 --- a/src/arch/wasm/Emit.zig +++ b/src/arch/wasm/Emit.zig @@ -330,14 +330,14 @@ fn emitImm64(emit: *Emit, inst: Mir.Inst.Index) !void { fn emitFloat32(emit: *Emit, inst: Mir.Inst.Index) !void { const value: f32 = emit.mir.instructions.items(.data)[inst].float32; try emit.code.append(std.wasm.opcode(.f32_const)); - try emit.code.writer().writeIntLittle(u32, @as(u32, @bitCast(value))); + try emit.code.writer().writeInt(u32, @bitCast(value), .Little); } fn emitFloat64(emit: *Emit, inst: Mir.Inst.Index) !void { const extra_index = emit.mir.instructions.items(.data)[inst].payload; const value = emit.mir.extraData(Mir.Float64, extra_index); try emit.code.append(std.wasm.opcode(.f64_const)); - try emit.code.writer().writeIntLittle(u64, value.data.toU64()); + try emit.code.writer().writeInt(u64, value.data.toU64(), .Little); } fn emitMemArg(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) !void { diff --git a/src/arch/x86_64/Emit.zig b/src/arch/x86_64/Emit.zig index 51fb906e00..e6f2db3401 100644 --- a/src/arch/x86_64/Emit.zig +++ b/src/arch/x86_64/Emit.zig @@ -253,7 +253,7 @@ fn fixupRelocs(emit: *Emit) Error!void { const target = emit.code_offset_mapping.get(reloc.target) orelse return emit.fail("JMP/CALL relocation target not found!", .{}); const disp = @as(i32, @intCast(@as(i64, @intCast(target)) - @as(i64, @intCast(reloc.source + reloc.length)))); - mem.writeIntLittle(i32, emit.code.items[reloc.offset..][0..4], disp); + mem.writeInt(i32, emit.code.items[reloc.offset..][0..4], disp, .Little); } } diff --git a/src/arch/x86_64/encoder.zig b/src/arch/x86_64/encoder.zig index b461e7acf0..9d629dbff7 100644 --- a/src/arch/x86_64/encoder.zig +++ b/src/arch/x86_64/encoder.zig @@ -998,7 +998,7 @@ fn Encoder(comptime T: type, comptime opts: Options) type { /// /// It is sign-extended to 64 bits by the cpu. pub fn disp32(self: Self, disp: i32) !void { - try self.writer.writeIntLittle(i32, disp); + try self.writer.writeInt(i32, disp, .Little); } /// Encode an 8 bit immediate @@ -1012,21 +1012,21 @@ fn Encoder(comptime T: type, comptime opts: Options) type { /// /// It is sign-extended to 64 bits by the cpu. pub fn imm16(self: Self, imm: u16) !void { - try self.writer.writeIntLittle(u16, imm); + try self.writer.writeInt(u16, imm, .Little); } /// Encode an 32 bit immediate /// /// It is sign-extended to 64 bits by the cpu. pub fn imm32(self: Self, imm: u32) !void { - try self.writer.writeIntLittle(u32, imm); + try self.writer.writeInt(u32, imm, .Little); } /// Encode an 64 bit immediate /// /// It is sign-extended to 64 bits by the cpu. pub fn imm64(self: Self, imm: u64) !void { - try self.writer.writeIntLittle(u64, imm); + try self.writer.writeInt(u64, imm, .Little); } }; } diff --git a/src/glibc.zig b/src/glibc.zig index 2321063166..1a50f6b7c5 100644 --- a/src/glibc.zig +++ b/src/glibc.zig @@ -751,7 +751,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: *std.Progress.Node) !vo var inc_i: usize = 0; - const fn_inclusions_len = mem.readIntLittle(u16, metadata.inclusions[inc_i..][0..2]); + const fn_inclusions_len = mem.readInt(u16, metadata.inclusions[inc_i..][0..2], .Little); inc_i += 2; var sym_i: usize = 0; @@ -768,7 +768,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: *std.Progress.Node) !vo versions_len = 0; break :n name; }; - const targets = mem.readIntLittle(u32, metadata.inclusions[inc_i..][0..4]); + const targets = mem.readInt(u32, metadata.inclusions[inc_i..][0..4], .Little); inc_i += 4; const lib_index = metadata.inclusions[inc_i]; @@ -882,7 +882,7 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: *std.Progress.Node) !vo try stubs_asm.appendSlice(".data\n"); - const obj_inclusions_len = mem.readIntLittle(u16, metadata.inclusions[inc_i..][0..2]); + const obj_inclusions_len = mem.readInt(u16, metadata.inclusions[inc_i..][0..2], .Little); inc_i += 2; sym_i = 0; @@ -899,10 +899,10 @@ pub fn buildSharedObjects(comp: *Compilation, prog_node: *std.Progress.Node) !vo versions_len = 0; break :n name; }; - const targets = mem.readIntLittle(u32, metadata.inclusions[inc_i..][0..4]); + const targets = mem.readInt(u32, metadata.inclusions[inc_i..][0..4], .Little); inc_i += 4; - const size = mem.readIntLittle(u16, metadata.inclusions[inc_i..][0..2]); + const size = mem.readInt(u16, metadata.inclusions[inc_i..][0..2], .Little); inc_i += 2; const lib_index = metadata.inclusions[inc_i]; diff --git a/src/link/Coff.zig b/src/link/Coff.zig index 340b60534d..affc7406b7 100644 --- a/src/link/Coff.zig +++ b/src/link/Coff.zig @@ -856,12 +856,12 @@ fn writeOffsetTableEntry(self: *Coff, index: usize) !void { switch (self.ptr_width) { .p32 => { var buf: [4]u8 = undefined; - mem.writeIntLittle(u32, &buf, @as(u32, @intCast(entry_value + self.getImageBase()))); + mem.writeInt(u32, &buf, @as(u32, @intCast(entry_value + self.getImageBase())), .Little); try self.base.file.?.pwriteAll(&buf, file_offset); }, .p64 => { var buf: [8]u8 = undefined; - mem.writeIntLittle(u64, &buf, entry_value + self.getImageBase()); + mem.writeInt(u64, &buf, entry_value + self.getImageBase(), .Little); try self.base.file.?.pwriteAll(&buf, file_offset); }, } @@ -889,14 +889,14 @@ fn writeOffsetTableEntry(self: *Coff, index: usize) !void { switch (self.ptr_width) { .p32 => { var buf: [4]u8 = undefined; - mem.writeIntLittle(u32, &buf, @as(u32, @intCast(entry_value + slide))); + mem.writeInt(u32, &buf, @as(u32, @intCast(entry_value + slide)), .Little); writeMem(handle, pvaddr, &buf) catch |err| { log.warn("writing to protected memory failed with error: {s}", .{@errorName(err)}); }; }, .p64 => { var buf: [8]u8 = undefined; - mem.writeIntLittle(u64, &buf, entry_value + slide); + mem.writeInt(u64, &buf, entry_value + slide, .Little); writeMem(handle, pvaddr, &buf) catch |err| { log.warn("writing to protected memory failed with error: {s}", .{@errorName(err)}); }; @@ -2076,7 +2076,7 @@ fn writeImportTables(self: *Coff) !void { lookup_table_offset += lookup_entry_size; // Names table entry - mem.writeIntLittle(u16, buffer.items[names_table_offset..][0..2], 0); // Hint set to 0 until we learn how to parse DLLs + mem.writeInt(u16, buffer.items[names_table_offset..][0..2], 0, .Little); // Hint set to 0 until we learn how to parse DLLs names_table_offset += 2; @memcpy(buffer.items[names_table_offset..][0..import_name.len], import_name); names_table_offset += @as(u32, @intCast(import_name.len)); @@ -2089,7 +2089,7 @@ fn writeImportTables(self: *Coff) !void { } // IAT sentinel - mem.writeIntLittle(u64, buffer.items[iat_offset..][0..lookup_entry_size], 0); + mem.writeInt(u64, buffer.items[iat_offset..][0..lookup_entry_size], 0, .Little); iat_offset += 8; // Lookup table sentinel @@ -2157,7 +2157,7 @@ fn writeStrtab(self: *Coff) !void { buffer.appendSliceAssumeCapacity(self.strtab.items()); // Here, we do a trick in that we do not commit the size of the strtab to strtab buffer, instead // we write the length of the strtab to a temporary buffer that goes to file. - mem.writeIntLittle(u32, buffer.items[0..4], @as(u32, @intCast(self.strtab.len()))); + mem.writeInt(u32, buffer.items[0..4], @as(u32, @intCast(self.strtab.len())), .Little); try self.base.file.?.pwriteAll(buffer.items, self.strtab_offset.?); } @@ -2180,7 +2180,7 @@ fn writeHeader(self: *Coff) !void { try buffer.ensureTotalCapacity(self.getSizeOfHeaders()); writer.writeAll(msdos_stub) catch unreachable; - mem.writeIntLittle(u32, buffer.items[0x3c..][0..4], msdos_stub.len); + mem.writeInt(u32, buffer.items[0x3c..][0..4], msdos_stub.len, .Little); writer.writeAll("PE\x00\x00") catch unreachable; var flags = coff.CoffHeaderFlags{ @@ -2548,7 +2548,7 @@ fn setSymbolName(self: *Coff, symbol: *coff.Symbol, name: []const u8) !void { } const offset = try self.strtab.insert(self.base.allocator, name); @memset(symbol.name[0..4], 0); - mem.writeIntLittle(u32, symbol.name[4..8], offset); + mem.writeInt(u32, symbol.name[4..8], offset, .Little); } fn logSymAttributes(sym: *const coff.Symbol, buf: *[4]u8) []const u8 { diff --git a/src/link/Coff/Relocation.zig b/src/link/Coff/Relocation.zig index ded7483667..050ab0d9be 100644 --- a/src/link/Coff/Relocation.zig +++ b/src/link/Coff/Relocation.zig @@ -137,7 +137,7 @@ fn resolveAarch64(self: Relocation, ctx: Context) void { }; inst.pc_relative_address.immhi = @as(u19, @truncate(pages >> 2)); inst.pc_relative_address.immlo = @as(u2, @truncate(pages)); - mem.writeIntLittle(u32, buffer[0..4], inst.toU32()); + mem.writeInt(u32, buffer[0..4], inst.toU32(), .Little); }, .got_pageoff, .import_pageoff, .pageoff => { assert(!self.pcrel); @@ -151,7 +151,7 @@ fn resolveAarch64(self: Relocation, ctx: Context) void { ), buffer[0..4]), }; inst.add_subtract_immediate.imm12 = narrowed; - mem.writeIntLittle(u32, buffer[0..4], inst.toU32()); + mem.writeInt(u32, buffer[0..4], inst.toU32(), .Little); } else { var inst = aarch64.Instruction{ .load_store_register = mem.bytesToValue(meta.TagPayload( @@ -173,18 +173,19 @@ fn resolveAarch64(self: Relocation, ctx: Context) void { } }; inst.load_store_register.offset = offset; - mem.writeIntLittle(u32, buffer[0..4], inst.toU32()); + mem.writeInt(u32, buffer[0..4], inst.toU32(), .Little); } }, .direct => { assert(!self.pcrel); switch (self.length) { - 2 => mem.writeIntLittle( + 2 => mem.writeInt( u32, buffer[0..4], @as(u32, @truncate(ctx.target_vaddr + ctx.image_base)), + .Little, ), - 3 => mem.writeIntLittle(u64, buffer[0..8], ctx.target_vaddr + ctx.image_base), + 3 => mem.writeInt(u64, buffer[0..8], ctx.target_vaddr + ctx.image_base, .Little), else => unreachable, } }, @@ -207,17 +208,17 @@ fn resolveX86(self: Relocation, ctx: Context) void { .got, .import => { assert(self.pcrel); const disp = @as(i32, @intCast(ctx.target_vaddr)) - @as(i32, @intCast(ctx.source_vaddr)) - 4; - mem.writeIntLittle(i32, buffer[0..4], disp); + mem.writeInt(i32, buffer[0..4], disp, .Little); }, .direct => { if (self.pcrel) { const disp = @as(i32, @intCast(ctx.target_vaddr)) - @as(i32, @intCast(ctx.source_vaddr)) - 4; - mem.writeIntLittle(i32, buffer[0..4], disp); + mem.writeInt(i32, buffer[0..4], disp, .Little); } else switch (ctx.ptr_width) { - .p32 => mem.writeIntLittle(u32, buffer[0..4], @as(u32, @intCast(ctx.target_vaddr + ctx.image_base))), + .p32 => mem.writeInt(u32, buffer[0..4], @as(u32, @intCast(ctx.target_vaddr + ctx.image_base)), .Little), .p64 => switch (self.length) { - 2 => mem.writeIntLittle(u32, buffer[0..4], @as(u32, @truncate(ctx.target_vaddr + ctx.image_base))), - 3 => mem.writeIntLittle(u64, buffer[0..8], ctx.target_vaddr + ctx.image_base), + 2 => mem.writeInt(u32, buffer[0..4], @as(u32, @truncate(ctx.target_vaddr + ctx.image_base)), .Little), + 3 => mem.writeInt(u64, buffer[0..8], ctx.target_vaddr + ctx.image_base, .Little), else => unreachable, }, } diff --git a/src/link/Elf/Atom.zig b/src/link/Elf/Atom.zig index bb988a678f..f3b41f2e10 100644 --- a/src/link/Elf/Atom.zig +++ b/src/link/Elf/Atom.zig @@ -786,43 +786,43 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, code: []u8) !void { elf.R_X86_64_PLT32, elf.R_X86_64_PC32, - => try cwriter.writeIntLittle(i32, @as(i32, @intCast(S + A - P))), + => try cwriter.writeInt(i32, @as(i32, @intCast(S + A - P)), .Little), - elf.R_X86_64_GOTPCREL => try cwriter.writeIntLittle(i32, @as(i32, @intCast(G + GOT + A - P))), - elf.R_X86_64_GOTPC32 => try cwriter.writeIntLittle(i32, @as(i32, @intCast(GOT + A - P))), - elf.R_X86_64_GOTPC64 => try cwriter.writeIntLittle(i64, GOT + A - P), + elf.R_X86_64_GOTPCREL => try cwriter.writeInt(i32, @as(i32, @intCast(G + GOT + A - P)), .Little), + elf.R_X86_64_GOTPC32 => try cwriter.writeInt(i32, @as(i32, @intCast(GOT + A - P)), .Little), + elf.R_X86_64_GOTPC64 => try cwriter.writeInt(i64, GOT + A - P, .Little), elf.R_X86_64_GOTPCRELX => { if (!target.flags.import and !target.isIFunc(elf_file) and !target.isAbs(elf_file)) blk: { x86_64.relaxGotpcrelx(code[r_offset - 2 ..]) catch break :blk; - try cwriter.writeIntLittle(i32, @as(i32, @intCast(S + A - P))); + try cwriter.writeInt(i32, @as(i32, @intCast(S + A - P)), .Little); continue; } - try cwriter.writeIntLittle(i32, @as(i32, @intCast(G + GOT + A - P))); + try cwriter.writeInt(i32, @as(i32, @intCast(G + GOT + A - P)), .Little); }, elf.R_X86_64_REX_GOTPCRELX => { if (!target.flags.import and !target.isIFunc(elf_file) and !target.isAbs(elf_file)) blk: { x86_64.relaxRexGotpcrelx(code[r_offset - 3 ..]) catch break :blk; - try cwriter.writeIntLittle(i32, @as(i32, @intCast(S + A - P))); + try cwriter.writeInt(i32, @as(i32, @intCast(S + A - P)), .Little); continue; } - try cwriter.writeIntLittle(i32, @as(i32, @intCast(G + GOT + A - P))); + try cwriter.writeInt(i32, @as(i32, @intCast(G + GOT + A - P)), .Little); }, - elf.R_X86_64_32 => try cwriter.writeIntLittle(u32, @as(u32, @truncate(@as(u64, @intCast(S + A))))), - elf.R_X86_64_32S => try cwriter.writeIntLittle(i32, @as(i32, @truncate(S + A))), + elf.R_X86_64_32 => try cwriter.writeInt(u32, @as(u32, @truncate(@as(u64, @intCast(S + A)))), .Little), + elf.R_X86_64_32S => try cwriter.writeInt(i32, @as(i32, @truncate(S + A)), .Little), - elf.R_X86_64_TPOFF32 => try cwriter.writeIntLittle(i32, @as(i32, @truncate(S + A - TP))), - elf.R_X86_64_TPOFF64 => try cwriter.writeIntLittle(i64, S + A - TP), + elf.R_X86_64_TPOFF32 => try cwriter.writeInt(i32, @as(i32, @truncate(S + A - TP)), .Little), + elf.R_X86_64_TPOFF64 => try cwriter.writeInt(i64, S + A - TP, .Little), - elf.R_X86_64_DTPOFF32 => try cwriter.writeIntLittle(i32, @as(i32, @truncate(S + A - DTP))), - elf.R_X86_64_DTPOFF64 => try cwriter.writeIntLittle(i64, S + A - DTP), + elf.R_X86_64_DTPOFF32 => try cwriter.writeInt(i32, @as(i32, @truncate(S + A - DTP)), .Little), + elf.R_X86_64_DTPOFF64 => try cwriter.writeInt(i64, S + A - DTP, .Little), elf.R_X86_64_TLSGD => { if (target.flags.has_tlsgd) { const S_ = @as(i64, @intCast(target.tlsGdAddress(elf_file))); - try cwriter.writeIntLittle(i32, @as(i32, @intCast(S_ + A - P))); + try cwriter.writeInt(i32, @as(i32, @intCast(S_ + A - P)), .Little); } else if (target.flags.has_gottp) { const S_ = @as(i64, @intCast(target.gotTpAddress(elf_file))); try x86_64.relaxTlsGdToIe(self, rels[i .. i + 2], @intCast(S_ - P), elf_file, &stream); @@ -843,7 +843,7 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, code: []u8) !void { if (elf_file.got.tlsld_index) |entry_index| { const tlsld_entry = elf_file.got.entries.items[entry_index]; const S_ = @as(i64, @intCast(tlsld_entry.address(elf_file))); - try cwriter.writeIntLittle(i32, @as(i32, @intCast(S_ + A - P))); + try cwriter.writeInt(i32, @as(i32, @intCast(S_ + A - P)), .Little); } else { try x86_64.relaxTlsLdToLe( self, @@ -859,10 +859,10 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, code: []u8) !void { elf.R_X86_64_GOTPC32_TLSDESC => { if (target.flags.has_tlsdesc) { const S_ = @as(i64, @intCast(target.tlsDescAddress(elf_file))); - try cwriter.writeIntLittle(i32, @as(i32, @intCast(S_ + A - P))); + try cwriter.writeInt(i32, @as(i32, @intCast(S_ + A - P)), .Little); } else { try x86_64.relaxGotPcTlsDesc(code[r_offset - 3 ..]); - try cwriter.writeIntLittle(i32, @as(i32, @intCast(S - TP))); + try cwriter.writeInt(i32, @as(i32, @intCast(S - TP)), .Little); } }, @@ -874,18 +874,18 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, code: []u8) !void { elf.R_X86_64_GOTTPOFF => { if (target.flags.has_gottp) { const S_ = @as(i64, @intCast(target.gotTpAddress(elf_file))); - try cwriter.writeIntLittle(i32, @as(i32, @intCast(S_ + A - P))); + try cwriter.writeInt(i32, @as(i32, @intCast(S_ + A - P)), .Little); } else { x86_64.relaxGotTpOff(code[r_offset - 3 ..]) catch unreachable; - try cwriter.writeIntLittle(i32, @as(i32, @intCast(S - TP))); + try cwriter.writeInt(i32, @as(i32, @intCast(S - TP)), .Little); } }, - elf.R_X86_64_GOT32 => try cwriter.writeIntLittle(i32, @as(i32, @intCast(G + GOT + A))), + elf.R_X86_64_GOT32 => try cwriter.writeInt(i32, @as(i32, @intCast(G + GOT + A)), .Little), // Zig custom relocations - Elf.R_X86_64_ZIG_GOT32 => try cwriter.writeIntLittle(u32, @as(u32, @intCast(ZIG_GOT + A))), - Elf.R_X86_64_ZIG_GOTPCREL => try cwriter.writeIntLittle(i32, @as(i32, @intCast(ZIG_GOT + A - P))), + Elf.R_X86_64_ZIG_GOT32 => try cwriter.writeInt(u32, @as(u32, @intCast(ZIG_GOT + A)), .Little), + Elf.R_X86_64_ZIG_GOTPCREL => try cwriter.writeInt(i32, @as(i32, @intCast(ZIG_GOT + A - P)), .Little), else => {}, } @@ -920,7 +920,7 @@ fn resolveDynAbsReloc( .copyrel, .cplt, .none, - => try writer.writeIntLittle(i32, @as(i32, @truncate(S + A))), + => try writer.writeInt(i32, @as(i32, @truncate(S + A)), .Little), .dyn_copyrel => { if (is_writeable or elf_file.base.options.z_nocopyreloc) { @@ -932,7 +932,7 @@ fn resolveDynAbsReloc( }); try applyDynamicReloc(A, elf_file, writer); } else { - try writer.writeIntLittle(i32, @as(i32, @truncate(S + A))); + try writer.writeInt(i32, @as(i32, @truncate(S + A)), .Little); } }, @@ -946,7 +946,7 @@ fn resolveDynAbsReloc( }); try applyDynamicReloc(A, elf_file, writer); } else { - try writer.writeIntLittle(i32, @as(i32, @truncate(S + A))); + try writer.writeInt(i32, @as(i32, @truncate(S + A)), .Little); } }, @@ -984,7 +984,7 @@ fn resolveDynAbsReloc( fn applyDynamicReloc(value: i64, elf_file: *Elf, writer: anytype) !void { _ = elf_file; // if (elf_file.options.apply_dynamic_relocs) { - try writer.writeIntLittle(i64, value); + try writer.writeInt(i64, value, .Little); // } } @@ -1058,22 +1058,22 @@ pub fn resolveRelocsNonAlloc(self: Atom, elf_file: *Elf, code: []u8, undefs: any switch (r_type) { elf.R_X86_64_NONE => unreachable, - elf.R_X86_64_8 => try cwriter.writeIntLittle(u8, @as(u8, @bitCast(@as(i8, @intCast(S + A))))), - elf.R_X86_64_16 => try cwriter.writeIntLittle(u16, @as(u16, @bitCast(@as(i16, @intCast(S + A))))), - elf.R_X86_64_32 => try cwriter.writeIntLittle(u32, @as(u32, @bitCast(@as(i32, @intCast(S + A))))), - elf.R_X86_64_32S => try cwriter.writeIntLittle(i32, @as(i32, @intCast(S + A))), - elf.R_X86_64_64 => try cwriter.writeIntLittle(i64, S + A), - elf.R_X86_64_DTPOFF32 => try cwriter.writeIntLittle(i32, @as(i32, @intCast(S + A - DTP))), - elf.R_X86_64_DTPOFF64 => try cwriter.writeIntLittle(i64, S + A - DTP), - elf.R_X86_64_GOTOFF64 => try cwriter.writeIntLittle(i64, S + A - GOT), - elf.R_X86_64_GOTPC64 => try cwriter.writeIntLittle(i64, GOT + A), + elf.R_X86_64_8 => try cwriter.writeInt(u8, @as(u8, @bitCast(@as(i8, @intCast(S + A)))), .Little), + elf.R_X86_64_16 => try cwriter.writeInt(u16, @as(u16, @bitCast(@as(i16, @intCast(S + A)))), .Little), + elf.R_X86_64_32 => try cwriter.writeInt(u32, @as(u32, @bitCast(@as(i32, @intCast(S + A)))), .Little), + elf.R_X86_64_32S => try cwriter.writeInt(i32, @as(i32, @intCast(S + A)), .Little), + elf.R_X86_64_64 => try cwriter.writeInt(i64, S + A, .Little), + elf.R_X86_64_DTPOFF32 => try cwriter.writeInt(i32, @as(i32, @intCast(S + A - DTP)), .Little), + elf.R_X86_64_DTPOFF64 => try cwriter.writeInt(i64, S + A - DTP, .Little), + elf.R_X86_64_GOTOFF64 => try cwriter.writeInt(i64, S + A - GOT, .Little), + elf.R_X86_64_GOTPC64 => try cwriter.writeInt(i64, GOT + A, .Little), elf.R_X86_64_SIZE32 => { const size = @as(i64, @intCast(target.elfSym(elf_file).st_size)); - try cwriter.writeIntLittle(u32, @as(u32, @bitCast(@as(i32, @intCast(size + A))))); + try cwriter.writeInt(u32, @as(u32, @bitCast(@as(i32, @intCast(size + A)))), .Little); }, elf.R_X86_64_SIZE64 => { const size = @as(i64, @intCast(target.elfSym(elf_file).st_size)); - try cwriter.writeIntLittle(i64, @as(i64, @intCast(size + A))); + try cwriter.writeInt(i64, @as(i64, @intCast(size + A)), .Little); }, else => try self.reportUnhandledRelocError(rel, elf_file), } @@ -1254,7 +1254,7 @@ const x86_64 = struct { 0x64, 0x48, 0x8b, 0x04, 0x25, 0, 0, 0, 0, // movq %fs:0,%rax 0x48, 0x03, 0x05, 0, 0, 0, 0, // add foo@gottpoff(%rip), %rax }; - std.mem.writeIntLittle(i32, insts[12..][0..4], value - 12); + std.mem.writeInt(i32, insts[12..][0..4], value - 12, .Little); try stream.seekBy(-4); try writer.writeAll(&insts); }, @@ -1292,7 +1292,7 @@ const x86_64 = struct { 0x64, 0x48, 0x8b, 0, // mov %fs:(%rax), %rax 0x48, 0x2d, 0, 0, 0, 0, // sub $tls_size, %rax }; - std.mem.writeIntLittle(i32, insts[8..][0..4], value); + std.mem.writeInt(i32, insts[8..][0..4], value, .Little); try stream.seekBy(-3); try writer.writeAll(&insts); }, @@ -1306,7 +1306,7 @@ const x86_64 = struct { 0x48, 0x2d, 0, 0, 0, 0, // sub $tls_size, %rax 0x90, // nop }; - std.mem.writeIntLittle(i32, insts[8..][0..4], value); + std.mem.writeInt(i32, insts[8..][0..4], value, .Little); try stream.seekBy(-3); try writer.writeAll(&insts); }, @@ -1392,7 +1392,7 @@ const x86_64 = struct { 0x64, 0x48, 0x8b, 0x04, 0x25, 0, 0, 0, 0, // movq %fs:0,%rax 0x48, 0x81, 0xc0, 0, 0, 0, 0, // add $tp_offset, %rax }; - std.mem.writeIntLittle(i32, insts[12..][0..4], value); + std.mem.writeInt(i32, insts[12..][0..4], value, .Little); try stream.seekBy(-4); try writer.writeAll(&insts); relocs_log.debug(" relaxing {} and {}", .{ diff --git a/src/link/Elf/eh_frame.zig b/src/link/Elf/eh_frame.zig index 468f673a9a..3f291f9a77 100644 --- a/src/link/Elf/eh_frame.zig +++ b/src/link/Elf/eh_frame.zig @@ -33,7 +33,7 @@ pub const Fde = struct { pub fn ciePointer(fde: Fde, elf_file: *Elf) u32 { const fde_data = fde.data(elf_file); - return std.mem.readIntLittle(u32, fde_data[4..8]); + return std.mem.readInt(u32, fde_data[4..8], .Little); } pub fn calcSize(fde: Fde) usize { @@ -217,10 +217,10 @@ pub const Iterator = struct { var stream = std.io.fixedBufferStream(it.data[it.pos..]); const reader = stream.reader(); - var size = try reader.readIntLittle(u32); + var size = try reader.readInt(u32, .Little); if (size == 0xFFFFFFFF) @panic("TODO"); - const id = try reader.readIntLittle(u32); + const id = try reader.readInt(u32, .Little); const record = Record{ .tag = if (id == 0) .cie else .fde, .offset = it.pos, @@ -298,10 +298,10 @@ fn resolveReloc(rec: anytype, sym: *const Symbol, rel: elf.Elf64_Rela, elf_file: var where = contents[offset..]; switch (rel.r_type()) { - elf.R_X86_64_32 => std.mem.writeIntLittle(i32, where[0..4], @as(i32, @truncate(S + A))), - elf.R_X86_64_64 => std.mem.writeIntLittle(i64, where[0..8], S + A), - elf.R_X86_64_PC32 => std.mem.writeIntLittle(i32, where[0..4], @as(i32, @intCast(S - P + A))), - elf.R_X86_64_PC64 => std.mem.writeIntLittle(i64, where[0..8], S - P + A), + elf.R_X86_64_32 => std.mem.writeInt(i32, where[0..4], @as(i32, @truncate(S + A)), .Little), + elf.R_X86_64_64 => std.mem.writeInt(i64, where[0..8], S + A, .Little), + elf.R_X86_64_PC32 => std.mem.writeInt(i32, where[0..4], @as(i32, @intCast(S - P + A)), .Little), + elf.R_X86_64_PC64 => std.mem.writeInt(i64, where[0..8], S - P + A, .Little), else => unreachable, } } @@ -338,10 +338,11 @@ pub fn writeEhFrame(elf_file: *Elf, writer: anytype) !void { const contents = try gpa.dupe(u8, fde.data(elf_file)); defer gpa.free(contents); - std.mem.writeIntLittle( + std.mem.writeInt( i32, contents[4..8], - @as(i32, @truncate(@as(i64, @intCast(fde.out_offset + 4)) - @as(i64, @intCast(fde.cie(elf_file).out_offset)))), + @truncate(@as(i64, @intCast(fde.out_offset + 4)) - @as(i64, @intCast(fde.cie(elf_file).out_offset))), + .Little, ); for (fde.relocs(elf_file)) |rel| { @@ -353,7 +354,7 @@ pub fn writeEhFrame(elf_file: *Elf, writer: anytype) !void { } } - try writer.writeIntLittle(u32, 0); + try writer.writeInt(u32, 0, .Little); } pub fn writeEhFrameHdr(elf_file: *Elf, writer: anytype) !void { @@ -365,14 +366,15 @@ pub fn writeEhFrameHdr(elf_file: *Elf, writer: anytype) !void { const eh_frame_shdr = elf_file.shdrs.items[elf_file.eh_frame_section_index.?]; const eh_frame_hdr_shdr = elf_file.shdrs.items[elf_file.eh_frame_hdr_section_index.?]; const num_fdes = @as(u32, @intCast(@divExact(eh_frame_hdr_shdr.sh_size - eh_frame_hdr_header_size, 8))); - try writer.writeIntLittle( + try writer.writeInt( u32, @as(u32, @bitCast(@as( i32, @truncate(@as(i64, @intCast(eh_frame_shdr.sh_addr)) - @as(i64, @intCast(eh_frame_hdr_shdr.sh_addr)) - 4), ))), + .Little, ); - try writer.writeIntLittle(u32, num_fdes); + try writer.writeInt(u32, num_fdes, .Little); const Entry = struct { init_addr: u32, @@ -401,7 +403,7 @@ pub fn writeEhFrameHdr(elf_file: *Elf, writer: anytype) !void { const S = @as(i64, @intCast(sym.address(.{}, elf_file))); const A = rel.r_addend; entries.appendAssumeCapacity(.{ - .init_addr = @as(u32, @bitCast(@as(i32, @truncate(S + A - @as(i64, @intCast(eh_frame_hdr_shdr.sh_addr)))))), + .init_addr = @bitCast(@as(i32, @truncate(S + A - @as(i64, @intCast(eh_frame_hdr_shdr.sh_addr))))), .fde_addr = @as( u32, @bitCast(@as(i32, @truncate(P - @as(i64, @intCast(eh_frame_hdr_shdr.sh_addr))))), diff --git a/src/link/Elf/synthetic_sections.zig b/src/link/Elf/synthetic_sections.zig index 91b9cc1248..0d78aea322 100644 --- a/src/link/Elf/synthetic_sections.zig +++ b/src/link/Elf/synthetic_sections.zig @@ -878,9 +878,9 @@ pub const PltSection = struct { 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp qword ptr [rip] -> .got.plt[2] }; var disp = @as(i64, @intCast(got_plt_addr + 8)) - @as(i64, @intCast(plt_addr + 8)) - 4; - mem.writeIntLittle(i32, preamble[8..][0..4], @as(i32, @intCast(disp))); + mem.writeInt(i32, preamble[8..][0..4], @as(i32, @intCast(disp)), .Little); disp = @as(i64, @intCast(got_plt_addr + 16)) - @as(i64, @intCast(plt_addr + 14)) - 4; - mem.writeIntLittle(i32, preamble[14..][0..4], @as(i32, @intCast(disp))); + mem.writeInt(i32, preamble[14..][0..4], @as(i32, @intCast(disp)), .Little); try writer.writeAll(&preamble); try writer.writeByteNTimes(0xcc, preamble_size - preamble.len); @@ -894,8 +894,8 @@ pub const PltSection = struct { 0x41, 0xbb, 0x00, 0x00, 0x00, 0x00, // mov r11d, N 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp qword ptr [rip] -> .got.plt[N] }; - mem.writeIntLittle(i32, entry[6..][0..4], @as(i32, @intCast(i))); - mem.writeIntLittle(i32, entry[12..][0..4], @as(i32, @intCast(disp))); + mem.writeInt(i32, entry[6..][0..4], @as(i32, @intCast(i)), .Little); + mem.writeInt(i32, entry[12..][0..4], @as(i32, @intCast(disp)), .Little); try writer.writeAll(&entry); } } @@ -971,17 +971,17 @@ pub const GotPltSection = struct { { // [0]: _DYNAMIC const symbol = elf_file.symbol(elf_file.dynamic_index.?); - try writer.writeIntLittle(u64, symbol.value); + try writer.writeInt(u64, symbol.value, .Little); } // [1]: 0x0 // [2]: 0x0 - try writer.writeIntLittle(u64, 0x0); - try writer.writeIntLittle(u64, 0x0); + try writer.writeInt(u64, 0x0, .Little); + try writer.writeInt(u64, 0x0, .Little); if (elf_file.plt_section_index) |shndx| { const plt_addr = elf_file.shdrs.items[shndx].sh_addr; for (0..elf_file.plt.symbols.items.len) |_| { // [N]: .plt - try writer.writeIntLittle(u64, plt_addr); + try writer.writeInt(u64, plt_addr, .Little); } } } @@ -1023,7 +1023,7 @@ pub const PltGotSection = struct { 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp qword ptr [rip] -> .got[N] 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, }; - mem.writeIntLittle(i32, entry[6..][0..4], @as(i32, @intCast(disp))); + mem.writeInt(i32, entry[6..][0..4], @as(i32, @intCast(disp)), .Little); try writer.writeAll(&entry); } } @@ -1258,8 +1258,8 @@ pub const HashSection = struct { } try hs.buffer.ensureTotalCapacityPrecise(gpa, (2 + nsyms * 2) * 4); - hs.buffer.writer(gpa).writeIntLittle(u32, @as(u32, @intCast(nsyms))) catch unreachable; - hs.buffer.writer(gpa).writeIntLittle(u32, @as(u32, @intCast(nsyms))) catch unreachable; + hs.buffer.writer(gpa).writeInt(u32, @as(u32, @intCast(nsyms)), .Little) catch unreachable; + hs.buffer.writer(gpa).writeInt(u32, @as(u32, @intCast(nsyms)), .Little) catch unreachable; hs.buffer.writer(gpa).writeAll(mem.sliceAsBytes(buckets)) catch unreachable; hs.buffer.writer(gpa).writeAll(mem.sliceAsBytes(chains)) catch unreachable; } @@ -1322,10 +1322,10 @@ pub const GnuHashSection = struct { var counting = std.io.countingWriter(writer); const cwriter = counting.writer(); - try cwriter.writeIntLittle(u32, hash.num_buckets); - try cwriter.writeIntLittle(u32, export_off); - try cwriter.writeIntLittle(u32, hash.num_bloom); - try cwriter.writeIntLittle(u32, bloom_shift); + try cwriter.writeInt(u32, hash.num_buckets, .Little); + try cwriter.writeInt(u32, export_off, .Little); + try cwriter.writeInt(u32, hash.num_bloom, .Little); + try cwriter.writeInt(u32, bloom_shift, .Little); const gpa = elf_file.base.allocator; const hashes = try gpa.alloc(u32, exports.len); diff --git a/src/link/MachO.zig b/src/link/MachO.zig index f3f9f5b4b8..55b9c617b1 100644 --- a/src/link/MachO.zig +++ b/src/link/MachO.zig @@ -1222,7 +1222,7 @@ fn writeOffsetTableEntry(self: *MachO, index: usize) !void { log.debug("writing GOT entry {d}: @{x} => {x}", .{ index, vmaddr, entry_value }); var buf: [@sizeOf(u64)]u8 = undefined; - mem.writeIntLittle(u64, &buf, entry_value); + mem.writeInt(u64, &buf, entry_value, .Little); try self.base.file.?.pwriteAll(&buf, file_offset); if (is_hot_update_compatible) { @@ -1329,7 +1329,7 @@ fn writeStubTableEntry(self: *MachO, index: usize) !void { { var buf: [@sizeOf(u64)]u8 = undefined; - mem.writeIntLittle(u64, &buf, stub_helper_addr); + mem.writeInt(u64, &buf, stub_helper_addr, .Little); const off = laptr_header.offset + @sizeOf(u64) * index; try self.base.file.?.pwriteAll(&buf, off); } @@ -3773,7 +3773,7 @@ fn collectBindData(self: *MachO, bind: anytype, raw_bindings: anytype) !void { const base_offset = sym.n_value - segment.vmaddr; const rel_offset = @as(u32, @intCast(rel.r_address - ctx.base_offset)); const offset = @as(u64, @intCast(base_offset + rel_offset)); - const addend = mem.readIntLittle(i64, code[rel_offset..][0..8]); + const addend = mem.readInt(i64, code[rel_offset..][0..8], .Little); const dylib_ordinal = @divTrunc(@as(i16, @bitCast(bind_sym.n_desc)), macho.N_SYMBOL_RESOLVER); log.debug(" | bind at {x}, import('{s}') in dylib({d})", .{ @@ -4502,7 +4502,7 @@ pub fn writeDysymtab(self: *MachO, ctx: SymtabCtx) !void { if (!self.stub_table.lookup.contains(entry)) continue; const target_sym = self.getSymbol(entry); assert(target_sym.undf()); - try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry).?); + try writer.writeInt(u32, iundefsym + ctx.imports_table.get(entry).?, .Little); } } @@ -4513,9 +4513,9 @@ pub fn writeDysymtab(self: *MachO, ctx: SymtabCtx) !void { if (!self.got_table.lookup.contains(entry)) continue; const target_sym = self.getSymbol(entry); if (target_sym.undf()) { - try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry).?); + try writer.writeInt(u32, iundefsym + ctx.imports_table.get(entry).?, .Little); } else { - try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL); + try writer.writeInt(u32, macho.INDIRECT_SYMBOL_LOCAL, .Little); } } } @@ -4527,7 +4527,7 @@ pub fn writeDysymtab(self: *MachO, ctx: SymtabCtx) !void { if (!self.stub_table.lookup.contains(entry)) continue; const target_sym = self.getSymbol(entry); assert(target_sym.undf()); - try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry).?); + try writer.writeInt(u32, iundefsym + ctx.imports_table.get(entry).?, .Little); } } diff --git a/src/link/MachO/Archive.zig b/src/link/MachO/Archive.zig index 6d1c769f04..fec7ce65ef 100644 --- a/src/link/MachO/Archive.zig +++ b/src/link/MachO/Archive.zig @@ -123,7 +123,7 @@ fn parseName(allocator: Allocator, name_or_length: ar_hdr.NameOrLength, reader: } fn parseTableOfContents(self: *Archive, allocator: Allocator, reader: anytype) !void { - const symtab_size = try reader.readIntLittle(u32); + const symtab_size = try reader.readInt(u32, .Little); var symtab = try allocator.alloc(u8, symtab_size); defer allocator.free(symtab); @@ -132,7 +132,7 @@ fn parseTableOfContents(self: *Archive, allocator: Allocator, reader: anytype) ! return error.MalformedArchive; }; - const strtab_size = try reader.readIntLittle(u32); + const strtab_size = try reader.readInt(u32, .Little); var strtab = try allocator.alloc(u8, strtab_size); defer allocator.free(strtab); @@ -145,11 +145,11 @@ fn parseTableOfContents(self: *Archive, allocator: Allocator, reader: anytype) ! var symtab_reader = symtab_stream.reader(); while (true) { - const n_strx = symtab_reader.readIntLittle(u32) catch |err| switch (err) { + const n_strx = symtab_reader.readInt(u32, .Little) catch |err| switch (err) { error.EndOfStream => break, else => |e| return e, }; - const object_offset = try symtab_reader.readIntLittle(u32); + const object_offset = try symtab_reader.readInt(u32, .Little); const sym_name = mem.sliceTo(@as([*:0]const u8, @ptrCast(strtab.ptr + n_strx)), 0); const owned_name = try allocator.dupe(u8, sym_name); diff --git a/src/link/MachO/Atom.zig b/src/link/MachO/Atom.zig index 25fc0aee24..4c8fc03e3c 100644 --- a/src/link/MachO/Atom.zig +++ b/src/link/MachO/Atom.zig @@ -443,9 +443,9 @@ pub fn parseRelocTarget(macho_file: *MachO, ctx: struct { const address_in_section = if (ctx.rel.r_pcrel == 0) blk: { break :blk if (ctx.rel.r_length == 3) - mem.readIntLittle(u64, ctx.code[rel_offset..][0..8]) + mem.readInt(u64, ctx.code[rel_offset..][0..8], .Little) else - mem.readIntLittle(u32, ctx.code[rel_offset..][0..4]); + mem.readInt(u32, ctx.code[rel_offset..][0..4], .Little); } else blk: { assert(macho_file.base.options.target.cpu.arch == .x86_64); const correction: u3 = switch (@as(macho.reloc_type_x86_64, @enumFromInt(ctx.rel.r_type))) { @@ -455,7 +455,7 @@ pub fn parseRelocTarget(macho_file: *MachO, ctx: struct { .X86_64_RELOC_SIGNED_4 => 4, else => unreachable, }; - const addend = mem.readIntLittle(i32, ctx.code[rel_offset..][0..4]); + const addend = mem.readInt(i32, ctx.code[rel_offset..][0..4], .Little); const target_address = @as(i64, @intCast(ctx.base_addr)) + ctx.rel.r_address + 4 + correction + addend; break :blk @as(u64, @intCast(target_address)); }; @@ -781,7 +781,7 @@ fn resolveRelocsArm64( ), code), }; inst.unconditional_branch_immediate.imm26 = @as(u26, @truncate(@as(u28, @bitCast(displacement >> 2)))); - mem.writeIntLittle(u32, code, inst.toU32()); + mem.writeInt(u32, code, inst.toU32(), .Little); }, .ARM64_RELOC_PAGE21, @@ -802,7 +802,7 @@ fn resolveRelocsArm64( }; inst.pc_relative_address.immhi = @as(u19, @truncate(pages >> 2)); inst.pc_relative_address.immlo = @as(u2, @truncate(pages)); - mem.writeIntLittle(u32, code, inst.toU32()); + mem.writeInt(u32, code, inst.toU32(), .Little); addend = null; }, @@ -821,7 +821,7 @@ fn resolveRelocsArm64( ), code), }; inst.add_subtract_immediate.imm12 = off; - mem.writeIntLittle(u32, code, inst.toU32()); + mem.writeInt(u32, code, inst.toU32(), .Little); } else { var inst = aarch64.Instruction{ .load_store_register = mem.bytesToValue(meta.TagPayload( @@ -839,7 +839,7 @@ fn resolveRelocsArm64( 3 => .load_store_64, }); inst.load_store_register.offset = off; - mem.writeIntLittle(u32, code, inst.toU32()); + mem.writeInt(u32, code, inst.toU32(), .Little); } addend = null; }, @@ -858,7 +858,7 @@ fn resolveRelocsArm64( ), code), }; inst.load_store_register.offset = off; - mem.writeIntLittle(u32, code, inst.toU32()); + mem.writeInt(u32, code, inst.toU32(), .Little); addend = null; }, @@ -918,7 +918,7 @@ fn resolveRelocsArm64( .sf = @as(u1, @truncate(reg_info.size)), }, }; - mem.writeIntLittle(u32, code, inst.toU32()); + mem.writeInt(u32, code, inst.toU32(), .Little); addend = null; }, @@ -926,14 +926,14 @@ fn resolveRelocsArm64( relocs_log.debug(" | target_addr = 0x{x}", .{target_addr}); const result = math.cast(i32, @as(i64, @intCast(target_addr)) - @as(i64, @intCast(source_addr))) orelse return error.Overflow; - mem.writeIntLittle(u32, atom_code[rel_offset..][0..4], @as(u32, @bitCast(result))); + mem.writeInt(u32, atom_code[rel_offset..][0..4], @as(u32, @bitCast(result)), .Little); }, .ARM64_RELOC_UNSIGNED => { var ptr_addend = if (rel.r_length == 3) - mem.readIntLittle(i64, atom_code[rel_offset..][0..8]) + mem.readInt(i64, atom_code[rel_offset..][0..8], .Little) else - mem.readIntLittle(i32, atom_code[rel_offset..][0..4]); + mem.readInt(i32, atom_code[rel_offset..][0..4], .Little); if (rel.r_extern == 0) { const base_addr = if (target.sym_index >= object.source_address_lookup.len) @@ -954,9 +954,9 @@ fn resolveRelocsArm64( relocs_log.debug(" | target_addr = 0x{x}", .{result}); if (rel.r_length == 3) { - mem.writeIntLittle(u64, atom_code[rel_offset..][0..8], @as(u64, @bitCast(result))); + mem.writeInt(u64, atom_code[rel_offset..][0..8], @as(u64, @bitCast(result)), .Little); } else { - mem.writeIntLittle(u32, atom_code[rel_offset..][0..4], @as(u32, @truncate(@as(u64, @bitCast(result))))); + mem.writeInt(u32, atom_code[rel_offset..][0..4], @as(u32, @truncate(@as(u64, @bitCast(result)))), .Little); } subtractor = null; @@ -1045,25 +1045,25 @@ fn resolveRelocsX86( switch (rel_type) { .X86_64_RELOC_BRANCH => { - const addend = mem.readIntLittle(i32, atom_code[rel_offset..][0..4]); + const addend = mem.readInt(i32, atom_code[rel_offset..][0..4], .Little); const adjusted_target_addr = @as(u64, @intCast(@as(i64, @intCast(target_addr)) + addend)); relocs_log.debug(" | target_addr = 0x{x}", .{adjusted_target_addr}); const disp = try Relocation.calcPcRelativeDisplacementX86(source_addr, adjusted_target_addr, 0); - mem.writeIntLittle(i32, atom_code[rel_offset..][0..4], disp); + mem.writeInt(i32, atom_code[rel_offset..][0..4], disp, .Little); }, .X86_64_RELOC_GOT, .X86_64_RELOC_GOT_LOAD, => { - const addend = mem.readIntLittle(i32, atom_code[rel_offset..][0..4]); + const addend = mem.readInt(i32, atom_code[rel_offset..][0..4], .Little); const adjusted_target_addr = @as(u64, @intCast(@as(i64, @intCast(target_addr)) + addend)); relocs_log.debug(" | target_addr = 0x{x}", .{adjusted_target_addr}); const disp = try Relocation.calcPcRelativeDisplacementX86(source_addr, adjusted_target_addr, 0); - mem.writeIntLittle(i32, atom_code[rel_offset..][0..4], disp); + mem.writeInt(i32, atom_code[rel_offset..][0..4], disp, .Little); }, .X86_64_RELOC_TLV => { - const addend = mem.readIntLittle(i32, atom_code[rel_offset..][0..4]); + const addend = mem.readInt(i32, atom_code[rel_offset..][0..4], .Little); const adjusted_target_addr = @as(u64, @intCast(@as(i64, @intCast(target_addr)) + addend)); relocs_log.debug(" | target_addr = 0x{x}", .{adjusted_target_addr}); const disp = try Relocation.calcPcRelativeDisplacementX86(source_addr, adjusted_target_addr, 0); @@ -1073,7 +1073,7 @@ fn resolveRelocsX86( atom_code[rel_offset - 2] = 0x8d; } - mem.writeIntLittle(i32, atom_code[rel_offset..][0..4], disp); + mem.writeInt(i32, atom_code[rel_offset..][0..4], disp, .Little); }, .X86_64_RELOC_SIGNED, @@ -1088,7 +1088,7 @@ fn resolveRelocsX86( .X86_64_RELOC_SIGNED_4 => 4, else => unreachable, }; - var addend = mem.readIntLittle(i32, atom_code[rel_offset..][0..4]) + correction; + var addend = mem.readInt(i32, atom_code[rel_offset..][0..4], .Little) + correction; if (rel.r_extern == 0) { const base_addr = if (target.sym_index >= object.source_address_lookup.len) @@ -1104,14 +1104,14 @@ fn resolveRelocsX86( relocs_log.debug(" | target_addr = 0x{x}", .{adjusted_target_addr}); const disp = try Relocation.calcPcRelativeDisplacementX86(source_addr, adjusted_target_addr, correction); - mem.writeIntLittle(i32, atom_code[rel_offset..][0..4], disp); + mem.writeInt(i32, atom_code[rel_offset..][0..4], disp, .Little); }, .X86_64_RELOC_UNSIGNED => { var addend = if (rel.r_length == 3) - mem.readIntLittle(i64, atom_code[rel_offset..][0..8]) + mem.readInt(i64, atom_code[rel_offset..][0..8], .Little) else - mem.readIntLittle(i32, atom_code[rel_offset..][0..4]); + mem.readInt(i32, atom_code[rel_offset..][0..4], .Little); if (rel.r_extern == 0) { const base_addr = if (target.sym_index >= object.source_address_lookup.len) @@ -1132,9 +1132,9 @@ fn resolveRelocsX86( relocs_log.debug(" | target_addr = 0x{x}", .{result}); if (rel.r_length == 3) { - mem.writeIntLittle(u64, atom_code[rel_offset..][0..8], @as(u64, @bitCast(result))); + mem.writeInt(u64, atom_code[rel_offset..][0..8], @as(u64, @bitCast(result)), .Little); } else { - mem.writeIntLittle(u32, atom_code[rel_offset..][0..4], @as(u32, @truncate(@as(u64, @bitCast(result))))); + mem.writeInt(u32, atom_code[rel_offset..][0..4], @as(u32, @truncate(@as(u64, @bitCast(result)))), .Little); } subtractor = null; diff --git a/src/link/MachO/CodeSignature.zig b/src/link/MachO/CodeSignature.zig index 973d9a2591..35538b4e97 100644 --- a/src/link/MachO/CodeSignature.zig +++ b/src/link/MachO/CodeSignature.zig @@ -115,14 +115,14 @@ pub fn writeAdhocSignature( self.code_directory.inner.length = self.code_directory.size(); header.length += self.code_directory.size(); - try writer.writeIntBig(u32, header.magic); - try writer.writeIntBig(u32, header.length); - try writer.writeIntBig(u32, header.count); + try writer.writeInt(u32, header.magic, .Big); + try writer.writeInt(u32, header.length, .Big); + try writer.writeInt(u32, header.count, .Big); var offset: u32 = @sizeOf(macho.SuperBlob) + @sizeOf(macho.BlobIndex) * @as(u32, @intCast(blobs.items.len)); for (blobs.items) |blob| { - try writer.writeIntBig(u32, blob.slotType()); - try writer.writeIntBig(u32, offset); + try writer.writeInt(u32, blob.slotType(), .Big); + try writer.writeInt(u32, offset, .Big); offset += blob.size(); } @@ -272,27 +272,27 @@ const CodeDirectory = struct { } fn write(self: CodeDirectory, writer: anytype) !void { - try writer.writeIntBig(u32, self.inner.magic); - try writer.writeIntBig(u32, self.inner.length); - try writer.writeIntBig(u32, self.inner.version); - try writer.writeIntBig(u32, self.inner.flags); - try writer.writeIntBig(u32, self.inner.hashOffset); - try writer.writeIntBig(u32, self.inner.identOffset); - try writer.writeIntBig(u32, self.inner.nSpecialSlots); - try writer.writeIntBig(u32, self.inner.nCodeSlots); - try writer.writeIntBig(u32, self.inner.codeLimit); + try writer.writeInt(u32, self.inner.magic, .Big); + try writer.writeInt(u32, self.inner.length, .Big); + try writer.writeInt(u32, self.inner.version, .Big); + try writer.writeInt(u32, self.inner.flags, .Big); + try writer.writeInt(u32, self.inner.hashOffset, .Big); + try writer.writeInt(u32, self.inner.identOffset, .Big); + try writer.writeInt(u32, self.inner.nSpecialSlots, .Big); + try writer.writeInt(u32, self.inner.nCodeSlots, .Big); + try writer.writeInt(u32, self.inner.codeLimit, .Big); try writer.writeByte(self.inner.hashSize); try writer.writeByte(self.inner.hashType); try writer.writeByte(self.inner.platform); try writer.writeByte(self.inner.pageSize); - try writer.writeIntBig(u32, self.inner.spare2); - try writer.writeIntBig(u32, self.inner.scatterOffset); - try writer.writeIntBig(u32, self.inner.teamOffset); - try writer.writeIntBig(u32, self.inner.spare3); - try writer.writeIntBig(u64, self.inner.codeLimit64); - try writer.writeIntBig(u64, self.inner.execSegBase); - try writer.writeIntBig(u64, self.inner.execSegLimit); - try writer.writeIntBig(u64, self.inner.execSegFlags); + try writer.writeInt(u32, self.inner.spare2, .Big); + try writer.writeInt(u32, self.inner.scatterOffset, .Big); + try writer.writeInt(u32, self.inner.teamOffset, .Big); + try writer.writeInt(u32, self.inner.spare3, .Big); + try writer.writeInt(u64, self.inner.codeLimit64, .Big); + try writer.writeInt(u64, self.inner.execSegBase, .Big); + try writer.writeInt(u64, self.inner.execSegLimit, .Big); + try writer.writeInt(u64, self.inner.execSegFlags, .Big); try writer.writeAll(self.ident); try writer.writeByte(0); @@ -325,9 +325,9 @@ const Requirements = struct { } fn write(self: Requirements, writer: anytype) !void { - try writer.writeIntBig(u32, macho.CSMAGIC_REQUIREMENTS); - try writer.writeIntBig(u32, self.size()); - try writer.writeIntBig(u32, 0); + try writer.writeInt(u32, macho.CSMAGIC_REQUIREMENTS, .Big); + try writer.writeInt(u32, self.size(), .Big); + try writer.writeInt(u32, 0, .Big); } }; @@ -348,8 +348,8 @@ const Entitlements = struct { } fn write(self: Entitlements, writer: anytype) !void { - try writer.writeIntBig(u32, macho.CSMAGIC_EMBEDDED_ENTITLEMENTS); - try writer.writeIntBig(u32, self.size()); + try writer.writeInt(u32, macho.CSMAGIC_EMBEDDED_ENTITLEMENTS, .Big); + try writer.writeInt(u32, self.size(), .Big); try writer.writeAll(self.inner); } }; @@ -371,8 +371,8 @@ const Signature = struct { } fn write(self: Signature, writer: anytype) !void { - try writer.writeIntBig(u32, macho.CSMAGIC_BLOBWRAPPER); - try writer.writeIntBig(u32, self.size()); + try writer.writeInt(u32, macho.CSMAGIC_BLOBWRAPPER, .Big); + try writer.writeInt(u32, self.size(), .Big); } }; diff --git a/src/link/MachO/DwarfInfo.zig b/src/link/MachO/DwarfInfo.zig index 1f151a1dd5..0db0238e54 100644 --- a/src/link/MachO/DwarfInfo.zig +++ b/src/link/MachO/DwarfInfo.zig @@ -121,19 +121,19 @@ pub const CompileUnit = struct { address_size: u8, fn read(reader: anytype) !Header { - var length: u64 = try reader.readIntLittle(u32); + var length: u64 = try reader.readInt(u32, .Little); const is_64bit = length == 0xffffffff; if (is_64bit) { - length = try reader.readIntLittle(u64); + length = try reader.readInt(u64, .Little); } - const version = try reader.readIntLittle(u16); + const version = try reader.readInt(u16, .Little); const debug_abbrev_offset = if (is_64bit) - try reader.readIntLittle(u64) + try reader.readInt(u64, .Little) else - try reader.readIntLittle(u32); - const address_size = try reader.readIntLittle(u8); + try reader.readInt(u32, .Little); + const address_size = try reader.readInt(u8, .Little); return Header{ .is_64bit = is_64bit, @@ -251,9 +251,9 @@ pub const Attribute = struct { }, dwarf.FORM.strp => { const off = if (cuh.is_64bit) - mem.readIntLittle(u64, debug_info[0..8]) + mem.readInt(u64, debug_info[0..8], .Little) else - mem.readIntLittle(u32, debug_info[0..4]); + mem.readInt(u32, debug_info[0..4], .Little); return ctx.getString(off); }, else => return null, @@ -267,9 +267,9 @@ pub const Attribute = struct { return switch (self.form) { dwarf.FORM.data1 => debug_info[0], - dwarf.FORM.data2 => mem.readIntLittle(u16, debug_info[0..2]), - dwarf.FORM.data4 => mem.readIntLittle(u32, debug_info[0..4]), - dwarf.FORM.data8 => mem.readIntLittle(u64, debug_info[0..8]), + dwarf.FORM.data2 => mem.readInt(u16, debug_info[0..2], .Little), + dwarf.FORM.data4 => mem.readInt(u32, debug_info[0..4], .Little), + dwarf.FORM.data8 => mem.readInt(u64, debug_info[0..8], .Little), dwarf.FORM.udata => try leb.readULEB128(u64, reader), dwarf.FORM.sdata => try leb.readILEB128(i64, reader), else => null, @@ -281,9 +281,9 @@ pub const Attribute = struct { const debug_info = self.getDebugInfo(ctx); return switch (cuh.address_size) { 1 => debug_info[0], - 2 => mem.readIntLittle(u16, debug_info[0..2]), - 4 => mem.readIntLittle(u32, debug_info[0..4]), - 8 => mem.readIntLittle(u64, debug_info[0..8]), + 2 => mem.readInt(u16, debug_info[0..2], .Little), + 4 => mem.readInt(u32, debug_info[0..4], .Little), + 8 => mem.readInt(u64, debug_info[0..8], .Little), else => unreachable, }; } @@ -380,9 +380,9 @@ fn findFormSize(self: DwarfInfo, form: u64, di_off: usize, cuh: CompileUnit.Head dwarf.FORM.block, => { const len: u64 = switch (form) { - dwarf.FORM.block1 => try reader.readIntLittle(u8), - dwarf.FORM.block2 => try reader.readIntLittle(u16), - dwarf.FORM.block4 => try reader.readIntLittle(u32), + dwarf.FORM.block1 => try reader.readInt(u8, .Little), + dwarf.FORM.block2 => try reader.readInt(u16, .Little), + dwarf.FORM.block4 => try reader.readInt(u32, .Little), dwarf.FORM.block => try leb.readULEB128(u64, reader), else => unreachable, }; diff --git a/src/link/MachO/Relocation.zig b/src/link/MachO/Relocation.zig index 5abef9a5ed..447e19be38 100644 --- a/src/link/MachO/Relocation.zig +++ b/src/link/MachO/Relocation.zig @@ -128,7 +128,7 @@ fn resolveAarch64(self: Relocation, source_addr: u64, target_addr: i64, code: [] ), buffer[0..4]), }; inst.unconditional_branch_immediate.imm26 = @as(u26, @truncate(@as(u28, @bitCast(displacement >> 2)))); - mem.writeIntLittle(u32, buffer[0..4], inst.toU32()); + mem.writeInt(u32, buffer[0..4], inst.toU32(), .Little); }, .page, .got_page => { const source_page = @as(i32, @intCast(source_addr >> 12)); @@ -142,7 +142,7 @@ fn resolveAarch64(self: Relocation, source_addr: u64, target_addr: i64, code: [] }; inst.pc_relative_address.immhi = @as(u19, @truncate(pages >> 2)); inst.pc_relative_address.immlo = @as(u2, @truncate(pages)); - mem.writeIntLittle(u32, buffer[0..4], inst.toU32()); + mem.writeInt(u32, buffer[0..4], inst.toU32(), .Little); }, .pageoff, .got_pageoff => { const narrowed = @as(u12, @truncate(@as(u64, @intCast(target_addr)))); @@ -154,7 +154,7 @@ fn resolveAarch64(self: Relocation, source_addr: u64, target_addr: i64, code: [] ), buffer[0..4]), }; inst.add_subtract_immediate.imm12 = narrowed; - mem.writeIntLittle(u32, buffer[0..4], inst.toU32()); + mem.writeInt(u32, buffer[0..4], inst.toU32(), .Little); } else { var inst = aarch64.Instruction{ .load_store_register = mem.bytesToValue(meta.TagPayload( @@ -176,12 +176,12 @@ fn resolveAarch64(self: Relocation, source_addr: u64, target_addr: i64, code: [] } }; inst.load_store_register.offset = offset; - mem.writeIntLittle(u32, buffer[0..4], inst.toU32()); + mem.writeInt(u32, buffer[0..4], inst.toU32(), .Little); } }, .tlv_initializer, .unsigned => switch (self.length) { - 2 => mem.writeIntLittle(u32, buffer[0..4], @as(u32, @truncate(@as(u64, @bitCast(target_addr))))), - 3 => mem.writeIntLittle(u64, buffer[0..8], @as(u64, @bitCast(target_addr))), + 2 => mem.writeInt(u32, buffer[0..4], @as(u32, @truncate(@as(u64, @bitCast(target_addr)))), .Little), + 3 => mem.writeInt(u64, buffer[0..8], @as(u64, @bitCast(target_addr)), .Little), else => unreachable, }, .got, .signed, .tlv => unreachable, // Invalid target architecture. @@ -192,15 +192,15 @@ fn resolveX8664(self: Relocation, source_addr: u64, target_addr: i64, code: []u8 switch (self.type) { .branch, .got, .tlv, .signed => { const displacement = @as(i32, @intCast(@as(i64, @intCast(target_addr)) - @as(i64, @intCast(source_addr)) - 4)); - mem.writeIntLittle(u32, code[self.offset..][0..4], @as(u32, @bitCast(displacement))); + mem.writeInt(u32, code[self.offset..][0..4], @as(u32, @bitCast(displacement)), .Little); }, .tlv_initializer, .unsigned => { switch (self.length) { 2 => { - mem.writeIntLittle(u32, code[self.offset..][0..4], @as(u32, @truncate(@as(u64, @bitCast(target_addr))))); + mem.writeInt(u32, code[self.offset..][0..4], @as(u32, @truncate(@as(u64, @bitCast(target_addr)))), .Little); }, 3 => { - mem.writeIntLittle(u64, code[self.offset..][0..8], @as(u64, @bitCast(target_addr))); + mem.writeInt(u64, code[self.offset..][0..8], @as(u64, @bitCast(target_addr)), .Little); }, else => unreachable, } diff --git a/src/link/MachO/UnwindInfo.zig b/src/link/MachO/UnwindInfo.zig index adb1051301..e8c4a918ef 100644 --- a/src/link/MachO/UnwindInfo.zig +++ b/src/link/MachO/UnwindInfo.zig @@ -149,7 +149,7 @@ const Page = struct { for (page.page_encodings[0..page.page_encodings_count]) |record_id| { const enc = info.records.items[record_id].compactUnwindEncoding; - try writer.writeIntLittle(u32, enc); + try writer.writeInt(u32, enc, .Little); } assert(page.count > 0); diff --git a/src/link/MachO/eh_frame.zig b/src/link/MachO/eh_frame.zig index 31b3bb3311..12516db7a1 100644 --- a/src/link/MachO/eh_frame.zig +++ b/src/link/MachO/eh_frame.zig @@ -209,7 +209,7 @@ pub fn write(macho_file: *MachO, unwind_info: *UnwindInfo) !void { const writer = buffer.writer(); for (eh_records.values()) |record| { - try writer.writeIntLittle(u32, record.size); + try writer.writeInt(u32, record.size, .Little); try buffer.appendSlice(record.data); } @@ -259,7 +259,7 @@ pub fn EhFrameRecord(comptime is_mutable: bool) type { base_offset: u64, }) u64 { assert(rec.tag == .fde); - const addend = mem.readIntLittle(i64, rec.data[4..][0..8]); + const addend = mem.readInt(i64, rec.data[4..][0..8], .Little); return @as(u64, @intCast(@as(i64, @intCast(ctx.base_addr + ctx.base_offset + 8)) + addend)); } @@ -269,7 +269,7 @@ pub fn EhFrameRecord(comptime is_mutable: bool) type { }) !void { assert(rec.tag == .fde); const addend = @as(i64, @intCast(value)) - @as(i64, @intCast(ctx.base_addr + ctx.base_offset + 8)); - mem.writeIntLittle(i64, rec.data[4..][0..8], addend); + mem.writeInt(i64, rec.data[4..][0..8], addend, .Little); } pub fn getPersonalityPointerReloc( @@ -343,13 +343,13 @@ pub fn EhFrameRecord(comptime is_mutable: bool) type { const target_addr = macho_file.getGotEntryAddress(target).?; const result = math.cast(i32, @as(i64, @intCast(target_addr)) - @as(i64, @intCast(source_addr))) orelse return error.Overflow; - mem.writeIntLittle(i32, rec.data[rel_offset..][0..4], result); + mem.writeInt(i32, rec.data[rel_offset..][0..4], result, .Little); }, .ARM64_RELOC_UNSIGNED => { assert(rel.r_extern == 1); const target_addr = Atom.getRelocTargetAddress(macho_file, target, false); const result = @as(i64, @intCast(target_addr)) - @as(i64, @intCast(source_addr)); - mem.writeIntLittle(i64, rec.data[rel_offset..][0..8], @as(i64, @intCast(result))); + mem.writeInt(i64, rec.data[rel_offset..][0..8], @as(i64, @intCast(result)), .Little); }, else => unreachable, } @@ -359,10 +359,10 @@ pub fn EhFrameRecord(comptime is_mutable: bool) type { switch (rel_type) { .X86_64_RELOC_GOT => { const target_addr = macho_file.getGotEntryAddress(target).?; - const addend = mem.readIntLittle(i32, rec.data[rel_offset..][0..4]); + const addend = mem.readInt(i32, rec.data[rel_offset..][0..4], .Little); const adjusted_target_addr = @as(u64, @intCast(@as(i64, @intCast(target_addr)) + addend)); const disp = try Relocation.calcPcRelativeDisplacementX86(source_addr, adjusted_target_addr, 0); - mem.writeIntLittle(i32, rec.data[rel_offset..][0..4], disp); + mem.writeInt(i32, rec.data[rel_offset..][0..4], disp, .Little); }, else => unreachable, } @@ -375,7 +375,7 @@ pub fn EhFrameRecord(comptime is_mutable: bool) type { pub fn getCiePointerSource(rec: Record, object_id: u32, macho_file: *MachO, offset: u32) u32 { assert(rec.tag == .fde); const cpu_arch = macho_file.base.options.target.cpu.arch; - const addend = mem.readIntLittle(u32, rec.data[0..4]); + const addend = mem.readInt(u32, rec.data[0..4], .Little); switch (cpu_arch) { .aarch64 => { const relocs = getRelocs(macho_file, object_id, offset); @@ -397,12 +397,12 @@ pub fn EhFrameRecord(comptime is_mutable: bool) type { pub fn getCiePointer(rec: Record) u32 { assert(rec.tag == .fde); - return mem.readIntLittle(u32, rec.data[0..4]); + return mem.readInt(u32, rec.data[0..4], .Little); } pub fn setCiePointer(rec: *Record, ptr: u32) void { assert(rec.tag == .fde); - mem.writeIntLittle(u32, rec.data[0..4], ptr); + mem.writeInt(u32, rec.data[0..4], ptr, .Little); } pub fn getAugmentationString(rec: Record) []const u8 { @@ -509,14 +509,14 @@ pub fn EhFrameRecord(comptime is_mutable: bool) type { if (enc == EH_PE.omit) return null; var ptr: i64 = switch (enc & 0x0F) { - EH_PE.absptr => @as(i64, @bitCast(try reader.readIntLittle(u64))), - EH_PE.udata2 => @as(i16, @bitCast(try reader.readIntLittle(u16))), - EH_PE.udata4 => @as(i32, @bitCast(try reader.readIntLittle(u32))), - EH_PE.udata8 => @as(i64, @bitCast(try reader.readIntLittle(u64))), + EH_PE.absptr => @as(i64, @bitCast(try reader.readInt(u64, .Little))), + EH_PE.udata2 => @as(i16, @bitCast(try reader.readInt(u16, .Little))), + EH_PE.udata4 => @as(i32, @bitCast(try reader.readInt(u32, .Little))), + EH_PE.udata8 => @as(i64, @bitCast(try reader.readInt(u64, .Little))), EH_PE.uleb128 => @as(i64, @bitCast(try leb.readULEB128(u64, reader))), - EH_PE.sdata2 => try reader.readIntLittle(i16), - EH_PE.sdata4 => try reader.readIntLittle(i32), - EH_PE.sdata8 => try reader.readIntLittle(i64), + EH_PE.sdata2 => try reader.readInt(i16, .Little), + EH_PE.sdata4 => try reader.readInt(i32, .Little), + EH_PE.sdata8 => try reader.readInt(i64, .Little), EH_PE.sleb128 => try leb.readILEB128(i64, reader), else => return null, }; @@ -552,14 +552,14 @@ pub fn EhFrameRecord(comptime is_mutable: bool) type { } switch (enc & 0x0F) { - EH_PE.absptr => try writer.writeIntLittle(u64, @as(u64, @bitCast(actual))), - EH_PE.udata2 => try writer.writeIntLittle(u16, @as(u16, @bitCast(@as(i16, @intCast(actual))))), - EH_PE.udata4 => try writer.writeIntLittle(u32, @as(u32, @bitCast(@as(i32, @intCast(actual))))), - EH_PE.udata8 => try writer.writeIntLittle(u64, @as(u64, @bitCast(actual))), + EH_PE.absptr => try writer.writeInt(u64, @as(u64, @bitCast(actual)), .Little), + EH_PE.udata2 => try writer.writeInt(u16, @as(u16, @bitCast(@as(i16, @intCast(actual)))), .Little), + EH_PE.udata4 => try writer.writeInt(u32, @as(u32, @bitCast(@as(i32, @intCast(actual)))), .Little), + EH_PE.udata8 => try writer.writeInt(u64, @as(u64, @bitCast(actual)), .Little), EH_PE.uleb128 => try leb.writeULEB128(writer, @as(u64, @bitCast(actual))), - EH_PE.sdata2 => try writer.writeIntLittle(i16, @as(i16, @intCast(actual))), - EH_PE.sdata4 => try writer.writeIntLittle(i32, @as(i32, @intCast(actual))), - EH_PE.sdata8 => try writer.writeIntLittle(i64, actual), + EH_PE.sdata2 => try writer.writeInt(i16, @as(i16, @intCast(actual)), .Little), + EH_PE.sdata4 => try writer.writeInt(i32, @as(i32, @intCast(actual)), .Little), + EH_PE.sdata8 => try writer.writeInt(i64, actual, .Little), EH_PE.sleb128 => try leb.writeILEB128(writer, actual), else => unreachable, } @@ -586,13 +586,13 @@ pub const Iterator = struct { var stream = std.io.fixedBufferStream(it.data[it.pos..]); const reader = stream.reader(); - var size = try reader.readIntLittle(u32); + var size = try reader.readInt(u32, .Little); if (size == 0xFFFFFFFF) { log.debug("MachO doesn't support 64bit DWARF CFI __eh_frame records", .{}); return error.BadDwarfCfi; } - const id = try reader.readIntLittle(u32); + const id = try reader.readInt(u32, .Little); const tag: EhFrameRecordTag = if (id == 0) .cie else .fde; const offset: u32 = 4; const record = EhFrameRecord(false){ diff --git a/src/link/MachO/stubs.zig b/src/link/MachO/stubs.zig index 54502d1a20..6d947983f6 100644 --- a/src/link/MachO/stubs.zig +++ b/src/link/MachO/stubs.zig @@ -53,7 +53,7 @@ pub fn writeStubHelperPreambleCode(args: struct { args.dyld_private_addr, 0, ); - try writer.writeIntLittle(i32, disp); + try writer.writeInt(i32, disp, .Little); } try writer.writeAll(&.{ 0x41, 0x53, 0xff, 0x25 }); { @@ -62,37 +62,37 @@ pub fn writeStubHelperPreambleCode(args: struct { args.dyld_stub_binder_got_addr, 0, ); - try writer.writeIntLittle(i32, disp); + try writer.writeInt(i32, disp, .Little); } }, .aarch64 => { { const pages = Relocation.calcNumberOfPages(args.source_addr, args.dyld_private_addr); - try writer.writeIntLittle(u32, aarch64.Instruction.adrp(.x17, pages).toU32()); + try writer.writeInt(u32, aarch64.Instruction.adrp(.x17, pages).toU32(), .Little); } { const off = try Relocation.calcPageOffset(args.dyld_private_addr, .arithmetic); - try writer.writeIntLittle(u32, aarch64.Instruction.add(.x17, .x17, off, false).toU32()); + try writer.writeInt(u32, aarch64.Instruction.add(.x17, .x17, off, false).toU32(), .Little); } - try writer.writeIntLittle(u32, aarch64.Instruction.stp( + try writer.writeInt(u32, aarch64.Instruction.stp( .x16, .x17, aarch64.Register.sp, aarch64.Instruction.LoadStorePairOffset.pre_index(-16), - ).toU32()); + ).toU32(), .Little); { const pages = Relocation.calcNumberOfPages(args.source_addr + 12, args.dyld_stub_binder_got_addr); - try writer.writeIntLittle(u32, aarch64.Instruction.adrp(.x16, pages).toU32()); + try writer.writeInt(u32, aarch64.Instruction.adrp(.x16, pages).toU32(), .Little); } { const off = try Relocation.calcPageOffset(args.dyld_stub_binder_got_addr, .load_store_64); - try writer.writeIntLittle(u32, aarch64.Instruction.ldr( + try writer.writeInt(u32, aarch64.Instruction.ldr( .x16, .x16, aarch64.Instruction.LoadStoreOffset.imm(off), - ).toU32()); + ).toU32(), .Little); } - try writer.writeIntLittle(u32, aarch64.Instruction.br(.x16).toU32()); + try writer.writeInt(u32, aarch64.Instruction.br(.x16).toU32(), .Little); }, else => unreachable, } @@ -108,7 +108,7 @@ pub fn writeStubHelperCode(args: struct { try writer.writeAll(&.{ 0x68, 0x0, 0x0, 0x0, 0x0, 0xe9 }); { const disp = try Relocation.calcPcRelativeDisplacementX86(args.source_addr + 6, args.target_addr, 0); - try writer.writeIntLittle(i32, disp); + try writer.writeInt(i32, disp, .Little); } }, .aarch64 => { @@ -117,13 +117,13 @@ pub fn writeStubHelperCode(args: struct { const div_res = try std.math.divExact(u64, stub_size - @sizeOf(u32), 4); break :blk std.math.cast(u18, div_res) orelse return error.Overflow; }; - try writer.writeIntLittle(u32, aarch64.Instruction.ldrLiteral( + try writer.writeInt(u32, aarch64.Instruction.ldrLiteral( .w16, literal, - ).toU32()); + ).toU32(), .Little); { const disp = try Relocation.calcPcRelativeDisplacementArm64(args.source_addr + 4, args.target_addr); - try writer.writeIntLittle(u32, aarch64.Instruction.b(disp).toU32()); + try writer.writeInt(u32, aarch64.Instruction.b(disp).toU32(), .Little); } try writer.writeAll(&.{ 0x0, 0x0, 0x0, 0x0 }); }, @@ -141,23 +141,23 @@ pub fn writeStubCode(args: struct { try writer.writeAll(&.{ 0xff, 0x25 }); { const disp = try Relocation.calcPcRelativeDisplacementX86(args.source_addr + 2, args.target_addr, 0); - try writer.writeIntLittle(i32, disp); + try writer.writeInt(i32, disp, .Little); } }, .aarch64 => { { const pages = Relocation.calcNumberOfPages(args.source_addr, args.target_addr); - try writer.writeIntLittle(u32, aarch64.Instruction.adrp(.x16, pages).toU32()); + try writer.writeInt(u32, aarch64.Instruction.adrp(.x16, pages).toU32(), .Little); } { const off = try Relocation.calcPageOffset(args.target_addr, .load_store_64); - try writer.writeIntLittle(u32, aarch64.Instruction.ldr( + try writer.writeInt(u32, aarch64.Instruction.ldr( .x16, .x16, aarch64.Instruction.LoadStoreOffset.imm(off), - ).toU32()); + ).toU32(), .Little); } - try writer.writeIntLittle(u32, aarch64.Instruction.br(.x16).toU32()); + try writer.writeInt(u32, aarch64.Instruction.br(.x16).toU32(), .Little); }, else => unreachable, } diff --git a/src/link/MachO/thunks.zig b/src/link/MachO/thunks.zig index 75f20bbf6d..21f5d2f410 100644 --- a/src/link/MachO/thunks.zig +++ b/src/link/MachO/thunks.zig @@ -349,10 +349,10 @@ pub fn writeThunkCode(macho_file: *MachO, thunk: *const Thunk, writer: anytype) .atom => macho_file.getSymbol(target).n_value, }; const pages = Relocation.calcNumberOfPages(source_addr, target_addr); - try writer.writeIntLittle(u32, aarch64.Instruction.adrp(.x16, pages).toU32()); + try writer.writeInt(u32, aarch64.Instruction.adrp(.x16, pages).toU32(), .Little); const off = try Relocation.calcPageOffset(target_addr, .arithmetic); - try writer.writeIntLittle(u32, aarch64.Instruction.add(.x16, .x16, off, false).toU32()); - try writer.writeIntLittle(u32, aarch64.Instruction.br(.x16).toU32()); + try writer.writeInt(u32, aarch64.Instruction.add(.x16, .x16, off, false).toU32(), .Little); + try writer.writeInt(u32, aarch64.Instruction.br(.x16).toU32(), .Little); } } diff --git a/src/link/MachO/zld.zig b/src/link/MachO/zld.zig index 6decd082de..ed1d3f0258 100644 --- a/src/link/MachO/zld.zig +++ b/src/link/MachO/zld.zig @@ -796,7 +796,7 @@ fn writePointerEntries(macho_file: *MachO, sect_id: u8, table: anytype) !void { defer buffer.deinit(); for (table.entries.items) |entry| { const sym = macho_file.getSymbol(entry); - buffer.writer().writeIntLittle(u64, sym.n_value) catch unreachable; + buffer.writer().writeInt(u64, sym.n_value, .Little) catch unreachable; } log.debug("writing __DATA_CONST,__got contents at file offset 0x{x}", .{header.offset}); try macho_file.base.file.?.pwriteAll(buffer.items, header.offset); @@ -880,7 +880,7 @@ fn writeLaSymbolPtrs(macho_file: *MachO) !void { for (0..macho_file.stub_table.count()) |index| { const target_addr = stub_helper_header.addr + stubs.stubHelperPreambleSize(cpu_arch) + stubs.stubHelperSize(cpu_arch) * index; - buffer.writer().writeIntLittle(u64, target_addr) catch unreachable; + buffer.writer().writeInt(u64, target_addr, .Little) catch unreachable; } log.debug("writing __DATA,__la_symbol_ptr contents at file offset 0x{x}", .{ diff --git a/src/link/Plan9.zig b/src/link/Plan9.zig index 96d2bdf7b4..04c8c9abe7 100644 --- a/src/link/Plan9.zig +++ b/src/link/Plan9.zig @@ -348,7 +348,7 @@ fn putFn(self: *Plan9, decl_index: Module.Decl.Index, out: FnDeclOutput) !void { // every 'z' starts with 0 try a.append(0); // path component value of '/' - try a.writer().writeIntBig(u16, 1); + try a.writer().writeInt(u16, 1, .Big); // getting the full file path var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; @@ -381,11 +381,11 @@ fn addPathComponents(self: *Plan9, path: []const u8, a: *std.ArrayList(u8)) !voi var it = std.mem.tokenizeScalar(u8, path, sep); while (it.next()) |component| { if (self.file_segments.get(component)) |num| { - try a.writer().writeIntBig(u16, num); + try a.writer().writeInt(u16, num, .Big); } else { self.file_segments_i += 1; try self.file_segments.put(self.base.allocator, component, self.file_segments_i); - try a.writer().writeIntBig(u16, self.file_segments_i); + try a.writer().writeInt(u16, self.file_segments_i, .Big); } } } @@ -607,7 +607,7 @@ pub fn changeLine(l: *std.ArrayList(u8), delta_line: i32) !void { try l.append(toadd); } else if (delta_line != 0) { try l.append(0); - try l.writer().writeIntBig(i32, delta_line); + try l.writer().writeInt(i32, delta_line, .Big); } } @@ -922,7 +922,7 @@ pub fn flushModule(self: *Plan9, comp: *Compilation, prog_node: *std.Progress.No @memcpy(hdr_slice, self.hdr.toU8s()[0..hdr_size]); // write the fat header for 64 bit entry points if (self.sixtyfour_bit) { - mem.writeIntSliceBig(u64, hdr_buf[32..40], self.entry_val.?); + mem.writeInt(u64, hdr_buf[32..40], self.entry_val.?, .Big); } // perform the relocs { @@ -1311,9 +1311,9 @@ pub fn writeSym(self: *Plan9, w: anytype, sym: aout.Sym) !void { // log.debug("write sym{{name: {s}, value: {x}}}", .{ sym.name, sym.value }); if (sym.type == .bad) return; // we don't want to write free'd symbols if (!self.sixtyfour_bit) { - try w.writeIntBig(u32, @as(u32, @intCast(sym.value))); + try w.writeInt(u32, @as(u32, @intCast(sym.value)), .Big); } else { - try w.writeIntBig(u64, sym.value); + try w.writeInt(u64, sym.value, .Big); } try w.writeByte(@intFromEnum(sym.type)); try w.writeAll(sym.name); diff --git a/src/link/Plan9/aout.zig b/src/link/Plan9/aout.zig index d6fbb47d35..8879a4832f 100644 --- a/src/link/Plan9/aout.zig +++ b/src/link/Plan9/aout.zig @@ -21,7 +21,7 @@ pub const ExecHdr = extern struct { var buf: [40]u8 = undefined; var i: u8 = 0; inline for (std.meta.fields(@This())) |f| { - std.mem.writeIntSliceBig(u32, buf[i..][0..4], @field(self, f.name)); + std.mem.writeInt(u32, buf[i..][0..4], @field(self, f.name), .Big); i += 4; } return buf; diff --git a/src/link/Wasm.zig b/src/link/Wasm.zig index 7755915a67..2be90fa15b 100644 --- a/src/link/Wasm.zig +++ b/src/link/Wasm.zig @@ -2371,7 +2371,7 @@ fn setupErrorsLen(wasm: *Wasm) !void { atom.deinit(wasm); break :blk index; } else new_atom: { - const atom_index = @as(Atom.Index, @intCast(wasm.managed_atoms.items.len)); + const atom_index: Atom.Index = @intCast(wasm.managed_atoms.items.len); try wasm.symbol_atom.put(wasm.base.allocator, loc, atom_index); try wasm.managed_atoms.append(wasm.base.allocator, undefined); break :new_atom atom_index; @@ -2380,7 +2380,7 @@ fn setupErrorsLen(wasm: *Wasm) !void { atom.* = Atom.empty; atom.sym_index = loc.index; atom.size = 2; - try atom.code.writer(wasm.base.allocator).writeIntLittle(u16, @as(u16, @intCast(errors_len))); + try atom.code.writer(wasm.base.allocator).writeInt(u16, @intCast(errors_len), .Little); try wasm.parseAtom(atom_index, .{ .data = .read_only }); } @@ -3151,7 +3151,7 @@ fn populateErrorNameTable(wasm: *Wasm) !void { const offset = @as(u32, @intCast(atom.code.items.len)); // first we create the data for the slice of the name try atom.code.appendNTimes(wasm.base.allocator, 0, 4); // ptr to name, will be relocated - try atom.code.writer(wasm.base.allocator).writeIntLittle(u32, len - 1); + try atom.code.writer(wasm.base.allocator).writeInt(u32, len - 1, .Little); // create relocation to the error name try atom.relocs.append(wasm.base.allocator, .{ .index = names_atom.sym_index, @@ -4286,11 +4286,11 @@ fn emitInit(writer: anytype, init_expr: std.wasm.InitExpression) !void { }, .f32_const => |val| { try writer.writeByte(std.wasm.opcode(.f32_const)); - try writer.writeIntLittle(u32, @as(u32, @bitCast(val))); + try writer.writeInt(u32, @bitCast(val), .Little); }, .f64_const => |val| { try writer.writeByte(std.wasm.opcode(.f64_const)); - try writer.writeIntLittle(u64, @as(u64, @bitCast(val))); + try writer.writeInt(u64, @bitCast(val), .Little); }, .global_get => |val| { try writer.writeByte(std.wasm.opcode(.global_get)); diff --git a/src/link/Wasm/Archive.zig b/src/link/Wasm/Archive.zig index c4fb9b8291..91e92ae36d 100644 --- a/src/link/Wasm/Archive.zig +++ b/src/link/Wasm/Archive.zig @@ -141,11 +141,11 @@ fn parseTableOfContents(archive: *Archive, allocator: Allocator, reader: anytype const size_trimmed = mem.trim(u8, &archive.header.ar_size, " "); const sym_tab_size = try std.fmt.parseInt(u32, size_trimmed, 10); - const num_symbols = try reader.readIntBig(u32); + const num_symbols = try reader.readInt(u32, .Big); const symbol_positions = try allocator.alloc(u32, num_symbols); defer allocator.free(symbol_positions); for (symbol_positions) |*index| { - index.* = try reader.readIntBig(u32); + index.* = try reader.readInt(u32, .Big); } const sym_tab = try allocator.alloc(u8, sym_tab_size - 4 - (4 * num_symbols)); diff --git a/src/link/Wasm/Atom.zig b/src/link/Wasm/Atom.zig index 348b9cf8bd..65e92ed140 100644 --- a/src/link/Wasm/Atom.zig +++ b/src/link/Wasm/Atom.zig @@ -114,10 +114,10 @@ pub fn resolveRelocs(atom: *Atom, wasm_bin: *const Wasm) void { .R_WASM_GLOBAL_INDEX_I32, .R_WASM_MEMORY_ADDR_I32, .R_WASM_SECTION_OFFSET_I32, - => std.mem.writeIntLittle(u32, atom.code.items[reloc.offset..][0..4], @as(u32, @intCast(value))), + => std.mem.writeInt(u32, atom.code.items[reloc.offset..][0..4], @as(u32, @intCast(value)), .Little), .R_WASM_TABLE_INDEX_I64, .R_WASM_MEMORY_ADDR_I64, - => std.mem.writeIntLittle(u64, atom.code.items[reloc.offset..][0..8], value), + => std.mem.writeInt(u64, atom.code.items[reloc.offset..][0..8], value, .Little), .R_WASM_GLOBAL_INDEX_LEB, .R_WASM_EVENT_INDEX_LEB, .R_WASM_FUNCTION_INDEX_LEB, diff --git a/src/link/Wasm/Object.zig b/src/link/Wasm/Object.zig index dbe369280e..6517d7ec20 100644 --- a/src/link/Wasm/Object.zig +++ b/src/link/Wasm/Object.zig @@ -344,7 +344,7 @@ fn Parser(comptime ReaderType: type) type { fn parseObject(parser: *ObjectParser, gpa: Allocator, is_object_file: *bool) Error!void { errdefer parser.object.deinit(gpa); try parser.verifyMagicBytes(); - const version = try parser.reader.reader().readIntLittle(u32); + const version = try parser.reader.reader().readInt(u32, .Little); parser.object.version = version; var relocatable_data = std.ArrayList(RelocatableData).init(gpa); diff --git a/src/resinator/ani.zig b/src/resinator/ani.zig index 7b8b05564f..a4273e8488 100644 --- a/src/resinator/ani.zig +++ b/src/resinator/ani.zig @@ -25,14 +25,14 @@ fn getAniheaderFlags(reader: anytype) !u32 { const riff_header = try reader.readBytesNoEof(4); if (!std.mem.eql(u8, &riff_header, "RIFF")) return error.InvalidFormat; - _ = try reader.readIntLittle(u32); // size of RIFF chunk + _ = try reader.readInt(u32, .Little); // size of RIFF chunk const form_type = try reader.readBytesNoEof(4); if (!std.mem.eql(u8, &form_type, "ACON")) return error.InvalidFormat; while (true) { const chunk_id = try reader.readBytesNoEof(4); - const chunk_len = try reader.readIntLittle(u32); + const chunk_len = try reader.readInt(u32, .Little); if (!std.mem.eql(u8, &chunk_id, "anih")) { // TODO: Move file cursor instead of skipBytes try reader.skipBytes(chunk_len, .{}); diff --git a/src/resinator/bmp.zig b/src/resinator/bmp.zig index 0b3205c16b..fb20dacdad 100644 --- a/src/resinator/bmp.zig +++ b/src/resinator/bmp.zig @@ -20,8 +20,10 @@ const std = @import("std"); const BitmapHeader = @import("ico.zig").BitmapHeader; +const builtin = @import("builtin"); +const native_endian = builtin.cpu.arch.endian(); -pub const windows_format_id = std.mem.readIntNative(u16, "BM"); +pub const windows_format_id = std.mem.readInt(u16, "BM", native_endian); pub const file_header_len = 14; pub const ReadError = error{ @@ -89,19 +91,19 @@ pub fn read(reader: anytype, max_size: u64) ReadError!BitmapInfo { var bitmap_info: BitmapInfo = undefined; const file_header = reader.readBytesNoEof(file_header_len) catch return error.UnexpectedEOF; - const id = std.mem.readIntNative(u16, file_header[0..2]); + const id = std.mem.readInt(u16, file_header[0..2], native_endian); if (id != windows_format_id) return error.InvalidFileHeader; - bitmap_info.pixel_data_offset = std.mem.readIntLittle(u32, file_header[10..14]); + bitmap_info.pixel_data_offset = std.mem.readInt(u32, file_header[10..14], .Little); if (bitmap_info.pixel_data_offset > max_size) return error.ImpossiblePixelDataOffset; - bitmap_info.dib_header_size = reader.readIntLittle(u32) catch return error.UnexpectedEOF; + bitmap_info.dib_header_size = reader.readInt(u32, .Little) catch return error.UnexpectedEOF; if (bitmap_info.pixel_data_offset < file_header_len + bitmap_info.dib_header_size) return error.ImpossiblePixelDataOffset; const dib_version = BitmapHeader.Version.get(bitmap_info.dib_header_size); switch (dib_version) { .@"nt3.1", .@"nt4.0", .@"nt5.0" => { var dib_header_buf: [@sizeOf(BITMAPINFOHEADER)]u8 align(@alignOf(BITMAPINFOHEADER)) = undefined; - std.mem.writeIntLittle(u32, dib_header_buf[0..4], bitmap_info.dib_header_size); + std.mem.writeInt(u32, dib_header_buf[0..4], bitmap_info.dib_header_size, .Little); reader.readNoEof(dib_header_buf[4..]) catch return error.UnexpectedEOF; var dib_header: *BITMAPINFOHEADER = @ptrCast(&dib_header_buf); structFieldsLittleToNative(BITMAPINFOHEADER, dib_header); @@ -116,7 +118,7 @@ pub fn read(reader: anytype, max_size: u64) ReadError!BitmapInfo { }, .@"win2.0" => { var dib_header_buf: [@sizeOf(BITMAPCOREHEADER)]u8 align(@alignOf(BITMAPCOREHEADER)) = undefined; - std.mem.writeIntLittle(u32, dib_header_buf[0..4], bitmap_info.dib_header_size); + std.mem.writeInt(u32, dib_header_buf[0..4], bitmap_info.dib_header_size, .Little); reader.readNoEof(dib_header_buf[4..]) catch return error.UnexpectedEOF; var dib_header: *BITMAPCOREHEADER = @ptrCast(&dib_header_buf); structFieldsLittleToNative(BITMAPCOREHEADER, dib_header); diff --git a/src/resinator/compile.zig b/src/resinator/compile.zig index 7a2f531a80..6f8878c411 100644 --- a/src/resinator/compile.zig +++ b/src/resinator/compile.zig @@ -28,6 +28,7 @@ const windows1252 = @import("windows1252.zig"); const lang = @import("lang.zig"); const code_pages = @import("code_pages.zig"); const errors = @import("errors.zig"); +const native_endian = builtin.cpu.arch.endian(); pub const CompileOptions = struct { cwd: std.fs.Dir, @@ -584,8 +585,8 @@ pub const Compiler = struct { // > resource if a RESDIR structure contains information about a cursor. // where LOCALHEADER is `struct { WORD xHotSpot; WORD yHotSpot; }` if (icon_dir.image_type == .cursor) { - try writer.writeIntLittle(u16, entry.type_specific_data.cursor.hotspot_x); - try writer.writeIntLittle(u16, entry.type_specific_data.cursor.hotspot_y); + try writer.writeInt(u16, entry.type_specific_data.cursor.hotspot_x, .Little); + try writer.writeInt(u16, entry.type_specific_data.cursor.hotspot_y, .Little); } try file.seekTo(entry.data_offset_from_start_of_file); @@ -666,7 +667,7 @@ pub const Compiler = struct { }, .dib => { var bitmap_header: *ico.BitmapHeader = @ptrCast(@alignCast(&header_bytes)); - if (builtin.cpu.arch.endian() == .Big) { + if (native_endian == .Big) { std.mem.byteSwapAllFields(ico.BitmapHeader, bitmap_header); } const bitmap_version = ico.BitmapHeader.Version.get(bitmap_header.bcSize); @@ -777,7 +778,7 @@ pub const Compiler = struct { if (bitmap_info.getActualPaletteByteLen() > bitmap_info.getExpectedPaletteByteLen()) { const num_ignored_bytes = bitmap_info.getActualPaletteByteLen() - bitmap_info.getExpectedPaletteByteLen(); var number_as_bytes: [8]u8 = undefined; - std.mem.writeIntNative(u64, &number_as_bytes, num_ignored_bytes); + std.mem.writeInt(u64, &number_as_bytes, num_ignored_bytes, native_endian); const value_string_index = try self.diagnostics.putString(&number_as_bytes); try self.addErrorDetails(.{ .err = .bmp_ignored_palette_bytes, @@ -792,8 +793,8 @@ pub const Compiler = struct { const max_missing_bytes = 4096; if (num_padding_bytes > max_missing_bytes) { var numbers_as_bytes: [16]u8 = undefined; - std.mem.writeIntNative(u64, numbers_as_bytes[0..8], num_padding_bytes); - std.mem.writeIntNative(u64, numbers_as_bytes[8..16], max_missing_bytes); + std.mem.writeInt(u64, numbers_as_bytes[0..8], num_padding_bytes, native_endian); + std.mem.writeInt(u64, numbers_as_bytes[8..16], max_missing_bytes, native_endian); const values_string_index = try self.diagnostics.putString(&numbers_as_bytes); try self.addErrorDetails(.{ .err = .bmp_too_many_missing_palette_bytes, @@ -809,7 +810,7 @@ pub const Compiler = struct { } var number_as_bytes: [8]u8 = undefined; - std.mem.writeIntNative(u64, &number_as_bytes, num_padding_bytes); + std.mem.writeInt(u64, &number_as_bytes, num_padding_bytes, native_endian); const value_string_index = try self.diagnostics.putString(&number_as_bytes); try self.addErrorDetails(.{ .err = .bmp_missing_palette_bytes, @@ -820,7 +821,7 @@ pub const Compiler = struct { const pixel_data_len = bitmap_info.getPixelDataLen(file_size); if (pixel_data_len > 0) { const miscompiled_bytes = @min(pixel_data_len, num_padding_bytes); - std.mem.writeIntNative(u64, &number_as_bytes, miscompiled_bytes); + std.mem.writeInt(u64, &number_as_bytes, miscompiled_bytes, native_endian); const miscompiled_bytes_string_index = try self.diagnostics.putString(&number_as_bytes); try self.addErrorDetails(.{ .err = .rc_would_miscompile_bmp_palette_padding, @@ -984,8 +985,8 @@ pub const Compiler = struct { pub fn write(self: Data, writer: anytype) !void { switch (self) { .number => |number| switch (number.is_long) { - false => try writer.writeIntLittle(WORD, number.asWord()), - true => try writer.writeIntLittle(DWORD, number.value), + false => try writer.writeInt(WORD, number.asWord(), .Little), + true => try writer.writeInt(DWORD, number.value, .Little), }, .ascii_string => |ascii_string| { try writer.writeAll(ascii_string); @@ -1315,9 +1316,9 @@ pub const Compiler = struct { try data_writer.writeByte(modifiers.value); try data_writer.writeByte(0); // padding - try data_writer.writeIntLittle(u16, key); - try data_writer.writeIntLittle(u16, cmd_id.asWord()); - try data_writer.writeIntLittle(u16, 0); // padding + try data_writer.writeInt(u16, key, .Little); + try data_writer.writeInt(u16, cmd_id.asWord(), .Little); + try data_writer.writeInt(u16, 0, .Little); // padding } } @@ -1700,34 +1701,34 @@ pub const Compiler = struct { if (node.help_id == null) break :help_id 0; break :help_id evaluateNumberExpression(node.help_id.?, self.source, self.input_code_pages).value; }; - try data_writer.writeIntLittle(u16, 1); // version number, always 1 - try data_writer.writeIntLittle(u16, 0xFFFF); // signature, always 0xFFFF - try data_writer.writeIntLittle(u32, help_id); - try data_writer.writeIntLittle(u32, optional_statement_values.exstyle); - try data_writer.writeIntLittle(u32, optional_statement_values.style); + try data_writer.writeInt(u16, 1, .Little); // version number, always 1 + try data_writer.writeInt(u16, 0xFFFF, .Little); // signature, always 0xFFFF + try data_writer.writeInt(u32, help_id, .Little); + try data_writer.writeInt(u32, optional_statement_values.exstyle, .Little); + try data_writer.writeInt(u32, optional_statement_values.style, .Little); } else { - try data_writer.writeIntLittle(u32, optional_statement_values.style); - try data_writer.writeIntLittle(u32, optional_statement_values.exstyle); + try data_writer.writeInt(u32, optional_statement_values.style, .Little); + try data_writer.writeInt(u32, optional_statement_values.exstyle, .Little); } // This limit is enforced by the parser, so we know the number of controls // is within the range of a u16. - try data_writer.writeIntLittle(u16, @as(u16, @intCast(node.controls.len))); - try data_writer.writeIntLittle(u16, x.asWord()); - try data_writer.writeIntLittle(u16, y.asWord()); - try data_writer.writeIntLittle(u16, width.asWord()); - try data_writer.writeIntLittle(u16, height.asWord()); + try data_writer.writeInt(u16, @as(u16, @intCast(node.controls.len)), .Little); + try data_writer.writeInt(u16, x.asWord(), .Little); + try data_writer.writeInt(u16, y.asWord(), .Little); + try data_writer.writeInt(u16, width.asWord(), .Little); + try data_writer.writeInt(u16, height.asWord(), .Little); // Menu if (optional_statement_values.menu) |menu| { try menu.write(data_writer); } else { - try data_writer.writeIntLittle(u16, 0); + try data_writer.writeInt(u16, 0, .Little); } // Class if (optional_statement_values.class) |class| { try class.write(data_writer); } else { - try data_writer.writeIntLittle(u16, 0); + try data_writer.writeInt(u16, 0, .Little); } // Caption if (optional_statement_values.caption) |caption| { @@ -1735,7 +1736,7 @@ pub const Compiler = struct { defer self.allocator.free(parsed); try data_writer.writeAll(std.mem.sliceAsBytes(parsed[0 .. parsed.len + 1])); } else { - try data_writer.writeIntLittle(u16, 0); + try data_writer.writeInt(u16, 0, .Little); } // Font if (optional_statement_values.font) |font| { @@ -1786,18 +1787,18 @@ pub const Compiler = struct { switch (resource) { .dialog => { // Note: Reverse order from DIALOGEX - try data_writer.writeIntLittle(u32, style); - try data_writer.writeIntLittle(u32, exstyle); + try data_writer.writeInt(u32, style, .Little); + try data_writer.writeInt(u32, exstyle, .Little); }, .dialogex => { const help_id: u32 = if (control.help_id) |help_id_expression| evaluateNumberExpression(help_id_expression, self.source, self.input_code_pages).value else 0; - try data_writer.writeIntLittle(u32, help_id); + try data_writer.writeInt(u32, help_id, .Little); // Note: Reverse order from DIALOG - try data_writer.writeIntLittle(u32, exstyle); - try data_writer.writeIntLittle(u32, style); + try data_writer.writeInt(u32, exstyle, .Little); + try data_writer.writeInt(u32, style, .Little); }, else => unreachable, } @@ -1807,15 +1808,15 @@ pub const Compiler = struct { const control_width = evaluateNumberExpression(control.width, self.source, self.input_code_pages); const control_height = evaluateNumberExpression(control.height, self.source, self.input_code_pages); - try data_writer.writeIntLittle(u16, control_x.asWord()); - try data_writer.writeIntLittle(u16, control_y.asWord()); - try data_writer.writeIntLittle(u16, control_width.asWord()); - try data_writer.writeIntLittle(u16, control_height.asWord()); + try data_writer.writeInt(u16, control_x.asWord(), .Little); + try data_writer.writeInt(u16, control_y.asWord(), .Little); + try data_writer.writeInt(u16, control_width.asWord(), .Little); + try data_writer.writeInt(u16, control_height.asWord(), .Little); const control_id = evaluateNumberExpression(control.id, self.source, self.input_code_pages); switch (resource) { - .dialog => try data_writer.writeIntLittle(u16, control_id.asWord()), - .dialogex => try data_writer.writeIntLittle(u32, control_id.value), + .dialog => try data_writer.writeInt(u16, control_id.asWord(), .Little), + .dialogex => try data_writer.writeInt(u32, control_id.value, .Little), else => unreachable, } @@ -1948,7 +1949,7 @@ pub const Compiler = struct { } // We know the extra_data_buf size fits within a u16. const extra_data_size: u16 = @intCast(extra_data_buf.items.len); - try data_writer.writeIntLittle(u16, extra_data_size); + try data_writer.writeInt(u16, extra_data_size, .Little); try data_writer.writeAll(extra_data_buf.items); } @@ -1962,21 +1963,21 @@ pub const Compiler = struct { // I'm assuming this is some sort of version // TODO: Try to find something mentioning this - try data_writer.writeIntLittle(u16, 1); - try data_writer.writeIntLittle(u16, button_width.asWord()); - try data_writer.writeIntLittle(u16, button_height.asWord()); - try data_writer.writeIntLittle(u16, @as(u16, @intCast(node.buttons.len))); + try data_writer.writeInt(u16, 1, .Little); + try data_writer.writeInt(u16, button_width.asWord(), .Little); + try data_writer.writeInt(u16, button_height.asWord(), .Little); + try data_writer.writeInt(u16, @as(u16, @intCast(node.buttons.len)), .Little); for (node.buttons) |button_or_sep| { switch (button_or_sep.id) { .literal => { // This is always SEPARATOR std.debug.assert(button_or_sep.cast(.literal).?.token.id == .literal); - try data_writer.writeIntLittle(u16, 0); + try data_writer.writeInt(u16, 0, .Little); }, .simple_statement => { const value_node = button_or_sep.cast(.simple_statement).?.value; const value = evaluateNumberExpression(value_node, self.source, self.input_code_pages); - try data_writer.writeIntLittle(u16, value.asWord()); + try data_writer.writeInt(u16, value.asWord(), .Little); }, else => unreachable, // This is a bug in the parser } @@ -2007,21 +2008,21 @@ pub const Compiler = struct { pub fn writeDialogFont(self: *Compiler, resource: Resource, values: FontStatementValues, writer: anytype) !void { const node = values.node; const point_size = evaluateNumberExpression(node.point_size, self.source, self.input_code_pages); - try writer.writeIntLittle(u16, point_size.asWord()); + try writer.writeInt(u16, point_size.asWord(), .Little); if (resource == .dialogex) { - try writer.writeIntLittle(u16, values.weight); + try writer.writeInt(u16, values.weight, .Little); } if (resource == .dialogex) { - try writer.writeIntLittle(u8, @intFromBool(values.italic)); + try writer.writeInt(u8, @intFromBool(values.italic), .Little); } if (node.char_set) |char_set| { const value = evaluateNumberExpression(char_set, self.source, self.input_code_pages); - try writer.writeIntLittle(u8, @as(u8, @truncate(value.value))); + try writer.writeInt(u8, @as(u8, @truncate(value.value)), .Little); } else if (resource == .dialogex) { - try writer.writeIntLittle(u8, 1); // DEFAULT_CHARSET + try writer.writeInt(u8, 1, .Little); // DEFAULT_CHARSET } const typeface = try self.parseQuotedStringAsWideString(node.typeface); @@ -2076,9 +2077,9 @@ pub const Compiler = struct { pub fn writeMenuData(self: *Compiler, node: *Node.Menu, data_writer: anytype, resource: Resource) !void { // menu header const version: u16 = if (resource == .menu) 0 else 1; - try data_writer.writeIntLittle(u16, version); + try data_writer.writeInt(u16, version, .Little); const header_size: u16 = if (resource == .menu) 0 else 4; - try data_writer.writeIntLittle(u16, header_size); // cbHeaderSize + try data_writer.writeInt(u16, header_size, .Little); // cbHeaderSize // Note: There can be extra bytes at the end of this header (`rgbExtra`), // but they are always zero-length for us, so we don't write anything // (the length of the rgbExtra field is inferred from the header_size). @@ -2088,9 +2089,9 @@ pub const Compiler = struct { if (resource == .menuex) { if (node.help_id) |help_id_node| { const help_id = evaluateNumberExpression(help_id_node, self.source, self.input_code_pages); - try data_writer.writeIntLittle(u32, help_id.value); + try data_writer.writeInt(u32, help_id.value, .Little); } else { - try data_writer.writeIntLittle(u32, 0); + try data_writer.writeInt(u32, 0, .Little); } } @@ -2110,9 +2111,9 @@ pub const Compiler = struct { // compiler still uses this alternate form, so that's what we use too. var flags = res.MenuItemFlags{}; if (is_last_of_parent) flags.markLast(); - try writer.writeIntLittle(u16, flags.value); - try writer.writeIntLittle(u16, 0); // id - try writer.writeIntLittle(u16, 0); // null-terminated UTF-16 text + try writer.writeInt(u16, flags.value, .Little); + try writer.writeInt(u16, 0, .Little); // id + try writer.writeInt(u16, 0, .Little); // null-terminated UTF-16 text }, .menu_item => { const menu_item = @fieldParentPtr(Node.MenuItem, "base", node); @@ -2123,10 +2124,10 @@ pub const Compiler = struct { flags.apply(option); } if (is_last_of_parent) flags.markLast(); - try writer.writeIntLittle(u16, flags.value); + try writer.writeInt(u16, flags.value, .Little); var result = evaluateNumberExpression(menu_item.result, self.source, self.input_code_pages); - try writer.writeIntLittle(u16, result.asWord()); + try writer.writeInt(u16, result.asWord(), .Little); var text = try self.parseQuotedStringAsWideString(menu_item.text); defer self.allocator.free(text); @@ -2141,7 +2142,7 @@ pub const Compiler = struct { flags.apply(option); } if (is_last_of_parent) flags.markLast(); - try writer.writeIntLittle(u16, flags.value); + try writer.writeInt(u16, flags.value, .Little); var text = try self.parseQuotedStringAsWideString(popup.text); defer self.allocator.free(text); @@ -2157,30 +2158,30 @@ pub const Compiler = struct { if (menu_item.type) |flags| { const value = evaluateNumberExpression(flags, self.source, self.input_code_pages); - try writer.writeIntLittle(u32, value.value); + try writer.writeInt(u32, value.value, .Little); } else { - try writer.writeIntLittle(u32, 0); + try writer.writeInt(u32, 0, .Little); } if (menu_item.state) |state| { const value = evaluateNumberExpression(state, self.source, self.input_code_pages); - try writer.writeIntLittle(u32, value.value); + try writer.writeInt(u32, value.value, .Little); } else { - try writer.writeIntLittle(u32, 0); + try writer.writeInt(u32, 0, .Little); } if (menu_item.id) |id| { const value = evaluateNumberExpression(id, self.source, self.input_code_pages); - try writer.writeIntLittle(u32, value.value); + try writer.writeInt(u32, value.value, .Little); } else { - try writer.writeIntLittle(u32, 0); + try writer.writeInt(u32, 0, .Little); } var flags: u16 = 0; if (is_last_of_parent) flags |= comptime @as(u16, @intCast(res.MF.END)); // This constant doesn't seem to have a named #define, it's different than MF_POPUP if (node_type == .popup_ex) flags |= 0x01; - try writer.writeIntLittle(u16, flags); + try writer.writeInt(u16, flags, .Little); var text = try self.parseQuotedStringAsWideString(menu_item.text); defer self.allocator.free(text); @@ -2195,9 +2196,9 @@ pub const Compiler = struct { if (node_type == .popup_ex) { if (menu_item.help_id) |help_id_node| { const help_id = evaluateNumberExpression(help_id_node, self.source, self.input_code_pages); - try writer.writeIntLittle(u32, help_id.value); + try writer.writeInt(u32, help_id.value, .Little); } else { - try writer.writeIntLittle(u32, 0); + try writer.writeInt(u32, 0, .Little); } for (menu_item.items, 0..) |item, i| { @@ -2218,15 +2219,15 @@ pub const Compiler = struct { var limited_writer = limitedWriter(data_buffer.writer(), std.math.maxInt(u16)); const data_writer = limited_writer.writer(); - try data_writer.writeIntLittle(u16, 0); // placeholder size - try data_writer.writeIntLittle(u16, res.FixedFileInfo.byte_len); - try data_writer.writeIntLittle(u16, res.VersionNode.type_binary); + try data_writer.writeInt(u16, 0, .Little); // placeholder size + try data_writer.writeInt(u16, res.FixedFileInfo.byte_len, .Little); + try data_writer.writeInt(u16, res.VersionNode.type_binary, .Little); const key_bytes = std.mem.sliceAsBytes(res.FixedFileInfo.key[0 .. res.FixedFileInfo.key.len + 1]); try data_writer.writeAll(key_bytes); // The number of bytes written up to this point is always the same, since the name // of the node is a constant (FixedFileInfo.key). The total number of bytes // written so far is 38, so we need 2 padding bytes to get back to DWORD alignment - try data_writer.writeIntLittle(u16, 0); + try data_writer.writeInt(u16, 0, .Little); var fixed_file_info = res.FixedFileInfo{}; for (node.fixed_info) |fixed_info| { @@ -2321,7 +2322,7 @@ pub const Compiler = struct { // limited the writer to maxInt(u16) const data_size: u16 = @intCast(data_buffer.items.len); // And now that we know the full size of this node (including its children), set its size - std.mem.writeIntLittle(u16, data_buffer.items[0..2], data_size); + std.mem.writeInt(u16, data_buffer.items[0..2], data_size, .Little); var header = try self.resourceHeader(node.id, node.versioninfo, .{ .data_size = data_size, @@ -2344,12 +2345,12 @@ pub const Compiler = struct { try writeDataPadding(writer, @as(u16, @intCast(buf.items.len))); const node_and_children_size_offset = buf.items.len; - try writer.writeIntLittle(u16, 0); // placeholder for size + try writer.writeInt(u16, 0, .Little); // placeholder for size const data_size_offset = buf.items.len; - try writer.writeIntLittle(u16, 0); // placeholder for data size + try writer.writeInt(u16, 0, .Little); // placeholder for data size const data_type_offset = buf.items.len; // Data type is string unless the node contains values that are numbers. - try writer.writeIntLittle(u16, res.VersionNode.type_string); + try writer.writeInt(u16, res.VersionNode.type_string, .Little); switch (node.id) { inline .block, .block_value => |node_type| { @@ -2411,17 +2412,17 @@ pub const Compiler = struct { const is_empty = parsed_to_first_null.len == 0; const is_only = block_or_value.values.len == 1; if ((!is_empty or !is_only) and (is_last or value_value_node.trailing_comma)) { - try writer.writeIntLittle(u16, 0); + try writer.writeInt(u16, 0, .Little); values_size += if (has_number_value) 2 else 1; } } } var data_size_slice = buf.items[data_size_offset..]; - std.mem.writeIntLittle(u16, data_size_slice[0..@sizeOf(u16)], @as(u16, @intCast(values_size))); + std.mem.writeInt(u16, data_size_slice[0..@sizeOf(u16)], @as(u16, @intCast(values_size)), .Little); if (has_number_value) { const data_type_slice = buf.items[data_type_offset..]; - std.mem.writeIntLittle(u16, data_type_slice[0..@sizeOf(u16)], res.VersionNode.type_binary); + std.mem.writeInt(u16, data_type_slice[0..@sizeOf(u16)], res.VersionNode.type_binary, .Little); } if (node_type == .block) { @@ -2436,7 +2437,7 @@ pub const Compiler = struct { const node_and_children_size = buf.items.len - node_and_children_size_offset; const node_and_children_size_slice = buf.items[node_and_children_size_offset..]; - std.mem.writeIntLittle(u16, node_and_children_size_slice[0..@sizeOf(u16)], @as(u16, @intCast(node_and_children_size))); + std.mem.writeInt(u16, node_and_children_size_slice[0..@sizeOf(u16)], @as(u16, @intCast(node_and_children_size)), .Little); } pub fn writeStringTable(self: *Compiler, node: *Node.StringTable) !void { @@ -2644,17 +2645,17 @@ pub const Compiler = struct { } fn writeSizeInfo(self: ResourceHeader, writer: anytype, size_info: SizeInfo) !void { - try writer.writeIntLittle(DWORD, self.data_size); // DataSize - try writer.writeIntLittle(DWORD, size_info.bytes); // HeaderSize + try writer.writeInt(DWORD, self.data_size, .Little); // DataSize + try writer.writeInt(DWORD, size_info.bytes, .Little); // HeaderSize try self.type_value.write(writer); // TYPE try self.name_value.write(writer); // NAME try writer.writeByteNTimes(0, size_info.padding_after_name); - try writer.writeIntLittle(DWORD, self.data_version); // DataVersion - try writer.writeIntLittle(WORD, self.memory_flags.value); // MemoryFlags - try writer.writeIntLittle(WORD, self.language.asInt()); // LanguageId - try writer.writeIntLittle(DWORD, self.version); // Version - try writer.writeIntLittle(DWORD, self.characteristics); // Characteristics + try writer.writeInt(DWORD, self.data_version, .Little); // DataVersion + try writer.writeInt(WORD, self.memory_flags.value, .Little); // MemoryFlags + try writer.writeInt(WORD, self.language.asInt(), .Little); // LanguageId + try writer.writeInt(DWORD, self.version, .Little); // Version + try writer.writeInt(DWORD, self.characteristics, .Little); // Characteristics } pub fn predefinedResourceType(self: ResourceHeader) ?res.RT { @@ -2997,7 +2998,7 @@ pub const FontDir = struct { defer header.deinit(compiler.allocator); try header.writeAssertNoOverflow(writer); - try writer.writeIntLittle(u16, num_fonts); + try writer.writeInt(u16, num_fonts, .Little); for (self.fonts.items) |font| { // The format of the FONTDIR is a strange beast. // Technically, each FONT is seemingly meant to be written as a @@ -3049,7 +3050,7 @@ pub const FontDir = struct { // device name/face name in the FONTDIR is reliable. // First, the ID is written, though - try writer.writeIntLittle(u16, font.id); + try writer.writeInt(u16, font.id, .Little); try writer.writeAll(&font.header_bytes); try writer.writeByteNTimes(0, 2); } @@ -3186,7 +3187,7 @@ pub const StringTable = struct { var string_i: u8 = 0; while (true) : (i += 1) { if (!self.set_indexes.isSet(i)) { - try data_writer.writeIntLittle(u16, 0); + try data_writer.writeInt(u16, 0, .Little); if (i == 15) break else continue; } @@ -3217,10 +3218,10 @@ pub const StringTable = struct { // If the option is set, then a NUL terminator is added unconditionally. // We already trimmed any trailing NULs, so we know it will be a new addition to the string. if (compiler.null_terminate_string_table_strings) string_len_in_utf16_code_units += 1; - try data_writer.writeIntLittle(u16, string_len_in_utf16_code_units); + try data_writer.writeInt(u16, string_len_in_utf16_code_units, .Little); try data_writer.writeAll(std.mem.sliceAsBytes(trimmed_string)); if (compiler.null_terminate_string_table_strings) { - try data_writer.writeIntLittle(u16, 0); + try data_writer.writeInt(u16, 0, .Little); } if (i == 15) break; diff --git a/src/resinator/errors.zig b/src/resinator/errors.zig index 08d09f1b9d..62c67ab90b 100644 --- a/src/resinator/errors.zig +++ b/src/resinator/errors.zig @@ -9,6 +9,8 @@ const bmp = @import("bmp.zig"); const parse = @import("parse.zig"); const lang = @import("lang.zig"); const CodePage = @import("code_pages.zig").CodePage; +const builtin = @import("builtin"); +const native_endian = builtin.cpu.arch.endian(); pub const Diagnostics = struct { errors: std.ArrayListUnmanaged(ErrorDetails) = .{}, @@ -649,24 +651,24 @@ pub const ErrorDetails = struct { }, .bmp_ignored_palette_bytes => { const bytes = strings[self.extra.number]; - const ignored_bytes = std.mem.readIntNative(u64, bytes[0..8]); + const ignored_bytes = std.mem.readInt(u64, bytes[0..8], native_endian); try writer.print("bitmap has {d} extra bytes preceding the pixel data which will be ignored", .{ignored_bytes}); }, .bmp_missing_palette_bytes => { const bytes = strings[self.extra.number]; - const missing_bytes = std.mem.readIntNative(u64, bytes[0..8]); + const missing_bytes = std.mem.readInt(u64, bytes[0..8], native_endian); try writer.print("bitmap has {d} missing color palette bytes which will be padded with zeroes", .{missing_bytes}); }, .rc_would_miscompile_bmp_palette_padding => { const bytes = strings[self.extra.number]; - const miscompiled_bytes = std.mem.readIntNative(u64, bytes[0..8]); + const miscompiled_bytes = std.mem.readInt(u64, bytes[0..8], native_endian); try writer.print("the missing color palette bytes would be miscompiled by the Win32 RC compiler (the added padding bytes would include {d} bytes of the pixel data)", .{miscompiled_bytes}); }, .bmp_too_many_missing_palette_bytes => switch (self.type) { .err, .warning => { const bytes = strings[self.extra.number]; - const missing_bytes = std.mem.readIntNative(u64, bytes[0..8]); - const max_missing_bytes = std.mem.readIntNative(u64, bytes[8..16]); + const missing_bytes = std.mem.readInt(u64, bytes[0..8], native_endian); + const max_missing_bytes = std.mem.readInt(u64, bytes[8..16], native_endian); try writer.print("bitmap has {} missing color palette bytes which exceeds the maximum of {}", .{ missing_bytes, max_missing_bytes }); }, // TODO: command line option diff --git a/src/resinator/ico.zig b/src/resinator/ico.zig index 205f5a0e59..9075de4ccc 100644 --- a/src/resinator/ico.zig +++ b/src/resinator/ico.zig @@ -5,6 +5,8 @@ //! https://learn.microsoft.com/en-us/windows/win32/menurc/localheader const std = @import("std"); +const builtin = @import("builtin"); +const native_endian = builtin.cpu.arch.endian(); pub const ReadError = std.mem.Allocator.Error || error{ InvalidHeader, InvalidImageType, ImpossibleDataSize, UnexpectedEOF, ReadError }; @@ -37,7 +39,7 @@ pub fn read(allocator: std.mem.Allocator, reader: anytype, max_size: u64) ReadEr // to do this. Maybe it makes more sense to handle the translation // at the call site instead of having a helper function here. pub fn readAnyError(allocator: std.mem.Allocator, reader: anytype, max_size: u64) !IconDir { - const reserved = try reader.readIntLittle(u16); + const reserved = try reader.readInt(u16, .Little); if (reserved != 0) { return error.InvalidHeader; } @@ -47,7 +49,7 @@ pub fn readAnyError(allocator: std.mem.Allocator, reader: anytype, max_size: u64 else => |e| return e, }; - const num_images = try reader.readIntLittle(u16); + const num_images = try reader.readInt(u16, .Little); // To avoid over-allocation in the case of a file that says it has way more // entries than it actually does, we use an ArrayList with a conservatively @@ -66,19 +68,19 @@ pub fn readAnyError(allocator: std.mem.Allocator, reader: anytype, max_size: u64 switch (image_type) { .icon => { entry.type_specific_data = .{ .icon = .{ - .color_planes = try reader.readIntLittle(u16), - .bits_per_pixel = try reader.readIntLittle(u16), + .color_planes = try reader.readInt(u16, .Little), + .bits_per_pixel = try reader.readInt(u16, .Little), } }; }, .cursor => { entry.type_specific_data = .{ .cursor = .{ - .hotspot_x = try reader.readIntLittle(u16), - .hotspot_y = try reader.readIntLittle(u16), + .hotspot_x = try reader.readInt(u16, .Little), + .hotspot_y = try reader.readInt(u16, .Little), } }; }, } - entry.data_size_in_bytes = try reader.readIntLittle(u32); - entry.data_offset_from_start_of_file = try reader.readIntLittle(u32); + entry.data_size_in_bytes = try reader.readInt(u32, .Little); + entry.data_offset_from_start_of_file = try reader.readInt(u32, .Little); // Validate that the offset/data size is feasible if (@as(u64, entry.data_offset_from_start_of_file) + entry.data_size_in_bytes > max_size) { return error.ImpossibleDataSize; @@ -133,10 +135,10 @@ pub const IconDir = struct { } pub fn writeResData(self: IconDir, writer: anytype, first_image_id: u16) !void { - try writer.writeIntLittle(u16, 0); - try writer.writeIntLittle(u16, @intFromEnum(self.image_type)); + try writer.writeInt(u16, 0, .Little); + try writer.writeInt(u16, @intFromEnum(self.image_type), .Little); // We know that entries.len must fit into a u16 - try writer.writeIntLittle(u16, @as(u16, @intCast(self.entries.len))); + try writer.writeInt(u16, @as(u16, @intCast(self.entries.len)), .Little); var image_id = first_image_id; for (self.entries) |entry| { @@ -173,23 +175,23 @@ pub const Entry = struct { pub fn writeResData(self: Entry, writer: anytype, id: u16) !void { switch (self.type_specific_data) { .icon => |icon_data| { - try writer.writeIntLittle(u8, @as(u8, @truncate(self.width))); - try writer.writeIntLittle(u8, @as(u8, @truncate(self.height))); - try writer.writeIntLittle(u8, self.num_colors); - try writer.writeIntLittle(u8, self.reserved); - try writer.writeIntLittle(u16, icon_data.color_planes); - try writer.writeIntLittle(u16, icon_data.bits_per_pixel); - try writer.writeIntLittle(u32, self.data_size_in_bytes); + try writer.writeInt(u8, @as(u8, @truncate(self.width)), .Little); + try writer.writeInt(u8, @as(u8, @truncate(self.height)), .Little); + try writer.writeInt(u8, self.num_colors, .Little); + try writer.writeInt(u8, self.reserved, .Little); + try writer.writeInt(u16, icon_data.color_planes, .Little); + try writer.writeInt(u16, icon_data.bits_per_pixel, .Little); + try writer.writeInt(u32, self.data_size_in_bytes, .Little); }, .cursor => |cursor_data| { - try writer.writeIntLittle(u16, self.width); - try writer.writeIntLittle(u16, self.height); - try writer.writeIntLittle(u16, cursor_data.hotspot_x); - try writer.writeIntLittle(u16, cursor_data.hotspot_y); - try writer.writeIntLittle(u32, self.data_size_in_bytes + 4); + try writer.writeInt(u16, self.width, .Little); + try writer.writeInt(u16, self.height, .Little); + try writer.writeInt(u16, cursor_data.hotspot_x, .Little); + try writer.writeInt(u16, cursor_data.hotspot_y, .Little); + try writer.writeInt(u32, self.data_size_in_bytes + 4, .Little); }, } - try writer.writeIntLittle(u16, id); + try writer.writeInt(u16, id, .Little); } }; @@ -235,21 +237,21 @@ pub const ImageFormat = enum { png, riff, - const riff_header = std.mem.readIntNative(u32, "RIFF"); - const png_signature = std.mem.readIntNative(u64, "\x89PNG\r\n\x1a\n"); - const ihdr_code = std.mem.readIntNative(u32, "IHDR"); - const acon_form_type = std.mem.readIntNative(u32, "ACON"); + const riff_header = std.mem.readInt(u32, "RIFF", native_endian); + const png_signature = std.mem.readInt(u64, "\x89PNG\r\n\x1a\n", native_endian); + const ihdr_code = std.mem.readInt(u32, "IHDR", native_endian); + const acon_form_type = std.mem.readInt(u32, "ACON", native_endian); pub fn detect(header_bytes: *const [16]u8) ImageFormat { - if (std.mem.readIntNative(u32, header_bytes[0..4]) == riff_header) return .riff; - if (std.mem.readIntNative(u64, header_bytes[0..8]) == png_signature) return .png; + if (std.mem.readInt(u32, header_bytes[0..4], native_endian) == riff_header) return .riff; + if (std.mem.readInt(u64, header_bytes[0..8], native_endian) == png_signature) return .png; return .dib; } pub fn validate(format: ImageFormat, header_bytes: *const [16]u8) bool { return switch (format) { - .png => std.mem.readIntNative(u32, header_bytes[12..16]) == ihdr_code, - .riff => std.mem.readIntNative(u32, header_bytes[8..12]) == acon_form_type, + .png => std.mem.readInt(u32, header_bytes[12..16], native_endian) == ihdr_code, + .riff => std.mem.readInt(u32, header_bytes[8..12], native_endian) == acon_form_type, .dib => true, }; } diff --git a/src/resinator/res.zig b/src/resinator/res.zig index d331644f61..c21f877245 100644 --- a/src/resinator/res.zig +++ b/src/resinator/res.zig @@ -249,14 +249,14 @@ pub const NameOrOrdinal = union(enum) { try writer.writeAll(std.mem.sliceAsBytes(name[0 .. name.len + 1])); }, .ordinal => |ordinal| { - try writer.writeIntLittle(u16, 0xffff); - try writer.writeIntLittle(u16, ordinal); + try writer.writeInt(u16, 0xffff, .Little); + try writer.writeInt(u16, ordinal, .Little); }, } } pub fn writeEmpty(writer: anytype) !void { - try writer.writeIntLittle(u16, 0); + try writer.writeInt(u16, 0, .Little); } pub fn fromString(allocator: Allocator, bytes: SourceBytes) !NameOrOrdinal { @@ -963,19 +963,19 @@ pub const FixedFileInfo = struct { }; pub fn write(self: FixedFileInfo, writer: anytype) !void { - try writer.writeIntLittle(u32, signature); - try writer.writeIntLittle(u32, version); - try writer.writeIntLittle(u32, self.file_version.mostSignificantCombinedParts()); - try writer.writeIntLittle(u32, self.file_version.leastSignificantCombinedParts()); - try writer.writeIntLittle(u32, self.product_version.mostSignificantCombinedParts()); - try writer.writeIntLittle(u32, self.product_version.leastSignificantCombinedParts()); - try writer.writeIntLittle(u32, self.file_flags_mask); - try writer.writeIntLittle(u32, self.file_flags); - try writer.writeIntLittle(u32, self.file_os); - try writer.writeIntLittle(u32, self.file_type); - try writer.writeIntLittle(u32, self.file_subtype); - try writer.writeIntLittle(u32, self.file_date.mostSignificantCombinedParts()); - try writer.writeIntLittle(u32, self.file_date.leastSignificantCombinedParts()); + try writer.writeInt(u32, signature, .Little); + try writer.writeInt(u32, version, .Little); + try writer.writeInt(u32, self.file_version.mostSignificantCombinedParts(), .Little); + try writer.writeInt(u32, self.file_version.leastSignificantCombinedParts(), .Little); + try writer.writeInt(u32, self.product_version.mostSignificantCombinedParts(), .Little); + try writer.writeInt(u32, self.product_version.leastSignificantCombinedParts(), .Little); + try writer.writeInt(u32, self.file_flags_mask, .Little); + try writer.writeInt(u32, self.file_flags, .Little); + try writer.writeInt(u32, self.file_os, .Little); + try writer.writeInt(u32, self.file_type, .Little); + try writer.writeInt(u32, self.file_subtype, .Little); + try writer.writeInt(u32, self.file_date.mostSignificantCombinedParts(), .Little); + try writer.writeInt(u32, self.file_date.leastSignificantCombinedParts(), .Little); } }; diff --git a/test/behavior/bugs/1851.zig b/test/behavior/bugs/1851.zig index a61e17e8df..787c8cbd86 100644 --- a/test/behavior/bugs/1851.zig +++ b/test/behavior/bugs/1851.zig @@ -7,6 +7,7 @@ test "allocation and looping over 3-byte integer" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest; + if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; if (builtin.zig_backend == .stage2_llvm and builtin.os.tag == .macos) { return error.SkipZigTest; // TODO diff --git a/test/behavior/struct.zig b/test/behavior/struct.zig index b8dde719cf..b46164a1b5 100644 --- a/test/behavior/struct.zig +++ b/test/behavior/struct.zig @@ -1351,6 +1351,7 @@ test "under-aligned struct field" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest; + if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; const U = extern union { fd: i32, @@ -1364,7 +1365,7 @@ test "under-aligned struct field" { var runtime: usize = 1234; const ptr = &S{ .events = 0, .data = .{ .u64 = runtime } }; const array = @as(*const [12]u8, @ptrCast(ptr)); - const result = std.mem.readIntNative(u64, array[4..12]); + const result = std.mem.readInt(u64, array[4..12], native_endian); try expect(result == 1234); }