diff --git a/CMakeLists.txt b/CMakeLists.txt index 13f777245f2f43e10415d4d63fc1467189af114f..5a0f70836c5b0c55f9e5964e9059c8d0d5175727 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -436,7 +436,6 @@ set(ZIG_STAGE2_SOURCES lib/std/elf.zig lib/std/fifo.zig lib/std/fmt.zig - lib/std/fmt/format_float.zig lib/std/fmt/parse_float.zig lib/std/fs.zig lib/std/fs/AtomicFile.zig @@ -454,12 +453,9 @@ set(ZIG_STAGE2_SOURCES lib/std/io/Reader.zig lib/std/io/Writer.zig lib/std/io/buffered_atomic_file.zig - lib/std/io/buffered_writer.zig lib/std/io/change_detection_stream.zig lib/std/io/counting_reader.zig - lib/std/io/counting_writer.zig lib/std/io/find_byte_writer.zig - lib/std/io/fixed_buffer_stream.zig lib/std/io/limited_reader.zig lib/std/io/seekable_stream.zig lib/std/json.zig diff --git a/lib/std/Build/Cache.zig b/lib/std/Build/Cache.zig index bf63acdead65bccf9bf775469692e9d72c36af23..9628423504d1dbb3a46a82e956712da94cd508e9 100644 --- a/lib/std/Build/Cache.zig +++ b/lib/std/Build/Cache.zig @@ -286,11 +286,9 @@ pub const HashHelper = struct { pub fn binToHex(bin_digest: BinDigest) HexDigest { var out_digest: HexDigest = undefined; - _ = fmt.bufPrint( - &out_digest, - "{s}", - .{fmt.fmtSliceHexLower(&bin_digest)}, - ) catch unreachable; + var bw: std.io.BufferedWriter = undefined; + bw.initFixed(&out_digest); + bw.printHex(&bin_digest, .lower) catch unreachable; return out_digest; } @@ -1133,11 +1131,11 @@ pub const Manifest = struct { const writer = contents.writer(); try writer.writeAll(manifest_header ++ "\n"); for (self.files.keys()) |file| { - try writer.print("{d} {d} {d} {} {d} {s}\n", .{ + try writer.print("{d} {d} {d} {x} {d} {s}\n", .{ file.stat.size, file.stat.inode, file.stat.mtime, - fmt.fmtSliceHexLower(&file.bin_digest), + &file.bin_digest, file.prefixed_path.prefix, file.prefixed_path.sub_path, }); diff --git a/lib/std/Build/Step/CheckObject.zig b/lib/std/Build/Step/CheckObject.zig index c2ff85c6f16b6595f97322a62a48ce087fe359f1..5b1806647cc9c0e9f6d2b7a0dc97f21c630d8f2d 100644 --- a/lib/std/Build/Step/CheckObject.zig +++ b/lib/std/Build/Step/CheckObject.zig @@ -963,7 +963,7 @@ const MachODumper = struct { .UUID => { const uuid = lc.cast(macho.uuid_command).?; try writer.writeByte('\n'); - try writer.print("uuid {x}", .{std.fmt.fmtSliceHexLower(&uuid.uuid)}); + try writer.print("uuid {x}", .{&uuid.uuid}); }, .DATA_IN_CODE, diff --git a/lib/std/Build/Step/Compile.zig b/lib/std/Build/Step/Compile.zig index 9352280d96418843ec062263c0592120df342ca2..01687bb40ef6c5984d7f3b7362a1bc8e75e4337e 100644 --- a/lib/std/Build/Step/Compile.zig +++ b/lib/std/Build/Step/Compile.zig @@ -1696,9 +1696,7 @@ fn getZigArgs(compile: *Compile, fuzz: bool) ![][]const u8 { if (compile.build_id orelse b.build_id) |build_id| { try zig_args.append(switch (build_id) { - .hexstring => |hs| b.fmt("--build-id=0x{s}", .{ - std.fmt.fmtSliceHexLower(hs.toSlice()), - }), + .hexstring => |hs| b.fmt("--build-id=0x{x}", .{hs.toSlice()}), .none, .fast, .uuid, .sha1, .md5 => b.fmt("--build-id={s}", .{@tagName(build_id)}), }); } @@ -1793,11 +1791,7 @@ fn getZigArgs(compile: *Compile, fuzz: bool) ![][]const u8 { var args_hash: [Sha256.digest_length]u8 = undefined; Sha256.hash(args, &args_hash, .{}); var args_hex_hash: [Sha256.digest_length * 2]u8 = undefined; - _ = try std.fmt.bufPrint( - &args_hex_hash, - "{s}", - .{std.fmt.fmtSliceHexLower(&args_hash)}, - ); + _ = try std.fmt.bufPrint(&args_hex_hash, "{x}", .{&args_hash}); const args_file = "args" ++ fs.path.sep_str ++ args_hex_hash; try b.cache_root.handle.writeFile(.{ .sub_path = args_file, .data = args }); diff --git a/lib/std/array_list.zig b/lib/std/array_list.zig index 2a9159aeac71116cb30b366e7a7566dbecf9ebae..952ca85facb06da0deb9d99602d2c87e68451cb2 100644 --- a/lib/std/array_list.zig +++ b/lib/std/array_list.zig @@ -338,23 +338,66 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?mem.Alignment) ty @memcpy(self.items[old_len..][0..items.len], items); } - pub const Writer = if (T != u8) - @compileError("The Writer interface is only defined for ArrayList(u8) " ++ - "but the given type is ArrayList(" ++ @typeName(T) ++ ")") - else - std.io.Writer(*Self, Allocator.Error, appendWrite); + /// Initializes a `std.io.Writer` which will append to the list. + pub fn writer(self: *Self) std.io.Writer { + comptime assert(T == u8); + return .{ + .context = self, + .vtable = &.{ + .writev = expanding_writev, + .writeFile = expanding_writeFile, + }, + }; + } - /// Initializes a Writer which will append to the list. - pub fn writer(self: *Self) Writer { - return .{ .context = self }; + fn expanding_writev(context: *anyopaque, data: []const []const u8) anyerror!usize { + const self: *Self = @alignCast(@ptrCast(context)); + const original_len = self.items.len; + var new_capacity: usize = self.capacity; + for (data) |bytes| new_capacity += bytes.len; + try self.ensureTotalCapacity(new_capacity); + for (data) |bytes| self.appendSliceAssumeCapacity(bytes); + return self.items.len - original_len; } - /// Same as `append` except it returns the number of bytes written, which is always the same - /// as `m.len`. The purpose of this function existing is to match `std.io.Writer` API. - /// Invalidates element pointers if additional memory is needed. - fn appendWrite(self: *Self, m: []const u8) Allocator.Error!usize { - try self.appendSlice(m); - return m.len; + fn expanding_writeFile( + context: *anyopaque, + file: std.fs.File, + offset: u64, + len: std.io.Writer.VTable.FileLen, + headers_and_trailers: []const []const u8, + headers_len: usize, + ) anyerror!usize { + const self: *Self = @alignCast(@ptrCast(context)); + const trailers = headers_and_trailers[headers_len..]; + const original_len = self.items.len; + if (len == .entire_file) { + var new_capacity: usize = self.capacity + std.atomic.cache_line; + for (headers_and_trailers) |bytes| new_capacity += bytes.len; + try self.ensureTotalCapacity(new_capacity); + for (headers_and_trailers[0..headers_len]) |bytes| self.appendSliceAssumeCapacity(bytes); + const dest = self.items.ptr[self.items.len..self.capacity]; + const n = try file.pread(dest, offset); + if (n == 0) { + new_capacity = self.capacity; + for (trailers) |bytes| new_capacity += bytes.len; + try self.ensureTotalCapacity(new_capacity); + for (trailers) |bytes| self.appendSliceAssumeCapacity(bytes); + return self.items.len - original_len; + } + self.items.len += n; + return self.items.len - original_len; + } + var new_capacity: usize = self.capacity + len.int(); + for (headers_and_trailers) |bytes| new_capacity += bytes.len; + try self.ensureTotalCapacity(new_capacity); + for (headers_and_trailers[0..headers_len]) |bytes| self.appendSliceAssumeCapacity(bytes); + const dest = self.items.ptr[self.items.len..][0..len.int()]; + const n = try file.pread(dest, offset); + self.items.len += n; + if (n < dest.len) return self.items.len - original_len; + for (trailers) |bytes| self.appendSliceAssumeCapacity(bytes); + return self.items.len - original_len; } pub const FixedWriter = std.io.Writer(*Self, Allocator.Error, appendWriteFixed); diff --git a/lib/std/crypto/25519/curve25519.zig b/lib/std/crypto/25519/curve25519.zig index 313dd577b01ed0338ed6fe4bc97c628b65f1d1fe..825f0bd94c05f12f2082197cab3e3f9d30a9302e 100644 --- a/lib/std/crypto/25519/curve25519.zig +++ b/lib/std/crypto/25519/curve25519.zig @@ -124,9 +124,9 @@ test "curve25519" { const p = try Curve25519.basePoint.clampedMul(s); try p.rejectIdentity(); var buf: [128]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&p.toBytes())}), "E6F2A4D1C28EE5C7AD0329268255A468AD407D2672824C0C0EB30EA6EF450145"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&p.toBytes()}), "E6F2A4D1C28EE5C7AD0329268255A468AD407D2672824C0C0EB30EA6EF450145"); const q = try p.clampedMul(s); - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&q.toBytes())}), "3614E119FFE55EC55B87D6B19971A9F4CBC78EFE80BEC55B96392BABCC712537"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&q.toBytes()}), "3614E119FFE55EC55B87D6B19971A9F4CBC78EFE80BEC55B96392BABCC712537"); try Curve25519.rejectNonCanonical(s); s[31] |= 0x80; diff --git a/lib/std/crypto/25519/ed25519.zig b/lib/std/crypto/25519/ed25519.zig index 94dd370d010dc184b91a32e364fbe2fcc5199669..8151228bf23993341f0277a1e464b0fc7861e332 100644 --- a/lib/std/crypto/25519/ed25519.zig +++ b/lib/std/crypto/25519/ed25519.zig @@ -509,8 +509,8 @@ test "key pair creation" { _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); const key_pair = try Ed25519.KeyPair.generateDeterministic(seed); var buf: [256]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.secret_key.toBytes())}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1662D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.public_key.toBytes())}), "2D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&key_pair.secret_key.toBytes()}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1662D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&key_pair.public_key.toBytes()}), "2D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); } test "signature" { @@ -520,7 +520,7 @@ test "signature" { const sig = try key_pair.sign("test", null); var buf: [128]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&sig.toBytes())}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&sig.toBytes()}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808"); try sig.verify("test", key_pair.public_key); try std.testing.expectError(error.SignatureVerificationFailed, sig.verify("TEST", key_pair.public_key)); } diff --git a/lib/std/crypto/25519/edwards25519.zig b/lib/std/crypto/25519/edwards25519.zig index 527536f17d22f54c87204e2fdbbd70024c3276da..47c07939ac680779ebb7bbe052b1a5974e801060 100644 --- a/lib/std/crypto/25519/edwards25519.zig +++ b/lib/std/crypto/25519/edwards25519.zig @@ -546,7 +546,7 @@ test "packing/unpacking" { var b = Edwards25519.basePoint; const pk = try b.mul(s); var buf: [128]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&pk.toBytes())}), "074BC7E0FCBD587FDBC0969444245FADC562809C8F6E97E949AF62484B5B81A6"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&pk.toBytes()}), "074BC7E0FCBD587FDBC0969444245FADC562809C8F6E97E949AF62484B5B81A6"); const small_order_ss: [7][32]u8 = .{ .{ diff --git a/lib/std/crypto/25519/ristretto255.zig b/lib/std/crypto/25519/ristretto255.zig index 5a00bf523ac0dfc6107879c1e565b7b6e75c5888..dd1a8a236e878f06409e9ba0a6017cc9b0683471 100644 --- a/lib/std/crypto/25519/ristretto255.zig +++ b/lib/std/crypto/25519/ristretto255.zig @@ -175,21 +175,21 @@ pub const Ristretto255 = struct { test "ristretto255" { const p = Ristretto255.basePoint; var buf: [256]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&p.toBytes())}), "E2F2AE0A6ABC4E71A884A961C500515F58E30B6AA582DD8DB6A65945E08D2D76"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&p.toBytes()}), "E2F2AE0A6ABC4E71A884A961C500515F58E30B6AA582DD8DB6A65945E08D2D76"); var r: [Ristretto255.encoded_length]u8 = undefined; _ = try fmt.hexToBytes(r[0..], "6a493210f7499cd17fecb510ae0cea23a110e8d5b901f8acadd3095c73a3b919"); var q = try Ristretto255.fromBytes(r); q = q.dbl().add(p); - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&q.toBytes())}), "E882B131016B52C1D3337080187CF768423EFCCBB517BB495AB812C4160FF44E"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&q.toBytes()}), "E882B131016B52C1D3337080187CF768423EFCCBB517BB495AB812C4160FF44E"); const s = [_]u8{15} ++ [_]u8{0} ** 31; const w = try p.mul(s); - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&w.toBytes())}), "E0C418F7C8D9C4CDD7395B93EA124F3AD99021BB681DFC3302A9D99A2E53E64E"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&w.toBytes()}), "E0C418F7C8D9C4CDD7395B93EA124F3AD99021BB681DFC3302A9D99A2E53E64E"); try std.testing.expect(p.dbl().dbl().dbl().dbl().equivalent(w.add(p))); const h = [_]u8{69} ** 32 ++ [_]u8{42} ** 32; const ph = Ristretto255.fromUniform(h); - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&ph.toBytes())}), "DCCA54E037A4311EFBEEF413ACD21D35276518970B7A61DC88F8587B493D5E19"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&ph.toBytes()}), "DCCA54E037A4311EFBEEF413ACD21D35276518970B7A61DC88F8587B493D5E19"); } diff --git a/lib/std/crypto/25519/scalar.zig b/lib/std/crypto/25519/scalar.zig index e7e74bf618f2c9d7b6d4ef766716661b39b6f6ca..b07b1c774c6dc8067ef2f451ebc0dd6b9533ddb0 100644 --- a/lib/std/crypto/25519/scalar.zig +++ b/lib/std/crypto/25519/scalar.zig @@ -850,10 +850,10 @@ test "scalar25519" { var y = x.toBytes(); try rejectNonCanonical(y); var buf: [128]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&y)}), "1E979B917937F3DE71D18077F961F6CEFF01030405060708010203040506070F"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&y}), "1E979B917937F3DE71D18077F961F6CEFF01030405060708010203040506070F"); const reduced = reduce(field_order_s); - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&reduced)}), "0000000000000000000000000000000000000000000000000000000000000000"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&reduced}), "0000000000000000000000000000000000000000000000000000000000000000"); } test "non-canonical scalar25519" { @@ -867,7 +867,7 @@ test "mulAdd overflow check" { const c: [32]u8 = [_]u8{0xff} ** 32; const x = mulAdd(a, b, c); var buf: [128]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&x)}), "D14DF91389432C25AD60FF9791B9FD1D67BEF517D273ECCE3D9A307C1B419903"); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&x}), "D14DF91389432C25AD60FF9791B9FD1D67BEF517D273ECCE3D9A307C1B419903"); } test "scalar field inversion" { diff --git a/lib/std/crypto/chacha20.zig b/lib/std/crypto/chacha20.zig index 287e664c2b8dea627c58eb2802c92c806c1b48a1..c605a6cb348b30596798f7734ebd3ef25ba477b7 100644 --- a/lib/std/crypto/chacha20.zig +++ b/lib/std/crypto/chacha20.zig @@ -1145,7 +1145,7 @@ test "xchacha20" { var c: [m.len]u8 = undefined; XChaCha20IETF.xor(c[0..], m[0..], 0, key, nonce); var buf: [2 * c.len]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&c)}), "E0A1BCF939654AFDBDC1746EC49832647C19D891F0D1A81FC0C1703B4514BDEA584B512F6908C2C5E9DD18D5CBC1805DE5803FE3B9CA5F193FB8359E91FAB0C3BB40309A292EB1CF49685C65C4A3ADF4F11DB0CD2B6B67FBC174BC2E860E8F769FD3565BBFAD1C845E05A0FED9BE167C240D"); + try testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&c}), "E0A1BCF939654AFDBDC1746EC49832647C19D891F0D1A81FC0C1703B4514BDEA584B512F6908C2C5E9DD18D5CBC1805DE5803FE3B9CA5F193FB8359E91FAB0C3BB40309A292EB1CF49685C65C4A3ADF4F11DB0CD2B6B67FBC174BC2E860E8F769FD3565BBFAD1C845E05A0FED9BE167C240D"); } { const ad = "Additional data"; @@ -1154,7 +1154,7 @@ test "xchacha20" { var out: [m.len]u8 = undefined; try XChaCha20Poly1305.decrypt(out[0..], c[0..m.len], c[m.len..].*, ad, nonce, key); var buf: [2 * c.len]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&c)}), "994D2DD32333F48E53650C02C7A2ABB8E018B0836D7175AEC779F52E961780768F815C58F1AA52D211498DB89B9216763F569C9433A6BBFCEFB4D4A49387A4C5207FBB3B5A92B5941294DF30588C6740D39DC16FA1F0E634F7246CF7CDCB978E44347D89381B7A74EB7084F754B90BDE9AAF5A94B8F2A85EFD0B50692AE2D425E234"); + try testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{&c}), "994D2DD32333F48E53650C02C7A2ABB8E018B0836D7175AEC779F52E961780768F815C58F1AA52D211498DB89B9216763F569C9433A6BBFCEFB4D4A49387A4C5207FBB3B5A92B5941294DF30588C6740D39DC16FA1F0E634F7246CF7CDCB978E44347D89381B7A74EB7084F754B90BDE9AAF5A94B8F2A85EFD0B50692AE2D425E234"); try testing.expectEqualSlices(u8, out[0..], m); c[0] +%= 1; try testing.expectError(error.AuthenticationFailed, XChaCha20Poly1305.decrypt(out[0..], c[0..m.len], c[m.len..].*, ad, nonce, key)); diff --git a/lib/std/crypto/ml_kem.zig b/lib/std/crypto/ml_kem.zig index 99cb493b34eeb87eee238876c9c4f5f89f65b0cc..ce3edf9eb5bbf81492d1dbf4487c754905cea406 100644 --- a/lib/std/crypto/ml_kem.zig +++ b/lib/std/crypto/ml_kem.zig @@ -1741,7 +1741,7 @@ test "NIST KAT test" { for (0..100) |i| { g.fill(&seed); try std.fmt.format(fw, "count = {}\n", .{i}); - try std.fmt.format(fw, "seed = {s}\n", .{std.fmt.fmtSliceHexUpper(&seed)}); + try std.fmt.format(fw, "seed = {X}\n", .{&seed}); var g2 = NistDRBG.init(seed); // This is not equivalent to g2.fill(kseed[:]). As the reference @@ -1756,16 +1756,16 @@ test "NIST KAT test" { const e = kp.public_key.encaps(eseed); const ss2 = try kp.secret_key.decaps(&e.ciphertext); try testing.expectEqual(ss2, e.shared_secret); - try std.fmt.format(fw, "pk = {s}\n", .{std.fmt.fmtSliceHexUpper(&kp.public_key.toBytes())}); - try std.fmt.format(fw, "sk = {s}\n", .{std.fmt.fmtSliceHexUpper(&kp.secret_key.toBytes())}); - try std.fmt.format(fw, "ct = {s}\n", .{std.fmt.fmtSliceHexUpper(&e.ciphertext)}); - try std.fmt.format(fw, "ss = {s}\n\n", .{std.fmt.fmtSliceHexUpper(&e.shared_secret)}); + try std.fmt.format(fw, "pk = {X}\n", .{&kp.public_key.toBytes()}); + try std.fmt.format(fw, "sk = {X}\n", .{&kp.secret_key.toBytes()}); + try std.fmt.format(fw, "ct = {X}\n", .{&e.ciphertext}); + try std.fmt.format(fw, "ss = {X}\n\n", .{&e.shared_secret}); } var out: [32]u8 = undefined; f.final(&out); var outHex: [64]u8 = undefined; - _ = try std.fmt.bufPrint(&outHex, "{s}", .{std.fmt.fmtSliceHexLower(&out)}); + _ = try std.fmt.bufPrint(&outHex, "{x}", .{&out}); try testing.expectEqual(outHex, modeHash[1].*); } } diff --git a/lib/std/crypto/tls/Client.zig b/lib/std/crypto/tls/Client.zig index bd5a74c2cb7a7785d11a7b4396a1bebcd143929d..727f1ddd63d13da8eb3ce0626352331924e9652a 100644 --- a/lib/std/crypto/tls/Client.zig +++ b/lib/std/crypto/tls/Client.zig @@ -1513,10 +1513,10 @@ fn logSecrets(key_log_file: std.fs.File, context: anytype, secrets: anytype) voi defer if (locked) key_log_file.unlock(); key_log_file.seekFromEnd(0) catch {}; inline for (@typeInfo(@TypeOf(secrets)).@"struct".fields) |field| key_log_file.writer().print("{s}" ++ - (if (@hasField(@TypeOf(context), "counter")) "_{d}" else "") ++ " {} {}\n", .{field.name} ++ + (if (@hasField(@TypeOf(context), "counter")) "_{d}" else "") ++ " {x} {x}\n", .{field.name} ++ (if (@hasField(@TypeOf(context), "counter")) .{context.counter} else .{}) ++ .{ - std.fmt.fmtSliceHexLower(context.client_random), - std.fmt.fmtSliceHexLower(@field(secrets, field.name)), + context.client_random, + @field(secrets, field.name), }) catch {}; } diff --git a/lib/std/debug.zig b/lib/std/debug.zig index dbf8e110a28d0db60b2ce02cdadeb47453f5a40d..586704572aa294be94b4b19701b053155918f129 100644 --- a/lib/std/debug.zig +++ b/lib/std/debug.zig @@ -204,13 +204,23 @@ pub fn unlockStdErr() void { std.Progress.unlockStdErr(); } +/// Allows the caller to freely write to stderr until `unlockStdErr` is called. +/// +/// During the lock, any `std.Progress` information is cleared from the terminal. +/// +/// Returns a `std.io.BufferedWriter` with empty buffer, meaning that it is +/// in fact unbuffered and does not need to be flushed. +pub fn lockStdErr2() std.io.BufferedWriter { + std.Progress.lockStdErr(); + return io.getStdErr().unbufferedWriter(); +} + /// Print to stderr, unbuffered, and silently returning on failure. Intended /// for use in "printf debugging." Use `std.log` functions for proper logging. pub fn print(comptime fmt: []const u8, args: anytype) void { - lockStdErr(); + var bw = lockStdErr2(); defer unlockStdErr(); - const stderr = io.getStdErr().writer(); - nosuspend stderr.print(fmt, args) catch return; + nosuspend bw.print(fmt, args) catch return; } pub fn getStderrMutex() *std.Thread.Mutex { @@ -265,7 +275,7 @@ fn dumpHexInternal(bytes: []const u8, ttyconf: std.io.tty.Config, writer: anytyp if (window.len < 16) { var missing_columns = (16 - window.len) * 3; if (window.len < 8) missing_columns += 1; - try writer.writeByteNTimes(' ', missing_columns); + try writer.splatByteAll(' ', missing_columns); } // 3. Print the characters. @@ -313,30 +323,32 @@ test dumpHexInternal { } /// Tries to print the current stack trace to stderr, unbuffered, and ignores any error returned. -/// TODO multithreaded awareness pub fn dumpCurrentStackTrace(start_addr: ?usize) void { - nosuspend { - if (builtin.target.cpu.arch.isWasm()) { - if (native_os == .wasi) { - const stderr = io.getStdErr().writer(); - stderr.print("Unable to dump stack trace: not implemented for Wasm\n", .{}) catch return; - } - return; + var stderr = lockStdErr2(); + defer unlockStdErr(); + nosuspend dumpCurrentStackTraceToWriter(start_addr, &stderr) catch return; +} + +/// Prints the current stack trace to the provided writer. +pub fn dumpCurrentStackTraceToWriter(start_addr: ?usize, writer: *std.io.BufferedWriter) !void { + if (builtin.target.cpu.arch.isWasm()) { + if (native_os == .wasi) { + try writer.writeAll("Unable to dump stack trace: not implemented for Wasm\n"); } - const stderr = io.getStdErr().writer(); - if (builtin.strip_debug_info) { - stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; - return; - } - const debug_info = getSelfDebugInfo() catch |err| { - stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return; - return; - }; - writeCurrentStackTrace(stderr, debug_info, io.tty.detectConfig(io.getStdErr()), start_addr) catch |err| { - stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return; - return; - }; + return; + } + if (builtin.strip_debug_info) { + try writer.writeAll("Unable to dump stack trace: debug info stripped\n"); + return; } + const debug_info = getSelfDebugInfo() catch |err| { + try writer.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}); + return; + }; + writeCurrentStackTrace(writer, debug_info, io.tty.detectConfig(io.getStdErr()), start_addr) catch |err| { + try writer.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}); + return; + }; } pub const have_ucontext = posix.ucontext_t != void; @@ -402,16 +414,14 @@ pub inline fn getContext(context: *ThreadContext) bool { /// Tries to print the stack trace starting from the supplied base pointer to stderr, /// unbuffered, and ignores any error returned. /// TODO multithreaded awareness -pub fn dumpStackTraceFromBase(context: *ThreadContext) void { +pub fn dumpStackTraceFromBase(context: *ThreadContext, stderr: *std.io.BufferedWriter) void { nosuspend { if (builtin.target.cpu.arch.isWasm()) { if (native_os == .wasi) { - const stderr = io.getStdErr().writer(); stderr.print("Unable to dump stack trace: not implemented for Wasm\n", .{}) catch return; } return; } - const stderr = io.getStdErr().writer(); if (builtin.strip_debug_info) { stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; return; @@ -510,21 +520,23 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void { nosuspend { if (builtin.target.cpu.arch.isWasm()) { if (native_os == .wasi) { - const stderr = io.getStdErr().writer(); - stderr.print("Unable to dump stack trace: not implemented for Wasm\n", .{}) catch return; + var stderr = lockStdErr2(); + defer unlockStdErr(); + stderr.writeAll("Unable to dump stack trace: not implemented for Wasm\n") catch return; } return; } - const stderr = io.getStdErr().writer(); + var stderr = lockStdErr2(); + defer unlockStdErr(); if (builtin.strip_debug_info) { - stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; + stderr.writeAll("Unable to dump stack trace: debug info stripped\n") catch return; return; } const debug_info = getSelfDebugInfo() catch |err| { stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return; return; }; - writeStackTrace(stack_trace, stderr, debug_info, io.tty.detectConfig(io.getStdErr())) catch |err| { + writeStackTrace(stack_trace, &stderr, debug_info, io.tty.detectConfig(io.getStdErr())) catch |err| { stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return; return; }; @@ -573,14 +585,14 @@ pub fn panicExtra( const size = 0x1000; const trunc_msg = "(msg truncated)"; var buf: [size + trunc_msg.len]u8 = undefined; + var bw: std.io.BufferedWriter = undefined; + bw.initFixed(buf[0..size]); // a minor annoyance with this is that it will result in the NoSpaceLeft // error being part of the @panic stack trace (but that error should // only happen rarely) - const msg = std.fmt.bufPrint(buf[0..size], format, args) catch |err| switch (err) { - error.NoSpaceLeft => blk: { - @memcpy(buf[size..], trunc_msg); - break :blk &buf; - }, + const msg = if (bw.print(format, args)) |_| bw.getWritten() else |_| blk: { + @memcpy(buf[size..], trunc_msg); + break :blk &buf; }; std.builtin.panic.call(msg, ret_addr); } @@ -675,10 +687,9 @@ pub fn defaultPanic( _ = panicking.fetchAdd(1, .seq_cst); { - lockStdErr(); + var stderr = lockStdErr2(); defer unlockStdErr(); - const stderr = io.getStdErr().writer(); if (builtin.single_threaded) { stderr.print("panic: ", .{}) catch posix.abort(); } else { @@ -688,7 +699,7 @@ pub fn defaultPanic( stderr.print("{s}\n", .{msg}) catch posix.abort(); if (@errorReturnTrace()) |t| dumpStackTrace(t.*); - dumpCurrentStackTrace(first_trace_addr orelse @returnAddress()); + dumpCurrentStackTraceToWriter(first_trace_addr orelse @returnAddress(), &stderr) catch {}; } waitForOtherThreadToFinishPanicking(); @@ -723,7 +734,7 @@ fn waitForOtherThreadToFinishPanicking() void { pub fn writeStackTrace( stack_trace: std.builtin.StackTrace, - out_stream: anytype, + writer: *std.io.BufferedWriter, debug_info: *SelfInfo, tty_config: io.tty.Config, ) !void { @@ -736,15 +747,15 @@ pub fn writeStackTrace( frame_index = (frame_index + 1) % stack_trace.instruction_addresses.len; }) { const return_address = stack_trace.instruction_addresses[frame_index]; - try printSourceAtAddress(debug_info, out_stream, return_address - 1, tty_config); + try printSourceAtAddress(debug_info, writer, return_address - 1, tty_config); } if (stack_trace.index > stack_trace.instruction_addresses.len) { const dropped_frames = stack_trace.index - stack_trace.instruction_addresses.len; - tty_config.setColor(out_stream, .bold) catch {}; - try out_stream.print("({d} additional stack frames skipped...)\n", .{dropped_frames}); - tty_config.setColor(out_stream, .reset) catch {}; + tty_config.setColor(writer, .bold) catch {}; + try writer.print("({d} additional stack frames skipped...)\n", .{dropped_frames}); + tty_config.setColor(writer, .reset) catch {}; } } @@ -954,7 +965,7 @@ pub const StackIterator = struct { }; pub fn writeCurrentStackTrace( - out_stream: anytype, + writer: *std.io.BufferedWriter, debug_info: *SelfInfo, tty_config: io.tty.Config, start_addr: ?usize, @@ -962,7 +973,7 @@ pub fn writeCurrentStackTrace( if (native_os == .windows) { var context: ThreadContext = undefined; assert(getContext(&context)); - return writeStackTraceWindows(out_stream, debug_info, tty_config, &context, start_addr); + return writeStackTraceWindows(writer, debug_info, tty_config, &context, start_addr); } var context: ThreadContext = undefined; const has_context = getContext(&context); @@ -973,7 +984,7 @@ pub fn writeCurrentStackTrace( defer it.deinit(); while (it.next()) |return_address| { - printLastUnwindError(&it, debug_info, out_stream, tty_config); + printLastUnwindError(&it, debug_info, writer, tty_config); // On arm64 macOS, the address of the last frame is 0x0 rather than 0x1 as on x86_64 macOS, // therefore, we do a check for `return_address == 0` before subtracting 1 from it to avoid @@ -981,8 +992,8 @@ pub fn writeCurrentStackTrace( // condition on the subsequent iteration and return `null` thus terminating the loop. // same behaviour for x86-windows-msvc const address = return_address -| 1; - try printSourceAtAddress(debug_info, out_stream, address, tty_config); - } else printLastUnwindError(&it, debug_info, out_stream, tty_config); + try printSourceAtAddress(debug_info, writer, address, tty_config); + } else printLastUnwindError(&it, debug_info, writer, tty_config); } pub noinline fn walkStackWindows(addresses: []usize, existing_context: ?*const windows.CONTEXT) usize { @@ -1042,7 +1053,7 @@ pub noinline fn walkStackWindows(addresses: []usize, existing_context: ?*const w } pub fn writeStackTraceWindows( - out_stream: anytype, + writer: *std.io.BufferedWriter, debug_info: *SelfInfo, tty_config: io.tty.Config, context: *const windows.CONTEXT, @@ -1058,14 +1069,14 @@ pub fn writeStackTraceWindows( return; } else 0; for (addrs[start_i..]) |addr| { - try printSourceAtAddress(debug_info, out_stream, addr - 1, tty_config); + try printSourceAtAddress(debug_info, writer, addr - 1, tty_config); } } -fn printUnknownSource(debug_info: *SelfInfo, out_stream: anytype, address: usize, tty_config: io.tty.Config) !void { +fn printUnknownSource(debug_info: *SelfInfo, writer: *std.io.BufferedWriter, address: usize, tty_config: io.tty.Config) !void { const module_name = debug_info.getModuleNameForAddress(address); return printLineInfo( - out_stream, + writer, null, address, "???", @@ -1075,38 +1086,38 @@ fn printUnknownSource(debug_info: *SelfInfo, out_stream: anytype, address: usize ); } -fn printLastUnwindError(it: *StackIterator, debug_info: *SelfInfo, out_stream: anytype, tty_config: io.tty.Config) void { +fn printLastUnwindError(it: *StackIterator, debug_info: *SelfInfo, writer: *std.io.BufferedWriter, tty_config: io.tty.Config) void { if (!have_ucontext) return; if (it.getLastError()) |unwind_error| { - printUnwindError(debug_info, out_stream, unwind_error.address, unwind_error.err, tty_config) catch {}; + printUnwindError(debug_info, writer, unwind_error.address, unwind_error.err, tty_config) catch {}; } } -fn printUnwindError(debug_info: *SelfInfo, out_stream: anytype, address: usize, err: UnwindError, tty_config: io.tty.Config) !void { +fn printUnwindError(debug_info: *SelfInfo, writer: *std.io.BufferedWriter, address: usize, err: UnwindError, tty_config: io.tty.Config) !void { const module_name = debug_info.getModuleNameForAddress(address) orelse "???"; - try tty_config.setColor(out_stream, .dim); + try tty_config.setColor(writer, .dim); if (err == error.MissingDebugInfo) { - try out_stream.print("Unwind information for `{s}:0x{x}` was not available, trace may be incomplete\n\n", .{ module_name, address }); + try writer.print("Unwind information for `{s}:0x{x}` was not available, trace may be incomplete\n\n", .{ module_name, address }); } else { - try out_stream.print("Unwind error at address `{s}:0x{x}` ({}), trace may be incomplete\n\n", .{ module_name, address, err }); + try writer.print("Unwind error at address `{s}:0x{x}` ({}), trace may be incomplete\n\n", .{ module_name, address, err }); } - try tty_config.setColor(out_stream, .reset); + try tty_config.setColor(writer, .reset); } -pub fn printSourceAtAddress(debug_info: *SelfInfo, out_stream: anytype, address: usize, tty_config: io.tty.Config) !void { +pub fn printSourceAtAddress(debug_info: *SelfInfo, writer: *std.io.BufferedWriter, address: usize, tty_config: io.tty.Config) !void { const module = debug_info.getModuleForAddress(address) catch |err| switch (err) { - error.MissingDebugInfo, error.InvalidDebugInfo => return printUnknownSource(debug_info, out_stream, address, tty_config), + error.MissingDebugInfo, error.InvalidDebugInfo => return printUnknownSource(debug_info, writer, address, tty_config), else => return err, }; const symbol_info = module.getSymbolAtAddress(debug_info.allocator, address) catch |err| switch (err) { - error.MissingDebugInfo, error.InvalidDebugInfo => return printUnknownSource(debug_info, out_stream, address, tty_config), + error.MissingDebugInfo, error.InvalidDebugInfo => return printUnknownSource(debug_info, writer, address, tty_config), else => return err, }; defer if (symbol_info.source_location) |sl| debug_info.allocator.free(sl.file_name); return printLineInfo( - out_stream, + writer, symbol_info.source_location, address, symbol_info.name, @@ -1117,7 +1128,7 @@ pub fn printSourceAtAddress(debug_info: *SelfInfo, out_stream: anytype, address: } fn printLineInfo( - out_stream: anytype, + writer: *std.io.BufferedWriter, source_location: ?SourceLocation, address: usize, symbol_name: []const u8, @@ -1126,34 +1137,34 @@ fn printLineInfo( comptime printLineFromFile: anytype, ) !void { nosuspend { - try tty_config.setColor(out_stream, .bold); + try tty_config.setColor(writer, .bold); if (source_location) |*sl| { - try out_stream.print("{s}:{d}:{d}", .{ sl.file_name, sl.line, sl.column }); + try writer.print("{s}:{d}:{d}", .{ sl.file_name, sl.line, sl.column }); } else { - try out_stream.writeAll("???:?:?"); + try writer.writeAll("???:?:?"); } - try tty_config.setColor(out_stream, .reset); - try out_stream.writeAll(": "); - try tty_config.setColor(out_stream, .dim); - try out_stream.print("0x{x} in {s} ({s})", .{ address, symbol_name, compile_unit_name }); - try tty_config.setColor(out_stream, .reset); - try out_stream.writeAll("\n"); + try tty_config.setColor(writer, .reset); + try writer.writeAll(": "); + try tty_config.setColor(writer, .dim); + try writer.print("0x{x} in {s} ({s})", .{ address, symbol_name, compile_unit_name }); + try tty_config.setColor(writer, .reset); + try writer.writeAll("\n"); // Show the matching source code line if possible if (source_location) |sl| { - if (printLineFromFile(out_stream, sl)) { + if (printLineFromFile(writer, sl)) { if (sl.column > 0) { // The caret already takes one char const space_needed = @as(usize, @intCast(sl.column - 1)); - try out_stream.writeByteNTimes(' ', space_needed); - try tty_config.setColor(out_stream, .green); - try out_stream.writeAll("^"); - try tty_config.setColor(out_stream, .reset); + try writer.splatByteAll(' ', space_needed); + try tty_config.setColor(writer, .green); + try writer.writeAll("^"); + try tty_config.setColor(writer, .reset); } - try out_stream.writeAll("\n"); + try writer.writeAll("\n"); } else |err| switch (err) { error.EndOfFile, error.FileNotFound => {}, error.BadPathName => {}, @@ -1164,7 +1175,7 @@ fn printLineInfo( } } -fn printLineFromFileAnyOs(out_stream: anytype, source_location: SourceLocation) !void { +fn printLineFromFileAnyOs(writer: *std.io.BufferedWriter, source_location: SourceLocation) !void { // Need this to always block even in async I/O mode, because this could potentially // be called from e.g. the event loop code crashing. var f = try fs.cwd().openFile(source_location.file_name, .{}); @@ -1197,24 +1208,24 @@ fn printLineFromFileAnyOs(out_stream: anytype, source_location: SourceLocation) if (mem.indexOfScalar(u8, slice, '\n')) |pos| { const line = slice[0 .. pos + 1]; mem.replaceScalar(u8, line, '\t', ' '); - return out_stream.writeAll(line); + return writer.writeAll(line); } else { // Line is the last inside the buffer, and requires another read to find delimiter. Alternatively the file ends. mem.replaceScalar(u8, slice, '\t', ' '); - try out_stream.writeAll(slice); + try writer.writeAll(slice); while (amt_read == buf.len) { amt_read = try f.read(buf[0..]); if (mem.indexOfScalar(u8, buf[0..amt_read], '\n')) |pos| { const line = buf[0 .. pos + 1]; mem.replaceScalar(u8, line, '\t', ' '); - return out_stream.writeAll(line); + return writer.writeAll(line); } else { const line = buf[0..amt_read]; mem.replaceScalar(u8, line, '\t', ' '); - try out_stream.writeAll(line); + try writer.writeAll(line); } } // Make sure printing last line of file inserts extra newline - try out_stream.writeByte('\n'); + try writer.writeByte('\n'); } } @@ -1274,9 +1285,9 @@ test printLineFromFileAnyOs { const overlap = 10; var writer = file.writer(); - try writer.writeByteNTimes('a', std.heap.page_size_min - overlap); + try writer.splatByteAll('a', std.heap.page_size_min - overlap); try writer.writeByte('\n'); - try writer.writeByteNTimes('a', overlap); + try writer.splatByteAll('a', overlap); try printLineFromFileAnyOs(output_stream, .{ .file_name = path, .line = 2, .column = 0 }); try expectEqualStrings(("a" ** overlap) ++ "\n", output.items); @@ -1289,7 +1300,7 @@ test printLineFromFileAnyOs { defer allocator.free(path); var writer = file.writer(); - try writer.writeByteNTimes('a', std.heap.page_size_max); + try writer.splatByteAll('a', std.heap.page_size_max); try printLineFromFileAnyOs(output_stream, .{ .file_name = path, .line = 1, .column = 0 }); try expectEqualStrings(("a" ** std.heap.page_size_max) ++ "\n", output.items); @@ -1302,7 +1313,7 @@ test printLineFromFileAnyOs { defer allocator.free(path); var writer = file.writer(); - try writer.writeByteNTimes('a', 3 * std.heap.page_size_max); + try writer.splatByteAll('a', 3 * std.heap.page_size_max); try expectError(error.EndOfFile, printLineFromFileAnyOs(output_stream, .{ .file_name = path, .line = 2, .column = 0 })); @@ -1328,7 +1339,7 @@ test printLineFromFileAnyOs { var writer = file.writer(); const real_file_start = 3 * std.heap.page_size_min; - try writer.writeByteNTimes('\n', real_file_start); + try writer.splatByteAll('\n', real_file_start); try writer.writeAll("abc\ndef"); try printLineFromFileAnyOs(output_stream, .{ .file_name = path, .line = real_file_start + 1, .column = 0 }); @@ -1461,7 +1472,7 @@ fn handleSegfaultPosix(sig: i32, info: *const posix.siginfo_t, ctx_ptr: ?*anyopa } fn dumpSegfaultInfoPosix(sig: i32, code: i32, addr: usize, ctx_ptr: ?*anyopaque) void { - const stderr = io.getStdErr().writer(); + var stderr = io.getStdErr().unbufferedWriter(); _ = switch (sig) { posix.SIG.SEGV => if (native_arch == .x86_64 and native_os == .linux and code == 128) // SI_KERNEL // x86_64 doesn't have a full 64-bit virtual address space. @@ -1471,7 +1482,7 @@ fn dumpSegfaultInfoPosix(sig: i32, code: i32, addr: usize, ctx_ptr: ?*anyopaque) // but can also happen when no addressable memory is involved; // for example when reading/writing model-specific registers // by executing `rdmsr` or `wrmsr` in user-space (unprivileged mode). - stderr.print("General protection exception (no address available)\n", .{}) + stderr.writeAll("General protection exception (no address available)\n") else stderr.print("Segmentation fault at address 0x{x}\n", .{addr}), posix.SIG.ILL => stderr.print("Illegal instruction at address 0x{x}\n", .{addr}), @@ -1509,7 +1520,7 @@ fn dumpSegfaultInfoPosix(sig: i32, code: i32, addr: usize, ctx_ptr: ?*anyopaque) }, @ptrCast(ctx)).__mcontext_data; } relocateContext(&new_ctx); - dumpStackTraceFromBase(&new_ctx); + dumpStackTraceFromBase(&new_ctx, &stderr); }, else => {}, } @@ -1557,7 +1568,7 @@ fn handleSegfaultWindowsExtra(info: *windows.EXCEPTION_POINTERS, msg: u8, label: } fn dumpSegfaultInfoWindows(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[]const u8) void { - const stderr = io.getStdErr().writer(); + var stderr = io.getStdErr().unbufferedWriter(); _ = switch (msg) { 0 => stderr.print("{s}\n", .{label.?}), 1 => stderr.print("Segmentation fault at address 0x{x}\n", .{info.ExceptionRecord.ExceptionInformation[1]}), @@ -1565,7 +1576,7 @@ fn dumpSegfaultInfoWindows(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[ else => unreachable, } catch posix.abort(); - dumpStackTraceFromBase(info.ContextRecord); + dumpStackTraceFromBase(info.ContextRecord, &stderr); } pub fn dumpStackPointerAddr(prefix: []const u8) void { @@ -1688,7 +1699,7 @@ pub fn ConfigurableTrace(comptime size: usize, comptime stack_frame_count: usize t: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, - writer: anytype, + writer: *std.io.BufferedWriter, ) !void { if (fmt.len != 0) std.fmt.invalidFmtError(fmt, t); _ = options; diff --git a/lib/std/debug/Dwarf.zig b/lib/std/debug/Dwarf.zig index 06b6c81075e494160f15ddbb6ddf05706b118b70..f5e488859988799845c5b0d79b5554b1de150c2f 100644 --- a/lib/std/debug/Dwarf.zig +++ b/lib/std/debug/Dwarf.zig @@ -2235,7 +2235,7 @@ pub const ElfModule = struct { const section_bytes = try chopSlice(mapped_mem, shdr.sh_offset, shdr.sh_size); sections[section_index.?] = if ((shdr.sh_flags & elf.SHF_COMPRESSED) > 0) blk: { - var section_stream = std.io.fixedBufferStream(section_bytes); + var section_stream: std.io.FixedBufferStream = .{ .buffer = section_bytes }; const section_reader = section_stream.reader(); const chdr = section_reader.readStruct(elf.Chdr) catch continue; if (chdr.ch_type != .ZLIB) continue; @@ -2302,11 +2302,7 @@ pub const ElfModule = struct { }; defer debuginfod_dir.close(); - const filename = std.fmt.allocPrint( - gpa, - "{s}/debuginfo", - .{std.fmt.fmtSliceHexLower(id)}, - ) catch break :blk; + const filename = std.fmt.allocPrint(gpa, "{x}/debuginfo", .{id}) catch break :blk; defer gpa.free(filename); const path: Path = .{ @@ -2330,12 +2326,8 @@ pub const ElfModule = struct { var id_prefix_buf: [2]u8 = undefined; var filename_buf: [38 + extension.len]u8 = undefined; - _ = std.fmt.bufPrint(&id_prefix_buf, "{s}", .{std.fmt.fmtSliceHexLower(id[0..1])}) catch unreachable; - const filename = std.fmt.bufPrint( - &filename_buf, - "{s}" ++ extension, - .{std.fmt.fmtSliceHexLower(id[1..])}, - ) catch break :blk; + _ = std.fmt.bufPrint(&id_prefix_buf, "{x}", .{id[0..1]}) catch unreachable; + const filename = std.fmt.bufPrint(&filename_buf, "{x}" ++ extension, .{id[1..]}) catch break :blk; for (global_debug_directories) |global_directory| { const path: Path = .{ diff --git a/lib/std/debug/Dwarf/call_frame.zig b/lib/std/debug/Dwarf/call_frame.zig index 3e3d2585db3275f36836e6f9e155430bf9402800..704060a81d0871c0b9f2d601e99fce6f88d7b5b0 100644 --- a/lib/std/debug/Dwarf/call_frame.zig +++ b/lib/std/debug/Dwarf/call_frame.zig @@ -51,7 +51,7 @@ const Opcode = enum(u8) { pub const hi_user = 0x3f; }; -fn readBlock(stream: *std.io.FixedBufferStream([]const u8)) ![]const u8 { +fn readBlock(stream: *std.io.FixedBufferStream) ![]const u8 { const reader = stream.reader(); const block_len = try leb.readUleb128(usize, reader); if (stream.pos + block_len > stream.buffer.len) return error.InvalidOperand; @@ -147,7 +147,7 @@ pub const Instruction = union(Opcode) { }, pub fn read( - stream: *std.io.FixedBufferStream([]const u8), + stream: *std.io.FixedBufferStream, addr_size_bytes: u8, endian: std.builtin.Endian, ) !Instruction { diff --git a/lib/std/debug/Dwarf/expression.zig b/lib/std/debug/Dwarf/expression.zig index c0ebea7504302d56cc29b65b58f18b694ad5be18..b68eb05bcfafb1be69c681f77e611ba438886b40 100644 --- a/lib/std/debug/Dwarf/expression.zig +++ b/lib/std/debug/Dwarf/expression.zig @@ -178,7 +178,7 @@ pub fn StackMachine(comptime options: Options) type { } } - pub fn readOperand(stream: *std.io.FixedBufferStream([]const u8), opcode: u8, context: Context) !?Operand { + pub fn readOperand(stream: *std.io.FixedBufferStream, opcode: u8, context: Context) !?Operand { const reader = stream.reader(); return switch (opcode) { OP.addr => generic(try reader.readInt(addr_type, options.endian)), @@ -293,7 +293,7 @@ pub fn StackMachine(comptime options: Options) type { initial_value: ?usize, ) Error!?Value { if (initial_value) |i| try self.stack.append(allocator, .{ .generic = i }); - var stream = std.io.fixedBufferStream(expression); + var stream: std.io.FixedBufferStream = .{ .buffer = expression }; while (try self.step(&stream, allocator, context)) {} if (self.stack.items.len == 0) return null; return self.stack.items[self.stack.items.len - 1]; @@ -302,7 +302,7 @@ pub fn StackMachine(comptime options: Options) type { /// Reads an opcode and its operands from `stream`, then executes it pub fn step( self: *Self, - stream: *std.io.FixedBufferStream([]const u8), + stream: *std.io.FixedBufferStream, allocator: std.mem.Allocator, context: Context, ) Error!bool { @@ -756,7 +756,7 @@ pub fn StackMachine(comptime options: Options) type { if (isOpcodeRegisterLocation(block[0])) { if (context.thread_context == null) return error.IncompleteExpressionContext; - var block_stream = std.io.fixedBufferStream(block); + var block_stream: std.io.FixedBufferStream = .{ .buffer = block }; const register = (try readOperand(&block_stream, block[0], context)).?.register; 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 }); diff --git a/lib/std/debug/SelfInfo.zig b/lib/std/debug/SelfInfo.zig index a879309870e520e1b46474a7789ebdc242edabb6..8e54dfae1904960d6a6f51a2baa377ee0629fbc7 100644 --- a/lib/std/debug/SelfInfo.zig +++ b/lib/std/debug/SelfInfo.zig @@ -2027,12 +2027,9 @@ pub const VirtualMachine = struct { var prev_row: Row = self.current_row; - var cie_stream = std.io.fixedBufferStream(cie.initial_instructions); - var fde_stream = std.io.fixedBufferStream(fde.instructions); - var streams = [_]*std.io.FixedBufferStream([]const u8){ - &cie_stream, - &fde_stream, - }; + var cie_stream: std.io.FixedBufferStream = .{ .buffer = cie.initial_instructions }; + var fde_stream: std.io.FixedBufferStream = .{ .buffer = fde.instructions }; + const streams: [2]*std.io.FixedBufferStream = .{ &cie_stream, &fde_stream }; for (&streams, 0..) |stream, i| { while (stream.pos < stream.buffer.len) { diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig index efd5ffd3a2e3b4a2cac3450ce7d5c304cf00fefc..b6568ce008720f14371660a6e548cb385936fcba 100644 --- a/lib/std/fmt.zig +++ b/lib/std/fmt.zig @@ -13,6 +13,8 @@ const lossyCast = math.lossyCast; const expectFmt = std.testing.expectFmt; const testing = std.testing; +pub const float = @import("fmt/float.zig"); + pub const default_max_depth = 3; pub const Alignment = enum { @@ -24,11 +26,14 @@ pub const Alignment = enum { const default_alignment = .right; const default_fill_char = ' '; -pub const FormatOptions = struct { +/// Deprecated; to be removed after 0.14.0 is tagged. +pub const FormatOptions = Options; + +pub const Options = struct { precision: ?usize = null, width: ?usize = null, alignment: Alignment = default_alignment, - fill: u21 = default_fill_char, + fill: u8 = default_fill_char, }; /// Renders fmt string with args, calling `writer` with slices of bytes. @@ -45,9 +50,10 @@ pub const FormatOptions = struct { /// - when using a field name, you are required to enclose the field name (an identifier) in square /// brackets, e.g. {[score]...} as opposed to the numeric index form which can be written e.g. {2...} /// - *specifier* is a type-dependent formatting option that determines how a type should formatted (see below) -/// - *fill* is a single unicode codepoint which is used to pad the formatted text +/// - *fill* is a single byte which is used to pad the formatted text /// - *alignment* is one of the three bytes '<', '^', or '>' to make the text left-, center-, or right-aligned, respectively -/// - *width* is the total width of the field in unicode codepoints +/// - *width* is the total width of the field in bytes. This is generally only +/// useful for ASCII text, such as numbers. /// - *precision* specifies how many decimals a formatted number should have /// /// Note that most of the parameters are optional and may be omitted. Also you can leave out separators like `:` and `.` when @@ -66,6 +72,9 @@ pub const FormatOptions = struct { /// - `o`: output integer value in octal notation /// - `c`: output integer as an ASCII character. Integer type must have 8 bits at max. /// - `u`: output integer as an UTF-8 sequence. Integer type must have 21 bits at max. +/// - `D`: output nanoseconds as duration +/// - `B`: output bytes in SI units (decimal) +/// - `Bi`: output bytes in IEC units (binary) /// - `?`: output optional value as either the unwrapped value, or `null`; may be followed by a format specifier for the underlying value. /// - `!`: output error union value as either the unwrapped value, or the formatted error value; may be followed by a format specifier for the underlying value. /// - `*`: output the address of the value instead of the value itself. @@ -73,7 +82,7 @@ pub const FormatOptions = struct { /// /// If a formatted user type contains a function of the type /// ``` -/// pub fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void +/// pub fn format(value: ?, comptime fmt: []const u8, options: std.fmt.Options, writer: anytype) !void /// ``` /// with `?` being the type formatted, this function will be called instead of the default implementation. /// This allows user types to be formatted in a logical manner instead of dumping all fields of the type. @@ -81,11 +90,7 @@ pub const FormatOptions = struct { /// A user type may be a `struct`, `vector`, `union` or `enum` type. /// /// To print literal curly braces, escape them by writing them twice, e.g. `{{` or `}}`. -pub fn format( - writer: anytype, - comptime fmt: []const u8, - args: anytype, -) !void { +pub fn format(bw: *std.io.BufferedWriter, comptime fmt: []const u8, args: anytype) anyerror!void { const ArgsType = @TypeOf(args); const args_type_info = @typeInfo(ArgsType); if (args_type_info != .@"struct") { @@ -130,7 +135,7 @@ pub fn format( // Write out the literal if (literal.len != 0) { - try writer.writeAll(literal); + try bw.writeAll(literal); literal = ""; } @@ -190,16 +195,15 @@ pub fn format( const arg_to_print = comptime arg_state.nextArg(arg_pos) orelse @compileError("too few arguments"); - try formatType( - @field(args, fields_info[arg_to_print].name), + try bw.printValue( placeholder.specifier_arg, - FormatOptions{ + .{ .fill = placeholder.fill, .alignment = placeholder.alignment, .width = width, .precision = precision, }, - writer, + @field(args, fields_info[arg_to_print].name), std.options.fmt_max_depth, ); } @@ -298,7 +302,7 @@ pub const Placeholder = struct { @compileError("extraneous trailing character '" ++ unicode.utf8EncodeComptime(ch) ++ "'"); } - return Placeholder{ + return .{ .specifier_arg = cacheString(specifier_arg[0..specifier_arg.len].*), .fill = fill orelse default_fill_char, .alignment = alignment orelse default_alignment, @@ -434,429 +438,12 @@ pub const ArgState = struct { } }; -pub fn formatAddress(value: anytype, options: FormatOptions, writer: anytype) @TypeOf(writer).Error!void { - _ = options; - const T = @TypeOf(value); - - switch (@typeInfo(T)) { - .pointer => |info| { - try writer.writeAll(@typeName(info.child) ++ "@"); - if (info.size == .slice) - try formatInt(@intFromPtr(value.ptr), 16, .lower, FormatOptions{}, writer) - else - try formatInt(@intFromPtr(value), 16, .lower, FormatOptions{}, writer); - return; - }, - .optional => |info| { - if (@typeInfo(info.child) == .pointer) { - try writer.writeAll(@typeName(info.child) ++ "@"); - try formatInt(@intFromPtr(value), 16, .lower, FormatOptions{}, writer); - return; - } - }, - else => {}, - } - - @compileError("cannot format non-pointer type " ++ @typeName(T) ++ " with * specifier"); -} - -// This ANY const is a workaround for: https://github.com/ziglang/zig/issues/7948 -const ANY = "any"; - -pub fn defaultSpec(comptime T: type) [:0]const u8 { - switch (@typeInfo(T)) { - .array, .vector => return ANY, - .pointer => |ptr_info| switch (ptr_info.size) { - .one => switch (@typeInfo(ptr_info.child)) { - .array => return ANY, - else => {}, - }, - .many, .c => return "*", - .slice => return ANY, - }, - .optional => |info| return "?" ++ defaultSpec(info.child), - .error_union => |info| return "!" ++ defaultSpec(info.payload), - else => {}, - } - return ""; -} - -fn stripOptionalOrErrorUnionSpec(comptime fmt: []const u8) []const u8 { - return if (std.mem.eql(u8, fmt[1..], ANY)) - ANY - else - fmt[1..]; -} - -pub fn invalidFmtError(comptime fmt: []const u8, value: anytype) void { - @compileError("invalid format string '" ++ fmt ++ "' for type '" ++ @typeName(@TypeOf(value)) ++ "'"); -} - -pub fn formatType( - value: anytype, - comptime fmt: []const u8, - options: FormatOptions, - writer: anytype, - max_depth: usize, -) @TypeOf(writer).Error!void { - const T = @TypeOf(value); - const actual_fmt = comptime if (std.mem.eql(u8, fmt, ANY)) - defaultSpec(T) - else if (fmt.len != 0 and (fmt[0] == '?' or fmt[0] == '!')) switch (@typeInfo(T)) { - .optional, .error_union => fmt, - else => stripOptionalOrErrorUnionSpec(fmt), - } else fmt; - - if (comptime std.mem.eql(u8, actual_fmt, "*")) { - return formatAddress(value, options, writer); - } - - if (std.meta.hasMethod(T, "format")) { - return try value.format(actual_fmt, options, writer); - } - - switch (@typeInfo(T)) { - .comptime_int, .int, .comptime_float, .float => { - return formatValue(value, actual_fmt, options, writer); - }, - .void => { - if (actual_fmt.len != 0) invalidFmtError(fmt, value); - return formatBuf("void", options, writer); - }, - .bool => { - if (actual_fmt.len != 0) invalidFmtError(fmt, value); - return formatBuf(if (value) "true" else "false", options, writer); - }, - .optional => { - if (actual_fmt.len == 0 or actual_fmt[0] != '?') - @compileError("cannot format optional without a specifier (i.e. {?} or {any})"); - const remaining_fmt = comptime stripOptionalOrErrorUnionSpec(actual_fmt); - if (value) |payload| { - return formatType(payload, remaining_fmt, options, writer, max_depth); - } else { - return formatBuf("null", options, writer); - } - }, - .error_union => { - if (actual_fmt.len == 0 or actual_fmt[0] != '!') - @compileError("cannot format error union without a specifier (i.e. {!} or {any})"); - const remaining_fmt = comptime stripOptionalOrErrorUnionSpec(actual_fmt); - if (value) |payload| { - return formatType(payload, remaining_fmt, options, writer, max_depth); - } else |err| { - return formatType(err, "", options, writer, max_depth); - } - }, - .error_set => { - if (actual_fmt.len != 0) invalidFmtError(fmt, value); - try writer.writeAll("error."); - return writer.writeAll(@errorName(value)); - }, - .@"enum" => |enumInfo| { - try writer.writeAll(@typeName(T)); - if (enumInfo.is_exhaustive) { - if (actual_fmt.len != 0) invalidFmtError(fmt, value); - try writer.writeAll("."); - try writer.writeAll(@tagName(value)); - return; - } - - // Use @tagName only if value is one of known fields - @setEvalBranchQuota(3 * enumInfo.fields.len); - inline for (enumInfo.fields) |enumField| { - if (@intFromEnum(value) == enumField.value) { - try writer.writeAll("."); - try writer.writeAll(@tagName(value)); - return; - } - } - - try writer.writeAll("("); - try formatType(@intFromEnum(value), actual_fmt, options, writer, max_depth); - try writer.writeAll(")"); - }, - .@"union" => |info| { - if (actual_fmt.len != 0) invalidFmtError(fmt, value); - try writer.writeAll(@typeName(T)); - if (max_depth == 0) { - return writer.writeAll("{ ... }"); - } - if (info.tag_type) |UnionTagType| { - try writer.writeAll("{ ."); - try writer.writeAll(@tagName(@as(UnionTagType, value))); - try writer.writeAll(" = "); - inline for (info.fields) |u_field| { - if (value == @field(UnionTagType, u_field.name)) { - try formatType(@field(value, u_field.name), ANY, options, writer, max_depth - 1); - } - } - try writer.writeAll(" }"); - } else { - try format(writer, "@{x}", .{@intFromPtr(&value)}); - } - }, - .@"struct" => |info| { - if (actual_fmt.len != 0) invalidFmtError(fmt, value); - if (info.is_tuple) { - // Skip the type and field names when formatting tuples. - if (max_depth == 0) { - return writer.writeAll("{ ... }"); - } - try writer.writeAll("{"); - inline for (info.fields, 0..) |f, i| { - if (i == 0) { - try writer.writeAll(" "); - } else { - try writer.writeAll(", "); - } - try formatType(@field(value, f.name), ANY, options, writer, max_depth - 1); - } - return writer.writeAll(" }"); - } - try writer.writeAll(@typeName(T)); - if (max_depth == 0) { - return writer.writeAll("{ ... }"); - } - try writer.writeAll("{"); - inline for (info.fields, 0..) |f, i| { - if (i == 0) { - try writer.writeAll(" ."); - } else { - try writer.writeAll(", ."); - } - try writer.writeAll(f.name); - try writer.writeAll(" = "); - try formatType(@field(value, f.name), ANY, options, writer, max_depth - 1); - } - try writer.writeAll(" }"); - }, - .pointer => |ptr_info| switch (ptr_info.size) { - .one => switch (@typeInfo(ptr_info.child)) { - .array, .@"enum", .@"union", .@"struct" => { - return formatType(value.*, actual_fmt, options, writer, max_depth); - }, - else => return format(writer, "{s}@{x}", .{ @typeName(ptr_info.child), @intFromPtr(value) }), - }, - .many, .c => { - if (actual_fmt.len == 0) - @compileError("cannot format pointer without a specifier (i.e. {s} or {*})"); - if (ptr_info.sentinel() != null) { - return formatType(mem.span(value), actual_fmt, options, writer, max_depth); - } - if (actual_fmt[0] == 's' and ptr_info.child == u8) { - return formatBuf(mem.span(value), options, writer); - } - invalidFmtError(fmt, value); - }, - .slice => { - if (actual_fmt.len == 0) - @compileError("cannot format slice without a specifier (i.e. {s} or {any})"); - if (max_depth == 0) { - return writer.writeAll("{ ... }"); - } - if (actual_fmt[0] == 's' and ptr_info.child == u8) { - return formatBuf(value, options, writer); - } - try writer.writeAll("{ "); - for (value, 0..) |elem, i| { - try formatType(elem, actual_fmt, options, writer, max_depth - 1); - if (i != value.len - 1) { - try writer.writeAll(", "); - } - } - try writer.writeAll(" }"); - }, - }, - .array => |info| { - if (actual_fmt.len == 0) - @compileError("cannot format array without a specifier (i.e. {s} or {any})"); - if (max_depth == 0) { - return writer.writeAll("{ ... }"); - } - if (actual_fmt[0] == 's' and info.child == u8) { - return formatBuf(&value, options, writer); - } - try writer.writeAll("{ "); - for (value, 0..) |elem, i| { - try formatType(elem, actual_fmt, options, writer, max_depth - 1); - if (i < value.len - 1) { - try writer.writeAll(", "); - } - } - try writer.writeAll(" }"); - }, - .vector => |info| { - if (max_depth == 0) { - return writer.writeAll("{ ... }"); - } - try writer.writeAll("{ "); - var i: usize = 0; - while (i < info.len) : (i += 1) { - try formatType(value[i], actual_fmt, options, writer, max_depth - 1); - if (i < info.len - 1) { - try writer.writeAll(", "); - } - } - try writer.writeAll(" }"); - }, - .@"fn" => @compileError("unable to format function body type, use '*const " ++ @typeName(T) ++ "' for a function pointer type"), - .type => { - if (actual_fmt.len != 0) invalidFmtError(fmt, value); - return formatBuf(@typeName(value), options, writer); - }, - .enum_literal => { - if (actual_fmt.len != 0) invalidFmtError(fmt, value); - const buffer = [_]u8{'.'} ++ @tagName(value); - return formatBuf(buffer, options, writer); - }, - .null => { - if (actual_fmt.len != 0) invalidFmtError(fmt, value); - return formatBuf("null", options, writer); - }, - else => @compileError("unable to format type '" ++ @typeName(T) ++ "'"), - } -} - -fn formatValue( - value: anytype, - comptime fmt: []const u8, - options: FormatOptions, - writer: anytype, -) !void { - const T = @TypeOf(value); - switch (@typeInfo(T)) { - .float, .comptime_float => return formatFloatValue(value, fmt, options, writer), - .int, .comptime_int => return formatIntValue(value, fmt, options, writer), - .bool => return formatBuf(if (value) "true" else "false", options, writer), - else => comptime unreachable, - } -} - -pub fn formatIntValue( - value: anytype, - comptime fmt: []const u8, - options: FormatOptions, - writer: anytype, -) !void { - comptime var base = 10; - comptime var case: Case = .lower; - - const int_value = if (@TypeOf(value) == comptime_int) blk: { - const Int = math.IntFittingRange(value, value); - break :blk @as(Int, value); - } else value; - - if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "d")) { - base = 10; - case = .lower; - } else if (comptime std.mem.eql(u8, fmt, "c")) { - if (@typeInfo(@TypeOf(int_value)).int.bits <= 8) { - return formatAsciiChar(@as(u8, int_value), options, writer); - } else { - @compileError("cannot print integer that is larger than 8 bits as an ASCII character"); - } - } else if (comptime std.mem.eql(u8, fmt, "u")) { - if (@typeInfo(@TypeOf(int_value)).int.bits <= 21) { - return formatUnicodeCodepoint(@as(u21, int_value), options, writer); - } else { - @compileError("cannot print integer that is larger than 21 bits as an UTF-8 sequence"); - } - } else if (comptime std.mem.eql(u8, fmt, "b")) { - base = 2; - case = .lower; - } else if (comptime std.mem.eql(u8, fmt, "x")) { - base = 16; - case = .lower; - } else if (comptime std.mem.eql(u8, fmt, "X")) { - base = 16; - case = .upper; - } else if (comptime std.mem.eql(u8, fmt, "o")) { - base = 8; - case = .lower; - } else { - invalidFmtError(fmt, value); - } - - return formatInt(int_value, base, case, options, writer); -} - -pub const format_float = @import("fmt/format_float.zig"); -pub const formatFloat = format_float.formatFloat; -pub const FormatFloatError = format_float.FormatError; - -fn formatFloatValue( - value: anytype, - comptime fmt: []const u8, - options: FormatOptions, - writer: anytype, -) !void { - var buf: [format_float.bufferSize(.decimal, f64)]u8 = undefined; - - if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "e")) { - const s = formatFloat(&buf, value, .{ .mode = .scientific, .precision = options.precision }) catch |err| switch (err) { - error.BufferTooSmall => "(float)", - }; - return formatBuf(s, options, writer); - } else if (comptime std.mem.eql(u8, fmt, "d")) { - const s = formatFloat(&buf, value, .{ .mode = .decimal, .precision = options.precision }) catch |err| switch (err) { - error.BufferTooSmall => "(float)", - }; - return formatBuf(s, options, writer); - } else if (comptime std.mem.eql(u8, fmt, "x")) { - var buf_stream = std.io.fixedBufferStream(&buf); - formatFloatHexadecimal(value, options, buf_stream.writer()) catch |err| switch (err) { - error.NoSpaceLeft => unreachable, - }; - return formatBuf(buf_stream.getWritten(), options, writer); - } else { - invalidFmtError(fmt, value); - } -} - test { - _ = &format_float; + _ = float; } pub const Case = enum { lower, upper }; -fn SliceHex(comptime case: Case) type { - const charset = "0123456789" ++ if (case == .upper) "ABCDEF" else "abcdef"; - - return struct { - pub fn format( - bytes: []const u8, - comptime fmt: []const u8, - options: std.fmt.FormatOptions, - writer: anytype, - ) !void { - _ = fmt; - _ = options; - var buf: [2]u8 = undefined; - - for (bytes) |c| { - buf[0] = charset[c >> 4]; - buf[1] = charset[c & 15]; - try writer.writeAll(&buf); - } - } - }; -} - -const formatSliceHexLower = SliceHex(.lower).format; -const formatSliceHexUpper = SliceHex(.upper).format; - -/// Return a Formatter for a []const u8 where every byte is formatted as a pair -/// of lowercase hexadecimal digits. -pub fn fmtSliceHexLower(bytes: []const u8) std.fmt.Formatter(formatSliceHexLower) { - return .{ .data = bytes }; -} - -/// Return a Formatter for a []const u8 where every byte is formatted as pair -/// of uppercase hexadecimal digits. -pub fn fmtSliceHexUpper(bytes: []const u8) std.fmt.Formatter(formatSliceHexUpper) { - return .{ .data = bytes }; -} - fn SliceEscape(comptime case: Case) type { const charset = "0123456789" ++ if (case == .upper) "ABCDEF" else "abcdef"; @@ -864,7 +451,7 @@ fn SliceEscape(comptime case: Case) type { pub fn format( bytes: []const u8, comptime fmt: []const u8, - options: std.fmt.FormatOptions, + options: std.fmt.Options, writer: anytype, ) !void { _ = fmt; @@ -904,352 +491,13 @@ pub fn fmtSliceEscapeUpper(bytes: []const u8) std.fmt.Formatter(formatSliceEscap return .{ .data = bytes }; } -fn Size(comptime base: comptime_int) type { - return struct { - fn format( - value: u64, - comptime fmt: []const u8, - options: FormatOptions, - writer: anytype, - ) !void { - _ = fmt; - if (value == 0) { - return formatBuf("0B", options, writer); - } - // The worst case in terms of space needed is 32 bytes + 3 for the suffix. - var buf: [format_float.min_buffer_size + 3]u8 = undefined; - - const mags_si = " kMGTPEZY"; - const mags_iec = " KMGTPEZY"; - - const log2 = math.log2(value); - const magnitude = switch (base) { - 1000 => @min(log2 / comptime math.log2(1000), mags_si.len - 1), - 1024 => @min(log2 / 10, mags_iec.len - 1), - else => unreachable, - }; - const new_value = lossyCast(f64, value) / math.pow(f64, lossyCast(f64, base), lossyCast(f64, magnitude)); - const suffix = switch (base) { - 1000 => mags_si[magnitude], - 1024 => mags_iec[magnitude], - else => unreachable, - }; - - const s = switch (magnitude) { - 0 => buf[0..formatIntBuf(&buf, value, 10, .lower, .{})], - else => formatFloat(&buf, new_value, .{ .mode = .decimal, .precision = options.precision }) catch |err| switch (err) { - error.BufferTooSmall => unreachable, - }, - }; - - var i: usize = s.len; - if (suffix == ' ') { - buf[i] = 'B'; - i += 1; - } else switch (base) { - 1000 => { - buf[i..][0..2].* = [_]u8{ suffix, 'B' }; - i += 2; - }, - 1024 => { - buf[i..][0..3].* = [_]u8{ suffix, 'i', 'B' }; - i += 3; - }, - else => unreachable, - } - - return formatBuf(buf[0..i], options, writer); - } - }; -} -const formatSizeDec = Size(1000).format; -const formatSizeBin = Size(1024).format; - -/// Return a Formatter for a u64 value representing a file size. -/// This formatter represents the number as multiple of 1000 and uses the SI -/// measurement units (kB, MB, GB, ...). -/// Format option `precision` is ignored when `value` is less than 1kB -pub fn fmtIntSizeDec(value: u64) std.fmt.Formatter(formatSizeDec) { - return .{ .data = value }; -} - -/// Return a Formatter for a u64 value representing a file size. -/// This formatter represents the number as multiple of 1024 and uses the IEC -/// measurement units (KiB, MiB, GiB, ...). -/// Format option `precision` is ignored when `value` is less than 1KiB -pub fn fmtIntSizeBin(value: u64) std.fmt.Formatter(formatSizeBin) { - return .{ .data = value }; -} - -fn checkTextFmt(comptime fmt: []const u8) void { - if (fmt.len != 1) - @compileError("unsupported format string '" ++ fmt ++ "' when formatting text"); - switch (fmt[0]) { - // Example of deprecation: - // '[deprecated_specifier]' => @compileError("specifier '[deprecated_specifier]' has been deprecated, wrap your argument in `std.some_function` instead"), - 'x' => @compileError("specifier 'x' has been deprecated, wrap your argument in std.fmt.fmtSliceHexLower instead"), - 'X' => @compileError("specifier 'X' has been deprecated, wrap your argument in std.fmt.fmtSliceHexUpper instead"), - else => {}, - } -} - -pub fn formatText( - bytes: []const u8, - comptime fmt: []const u8, - options: FormatOptions, - writer: anytype, -) !void { - comptime checkTextFmt(fmt); - return formatBuf(bytes, options, writer); -} - -pub fn formatAsciiChar( - c: u8, - options: FormatOptions, - writer: anytype, -) !void { - return formatBuf(@as(*const [1]u8, &c), options, writer); -} - -pub fn formatUnicodeCodepoint( - c: u21, - options: FormatOptions, - writer: anytype, -) !void { - var buf: [4]u8 = undefined; - const len = unicode.utf8Encode(c, &buf) catch |err| switch (err) { - error.Utf8CannotEncodeSurrogateHalf, error.CodepointTooLarge => { - return formatBuf(&unicode.utf8EncodeComptime(unicode.replacement_character), options, writer); - }, - }; - return formatBuf(buf[0..len], options, writer); -} - -pub fn formatBuf( - buf: []const u8, - options: FormatOptions, - writer: anytype, -) !void { - if (options.width) |min_width| { - // In case of error assume the buffer content is ASCII-encoded - const width = unicode.utf8CountCodepoints(buf) catch buf.len; - const padding = if (width < min_width) min_width - width else 0; - - if (padding == 0) - return writer.writeAll(buf); - - var fill_buffer: [4]u8 = undefined; - const fill_utf8 = if (unicode.utf8Encode(options.fill, &fill_buffer)) |len| - fill_buffer[0..len] - else |err| switch (err) { - error.Utf8CannotEncodeSurrogateHalf, - error.CodepointTooLarge, - => &unicode.utf8EncodeComptime(unicode.replacement_character), - }; - switch (options.alignment) { - .left => { - try writer.writeAll(buf); - try writer.writeBytesNTimes(fill_utf8, padding); - }, - .center => { - const left_padding = padding / 2; - const right_padding = (padding + 1) / 2; - try writer.writeBytesNTimes(fill_utf8, left_padding); - try writer.writeAll(buf); - try writer.writeBytesNTimes(fill_utf8, right_padding); - }, - .right => { - try writer.writeBytesNTimes(fill_utf8, padding); - try writer.writeAll(buf); - }, - } - } else { - // Fast path, avoid counting the number of codepoints - try writer.writeAll(buf); - } -} - -pub fn formatFloatHexadecimal( - value: anytype, - options: FormatOptions, - writer: anytype, -) !void { - if (math.signbit(value)) { - try writer.writeByte('-'); - } - if (math.isNan(value)) { - return writer.writeAll("nan"); - } - if (math.isInf(value)) { - return writer.writeAll("inf"); - } - - const T = @TypeOf(value); - const TU = std.meta.Int(.unsigned, @bitSizeOf(T)); - - const mantissa_bits = math.floatMantissaBits(T); - const fractional_bits = math.floatFractionalBits(T); - const exponent_bits = math.floatExponentBits(T); - const mantissa_mask = (1 << mantissa_bits) - 1; - const exponent_mask = (1 << exponent_bits) - 1; - const exponent_bias = (1 << (exponent_bits - 1)) - 1; - - const as_bits = @as(TU, @bitCast(value)); - var mantissa = as_bits & mantissa_mask; - var exponent: i32 = @as(u16, @truncate((as_bits >> mantissa_bits) & exponent_mask)); - - const is_denormal = exponent == 0 and mantissa != 0; - const is_zero = exponent == 0 and mantissa == 0; - - if (is_zero) { - // Handle this case here to simplify the logic below. - try writer.writeAll("0x0"); - if (options.precision) |precision| { - if (precision > 0) { - try writer.writeAll("."); - try writer.writeByteNTimes('0', precision); - } - } else { - try writer.writeAll(".0"); - } - try writer.writeAll("p0"); - return; - } - - if (is_denormal) { - // Adjust the exponent for printing. - exponent += 1; - } else { - if (fractional_bits == mantissa_bits) - mantissa |= 1 << fractional_bits; // Add the implicit integer bit. - } - - const mantissa_digits = (fractional_bits + 3) / 4; - // Fill in zeroes to round the fraction width to a multiple of 4. - mantissa <<= mantissa_digits * 4 - fractional_bits; - - if (options.precision) |precision| { - // Round if needed. - if (precision < mantissa_digits) { - // We always have at least 4 extra bits. - var extra_bits = (mantissa_digits - precision) * 4; - // The result LSB is the Guard bit, we need two more (Round and - // Sticky) to round the value. - while (extra_bits > 2) { - mantissa = (mantissa >> 1) | (mantissa & 1); - extra_bits -= 1; - } - // Round to nearest, tie to even. - mantissa |= @intFromBool(mantissa & 0b100 != 0); - mantissa += 1; - // Drop the excess bits. - mantissa >>= 2; - // Restore the alignment. - mantissa <<= @as(math.Log2Int(TU), @intCast((mantissa_digits - precision) * 4)); - - const overflow = mantissa & (1 << 1 + mantissa_digits * 4) != 0; - // Prefer a normalized result in case of overflow. - if (overflow) { - mantissa >>= 1; - exponent += 1; - } - } - } - - // +1 for the decimal part. - var buf: [1 + mantissa_digits]u8 = undefined; - _ = formatIntBuf(&buf, mantissa, 16, .lower, .{ .fill = '0', .width = 1 + mantissa_digits }); - - try writer.writeAll("0x"); - try writer.writeByte(buf[0]); - const trimmed = mem.trimEnd(u8, buf[1..], "0"); - if (options.precision) |precision| { - if (precision > 0) try writer.writeAll("."); - } else if (trimmed.len > 0) { - try writer.writeAll("."); - } - try writer.writeAll(trimmed); - // Add trailing zeros if explicitly requested. - if (options.precision) |precision| if (precision > 0) { - if (precision > trimmed.len) - try writer.writeByteNTimes('0', precision - trimmed.len); - }; - try writer.writeAll("p"); - try formatInt(exponent - exponent_bias, 10, .lower, .{}, writer); -} - -pub fn formatInt( - value: anytype, - base: u8, - case: Case, - options: FormatOptions, - writer: anytype, -) !void { - assert(base >= 2); - - const int_value = if (@TypeOf(value) == comptime_int) blk: { - const Int = math.IntFittingRange(value, value); - break :blk @as(Int, value); - } else value; - - const value_info = @typeInfo(@TypeOf(int_value)).int; - - // The type must have the same size as `base` or be wider in order for the - // division to work - const min_int_bits = comptime @max(value_info.bits, 8); - const MinInt = std.meta.Int(.unsigned, min_int_bits); - - const abs_value = @abs(int_value); - // The worst case in terms of space needed is base 2, plus 1 for the sign - var buf: [1 + @max(@as(comptime_int, value_info.bits), 1)]u8 = undefined; - - var a: MinInt = abs_value; - var index: usize = buf.len; - - if (base == 10) { - while (a >= 100) : (a = @divTrunc(a, 100)) { - index -= 2; - buf[index..][0..2].* = digits2(@intCast(a % 100)); - } - - if (a < 10) { - index -= 1; - buf[index] = '0' + @as(u8, @intCast(a)); - } else { - index -= 2; - buf[index..][0..2].* = digits2(@intCast(a)); - } - } else { - while (true) { - const digit = a % base; - index -= 1; - buf[index] = digitToChar(@intCast(digit), case); - a /= base; - if (a == 0) break; - } - } - - if (value_info.signedness == .signed) { - if (value < 0) { - // Negative integer - index -= 1; - buf[index] = '-'; - } else if (options.width == null or options.width.? == 0) { - // Positive integer, omit the plus sign - } else { - // Positive integer - index -= 1; - buf[index] = '+'; - } - } - - return formatBuf(buf[index..], options, writer); -} - -pub fn formatIntBuf(out_buf: []u8, value: anytype, base: u8, case: Case, options: FormatOptions) usize { - var fbs = std.io.fixedBufferStream(out_buf); - formatInt(value, base, case, options, fbs.writer()) catch unreachable; - return fbs.pos; +/// Asserts the rendered integer value fits in `buffer`. +/// Returns the end index within `buffer`. +pub fn printInt(buffer: []u8, value: anytype, base: u8, case: Case, options: Options) usize { + var bw: std.io.BufferedWriter = undefined; + bw.initFixed(buffer); + bw.printIntOptions(value, base, case, options) catch unreachable; + return bw.end; } /// Converts values in the range [0, 100) to a base 10 string. @@ -1261,214 +509,6 @@ pub fn digits2(value: u8) [2]u8 { } } -const FormatDurationData = struct { - ns: u64, - negative: bool = false, -}; - -fn formatDuration(data: FormatDurationData, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { - _ = fmt; - - // worst case: "-XXXyXXwXXdXXhXXmXX.XXXs".len = 24 - var buf: [24]u8 = undefined; - var fbs = std.io.fixedBufferStream(&buf); - var buf_writer = fbs.writer(); - if (data.negative) { - buf_writer.writeByte('-') catch unreachable; - } - - var ns_remaining = data.ns; - inline for (.{ - .{ .ns = 365 * std.time.ns_per_day, .sep = 'y' }, - .{ .ns = std.time.ns_per_week, .sep = 'w' }, - .{ .ns = std.time.ns_per_day, .sep = 'd' }, - .{ .ns = std.time.ns_per_hour, .sep = 'h' }, - .{ .ns = std.time.ns_per_min, .sep = 'm' }, - }) |unit| { - if (ns_remaining >= unit.ns) { - const units = ns_remaining / unit.ns; - formatInt(units, 10, .lower, .{}, buf_writer) catch unreachable; - buf_writer.writeByte(unit.sep) catch unreachable; - ns_remaining -= units * unit.ns; - if (ns_remaining == 0) - return formatBuf(fbs.getWritten(), options, writer); - } - } - - inline for (.{ - .{ .ns = std.time.ns_per_s, .sep = "s" }, - .{ .ns = std.time.ns_per_ms, .sep = "ms" }, - .{ .ns = std.time.ns_per_us, .sep = "us" }, - }) |unit| { - const kunits = ns_remaining * 1000 / unit.ns; - if (kunits >= 1000) { - formatInt(kunits / 1000, 10, .lower, .{}, buf_writer) catch unreachable; - const frac = kunits % 1000; - if (frac > 0) { - // Write up to 3 decimal places - var decimal_buf = [_]u8{ '.', 0, 0, 0 }; - _ = formatIntBuf(decimal_buf[1..], frac, 10, .lower, .{ .fill = '0', .width = 3 }); - var end: usize = 4; - while (end > 1) : (end -= 1) { - if (decimal_buf[end - 1] != '0') break; - } - buf_writer.writeAll(decimal_buf[0..end]) catch unreachable; - } - buf_writer.writeAll(unit.sep) catch unreachable; - return formatBuf(fbs.getWritten(), options, writer); - } - } - - formatInt(ns_remaining, 10, .lower, .{}, buf_writer) catch unreachable; - buf_writer.writeAll("ns") catch unreachable; - return formatBuf(fbs.getWritten(), options, writer); -} - -/// Return a Formatter for number of nanoseconds according to its magnitude: -/// [#y][#w][#d][#h][#m]#[.###][n|u|m]s -pub fn fmtDuration(ns: u64) Formatter(formatDuration) { - const data = FormatDurationData{ .ns = ns }; - return .{ .data = data }; -} - -test fmtDuration { - var buf: [24]u8 = undefined; - inline for (.{ - .{ .s = "0ns", .d = 0 }, - .{ .s = "1ns", .d = 1 }, - .{ .s = "999ns", .d = std.time.ns_per_us - 1 }, - .{ .s = "1us", .d = std.time.ns_per_us }, - .{ .s = "1.45us", .d = 1450 }, - .{ .s = "1.5us", .d = 3 * std.time.ns_per_us / 2 }, - .{ .s = "14.5us", .d = 14500 }, - .{ .s = "145us", .d = 145000 }, - .{ .s = "999.999us", .d = std.time.ns_per_ms - 1 }, - .{ .s = "1ms", .d = std.time.ns_per_ms + 1 }, - .{ .s = "1.5ms", .d = 3 * std.time.ns_per_ms / 2 }, - .{ .s = "1.11ms", .d = 1110000 }, - .{ .s = "1.111ms", .d = 1111000 }, - .{ .s = "1.111ms", .d = 1111100 }, - .{ .s = "999.999ms", .d = std.time.ns_per_s - 1 }, - .{ .s = "1s", .d = std.time.ns_per_s }, - .{ .s = "59.999s", .d = std.time.ns_per_min - 1 }, - .{ .s = "1m", .d = std.time.ns_per_min }, - .{ .s = "1h", .d = std.time.ns_per_hour }, - .{ .s = "1d", .d = std.time.ns_per_day }, - .{ .s = "1w", .d = std.time.ns_per_week }, - .{ .s = "1y", .d = 365 * std.time.ns_per_day }, - .{ .s = "1y52w23h59m59.999s", .d = 730 * std.time.ns_per_day - 1 }, // 365d = 52w1d - .{ .s = "1y1h1.001s", .d = 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + std.time.ns_per_ms }, - .{ .s = "1y1h1s", .d = 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + 999 * std.time.ns_per_us }, - .{ .s = "1y1h999.999us", .d = 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms - 1 }, - .{ .s = "1y1h1ms", .d = 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms }, - .{ .s = "1y1h1ms", .d = 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms + 1 }, - .{ .s = "1y1m999ns", .d = 365 * std.time.ns_per_day + std.time.ns_per_min + 999 }, - .{ .s = "584y49w23h34m33.709s", .d = math.maxInt(u64) }, - }) |tc| { - const slice = try bufPrint(&buf, "{}", .{fmtDuration(tc.d)}); - try std.testing.expectEqualStrings(tc.s, slice); - } - - inline for (.{ - .{ .s = "=======0ns", .f = "{s:=>10}", .d = 0 }, - .{ .s = "1ns=======", .f = "{s:=<10}", .d = 1 }, - .{ .s = " 999ns ", .f = "{s:^10}", .d = std.time.ns_per_us - 1 }, - }) |tc| { - const slice = try bufPrint(&buf, tc.f, .{fmtDuration(tc.d)}); - try std.testing.expectEqualStrings(tc.s, slice); - } -} - -fn formatDurationSigned(ns: i64, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { - const data = FormatDurationData{ .ns = @abs(ns), .negative = ns < 0 }; - try formatDuration(data, fmt, options, writer); -} - -/// Return a Formatter for number of nanoseconds according to its signed magnitude: -/// [#y][#w][#d][#h][#m]#[.###][n|u|m]s -pub fn fmtDurationSigned(ns: i64) Formatter(formatDurationSigned) { - return .{ .data = ns }; -} - -test fmtDurationSigned { - var buf: [24]u8 = undefined; - inline for (.{ - .{ .s = "0ns", .d = 0 }, - .{ .s = "1ns", .d = 1 }, - .{ .s = "-1ns", .d = -(1) }, - .{ .s = "999ns", .d = std.time.ns_per_us - 1 }, - .{ .s = "-999ns", .d = -(std.time.ns_per_us - 1) }, - .{ .s = "1us", .d = std.time.ns_per_us }, - .{ .s = "-1us", .d = -(std.time.ns_per_us) }, - .{ .s = "1.45us", .d = 1450 }, - .{ .s = "-1.45us", .d = -(1450) }, - .{ .s = "1.5us", .d = 3 * std.time.ns_per_us / 2 }, - .{ .s = "-1.5us", .d = -(3 * std.time.ns_per_us / 2) }, - .{ .s = "14.5us", .d = 14500 }, - .{ .s = "-14.5us", .d = -(14500) }, - .{ .s = "145us", .d = 145000 }, - .{ .s = "-145us", .d = -(145000) }, - .{ .s = "999.999us", .d = std.time.ns_per_ms - 1 }, - .{ .s = "-999.999us", .d = -(std.time.ns_per_ms - 1) }, - .{ .s = "1ms", .d = std.time.ns_per_ms + 1 }, - .{ .s = "-1ms", .d = -(std.time.ns_per_ms + 1) }, - .{ .s = "1.5ms", .d = 3 * std.time.ns_per_ms / 2 }, - .{ .s = "-1.5ms", .d = -(3 * std.time.ns_per_ms / 2) }, - .{ .s = "1.11ms", .d = 1110000 }, - .{ .s = "-1.11ms", .d = -(1110000) }, - .{ .s = "1.111ms", .d = 1111000 }, - .{ .s = "-1.111ms", .d = -(1111000) }, - .{ .s = "1.111ms", .d = 1111100 }, - .{ .s = "-1.111ms", .d = -(1111100) }, - .{ .s = "999.999ms", .d = std.time.ns_per_s - 1 }, - .{ .s = "-999.999ms", .d = -(std.time.ns_per_s - 1) }, - .{ .s = "1s", .d = std.time.ns_per_s }, - .{ .s = "-1s", .d = -(std.time.ns_per_s) }, - .{ .s = "59.999s", .d = std.time.ns_per_min - 1 }, - .{ .s = "-59.999s", .d = -(std.time.ns_per_min - 1) }, - .{ .s = "1m", .d = std.time.ns_per_min }, - .{ .s = "-1m", .d = -(std.time.ns_per_min) }, - .{ .s = "1h", .d = std.time.ns_per_hour }, - .{ .s = "-1h", .d = -(std.time.ns_per_hour) }, - .{ .s = "1d", .d = std.time.ns_per_day }, - .{ .s = "-1d", .d = -(std.time.ns_per_day) }, - .{ .s = "1w", .d = std.time.ns_per_week }, - .{ .s = "-1w", .d = -(std.time.ns_per_week) }, - .{ .s = "1y", .d = 365 * std.time.ns_per_day }, - .{ .s = "-1y", .d = -(365 * std.time.ns_per_day) }, - .{ .s = "1y52w23h59m59.999s", .d = 730 * std.time.ns_per_day - 1 }, // 365d = 52w1d - .{ .s = "-1y52w23h59m59.999s", .d = -(730 * std.time.ns_per_day - 1) }, // 365d = 52w1d - .{ .s = "1y1h1.001s", .d = 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + std.time.ns_per_ms }, - .{ .s = "-1y1h1.001s", .d = -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + std.time.ns_per_ms) }, - .{ .s = "1y1h1s", .d = 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + 999 * std.time.ns_per_us }, - .{ .s = "-1y1h1s", .d = -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + 999 * std.time.ns_per_us) }, - .{ .s = "1y1h999.999us", .d = 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms - 1 }, - .{ .s = "-1y1h999.999us", .d = -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms - 1) }, - .{ .s = "1y1h1ms", .d = 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms }, - .{ .s = "-1y1h1ms", .d = -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms) }, - .{ .s = "1y1h1ms", .d = 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms + 1 }, - .{ .s = "-1y1h1ms", .d = -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms + 1) }, - .{ .s = "1y1m999ns", .d = 365 * std.time.ns_per_day + std.time.ns_per_min + 999 }, - .{ .s = "-1y1m999ns", .d = -(365 * std.time.ns_per_day + std.time.ns_per_min + 999) }, - .{ .s = "292y24w3d23h47m16.854s", .d = math.maxInt(i64) }, - .{ .s = "-292y24w3d23h47m16.854s", .d = math.minInt(i64) + 1 }, - .{ .s = "-292y24w3d23h47m16.854s", .d = math.minInt(i64) }, - }) |tc| { - const slice = try bufPrint(&buf, "{}", .{fmtDurationSigned(tc.d)}); - try std.testing.expectEqualStrings(tc.s, slice); - } - - inline for (.{ - .{ .s = "=======0ns", .f = "{s:=>10}", .d = 0 }, - .{ .s = "1ns=======", .f = "{s:=<10}", .d = 1 }, - .{ .s = "-1ns======", .f = "{s:=<10}", .d = -(1) }, - .{ .s = " -999ns ", .f = "{s:^10}", .d = -(std.time.ns_per_us - 1) }, - }) |tc| { - const slice = try bufPrint(&buf, tc.f, .{fmtDurationSigned(tc.d)}); - try std.testing.expectEqualStrings(tc.s, slice); - } -} - pub const ParseIntError = error{ /// The result cannot fit in the type specified Overflow, @@ -1484,7 +524,7 @@ pub const ParseIntError = error{ /// fn formatExample( /// data: T, /// comptime fmt: []const u8, -/// options: std.fmt.FormatOptions, +/// options: std.fmt.Options, /// writer: anytype, /// ) !void; /// @@ -1495,9 +535,9 @@ pub fn Formatter(comptime formatFn: anytype) type { pub fn format( self: @This(), comptime fmt: []const u8, - options: std.fmt.FormatOptions, - writer: anytype, - ) @TypeOf(writer).Error!void { + options: std.fmt.Options, + writer: *std.io.BufferedWriter, + ) anyerror!void { try formatFn(self.data, fmt, options, writer); } }; @@ -1796,12 +836,13 @@ pub const BufPrintError = error{ /// Print a Formatter string into `buf`. Actually just a thin wrapper around `format` and `fixedBufferStream`. /// Returns a slice of the bytes printed to. pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintError![]u8 { - var fbs = std.io.fixedBufferStream(buf); - format(fbs.writer().any(), fmt, args) catch |err| switch (err) { + var bw: std.io.BufferedWriter = undefined; + bw.initFixed(buf); + bw.print(fmt, args) catch |err| switch (err) { error.NoSpaceLeft => return error.NoSpaceLeft, else => unreachable, }; - return fbs.getWritten(); + return bw.getWritten(); } pub fn bufPrintZ(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintError![:0]u8 { @@ -1809,10 +850,11 @@ pub fn bufPrintZ(buf: []u8, comptime fmt: []const u8, args: anytype) BufPrintErr return result[0 .. result.len - 1 :0]; } -/// Count the characters needed for format. Useful for preallocating memory +/// Count the characters needed for format. pub fn count(comptime fmt: []const u8, args: anytype) u64 { - var counting_writer = std.io.countingWriter(std.io.null_writer); - format(counting_writer.writer().any(), fmt, args) catch unreachable; + var counting_writer: std.io.CountingWriter = .{ .child_writer = std.io.null_writer }; + var bw = counting_writer.unbufferedWriter(); + bw.print(fmt, args) catch unreachable; return counting_writer.bytes_written; } @@ -1831,31 +873,6 @@ pub fn allocPrintZ(allocator: mem.Allocator, comptime fmt: []const u8, args: any return result[0 .. result.len - 1 :0]; } -test bufPrintIntToSlice { - var buffer: [100]u8 = undefined; - const buf = buffer[0..]; - - try std.testing.expectEqualSlices(u8, "-1", bufPrintIntToSlice(buf, @as(i1, -1), 10, .lower, FormatOptions{})); - - try std.testing.expectEqualSlices(u8, "-101111000110000101001110", bufPrintIntToSlice(buf, @as(i32, -12345678), 2, .lower, FormatOptions{})); - try std.testing.expectEqualSlices(u8, "-12345678", bufPrintIntToSlice(buf, @as(i32, -12345678), 10, .lower, FormatOptions{})); - try std.testing.expectEqualSlices(u8, "-bc614e", bufPrintIntToSlice(buf, @as(i32, -12345678), 16, .lower, FormatOptions{})); - try std.testing.expectEqualSlices(u8, "-BC614E", bufPrintIntToSlice(buf, @as(i32, -12345678), 16, .upper, FormatOptions{})); - - try std.testing.expectEqualSlices(u8, "12345678", bufPrintIntToSlice(buf, @as(u32, 12345678), 10, .upper, FormatOptions{})); - - try std.testing.expectEqualSlices(u8, " 666", bufPrintIntToSlice(buf, @as(u32, 666), 10, .lower, FormatOptions{ .width = 6 })); - try std.testing.expectEqualSlices(u8, " 1234", bufPrintIntToSlice(buf, @as(u32, 0x1234), 16, .lower, FormatOptions{ .width = 6 })); - try std.testing.expectEqualSlices(u8, "1234", bufPrintIntToSlice(buf, @as(u32, 0x1234), 16, .lower, FormatOptions{ .width = 1 })); - - try std.testing.expectEqualSlices(u8, "+42", bufPrintIntToSlice(buf, @as(i32, 42), 10, .lower, FormatOptions{ .width = 3 })); - try std.testing.expectEqualSlices(u8, "-42", bufPrintIntToSlice(buf, @as(i32, -42), 10, .lower, FormatOptions{ .width = 3 })); -} - -pub fn bufPrintIntToSlice(buf: []u8, value: anytype, base: u8, case: Case, options: FormatOptions) []u8 { - return buf[0..formatIntBuf(buf, value, base, case, options)]; -} - pub inline fn comptimePrint(comptime fmt: []const u8, args: anytype) *const [count(fmt, args):0]u8 { comptime { var buf: [count(fmt, args):0]u8 = undefined; @@ -1994,15 +1011,16 @@ test "buffer" { { var buf1: [32]u8 = undefined; var fbs = std.io.fixedBufferStream(&buf1); - try formatType(1234, "", FormatOptions{}, fbs.writer(), std.options.fmt_max_depth); + var bw = fbs.writer(); + try bw.printValue("", .{}, 1234, std.options.fmt_max_depth); try std.testing.expectEqualStrings("1234", fbs.getWritten()); fbs.reset(); - try formatType('a', "c", FormatOptions{}, fbs.writer(), std.options.fmt_max_depth); + try bw.printValue("c", .{}, 'a', std.options.fmt_max_depth); try std.testing.expectEqualStrings("a", fbs.getWritten()); fbs.reset(); - try formatType(0b1100, "b", FormatOptions{}, fbs.writer(), std.options.fmt_max_depth); + try bw.printValue("b", .{}, 0b1100, std.options.fmt_max_depth); try std.testing.expectEqualStrings("1100", fbs.getWritten()); } } @@ -2083,7 +1101,7 @@ test "slice" { const S2 = struct { x: u8, - pub fn format(s: @This(), comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { + pub fn format(s: @This(), comptime _: []const u8, _: std.fmt.Options, writer: anytype) !void { try writer.print("S2({})", .{s.x}); } }; @@ -2129,21 +1147,6 @@ test "cstr" { ); } -test "filesize" { - try expectFmt("file size: 42B\n", "file size: {}\n", .{fmtIntSizeDec(42)}); - try expectFmt("file size: 42B\n", "file size: {}\n", .{fmtIntSizeBin(42)}); - try expectFmt("file size: 63MB\n", "file size: {}\n", .{fmtIntSizeDec(63 * 1000 * 1000)}); - try expectFmt("file size: 63MiB\n", "file size: {}\n", .{fmtIntSizeBin(63 * 1024 * 1024)}); - try expectFmt("file size: 42B\n", "file size: {:.2}\n", .{fmtIntSizeDec(42)}); - try expectFmt("file size: 42B\n", "file size: {:>9.2}\n", .{fmtIntSizeDec(42)}); - try expectFmt("file size: 66.06MB\n", "file size: {:.2}\n", .{fmtIntSizeDec(63 * 1024 * 1024)}); - try expectFmt("file size: 60.08MiB\n", "file size: {:.2}\n", .{fmtIntSizeBin(63 * 1000 * 1000)}); - try expectFmt("file size: =66.06MB=\n", "file size: {:=^9.2}\n", .{fmtIntSizeDec(63 * 1024 * 1024)}); - try expectFmt("file size: 66.06MB\n", "file size: {: >9.2}\n", .{fmtIntSizeDec(63 * 1024 * 1024)}); - try expectFmt("file size: 66.06MB \n", "file size: {: <9.2}\n", .{fmtIntSizeDec(63 * 1024 * 1024)}); - try expectFmt("file size: 0.01844674407370955ZB\n", "file size: {}\n", .{fmtIntSizeDec(math.maxInt(u64))}); -} - test "struct" { { const Struct = struct { @@ -2354,7 +1357,7 @@ test "custom" { pub fn format( self: SelfType, comptime fmt: []const u8, - options: FormatOptions, + options: Options, writer: anytype, ) !void { _ = options; @@ -2439,17 +1442,6 @@ test "struct.zero-size" { try expectFmt("fmt.test.struct.zero-size.B{ .a = fmt.test.struct.zero-size.A{ }, .c = 0 }", "{}", .{b}); } -test "bytes.hex" { - const some_bytes = "\xCA\xFE\xBA\xBE"; - try expectFmt("lowercase: cafebabe\n", "lowercase: {x}\n", .{fmtSliceHexLower(some_bytes)}); - try expectFmt("uppercase: CAFEBABE\n", "uppercase: {X}\n", .{fmtSliceHexUpper(some_bytes)}); - //Test Slices - try expectFmt("uppercase: CAFE\n", "uppercase: {X}\n", .{fmtSliceHexUpper(some_bytes[0..2])}); - try expectFmt("lowercase: babe\n", "lowercase: {x}\n", .{fmtSliceHexLower(some_bytes[2..])}); - const bytes_with_zeros = "\x00\x0E\xBA\xBE"; - try expectFmt("lowercase: 000ebabe\n", "lowercase: {x}\n", .{fmtSliceHexLower(bytes_with_zeros)}); -} - /// Encodes a sequence of bytes as hexadecimal digits. /// Returns an array containing the encoded bytes. pub fn bytesToHex(input: anytype, case: Case) [input.len * 2]u8 { @@ -2494,110 +1486,14 @@ test bytesToHex { test hexToBytes { var buf: [32]u8 = undefined; - try expectFmt("90" ** 32, "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, "90" ** 32))}); - try expectFmt("ABCD", "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, "ABCD"))}); - try expectFmt("", "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, ""))}); + try expectFmt("90" ** 32, "{X}", .{try hexToBytes(&buf, "90" ** 32)}); + try expectFmt("ABCD", "{X}", .{try hexToBytes(&buf, "ABCD")}); + try expectFmt("", "{X}", .{try hexToBytes(&buf, "")}); try std.testing.expectError(error.InvalidCharacter, hexToBytes(&buf, "012Z")); try std.testing.expectError(error.InvalidLength, hexToBytes(&buf, "AAA")); try std.testing.expectError(error.NoSpaceLeft, hexToBytes(buf[0..1], "ABAB")); } -test "formatIntValue with comptime_int" { - const value: comptime_int = 123456789123456789; - - var buf: [20]u8 = undefined; - var fbs = std.io.fixedBufferStream(&buf); - try formatIntValue(value, "", FormatOptions{}, fbs.writer()); - try std.testing.expectEqualStrings("123456789123456789", fbs.getWritten()); -} - -test "formatFloatValue with comptime_float" { - const value: comptime_float = 1.0; - - var buf: [20]u8 = undefined; - var fbs = std.io.fixedBufferStream(&buf); - try formatFloatValue(value, "", FormatOptions{}, fbs.writer()); - try std.testing.expectEqualStrings(fbs.getWritten(), "1e0"); - - try expectFmt("1e0", "{}", .{value}); - try expectFmt("1e0", "{}", .{1.0}); -} - -test "formatType max_depth" { - const Vec2 = struct { - const SelfType = @This(); - x: f32, - y: f32, - - pub fn format( - self: SelfType, - comptime fmt: []const u8, - options: FormatOptions, - writer: anytype, - ) !void { - _ = options; - if (fmt.len == 0) { - return std.fmt.format(writer, "({d:.3},{d:.3})", .{ self.x, self.y }); - } else { - @compileError("unknown format string: '" ++ fmt ++ "'"); - } - } - }; - const E = enum { - One, - Two, - Three, - }; - const TU = union(enum) { - const SelfType = @This(); - float: f32, - int: u32, - ptr: ?*SelfType, - }; - const S = struct { - const SelfType = @This(); - a: ?*SelfType, - tu: TU, - e: E, - vec: Vec2, - }; - - var inst = S{ - .a = null, - .tu = TU{ .ptr = null }, - .e = E.Two, - .vec = Vec2{ .x = 10.2, .y = 2.22 }, - }; - inst.a = &inst; - inst.tu.ptr = &inst.tu; - - var buf: [1000]u8 = undefined; - var fbs = std.io.fixedBufferStream(&buf); - try formatType(inst, "", FormatOptions{}, fbs.writer(), 0); - try std.testing.expectEqualStrings("fmt.test.formatType max_depth.S{ ... }", fbs.getWritten()); - - fbs.reset(); - try formatType(inst, "", FormatOptions{}, fbs.writer(), 1); - try std.testing.expectEqualStrings("fmt.test.formatType max_depth.S{ .a = fmt.test.formatType max_depth.S{ ... }, .tu = fmt.test.formatType max_depth.TU{ ... }, .e = fmt.test.formatType max_depth.E.Two, .vec = (10.200,2.220) }", fbs.getWritten()); - - fbs.reset(); - try formatType(inst, "", FormatOptions{}, fbs.writer(), 2); - try std.testing.expectEqualStrings("fmt.test.formatType max_depth.S{ .a = fmt.test.formatType max_depth.S{ .a = fmt.test.formatType max_depth.S{ ... }, .tu = fmt.test.formatType max_depth.TU{ ... }, .e = fmt.test.formatType max_depth.E.Two, .vec = (10.200,2.220) }, .tu = fmt.test.formatType max_depth.TU{ .ptr = fmt.test.formatType max_depth.TU{ ... } }, .e = fmt.test.formatType max_depth.E.Two, .vec = (10.200,2.220) }", fbs.getWritten()); - - fbs.reset(); - try formatType(inst, "", FormatOptions{}, fbs.writer(), 3); - try std.testing.expectEqualStrings("fmt.test.formatType max_depth.S{ .a = fmt.test.formatType max_depth.S{ .a = fmt.test.formatType max_depth.S{ .a = fmt.test.formatType max_depth.S{ ... }, .tu = fmt.test.formatType max_depth.TU{ ... }, .e = fmt.test.formatType max_depth.E.Two, .vec = (10.200,2.220) }, .tu = fmt.test.formatType max_depth.TU{ .ptr = fmt.test.formatType max_depth.TU{ ... } }, .e = fmt.test.formatType max_depth.E.Two, .vec = (10.200,2.220) }, .tu = fmt.test.formatType max_depth.TU{ .ptr = fmt.test.formatType max_depth.TU{ .ptr = fmt.test.formatType max_depth.TU{ ... } } }, .e = fmt.test.formatType max_depth.E.Two, .vec = (10.200,2.220) }", fbs.getWritten()); - - const vec: @Vector(4, i32) = .{ 1, 2, 3, 4 }; - fbs.reset(); - try formatType(vec, "", FormatOptions{}, fbs.writer(), 0); - try std.testing.expectEqualStrings("{ ... }", fbs.getWritten()); - - fbs.reset(); - try formatType(vec, "", FormatOptions{}, fbs.writer(), 1); - try std.testing.expectEqualStrings("{ 1, 2, 3, 4 }", fbs.getWritten()); -} - test "positional" { try expectFmt("2 1 0", "{2} {1} {0}", .{ @as(usize, 0), @as(usize, 1), @as(usize, 2) }); try expectFmt("2 1 0", "{2} {1} {}", .{ @as(usize, 0), @as(usize, 1), @as(usize, 2) }); @@ -2742,7 +1638,7 @@ test "recursive format function" { Leaf: i32, Branch: struct { left: *const R, right: *const R }, - pub fn format(self: R, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { + pub fn format(self: R, comptime _: []const u8, _: std.fmt.Options, writer: anytype) !void { return switch (self) { .Leaf => |n| std.fmt.format(writer, "Leaf({})", .{n}), .Branch => |b| std.fmt.format(writer, "Branch({}, {})", .{ b.left, b.right }), diff --git a/lib/std/fmt/float.zig b/lib/std/fmt/float.zig new file mode 100644 index 0000000000000000000000000000000000000000..16df95ad28e75c34f4922dceadb31b20f2e0c3fe --- /dev/null +++ b/lib/std/fmt/float.zig @@ -0,0 +1,1695 @@ +//! This file implements the ryu floating point conversion algorithm: +//! https://dl.acm.org/doi/pdf/10.1145/3360595 + +const std = @import("std"); +const expectFmt = std.testing.expectFmt; + +const special_exponent = 0x7fffffff; + +/// Any buffer used for `format` must be at least this large. This is asserted. A runtime check will +/// additionally be performed if more bytes are required. +pub const min_buffer_size = 53; + +/// Returns the minimum buffer size needed to print every float of a specific type and format. +pub fn bufferSize(comptime mode: Mode, comptime T: type) comptime_int { + comptime std.debug.assert(@typeInfo(T) == .float); + return switch (mode) { + .scientific => 53, + // Based on minimum subnormal values. + .decimal => switch (@bitSizeOf(T)) { + 16 => @max(15, min_buffer_size), + 32 => 55, + 64 => 347, + 80 => 4996, + 128 => 5011, + else => unreachable, + }, + }; +} + +pub const Error = error{ + BufferTooSmall, +}; + +pub const Mode = enum { + scientific, + decimal, +}; + +pub const Options = struct { + mode: Mode = .scientific, + precision: ?usize = null, +}; + +/// Format a floating-point value and write it to buffer. Returns a slice to the buffer containing +/// the string representation. +/// +/// Full precision is the default. Any full precision float can be reparsed with std.fmt.parseFloat +/// unambiguously. +/// +/// Scientific mode is recommended generally as the output is more compact and any type can be +/// written in full precision using a buffer of only `min_buffer_size`. +/// +/// When printing full precision decimals, use `bufferSize` to get the required space. It is +/// recommended to bound decimal output with a fixed precision to reduce the required buffer size. +pub fn render(buf: []u8, value: anytype, options: Options) Error![]const u8 { + const v = switch (@TypeOf(value)) { + // comptime_float internally is a f128; this preserves precision. + comptime_float => @as(f128, value), + else => value, + }; + + const T = @TypeOf(v); + comptime std.debug.assert(@typeInfo(T) == .float); + const I = @Type(.{ .int = .{ .signedness = .unsigned, .bits = @bitSizeOf(T) } }); + + const DT = if (@bitSizeOf(T) <= 64) u64 else u128; + const tables = switch (DT) { + u64 => if (@import("builtin").mode == .ReleaseSmall) &Backend64_TablesSmall else &Backend64_TablesFull, + u128 => &Backend128_Tables, + else => unreachable, + }; + + const has_explicit_leading_bit = std.math.floatMantissaBits(T) - std.math.floatFractionalBits(T) != 0; + const d = binaryToDecimal(DT, @as(I, @bitCast(v)), std.math.floatMantissaBits(T), std.math.floatExponentBits(T), has_explicit_leading_bit, tables); + + return switch (options.mode) { + .scientific => formatScientific(DT, buf, d, options.precision), + .decimal => formatDecimal(DT, buf, d, options.precision), + }; +} + +pub fn FloatDecimal(comptime T: type) type { + comptime std.debug.assert(T == u64 or T == u128); + return struct { + mantissa: T, + exponent: i32, + sign: bool, + }; +} + +fn copySpecialStr(buf: []u8, f: anytype) []const u8 { + if (f.sign) { + buf[0] = '-'; + } + const offset: usize = @intFromBool(f.sign); + if (f.mantissa != 0) { + @memcpy(buf[offset..][0..3], "nan"); + return buf[0 .. 3 + offset]; + } + @memcpy(buf[offset..][0..3], "inf"); + return buf[0 .. 3 + offset]; +} + +fn writeDecimal(buf: []u8, value: anytype, count: usize) void { + var i: usize = 0; + + while (i + 2 < count) : (i += 2) { + const c: u8 = @intCast(value.* % 100); + value.* /= 100; + const d = std.fmt.digits2(c); + buf[count - i - 1] = d[1]; + buf[count - i - 2] = d[0]; + } + + while (i < count) : (i += 1) { + const c: u8 = @intCast(value.* % 10); + value.* /= 10; + buf[count - i - 1] = '0' + c; + } +} + +fn isPowerOf10(n_: u128) bool { + var n = n_; + while (n != 0) : (n /= 10) { + if (n % 10 != 0) return false; + } + return true; +} + +const RoundMode = enum { + /// 1234.56 = precision 2 + decimal, + /// 1.23456e3 = precision 5 + scientific, +}; + +fn round(comptime T: type, f: FloatDecimal(T), mode: RoundMode, precision: usize) FloatDecimal(T) { + var round_digit: usize = 0; + var output = f.mantissa; + var exp = f.exponent; + const olength = decimalLength(output); + + switch (mode) { + .decimal => { + if (f.exponent > 0) { + round_digit = (olength - 1) + precision + @as(usize, @intCast(f.exponent)); + } else { + const min_exp_required = @as(usize, @intCast(-f.exponent)); + if (precision + olength > min_exp_required) { + round_digit = precision + olength - min_exp_required; + } + } + }, + .scientific => { + round_digit = 1 + precision; + }, + } + + if (round_digit < olength) { + var nlength = olength; + for (round_digit + 1..olength) |_| { + output /= 10; + exp += 1; + nlength -= 1; + } + + if (output % 10 >= 5) { + output /= 10; + output += 1; + exp += 1; + + // e.g. 9999 -> 10000 + if (isPowerOf10(output)) { + output /= 10; + exp += 1; + } + } + } + + return .{ + .mantissa = output, + .exponent = exp, + .sign = f.sign, + }; +} + +/// Write a FloatDecimal to a buffer in scientific form. +/// +/// The buffer provided must be greater than `min_buffer_size` in length. If no precision is +/// specified, this function will never return an error. If a precision is specified, up to +/// `8 + precision` bytes will be written to the buffer. An error will be returned if the content +/// will not fit. +/// +/// It is recommended to bound decimal formatting with an exact precision. +pub fn formatScientific(comptime T: type, buf: []u8, f_: FloatDecimal(T), precision: ?usize) Error![]const u8 { + std.debug.assert(buf.len >= min_buffer_size); + var f = f_; + + if (f.exponent == special_exponent) { + return copySpecialStr(buf, f); + } + + if (precision) |prec| { + f = round(T, f, .scientific, prec); + } + + var output = f.mantissa; + const olength = decimalLength(output); + + if (precision) |prec| { + // fixed bound: sign(1) + leading_digit(1) + point(1) + exp_sign(1) + exp_max(4) + const req_bytes = 8 + prec; + if (buf.len < req_bytes) { + return error.BufferTooSmall; + } + } + + // Step 5: Print the scientific representation + var index: usize = 0; + if (f.sign) { + buf[index] = '-'; + index += 1; + } + + // 1.12345 + writeDecimal(buf[index + 2 ..], &output, olength - 1); + buf[index] = '0' + @as(u8, @intCast(output % 10)); + buf[index + 1] = '.'; + index += 2; + const dp_index = index; + if (olength > 1) index += olength - 1 else index -= 1; + + if (precision) |prec| { + index += @intFromBool(olength == 1); + if (prec > olength - 1) { + const len = prec - (olength - 1); + @memset(buf[index..][0..len], '0'); + index += len; + } else { + index = dp_index + prec - @intFromBool(prec == 0); + } + } + + // e100 + buf[index] = 'e'; + index += 1; + var exp = f.exponent + @as(i32, @intCast(olength)) - 1; + if (exp < 0) { + buf[index] = '-'; + index += 1; + exp = -exp; + } + var uexp: u32 = @intCast(exp); + const elength = decimalLength(uexp); + writeDecimal(buf[index..], &uexp, elength); + index += elength; + + return buf[0..index]; +} + +/// Write a FloatDecimal to a buffer in decimal form. +/// +/// The buffer provided must be greater than `min_buffer_size` bytes in length. If no precision is +/// specified, this may still return an error. If precision is specified, `2 + precision` bytes will +/// always be written. +pub fn formatDecimal(comptime T: type, buf: []u8, f_: FloatDecimal(T), precision: ?usize) Error![]const u8 { + std.debug.assert(buf.len >= min_buffer_size); + var f = f_; + + if (f.exponent == special_exponent) { + return copySpecialStr(buf, f); + } + + if (precision) |prec| { + f = round(T, f, .decimal, prec); + } + + var output = f.mantissa; + const olength = decimalLength(output); + + // fixed bound: leading_digit(1) + point(1) + const req_bytes = if (f.exponent >= 0) + @as(usize, 2) + @abs(f.exponent) + olength + (precision orelse 0) + else + @as(usize, 2) + @max(@abs(f.exponent) + olength, precision orelse 0); + if (buf.len < req_bytes) { + return error.BufferTooSmall; + } + + // Step 5: Print the decimal representation + var index: usize = 0; + if (f.sign) { + buf[index] = '-'; + index += 1; + } + + const dp_offset = f.exponent + cast_i32(olength); + if (dp_offset <= 0) { + // 0.000001234 + buf[index] = '0'; + buf[index + 1] = '.'; + index += 2; + const dp_index = index; + + const dp_poffset: u32 = @intCast(-dp_offset); + @memset(buf[index..][0..dp_poffset], '0'); + index += dp_poffset; + writeDecimal(buf[index..], &output, olength); + index += olength; + + if (precision) |prec| { + const dp_written = index - dp_index; + if (prec > dp_written) { + @memset(buf[index..][0 .. prec - dp_written], '0'); + } + index = dp_index + prec - @intFromBool(prec == 0); + } + } else { + // 123456000 + const dp_uoffset: usize = @intCast(dp_offset); + if (dp_uoffset >= olength) { + writeDecimal(buf[index..], &output, olength); + index += olength; + @memset(buf[index..][0 .. dp_uoffset - olength], '0'); + index += dp_uoffset - olength; + + if (precision) |prec| { + if (prec != 0) { + buf[index] = '.'; + index += 1; + @memset(buf[index..][0..prec], '0'); + index += prec; + } + } + } else { + // 12345.6789 + writeDecimal(buf[index + dp_uoffset + 1 ..], &output, olength - dp_uoffset); + buf[index + dp_uoffset] = '.'; + const dp_index = index + dp_uoffset + 1; + writeDecimal(buf[index..], &output, dp_uoffset); + index += olength + 1; + + if (precision) |prec| { + const dp_written = olength - dp_uoffset; + if (prec > dp_written) { + @memset(buf[index..][0 .. prec - dp_written], '0'); + } + index = dp_index + prec - @intFromBool(prec == 0); + } + } + } + + return buf[0..index]; +} + +fn cast_i32(v: anytype) i32 { + return @intCast(v); +} + +/// Convert a binary float representation to decimal. +pub fn binaryToDecimal(comptime T: type, bits: T, mantissa_bits: std.math.Log2Int(T), exponent_bits: u5, explicit_leading_bit: bool, comptime tables: anytype) FloatDecimal(T) { + if (T != tables.T) { + @compileError("table type does not match backend type: " ++ @typeName(tables.T) ++ " != " ++ @typeName(T)); + } + + const bias = (@as(u32, 1) << (exponent_bits - 1)) - 1; + const ieee_sign = ((bits >> (mantissa_bits + exponent_bits)) & 1) != 0; + const ieee_mantissa = bits & ((@as(T, 1) << mantissa_bits) - 1); + const ieee_exponent: u32 = @intCast((bits >> mantissa_bits) & ((@as(T, 1) << exponent_bits) - 1)); + + if (ieee_exponent == 0 and ieee_mantissa == 0) { + return .{ + .mantissa = 0, + .exponent = 0, + .sign = ieee_sign, + }; + } + if (ieee_exponent == ((@as(u32, 1) << exponent_bits) - 1)) { + return .{ + .mantissa = if (explicit_leading_bit) ieee_mantissa & ((@as(T, 1) << (mantissa_bits - 1)) - 1) else ieee_mantissa, + .exponent = special_exponent, + .sign = ieee_sign, + }; + } + + var e2: i32 = undefined; + var m2: T = undefined; + if (explicit_leading_bit) { + if (ieee_exponent == 0) { + e2 = 1 - cast_i32(bias) - cast_i32(mantissa_bits) + 1 - 2; + } else { + e2 = cast_i32(ieee_exponent) - cast_i32(bias) - cast_i32(mantissa_bits) + 1 - 2; + } + m2 = ieee_mantissa; + } else { + if (ieee_exponent == 0) { + e2 = 1 - cast_i32(bias) - cast_i32(mantissa_bits) - 2; + m2 = ieee_mantissa; + } else { + e2 = cast_i32(ieee_exponent) - cast_i32(bias) - cast_i32(mantissa_bits) - 2; + m2 = (@as(T, 1) << mantissa_bits) | ieee_mantissa; + } + } + const even = (m2 & 1) == 0; + const accept_bounds = even; + + // Step 2: Determine the interval of legal decimal representations. + const mv = 4 * m2; + const mm_shift: u1 = @intFromBool((ieee_mantissa != if (explicit_leading_bit) (@as(T, 1) << (mantissa_bits - 1)) else 0) or (ieee_exponent == 0)); + + // Step 3: Convert to a decimal power base using 128-bit arithmetic. + var vr: T = undefined; + var vp: T = undefined; + var vm: T = undefined; + var e10: i32 = undefined; + var vm_is_trailing_zeros = false; + var vr_is_trailing_zeros = false; + if (e2 >= 0) { + const q: u32 = log10Pow2(@intCast(e2)) - @intFromBool(e2 > 3); + e10 = cast_i32(q); + const k: i32 = @intCast(tables.POW5_INV_BITCOUNT + pow5Bits(q) - 1); + const i: u32 = @intCast(-e2 + cast_i32(q) + k); + + const pow5 = tables.computeInvPow5(q); + vr = tables.mulShift(4 * m2, &pow5, i); + vp = tables.mulShift(4 * m2 + 2, &pow5, i); + vm = tables.mulShift(4 * m2 - 1 - mm_shift, &pow5, i); + + if (q <= tables.bound1) { + if (mv % 5 == 0) { + vr_is_trailing_zeros = multipleOfPowerOf5(mv, if (tables.adjust_q) q -% 1 else q); + } else if (accept_bounds) { + vm_is_trailing_zeros = multipleOfPowerOf5(mv - 1 - mm_shift, q); + } else { + vp -= @intFromBool(multipleOfPowerOf5(mv + 2, q)); + } + } + } else { + const q: u32 = log10Pow5(@intCast(-e2)) - @intFromBool(-e2 > 1); + e10 = cast_i32(q) + e2; + const i: i32 = -e2 - cast_i32(q); + const k: i32 = cast_i32(pow5Bits(@intCast(i))) - tables.POW5_BITCOUNT; + const j: u32 = @intCast(cast_i32(q) - k); + + const pow5 = tables.computePow5(@intCast(i)); + vr = tables.mulShift(4 * m2, &pow5, j); + vp = tables.mulShift(4 * m2 + 2, &pow5, j); + vm = tables.mulShift(4 * m2 - 1 - mm_shift, &pow5, j); + + if (q <= 1) { + vr_is_trailing_zeros = true; + if (accept_bounds) { + vm_is_trailing_zeros = mm_shift == 1; + } else { + vp -= 1; + } + } else if (q < tables.bound2) { + vr_is_trailing_zeros = multipleOfPowerOf2(mv, if (tables.adjust_q) q - 1 else q); + } + } + + // Step 4: Find the shortest decimal representation in the interval of legal representations. + var removed: u32 = 0; + var last_removed_digit: u8 = 0; + + while (vp / 10 > vm / 10) { + vm_is_trailing_zeros = vm_is_trailing_zeros and vm % 10 == 0; + vr_is_trailing_zeros = vr_is_trailing_zeros and last_removed_digit == 0; + last_removed_digit = @intCast(vr % 10); + vr /= 10; + vp /= 10; + vm /= 10; + removed += 1; + } + + if (vm_is_trailing_zeros) { + while (vm % 10 == 0) { + vr_is_trailing_zeros = vr_is_trailing_zeros and last_removed_digit == 0; + last_removed_digit = @intCast(vr % 10); + vr /= 10; + vp /= 10; + vm /= 10; + removed += 1; + } + } + + if (vr_is_trailing_zeros and (last_removed_digit == 5) and (vr % 2 == 0)) { + last_removed_digit = 4; + } + + return .{ + .mantissa = vr + @intFromBool((vr == vm and (!accept_bounds or !vm_is_trailing_zeros)) or last_removed_digit >= 5), + .exponent = e10 + cast_i32(removed), + .sign = ieee_sign, + }; +} + +fn decimalLength(v: anytype) u32 { + switch (@TypeOf(v)) { + u32, u64 => { + std.debug.assert(v < 100000000000000000); + if (v >= 10000000000000000) return 17; + if (v >= 1000000000000000) return 16; + if (v >= 100000000000000) return 15; + if (v >= 10000000000000) return 14; + if (v >= 1000000000000) return 13; + if (v >= 100000000000) return 12; + if (v >= 10000000000) return 11; + if (v >= 1000000000) return 10; + if (v >= 100000000) return 9; + if (v >= 10000000) return 8; + if (v >= 1000000) return 7; + if (v >= 100000) return 6; + if (v >= 10000) return 5; + if (v >= 1000) return 4; + if (v >= 100) return 3; + if (v >= 10) return 2; + return 1; + }, + u128 => { + const LARGEST_POW10 = (@as(u128, 5421010862427522170) << 64) | 687399551400673280; + var p10 = LARGEST_POW10; + var i: u32 = 39; + while (i > 0) : (i -= 1) { + if (v >= p10) return i; + p10 /= 10; + } + return 1; + }, + else => unreachable, + } +} + +// floor(log_10(2^e)) +fn log10Pow2(e: u32) u32 { + std.debug.assert(e <= 1 << 15); + return @intCast((@as(u64, @intCast(e)) * 169464822037455) >> 49); +} + +// floor(log_10(5^e)) +fn log10Pow5(e: u32) u32 { + std.debug.assert(e <= 1 << 15); + return @intCast((@as(u64, @intCast(e)) * 196742565691928) >> 48); +} + +// if (e == 0) 1 else ceil(log_2(5^e)) +fn pow5Bits(e: u32) u32 { + std.debug.assert(e <= 1 << 15); + return @intCast(((@as(u64, @intCast(e)) * 163391164108059) >> 46) + 1); +} + +fn pow5Factor(value_: anytype) u32 { + var count: u32 = 0; + var value = value_; + while (value > 0) : ({ + count += 1; + value /= 5; + }) { + if (value % 5 != 0) return count; + } + return 0; +} + +fn multipleOfPowerOf5(value: anytype, p: u32) bool { + const T = @TypeOf(value); + std.debug.assert(@typeInfo(T) == .int); + return pow5Factor(value) >= p; +} + +fn multipleOfPowerOf2(value: anytype, p: u32) bool { + const T = @TypeOf(value); + std.debug.assert(@typeInfo(T) == .int); + return (value & ((@as(T, 1) << @as(std.math.Log2Int(T), @intCast(p))) - 1)) == 0; +} + +fn mulShift128(m: u128, mul: *const [4]u64, j: u32) u128 { + std.debug.assert(j > 128); + const a: [2]u64 = .{ @truncate(m), @truncate(m >> 64) }; + const r = mul_128_256_shift(&a, mul, j, 0); + return (@as(u128, r[1]) << 64) | r[0]; +} + +fn mul_128_256_shift(a: *const [2]u64, b: *const [4]u64, shift: u32, corr: u32) [4]u64 { + std.debug.assert(shift > 0); + std.debug.assert(shift < 256); + + const b00 = @as(u128, a[0]) * b[0]; + const b01 = @as(u128, a[0]) * b[1]; + const b02 = @as(u128, a[0]) * b[2]; + const b03 = @as(u128, a[0]) * b[3]; + const b10 = @as(u128, a[1]) * b[0]; + const b11 = @as(u128, a[1]) * b[1]; + const b12 = @as(u128, a[1]) * b[2]; + const b13 = @as(u128, a[1]) * b[3]; + + const s0 = b00; + const s1 = b01 +% b10; + const c1: u128 = @intFromBool(s1 < b01); + const s2 = b02 +% b11; + const c2: u128 = @intFromBool(s2 < b02); + const s3 = b03 +% b12; + const c3: u128 = @intFromBool(s3 < b03); + + const p0 = s0 +% (s1 << 64); + const d0: u128 = @intFromBool(p0 < b00); + const q1 = s2 +% (s1 >> 64) +% (s3 << 64); + const d1: u128 = @intFromBool(q1 < s2); + const p1 = q1 +% (c1 << 64) +% d0; + const d2: u128 = @intFromBool(p1 < q1); + const p2 = b13 +% (s3 >> 64) +% c2 +% (c3 << 64) +% d1 +% d2; + + var r0: u128 = undefined; + var r1: u128 = undefined; + if (shift < 128) { + const cshift: u7 = @intCast(shift); + const sshift: u7 = @intCast(128 - shift); + r0 = corr +% ((p0 >> cshift) | (p1 << sshift)); + r1 = ((p1 >> cshift) | (p2 << sshift)) +% @intFromBool(r0 < corr); + } else if (shift == 128) { + r0 = corr +% p1; + r1 = p2 +% @intFromBool(r0 < corr); + } else { + const ashift: u7 = @intCast(shift - 128); + const sshift: u7 = @intCast(256 - shift); + r0 = corr +% ((p1 >> ashift) | (p2 << sshift)); + r1 = (p2 >> ashift) +% @intFromBool(r0 < corr); + } + + return .{ @truncate(r0), @truncate(r0 >> 64), @truncate(r1), @truncate(r1 >> 64) }; +} + +pub const Backend128_Tables = struct { + const T = u128; + const mulShift = mulShift128; + const POW5_INV_BITCOUNT = FLOAT128_POW5_INV_BITCOUNT; + const POW5_BITCOUNT = FLOAT128_POW5_BITCOUNT; + + const bound1 = 55; + const bound2 = 127; + const adjust_q = true; + + fn computePow5(i: u32) [4]u64 { + const base = i / FLOAT128_POW5_TABLE_SIZE; + const base2 = base * FLOAT128_POW5_TABLE_SIZE; + const mul = &FLOAT128_POW5_SPLIT[base]; + if (i == base2) { + return mul.*; + } else { + const offset = i - base2; + const m = &FLOAT128_POW5_TABLE[offset]; + const delta = pow5Bits(i) - pow5Bits(base2); + + const shift: u6 = @intCast(2 * (i % 32)); + const corr: u32 = @intCast((FLOAT128_POW5_ERRORS[i / 32] >> shift) & 3); + return mul_128_256_shift(m, mul, delta, corr); + } + } + + fn computeInvPow5(i: u32) [4]u64 { + const base = (i + FLOAT128_POW5_TABLE_SIZE - 1) / FLOAT128_POW5_TABLE_SIZE; + const base2 = base * FLOAT128_POW5_TABLE_SIZE; + const mul = &FLOAT128_POW5_INV_SPLIT[base]; // 1 / 5^base2 + if (i == base2) { + return .{ mul[0] + 1, mul[1], mul[2], mul[3] }; + } else { + const offset = base2 - i; + const m = &FLOAT128_POW5_TABLE[offset]; // 5^offset + const delta = pow5Bits(base2) - pow5Bits(i); + + const shift: u6 = @intCast(2 * (i % 32)); + const corr: u32 = @intCast(((FLOAT128_POW5_INV_ERRORS[i / 32] >> shift) & 3) + 1); + return mul_128_256_shift(m, mul, delta, corr); + } + } +}; + +fn mulShift64(m: u64, mul: *const [2]u64, j: u32) u64 { + std.debug.assert(j > 64); + const b0 = @as(u128, m) * mul[0]; + const b2 = @as(u128, m) * mul[1]; + + if (j < 128) { + const shift: u6 = @intCast(j - 64); + return @intCast(((b0 >> 64) + b2) >> shift); + } else { + return 0; + } +} + +pub const Backend64_TablesFull = struct { + const T = u64; + const mulShift = mulShift64; + const POW5_INV_BITCOUNT = FLOAT64_POW5_INV_BITCOUNT; + const POW5_BITCOUNT = FLOAT64_POW5_BITCOUNT; + + const bound1 = 21; + const bound2 = 63; + const adjust_q = false; + + fn computePow5(i: u32) [2]u64 { + return FLOAT64_POW5_SPLIT[i]; + } + + fn computeInvPow5(i: u32) [2]u64 { + return FLOAT64_POW5_INV_SPLIT[i]; + } +}; + +pub const Backend64_TablesSmall = struct { + const T = u64; + const mulShift = mulShift64; + const POW5_INV_BITCOUNT = FLOAT64_POW5_INV_BITCOUNT; + const POW5_BITCOUNT = FLOAT64_POW5_BITCOUNT; + + const bound1 = 21; + const bound2 = 63; + const adjust_q = false; + + fn computePow5(i: u32) [2]u64 { + const base = i / FLOAT64_POW5_TABLE_SIZE; + const base2 = base * FLOAT64_POW5_TABLE_SIZE; + const mul = &FLOAT64_POW5_SPLIT2[base]; + if (i == base2) { + return .{ mul[0], mul[1] }; + } else { + const offset = i - base2; + const m = FLOAT64_POW5_TABLE[offset]; + const b0 = @as(u128, m) * mul[0]; + const b2 = @as(u128, m) * mul[1]; + const delta: u7 = @intCast(pow5Bits(i) - pow5Bits(base2)); + const shift: u5 = @intCast((i % 16) << 1); + const shifted_sum = ((b0 >> delta) + (b2 << (64 - delta))) + 1 + ((FLOAT64_POW5_OFFSETS[i / 16] >> shift) & 3); + return .{ @truncate(shifted_sum), @truncate(shifted_sum >> 64) }; + } + } + + fn computeInvPow5(i: u32) [2]u64 { + const base = (i + FLOAT64_POW5_TABLE_SIZE - 1) / FLOAT64_POW5_TABLE_SIZE; + const base2 = base * FLOAT64_POW5_TABLE_SIZE; + const mul = &FLOAT64_POW5_INV_SPLIT2[base]; // 1 / 5^base2 + if (i == base2) { + return .{ mul[0], mul[1] }; + } else { + const offset = base2 - i; + const m = FLOAT64_POW5_TABLE[offset]; // 5^offset + const b0 = @as(u128, m) * (mul[0] - 1); + const b2 = @as(u128, m) * mul[1]; // 1/5^base2 * 5^offset = 1/5^(base2-offset) = 1/5^i + const delta: u7 = @intCast(pow5Bits(base2) - pow5Bits(i)); + const shift: u5 = @intCast((i % 16) << 1); + const shifted_sum = ((b0 >> delta) + (b2 << (64 - delta))) + 1 + ((FLOAT64_POW5_INV_OFFSETS[i / 16] >> shift) & 3); + return .{ @truncate(shifted_sum), @truncate(shifted_sum >> 64) }; + } + } +}; + +const FLOAT64_POW5_INV_BITCOUNT = 125; +const FLOAT64_POW5_BITCOUNT = 125; + +// zig fmt: off +// +// f64 small tables: 816 bytes + +const FLOAT64_POW5_TABLE_SIZE: comptime_int = FLOAT64_POW5_TABLE.len; + +const FLOAT64_POW5_TABLE: [26]u64 = .{ + 1, 5, + 25, 125, + 625, 3125, + 15625, 78125, + 390625, 1953125, + 9765625, 48828125, + 244140625, 1220703125, + 6103515625, 30517578125, + 152587890625, 762939453125, + 3814697265625, 19073486328125, + 95367431640625, 476837158203125, + 2384185791015625, 11920928955078125, + 59604644775390625, 298023223876953125, +}; + +const FLOAT64_POW5_SPLIT2: [13][2]u64 = .{ + .{ 0, 1152921504606846976 }, + .{ 0, 1490116119384765625 }, + .{ 1032610780636961552, 1925929944387235853 }, + .{ 7910200175544436838, 1244603055572228341 }, + .{ 16941905809032713930, 1608611746708759036 }, + .{ 13024893955298202172, 2079081953128979843 }, + .{ 6607496772837067824, 1343575221513417750 }, + .{ 17332926989895652603, 1736530273035216783 }, + .{ 13037379183483547984, 2244412773384604712 }, + .{ 1605989338741628675, 1450417759929778918 }, + .{ 9630225068416591280, 1874621017369538693 }, + .{ 665883850346957067, 1211445438634777304 }, + .{ 14931890668723713708, 1565756531257009982 } +}; + +const FLOAT64_POW5_OFFSETS: [21]u32 = .{ + 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x40000000, 0x59695995, 0x55545555, 0x56555515, + 0x41150504, 0x40555410, 0x44555145, 0x44504540, + 0x45555550, 0x40004000, 0x96440440, 0x55565565, + 0x54454045, 0x40154151, 0x55559155, 0x51405555, + 0x00000105, +}; + +const FLOAT64_POW5_INV_SPLIT2: [15][2]u64 = .{ + .{ 1, 2305843009213693952 }, + .{ 5955668970331000884, 1784059615882449851 }, + .{ 8982663654677661702, 1380349269358112757 }, + .{ 7286864317269821294, 2135987035920910082 }, + .{ 7005857020398200553, 1652639921975621497 }, + .{ 17965325103354776697, 1278668206209430417 }, + .{ 8928596168509315048, 1978643211784836272 }, + .{ 10075671573058298858, 1530901034580419511 }, + .{ 597001226353042382, 1184477304306571148 }, + .{ 1527430471115325346, 1832889850782397517 }, + .{ 12533209867169019542, 1418129833677084982 }, + .{ 5577825024675947042, 2194449627517475473 }, + .{ 11006974540203867551, 1697873161311732311 }, + .{ 10313493231639821582, 1313665730009899186 }, + .{ 12701016819766672773, 2032799256770390445 } +}; + +const FLOAT64_POW5_INV_OFFSETS: [19]u32 = .{ + 0x54544554, 0x04055545, 0x10041000, 0x00400414, + 0x40010000, 0x41155555, 0x00000454, 0x00010044, + 0x40000000, 0x44000041, 0x50454450, 0x55550054, + 0x51655554, 0x40004000, 0x01000001, 0x00010500, + 0x51515411, 0x05555554, 0x00000000, +}; + + +// zig fmt: off + +// f64 full tables: 10688 bytes + +const FLOAT64_POW5_SPLIT: [326][2]u64 = .{ + .{ 0, 1152921504606846976 }, .{ 0, 1441151880758558720 }, + .{ 0, 1801439850948198400 }, .{ 0, 2251799813685248000 }, + .{ 0, 1407374883553280000 }, .{ 0, 1759218604441600000 }, + .{ 0, 2199023255552000000 }, .{ 0, 1374389534720000000 }, + .{ 0, 1717986918400000000 }, .{ 0, 2147483648000000000 }, + .{ 0, 1342177280000000000 }, .{ 0, 1677721600000000000 }, + .{ 0, 2097152000000000000 }, .{ 0, 1310720000000000000 }, + .{ 0, 1638400000000000000 }, .{ 0, 2048000000000000000 }, + .{ 0, 1280000000000000000 }, .{ 0, 1600000000000000000 }, + .{ 0, 2000000000000000000 }, .{ 0, 1250000000000000000 }, + .{ 0, 1562500000000000000 }, .{ 0, 1953125000000000000 }, + .{ 0, 1220703125000000000 }, .{ 0, 1525878906250000000 }, + .{ 0, 1907348632812500000 }, .{ 0, 1192092895507812500 }, + .{ 0, 1490116119384765625 }, .{ 4611686018427387904, 1862645149230957031 }, + .{ 9799832789158199296, 1164153218269348144 }, .{ 12249790986447749120, 1455191522836685180 }, + .{ 15312238733059686400, 1818989403545856475 }, .{ 14528612397897220096, 2273736754432320594 }, + .{ 13692068767113150464, 1421085471520200371 }, .{ 12503399940464050176, 1776356839400250464 }, + .{ 15629249925580062720, 2220446049250313080 }, .{ 9768281203487539200, 1387778780781445675 }, + .{ 7598665485932036096, 1734723475976807094 }, .{ 274959820560269312, 2168404344971008868 }, + .{ 9395221924704944128, 1355252715606880542 }, .{ 2520655369026404352, 1694065894508600678 }, + .{ 12374191248137781248, 2117582368135750847 }, .{ 14651398557727195136, 1323488980084844279 }, + .{ 13702562178731606016, 1654361225106055349 }, .{ 3293144668132343808, 2067951531382569187 }, + .{ 18199116482078572544, 1292469707114105741 }, .{ 8913837547316051968, 1615587133892632177 }, + .{ 15753982952572452864, 2019483917365790221 }, .{ 12152082354571476992, 1262177448353618888 }, + .{ 15190102943214346240, 1577721810442023610 }, .{ 9764256642163156992, 1972152263052529513 }, + .{ 17631875447420442880, 1232595164407830945 }, .{ 8204786253993389888, 1540743955509788682 }, + .{ 1032610780636961552, 1925929944387235853 }, .{ 2951224747111794922, 1203706215242022408 }, + .{ 3689030933889743652, 1504632769052528010 }, .{ 13834660704216955373, 1880790961315660012 }, + .{ 17870034976990372916, 1175494350822287507 }, .{ 17725857702810578241, 1469367938527859384 }, + .{ 3710578054803671186, 1836709923159824231 }, .{ 26536550077201078, 2295887403949780289 }, + .{ 11545800389866720434, 1434929627468612680 }, .{ 14432250487333400542, 1793662034335765850 }, + .{ 8816941072311974870, 2242077542919707313 }, .{ 17039803216263454053, 1401298464324817070 }, + .{ 12076381983474541759, 1751623080406021338 }, .{ 5872105442488401391, 2189528850507526673 }, + .{ 15199280947623720629, 1368455531567204170 }, .{ 9775729147674874978, 1710569414459005213 }, + .{ 16831347453020981627, 2138211768073756516 }, .{ 1296220121283337709, 1336382355046097823 }, + .{ 15455333206886335848, 1670477943807622278 }, .{ 10095794471753144002, 2088097429759527848 }, + .{ 6309871544845715001, 1305060893599704905 }, .{ 12499025449484531656, 1631326116999631131 }, + .{ 11012095793428276666, 2039157646249538914 }, .{ 11494245889320060820, 1274473528905961821 }, + .{ 532749306367912313, 1593091911132452277 }, .{ 5277622651387278295, 1991364888915565346 }, + .{ 7910200175544436838, 1244603055572228341 }, .{ 14499436237857933952, 1555753819465285426 }, + .{ 8900923260467641632, 1944692274331606783 }, .{ 12480606065433357876, 1215432671457254239 }, + .{ 10989071563364309441, 1519290839321567799 }, .{ 9124653435777998898, 1899113549151959749 }, + .{ 8008751406574943263, 1186945968219974843 }, .{ 5399253239791291175, 1483682460274968554 }, + .{ 15972438586593889776, 1854603075343710692 }, .{ 759402079766405302, 1159126922089819183 }, + .{ 14784310654990170340, 1448908652612273978 }, .{ 9257016281882937117, 1811135815765342473 }, + .{ 16182956370781059300, 2263919769706678091 }, .{ 7808504722524468110, 1414949856066673807 }, + .{ 5148944884728197234, 1768687320083342259 }, .{ 1824495087482858639, 2210859150104177824 }, + .{ 1140309429676786649, 1381786968815111140 }, .{ 1425386787095983311, 1727233711018888925 }, + .{ 6393419502297367043, 2159042138773611156 }, .{ 13219259225790630210, 1349401336733506972 }, + .{ 16524074032238287762, 1686751670916883715 }, .{ 16043406521870471799, 2108439588646104644 }, + .{ 803757039314269066, 1317774742903815403 }, .{ 14839754354425000045, 1647218428629769253 }, + .{ 4714634887749086344, 2059023035787211567 }, .{ 9864175832484260821, 1286889397367007229 }, + .{ 16941905809032713930, 1608611746708759036 }, .{ 2730638187581340797, 2010764683385948796 }, + .{ 10930020904093113806, 1256727927116217997 }, .{ 18274212148543780162, 1570909908895272496 }, + .{ 4396021111970173586, 1963637386119090621 }, .{ 5053356204195052443, 1227273366324431638 }, + .{ 15540067292098591362, 1534091707905539547 }, .{ 14813398096695851299, 1917614634881924434 }, + .{ 13870059828862294966, 1198509146801202771 }, .{ 12725888767650480803, 1498136433501503464 }, + .{ 15907360959563101004, 1872670541876879330 }, .{ 14553786618154326031, 1170419088673049581 }, + .{ 4357175217410743827, 1463023860841311977 }, .{ 10058155040190817688, 1828779826051639971 }, + .{ 7961007781811134206, 2285974782564549964 }, .{ 14199001900486734687, 1428734239102843727 }, + .{ 13137066357181030455, 1785917798878554659 }, .{ 11809646928048900164, 2232397248598193324 }, + .{ 16604401366885338411, 1395248280373870827 }, .{ 16143815690179285109, 1744060350467338534 }, + .{ 10956397575869330579, 2180075438084173168 }, .{ 6847748484918331612, 1362547148802608230 }, + .{ 17783057643002690323, 1703183936003260287 }, .{ 17617136035325974999, 2128979920004075359 }, + .{ 17928239049719816230, 1330612450002547099 }, .{ 17798612793722382384, 1663265562503183874 }, + .{ 13024893955298202172, 2079081953128979843 }, .{ 5834715712847682405, 1299426220705612402 }, + .{ 16516766677914378815, 1624282775882015502 }, .{ 11422586310538197711, 2030353469852519378 }, + .{ 11750802462513761473, 1268970918657824611 }, .{ 10076817059714813937, 1586213648322280764 }, + .{ 12596021324643517422, 1982767060402850955 }, .{ 5566670318688504437, 1239229412751781847 }, + .{ 2346651879933242642, 1549036765939727309 }, .{ 7545000868343941206, 1936295957424659136 }, + .{ 4715625542714963254, 1210184973390411960 }, .{ 5894531928393704067, 1512731216738014950 }, + .{ 16591536947346905892, 1890914020922518687 }, .{ 17287239619732898039, 1181821263076574179 }, + .{ 16997363506238734644, 1477276578845717724 }, .{ 2799960309088866689, 1846595723557147156 }, + .{ 10973347230035317489, 1154122327223216972 }, .{ 13716684037544146861, 1442652909029021215 }, + .{ 12534169028502795672, 1803316136286276519 }, .{ 11056025267201106687, 2254145170357845649 }, + .{ 18439230838069161439, 1408840731473653530 }, .{ 13825666510731675991, 1761050914342066913 }, + .{ 3447025083132431277, 2201313642927583642 }, .{ 6766076695385157452, 1375821026829739776 }, + .{ 8457595869231446815, 1719776283537174720 }, .{ 10571994836539308519, 2149720354421468400 }, + .{ 6607496772837067824, 1343575221513417750 }, .{ 17482743002901110588, 1679469026891772187 }, + .{ 17241742735199000331, 2099336283614715234 }, .{ 15387775227926763111, 1312085177259197021 }, + .{ 5399660979626290177, 1640106471573996277 }, .{ 11361262242960250625, 2050133089467495346 }, + .{ 11712474920277544544, 1281333180917184591 }, .{ 10028907631919542777, 1601666476146480739 }, + .{ 7924448521472040567, 2002083095183100924 }, .{ 14176152362774801162, 1251301934489438077 }, + .{ 3885132398186337741, 1564127418111797597 }, .{ 9468101516160310080, 1955159272639746996 }, + .{ 15140935484454969608, 1221974545399841872 }, .{ 479425281859160394, 1527468181749802341 }, + .{ 5210967620751338397, 1909335227187252926 }, .{ 17091912818251750210, 1193334516992033078 }, + .{ 12141518985959911954, 1491668146240041348 }, .{ 15176898732449889943, 1864585182800051685 }, + .{ 11791404716994875166, 1165365739250032303 }, .{ 10127569877816206054, 1456707174062540379 }, + .{ 8047776328842869663, 1820883967578175474 }, .{ 836348374198811271, 2276104959472719343 }, + .{ 7440246761515338900, 1422565599670449589 }, .{ 13911994470321561530, 1778206999588061986 }, + .{ 8166621051047176104, 2222758749485077483 }, .{ 2798295147690791113, 1389224218428173427 }, + .{ 17332926989895652603, 1736530273035216783 }, .{ 17054472718942177850, 2170662841294020979 }, + .{ 8353202440125167204, 1356664275808763112 }, .{ 10441503050156459005, 1695830344760953890 }, + .{ 3828506775840797949, 2119787930951192363 }, .{ 86973725686804766, 1324867456844495227 }, + .{ 13943775212390669669, 1656084321055619033 }, .{ 3594660960206173375, 2070105401319523792 }, + .{ 2246663100128858359, 1293815875824702370 }, .{ 12031700912015848757, 1617269844780877962 }, + .{ 5816254103165035138, 2021587305976097453 }, .{ 5941001823691840913, 1263492066235060908 }, + .{ 7426252279614801142, 1579365082793826135 }, .{ 4671129331091113523, 1974206353492282669 }, + .{ 5225298841145639904, 1233878970932676668 }, .{ 6531623551432049880, 1542348713665845835 }, + .{ 3552843420862674446, 1927935892082307294 }, .{ 16055585193321335241, 1204959932551442058 }, + .{ 10846109454796893243, 1506199915689302573 }, .{ 18169322836923504458, 1882749894611628216 }, + .{ 11355826773077190286, 1176718684132267635 }, .{ 9583097447919099954, 1470898355165334544 }, + .{ 11978871809898874942, 1838622943956668180 }, .{ 14973589762373593678, 2298278679945835225 }, + .{ 2440964573842414192, 1436424174966147016 }, .{ 3051205717303017741, 1795530218707683770 }, + .{ 13037379183483547984, 2244412773384604712 }, .{ 8148361989677217490, 1402757983365377945 }, + .{ 14797138505523909766, 1753447479206722431 }, .{ 13884737113477499304, 2191809349008403039 }, + .{ 15595489723564518921, 1369880843130251899 }, .{ 14882676136028260747, 1712351053912814874 }, + .{ 9379973133180550126, 2140438817391018593 }, .{ 17391698254306313589, 1337774260869386620 }, + .{ 3292878744173340370, 1672217826086733276 }, .{ 4116098430216675462, 2090272282608416595 }, + .{ 266718509671728212, 1306420176630260372 }, .{ 333398137089660265, 1633025220787825465 }, + .{ 5028433689789463235, 2041281525984781831 }, .{ 10060300083759496378, 1275800953740488644 }, + .{ 12575375104699370472, 1594751192175610805 }, .{ 1884160825592049379, 1993438990219513507 }, + .{ 17318501580490888525, 1245899368887195941 }, .{ 7813068920331446945, 1557374211108994927 }, + .{ 5154650131986920777, 1946717763886243659 }, .{ 915813323278131534, 1216698602428902287 }, + .{ 14979824709379828129, 1520873253036127858 }, .{ 9501408849870009354, 1901091566295159823 }, + .{ 12855909558809837702, 1188182228934474889 }, .{ 2234828893230133415, 1485227786168093612 }, + .{ 2793536116537666769, 1856534732710117015 }, .{ 8663489100477123587, 1160334207943823134 }, + .{ 1605989338741628675, 1450417759929778918 }, .{ 11230858710281811652, 1813022199912223647 }, + .{ 9426887369424876662, 2266277749890279559 }, .{ 12809333633531629769, 1416423593681424724 }, + .{ 16011667041914537212, 1770529492101780905 }, .{ 6179525747111007803, 2213161865127226132 }, + .{ 13085575628799155685, 1383226165704516332 }, .{ 16356969535998944606, 1729032707130645415 }, + .{ 15834525901571292854, 2161290883913306769 }, .{ 2979049660840976177, 1350806802445816731 }, + .{ 17558870131333383934, 1688508503057270913 }, .{ 8113529608884566205, 2110635628821588642 }, + .{ 9682642023980241782, 1319147268013492901 }, .{ 16714988548402690132, 1648934085016866126 }, + .{ 11670363648648586857, 2061167606271082658 }, .{ 11905663298832754689, 1288229753919426661 }, + .{ 1047021068258779650, 1610287192399283327 }, .{ 15143834390605638274, 2012858990499104158 }, + .{ 4853210475701136017, 1258036869061940099 }, .{ 1454827076199032118, 1572546086327425124 }, + .{ 1818533845248790147, 1965682607909281405 }, .{ 3442426662494187794, 1228551629943300878 }, + .{ 13526405364972510550, 1535689537429126097 }, .{ 3072948650933474476, 1919611921786407622 }, + .{ 15755650962115585259, 1199757451116504763 }, .{ 15082877684217093670, 1499696813895630954 }, + .{ 9630225068416591280, 1874621017369538693 }, .{ 8324733676974063502, 1171638135855961683 }, + .{ 5794231077790191473, 1464547669819952104 }, .{ 7242788847237739342, 1830684587274940130 }, + .{ 18276858095901949986, 2288355734093675162 }, .{ 16034722328366106645, 1430222333808546976 }, + .{ 1596658836748081690, 1787777917260683721 }, .{ 6607509564362490017, 2234722396575854651 }, + .{ 1823850468512862308, 1396701497859909157 }, .{ 6891499104068465790, 1745876872324886446 }, + .{ 17837745916940358045, 2182346090406108057 }, .{ 4231062170446641922, 1363966306503817536 }, + .{ 5288827713058302403, 1704957883129771920 }, .{ 6611034641322878003, 2131197353912214900 }, + .{ 13355268687681574560, 1331998346195134312 }, .{ 16694085859601968200, 1664997932743917890 }, + .{ 11644235287647684442, 2081247415929897363 }, .{ 4971804045566108824, 1300779634956185852 }, + .{ 6214755056957636030, 1625974543695232315 }, .{ 3156757802769657134, 2032468179619040394 }, + .{ 6584659645158423613, 1270292612261900246 }, .{ 17454196593302805324, 1587865765327375307 }, + .{ 17206059723201118751, 1984832206659219134 }, .{ 6142101308573311315, 1240520129162011959 }, + .{ 3065940617289251240, 1550650161452514949 }, .{ 8444111790038951954, 1938312701815643686 }, + .{ 665883850346957067, 1211445438634777304 }, .{ 832354812933696334, 1514306798293471630 }, + .{ 10263815553021896226, 1892883497866839537 }, .{ 17944099766707154901, 1183052186166774710 }, + .{ 13206752671529167818, 1478815232708468388 }, .{ 16508440839411459773, 1848519040885585485 }, + .{ 12623618533845856310, 1155324400553490928 }, .{ 15779523167307320387, 1444155500691863660 }, + .{ 1277659885424598868, 1805194375864829576 }, .{ 1597074856780748586, 2256492969831036970 }, + .{ 5609857803915355770, 1410308106144398106 }, .{ 16235694291748970521, 1762885132680497632 }, + .{ 1847873790976661535, 2203606415850622041 }, .{ 12684136165428883219, 1377254009906638775 }, + .{ 11243484188358716120, 1721567512383298469 }, .{ 219297180166231438, 2151959390479123087 }, + .{ 7054589765244976505, 1344974619049451929 }, .{ 13429923224983608535, 1681218273811814911 }, + .{ 12175718012802122765, 2101522842264768639 }, .{ 14527352785642408584, 1313451776415480399 }, + .{ 13547504963625622826, 1641814720519350499 }, .{ 12322695186104640628, 2052268400649188124 }, + .{ 16925056528170176201, 1282667750405742577 }, .{ 7321262604930556539, 1603334688007178222 }, + .{ 18374950293017971482, 2004168360008972777 }, .{ 4566814905495150320, 1252605225005607986 }, + .{ 14931890668723713708, 1565756531257009982 }, .{ 9441491299049866327, 1957195664071262478 }, + .{ 1289246043478778550, 1223247290044539049 }, .{ 6223243572775861092, 1529059112555673811 }, + .{ 3167368447542438461, 1911323890694592264 }, .{ 1979605279714024038, 1194577431684120165 }, + .{ 7086192618069917952, 1493221789605150206 }, .{ 18081112809442173248, 1866527237006437757 }, + .{ 13606538515115052232, 1166579523129023598 }, .{ 7784801107039039482, 1458224403911279498 }, + .{ 507629346944023544, 1822780504889099373 }, .{ 5246222702107417334, 2278475631111374216 }, + .{ 3278889188817135834, 1424047269444608885 }, .{ 8710297504448807696, 1780059086805761106 } +}; + +const FLOAT64_POW5_INV_SPLIT: [342][2]u64 = .{ + .{ 1, 2305843009213693952 }, .{ 11068046444225730970, 1844674407370955161 }, + .{ 5165088340638674453, 1475739525896764129 }, .{ 7821419487252849886, 1180591620717411303 }, + .{ 8824922364862649494, 1888946593147858085 }, .{ 7059937891890119595, 1511157274518286468 }, + .{ 13026647942995916322, 1208925819614629174 }, .{ 9774590264567735146, 1934281311383406679 }, + .{ 11509021026396098440, 1547425049106725343 }, .{ 16585914450600699399, 1237940039285380274 }, + .{ 15469416676735388068, 1980704062856608439 }, .{ 16064882156130220778, 1584563250285286751 }, + .{ 9162556910162266299, 1267650600228229401 }, .{ 7281393426775805432, 2028240960365167042 }, + .{ 16893161185646375315, 1622592768292133633 }, .{ 2446482504291369283, 1298074214633706907 }, + .{ 7603720821608101175, 2076918743413931051 }, .{ 2393627842544570617, 1661534994731144841 }, + .{ 16672297533003297786, 1329227995784915872 }, .{ 11918280793837635165, 2126764793255865396 }, + .{ 5845275820328197809, 1701411834604692317 }, .{ 15744267100488289217, 1361129467683753853 }, + .{ 3054734472329800808, 2177807148294006166 }, .{ 17201182836831481939, 1742245718635204932 }, + .{ 6382248639981364905, 1393796574908163946 }, .{ 2832900194486363201, 2230074519853062314 }, + .{ 5955668970331000884, 1784059615882449851 }, .{ 1075186361522890384, 1427247692705959881 }, + .{ 12788344622662355584, 2283596308329535809 }, .{ 13920024512871794791, 1826877046663628647 }, + .{ 3757321980813615186, 1461501637330902918 }, .{ 10384555214134712795, 1169201309864722334 }, + .{ 5547241898389809503, 1870722095783555735 }, .{ 4437793518711847602, 1496577676626844588 }, + .{ 10928932444453298728, 1197262141301475670 }, .{ 17486291911125277965, 1915619426082361072 }, + .{ 6610335899416401726, 1532495540865888858 }, .{ 12666966349016942027, 1225996432692711086 }, + .{ 12888448528943286597, 1961594292308337738 }, .{ 17689456452638449924, 1569275433846670190 }, + .{ 14151565162110759939, 1255420347077336152 }, .{ 7885109000409574610, 2008672555323737844 }, + .{ 9997436015069570011, 1606938044258990275 }, .{ 7997948812055656009, 1285550435407192220 }, + .{ 12796718099289049614, 2056880696651507552 }, .{ 2858676849947419045, 1645504557321206042 }, + .{ 13354987924183666206, 1316403645856964833 }, .{ 17678631863951955605, 2106245833371143733 }, + .{ 3074859046935833515, 1684996666696914987 }, .{ 13527933681774397782, 1347997333357531989 }, + .{ 10576647446613305481, 2156795733372051183 }, .{ 15840015586774465031, 1725436586697640946 }, + .{ 8982663654677661702, 1380349269358112757 }, .{ 18061610662226169046, 2208558830972980411 }, + .{ 10759939715039024913, 1766847064778384329 }, .{ 12297300586773130254, 1413477651822707463 }, + .{ 15986332124095098083, 2261564242916331941 }, .{ 9099716884534168143, 1809251394333065553 }, + .{ 14658471137111155161, 1447401115466452442 }, .{ 4348079280205103483, 1157920892373161954 }, + .{ 14335624477811986218, 1852673427797059126 }, .{ 7779150767507678651, 1482138742237647301 }, + .{ 2533971799264232598, 1185710993790117841 }, .{ 15122401323048503126, 1897137590064188545 }, + .{ 12097921058438802501, 1517710072051350836 }, .{ 5988988032009131678, 1214168057641080669 }, + .{ 16961078480698431330, 1942668892225729070 }, .{ 13568862784558745064, 1554135113780583256 }, + .{ 7165741412905085728, 1243308091024466605 }, .{ 11465186260648137165, 1989292945639146568 }, + .{ 16550846638002330379, 1591434356511317254 }, .{ 16930026125143774626, 1273147485209053803 }, + .{ 4951948911778577463, 2037035976334486086 }, .{ 272210314680951647, 1629628781067588869 }, + .{ 3907117066486671641, 1303703024854071095 }, .{ 6251387306378674625, 2085924839766513752 }, + .{ 16069156289328670670, 1668739871813211001 }, .{ 9165976216721026213, 1334991897450568801 }, + .{ 7286864317269821294, 2135987035920910082 }, .{ 16897537898041588005, 1708789628736728065 }, + .{ 13518030318433270404, 1367031702989382452 }, .{ 6871453250525591353, 2187250724783011924 }, + .{ 9186511415162383406, 1749800579826409539 }, .{ 11038557946871817048, 1399840463861127631 }, + .{ 10282995085511086630, 2239744742177804210 }, .{ 8226396068408869304, 1791795793742243368 }, + .{ 13959814484210916090, 1433436634993794694 }, .{ 11267656730511734774, 2293498615990071511 }, + .{ 5324776569667477496, 1834798892792057209 }, .{ 7949170070475892320, 1467839114233645767 }, + .{ 17427382500606444826, 1174271291386916613 }, .{ 5747719112518849781, 1878834066219066582 }, + .{ 15666221734240810795, 1503067252975253265 }, .{ 12532977387392648636, 1202453802380202612 }, + .{ 5295368560860596524, 1923926083808324180 }, .{ 4236294848688477220, 1539140867046659344 }, + .{ 7078384693692692099, 1231312693637327475 }, .{ 11325415509908307358, 1970100309819723960 }, + .{ 9060332407926645887, 1576080247855779168 }, .{ 14626963555825137356, 1260864198284623334 }, + .{ 12335095245094488799, 2017382717255397335 }, .{ 9868076196075591040, 1613906173804317868 }, + .{ 15273158586344293478, 1291124939043454294 }, .{ 13369007293925138595, 2065799902469526871 }, + .{ 7005857020398200553, 1652639921975621497 }, .{ 16672732060544291412, 1322111937580497197 }, + .{ 11918976037903224966, 2115379100128795516 }, .{ 5845832015580669650, 1692303280103036413 }, + .{ 12055363241948356366, 1353842624082429130 }, .{ 841837113407818570, 2166148198531886609 }, + .{ 4362818505468165179, 1732918558825509287 }, .{ 14558301248600263113, 1386334847060407429 }, + .{ 12225235553534690011, 2218135755296651887 }, .{ 2401490813343931363, 1774508604237321510 }, + .{ 1921192650675145090, 1419606883389857208 }, .{ 17831303500047873437, 2271371013423771532 }, + .{ 6886345170554478103, 1817096810739017226 }, .{ 1819727321701672159, 1453677448591213781 }, + .{ 16213177116328979020, 1162941958872971024 }, .{ 14873036941900635463, 1860707134196753639 }, + .{ 15587778368262418694, 1488565707357402911 }, .{ 8780873879868024632, 1190852565885922329 }, + .{ 2981351763563108441, 1905364105417475727 }, .{ 13453127855076217722, 1524291284333980581 }, + .{ 7073153469319063855, 1219433027467184465 }, .{ 11317045550910502167, 1951092843947495144 }, + .{ 12742985255470312057, 1560874275157996115 }, .{ 10194388204376249646, 1248699420126396892 }, + .{ 1553625868034358140, 1997919072202235028 }, .{ 8621598323911307159, 1598335257761788022 }, + .{ 17965325103354776697, 1278668206209430417 }, .{ 13987124906400001422, 2045869129935088668 }, + .{ 121653480894270168, 1636695303948070935 }, .{ 97322784715416134, 1309356243158456748 }, + .{ 14913111714512307107, 2094969989053530796 }, .{ 8241140556867935363, 1675975991242824637 }, + .{ 17660958889720079260, 1340780792994259709 }, .{ 17189487779326395846, 2145249268790815535 }, + .{ 13751590223461116677, 1716199415032652428 }, .{ 18379969808252713988, 1372959532026121942 }, + .{ 14650556434236701088, 2196735251241795108 }, .{ 652398703163629901, 1757388200993436087 }, + .{ 11589965406756634890, 1405910560794748869 }, .{ 7475898206584884855, 2249456897271598191 }, + .{ 2291369750525997561, 1799565517817278553 }, .{ 9211793429904618695, 1439652414253822842 }, + .{ 18428218302589300235, 2303443862806116547 }, .{ 7363877012587619542, 1842755090244893238 }, + .{ 13269799239553916280, 1474204072195914590 }, .{ 10615839391643133024, 1179363257756731672 }, + .{ 2227947767661371545, 1886981212410770676 }, .{ 16539753473096738529, 1509584969928616540 }, + .{ 13231802778477390823, 1207667975942893232 }, .{ 6413489186596184024, 1932268761508629172 }, + .{ 16198837793502678189, 1545815009206903337 }, .{ 5580372605318321905, 1236652007365522670 }, + .{ 8928596168509315048, 1978643211784836272 }, .{ 18210923379033183008, 1582914569427869017 }, + .{ 7190041073742725760, 1266331655542295214 }, .{ 436019273762630246, 2026130648867672343 }, + .{ 7727513048493924843, 1620904519094137874 }, .{ 9871359253537050198, 1296723615275310299 }, + .{ 4726128361433549347, 2074757784440496479 }, .{ 7470251503888749801, 1659806227552397183 }, + .{ 13354898832594820487, 1327844982041917746 }, .{ 13989140502667892133, 2124551971267068394 }, + .{ 14880661216876224029, 1699641577013654715 }, .{ 11904528973500979224, 1359713261610923772 }, + .{ 4289851098633925465, 2175541218577478036 }, .{ 18189276137874781665, 1740432974861982428 }, + .{ 3483374466074094362, 1392346379889585943 }, .{ 1884050330976640656, 2227754207823337509 }, + .{ 5196589079523222848, 1782203366258670007 }, .{ 15225317707844309248, 1425762693006936005 }, + .{ 5913764258841343181, 2281220308811097609 }, .{ 8420360221814984868, 1824976247048878087 }, + .{ 17804334621677718864, 1459980997639102469 }, .{ 17932816512084085415, 1167984798111281975 }, + .{ 10245762345624985047, 1868775676978051161 }, .{ 4507261061758077715, 1495020541582440929 }, + .{ 7295157664148372495, 1196016433265952743 }, .{ 7982903447895485668, 1913626293225524389 }, + .{ 10075671573058298858, 1530901034580419511 }, .{ 4371188443704728763, 1224720827664335609 }, + .{ 14372599139411386667, 1959553324262936974 }, .{ 15187428126271019657, 1567642659410349579 }, + .{ 15839291315758726049, 1254114127528279663 }, .{ 3206773216762499739, 2006582604045247462 }, + .{ 13633465017635730761, 1605266083236197969 }, .{ 14596120828850494932, 1284212866588958375 }, + .{ 4907049252451240275, 2054740586542333401 }, .{ 236290587219081897, 1643792469233866721 }, + .{ 14946427728742906810, 1315033975387093376 }, .{ 16535586736504830250, 2104054360619349402 }, + .{ 5849771759720043554, 1683243488495479522 }, .{ 15747863852001765813, 1346594790796383617 }, + .{ 10439186904235184007, 2154551665274213788 }, .{ 15730047152871967852, 1723641332219371030 }, + .{ 12584037722297574282, 1378913065775496824 }, .{ 9066413911450387881, 2206260905240794919 }, + .{ 10942479943902220628, 1765008724192635935 }, .{ 8753983955121776503, 1412006979354108748 }, + .{ 10317025513452932081, 2259211166966573997 }, .{ 874922781278525018, 1807368933573259198 }, + .{ 8078635854506640661, 1445895146858607358 }, .{ 13841606313089133175, 1156716117486885886 }, + .{ 14767872471458792434, 1850745787979017418 }, .{ 746251532941302978, 1480596630383213935 }, + .{ 597001226353042382, 1184477304306571148 }, .{ 15712597221132509104, 1895163686890513836 }, + .{ 8880728962164096960, 1516130949512411069 }, .{ 10793931984473187891, 1212904759609928855 }, + .{ 17270291175157100626, 1940647615375886168 }, .{ 2748186495899949531, 1552518092300708935 }, + .{ 2198549196719959625, 1242014473840567148 }, .{ 18275073973719576693, 1987223158144907436 }, + .{ 10930710364233751031, 1589778526515925949 }, .{ 12433917106128911148, 1271822821212740759 }, + .{ 8826220925580526867, 2034916513940385215 }, .{ 7060976740464421494, 1627933211152308172 }, + .{ 16716827836597268165, 1302346568921846537 }, .{ 11989529279587987770, 2083754510274954460 }, + .{ 9591623423670390216, 1667003608219963568 }, .{ 15051996368420132820, 1333602886575970854 }, + .{ 13015147745246481542, 2133764618521553367 }, .{ 3033420566713364587, 1707011694817242694 }, + .{ 6116085268112601993, 1365609355853794155 }, .{ 9785736428980163188, 2184974969366070648 }, + .{ 15207286772667951197, 1747979975492856518 }, .{ 1097782973908629988, 1398383980394285215 }, + .{ 1756452758253807981, 2237414368630856344 }, .{ 5094511021344956708, 1789931494904685075 }, + .{ 4075608817075965366, 1431945195923748060 }, .{ 6520974107321544586, 2291112313477996896 }, + .{ 1527430471115325346, 1832889850782397517 }, .{ 12289990821117991246, 1466311880625918013 }, + .{ 17210690286378213644, 1173049504500734410 }, .{ 9090360384495590213, 1876879207201175057 }, + .{ 18340334751822203140, 1501503365760940045 }, .{ 14672267801457762512, 1201202692608752036 }, + .{ 16096930852848599373, 1921924308174003258 }, .{ 1809498238053148529, 1537539446539202607 }, + .{ 12515645034668249793, 1230031557231362085 }, .{ 1578287981759648052, 1968050491570179337 }, + .{ 12330676829633449412, 1574440393256143469 }, .{ 13553890278448669853, 1259552314604914775 }, + .{ 3239480371808320148, 2015283703367863641 }, .{ 17348979556414297411, 1612226962694290912 }, + .{ 6500486015647617283, 1289781570155432730 }, .{ 10400777625036187652, 2063650512248692368 }, + .{ 15699319729512770768, 1650920409798953894 }, .{ 16248804598352126938, 1320736327839163115 }, + .{ 7551343283653851484, 2113178124542660985 }, .{ 6041074626923081187, 1690542499634128788 }, + .{ 12211557331022285596, 1352433999707303030 }, .{ 1091747655926105338, 2163894399531684849 }, + .{ 4562746939482794594, 1731115519625347879 }, .{ 7339546366328145998, 1384892415700278303 }, + .{ 8053925371383123274, 2215827865120445285 }, .{ 6443140297106498619, 1772662292096356228 }, + .{ 12533209867169019542, 1418129833677084982 }, .{ 5295740528502789974, 2269007733883335972 }, + .{ 15304638867027962949, 1815206187106668777 }, .{ 4865013464138549713, 1452164949685335022 }, + .{ 14960057215536570740, 1161731959748268017 }, .{ 9178696285890871890, 1858771135597228828 }, + .{ 14721654658196518159, 1487016908477783062 }, .{ 4398626097073393881, 1189613526782226450 }, + .{ 7037801755317430209, 1903381642851562320 }, .{ 5630241404253944167, 1522705314281249856 }, + .{ 814844308661245011, 1218164251424999885 }, .{ 1303750893857992017, 1949062802279999816 }, + .{ 15800395974054034906, 1559250241823999852 }, .{ 5261619149759407279, 1247400193459199882 }, + .{ 12107939454356961969, 1995840309534719811 }, .{ 5997002748743659252, 1596672247627775849 }, + .{ 8486951013736837725, 1277337798102220679 }, .{ 2511075177753209390, 2043740476963553087 }, + .{ 13076906586428298482, 1634992381570842469 }, .{ 14150874083884549109, 1307993905256673975 }, + .{ 4194654460505726958, 2092790248410678361 }, .{ 18113118827372222859, 1674232198728542688 }, + .{ 3422448617672047318, 1339385758982834151 }, .{ 16543964232501006678, 2143017214372534641 }, + .{ 9545822571258895019, 1714413771498027713 }, .{ 15015355686490936662, 1371531017198422170 }, + .{ 5577825024675947042, 2194449627517475473 }, .{ 11840957649224578280, 1755559702013980378 }, + .{ 16851463748863483271, 1404447761611184302 }, .{ 12204946739213931940, 2247116418577894884 }, + .{ 13453306206113055875, 1797693134862315907 }, .{ 3383947335406624054, 1438154507889852726 }, + .{ 16482362180876329456, 2301047212623764361 }, .{ 9496540929959153242, 1840837770099011489 }, + .{ 11286581558709232917, 1472670216079209191 }, .{ 5339916432225476010, 1178136172863367353 }, + .{ 4854517476818851293, 1885017876581387765 }, .{ 3883613981455081034, 1508014301265110212 }, + .{ 14174937629389795797, 1206411441012088169 }, .{ 11611853762797942306, 1930258305619341071 }, + .{ 5600134195496443521, 1544206644495472857 }, .{ 15548153800622885787, 1235365315596378285 }, + .{ 6430302007287065643, 1976584504954205257 }, .{ 16212288050055383484, 1581267603963364205 }, + .{ 12969830440044306787, 1265014083170691364 }, .{ 9683682259845159889, 2024022533073106183 }, + .{ 15125643437359948558, 1619218026458484946 }, .{ 8411165935146048523, 1295374421166787957 }, + .{ 17147214310975587960, 2072599073866860731 }, .{ 10028422634038560045, 1658079259093488585 }, + .{ 8022738107230848036, 1326463407274790868 }, .{ 9147032156827446534, 2122341451639665389 }, + .{ 11006974540203867551, 1697873161311732311 }, .{ 5116230817421183718, 1358298529049385849 }, + .{ 15564666937357714594, 2173277646479017358 }, .{ 1383687105660440706, 1738622117183213887 }, + .{ 12174996128754083534, 1390897693746571109 }, .{ 8411947361780802685, 2225436309994513775 }, + .{ 6729557889424642148, 1780349047995611020 }, .{ 5383646311539713719, 1424279238396488816 }, + .{ 1235136468979721303, 2278846781434382106 }, .{ 15745504434151418335, 1823077425147505684 }, + .{ 16285752362063044992, 1458461940118004547 }, .{ 5649904260166615347, 1166769552094403638 }, + .{ 5350498001524674232, 1866831283351045821 }, .{ 591049586477829062, 1493465026680836657 }, + .{ 11540886113407994219, 1194772021344669325 }, .{ 18673707743239135, 1911635234151470921 }, + .{ 14772334225162232601, 1529308187321176736 }, .{ 8128518565387875758, 1223446549856941389 }, + .{ 1937583260394870242, 1957514479771106223 }, .{ 8928764237799716840, 1566011583816884978 }, + .{ 14521709019723594119, 1252809267053507982 }, .{ 8477339172590109297, 2004494827285612772 }, + .{ 17849917782297818407, 1603595861828490217 }, .{ 6901236596354434079, 1282876689462792174 }, + .{ 18420676183650915173, 2052602703140467478 }, .{ 3668494502695001169, 1642082162512373983 }, + .{ 10313493231639821582, 1313665730009899186 }, .{ 9122891541139893884, 2101865168015838698 }, + .{ 14677010862395735754, 1681492134412670958 }, .{ 673562245690857633, 1345193707530136767 } +}; + +// zig fmt: off +// +// f128 small tables: 9072 bytes + +const FLOAT128_POW5_INV_BITCOUNT = 249; +const FLOAT128_POW5_BITCOUNT = 249; +const FLOAT128_POW5_TABLE_SIZE: comptime_int = FLOAT128_POW5_TABLE.len; + +const FLOAT128_POW5_TABLE: [56][2]u64 = .{ + .{ 1, 0 }, + .{ 5, 0 }, + .{ 25, 0 }, + .{ 125, 0 }, + .{ 625, 0 }, + .{ 3125, 0 }, + .{ 15625, 0 }, + .{ 78125, 0 }, + .{ 390625, 0 }, + .{ 1953125, 0 }, + .{ 9765625, 0 }, + .{ 48828125, 0 }, + .{ 244140625, 0 }, + .{ 1220703125, 0 }, + .{ 6103515625, 0 }, + .{ 30517578125, 0 }, + .{ 152587890625, 0 }, + .{ 762939453125, 0 }, + .{ 3814697265625, 0 }, + .{ 19073486328125, 0 }, + .{ 95367431640625, 0 }, + .{ 476837158203125, 0 }, + .{ 2384185791015625, 0 }, + .{ 11920928955078125, 0 }, + .{ 59604644775390625, 0 }, + .{ 298023223876953125, 0 }, + .{ 1490116119384765625, 0 }, + .{ 7450580596923828125, 0 }, + .{ 359414837200037393, 2 }, + .{ 1797074186000186965, 10 }, + .{ 8985370930000934825, 50 }, + .{ 8033366502585570893, 252 }, + .{ 3273344365508751233, 1262 }, + .{ 16366721827543756165, 6310 }, + .{ 8046632842880574361, 31554 }, + .{ 3339676066983768573, 157772 }, + .{ 16698380334918842865, 788860 }, + .{ 9704925379756007861, 3944304 }, + .{ 11631138751360936073, 19721522 }, + .{ 2815461535676025517, 98607613 }, + .{ 14077307678380127585, 493038065 }, + .{ 15046306170771983077, 2465190328 }, + .{ 1444554559021708921, 12325951644 }, + .{ 7222772795108544605, 61629758220 }, + .{ 17667119901833171409, 308148791101 }, + .{ 14548623214327650581, 1540743955509 }, + .{ 17402883850509598057, 7703719777548 }, + .{ 13227442957709783821, 38518598887744 }, + .{ 10796982567420264257, 192592994438723 }, + .{ 17091424689682218053, 962964972193617 }, + .{ 11670147153572883801, 4814824860968089 }, + .{ 3010503546735764157, 24074124304840448 }, + .{ 15052517733678820785, 120370621524202240 }, + .{ 1475612373555897461, 601853107621011204 }, + .{ 7378061867779487305, 3009265538105056020 }, + .{ 18443565265187884909, 15046327690525280101 }, +}; + +const FLOAT128_POW5_SPLIT: [89][4]u64 = .{ + .{ 0, 0, 0, 72057594037927936 }, + .{ 0, 5206161169240293376, 4575641699882439235, 73468396926392969 }, + .{ 3360510775605221349, 6983200512169538081, 4325643253124434363, 74906821675075173 }, + .{ 11917660854915489451, 9652941469841108803, 946308467778435600, 76373409087490117 }, + .{ 1994853395185689235, 16102657350889591545, 6847013871814915412, 77868710555449746 }, + .{ 958415760277438274, 15059347134713823592, 7329070255463483331, 79393288266368765 }, + .{ 2065144883315240188, 7145278325844925976, 14718454754511147343, 80947715414629833 }, + .{ 8980391188862868935, 13709057401304208685, 8230434828742694591, 82532576417087045 }, + .{ 432148644612782575, 7960151582448466064, 12056089168559840552, 84148467132788711 }, + .{ 484109300864744403, 15010663910730448582, 16824949663447227068, 85795995087002057 }, + .{ 14793711725276144220, 16494403799991899904, 10145107106505865967, 87475779699624060 }, + .{ 15427548291869817042, 12330588654550505203, 13980791795114552342, 89188452518064298 }, + .{ 9979404135116626552, 13477446383271537499, 14459862802511591337, 90934657454687378 }, + .{ 12385121150303452775, 9097130814231585614, 6523855782339765207, 92715051028904201 }, + .{ 1822931022538209743, 16062974719797586441, 3619180286173516788, 94530302614003091 }, + .{ 12318611738248470829, 13330752208259324507, 10986694768744162601, 96381094688813589 }, + .{ 13684493829640282333, 7674802078297225834, 15208116197624593182, 98268123094297527 }, + .{ 5408877057066295332, 6470124174091971006, 15112713923117703147, 100192097295163851 }, + .{ 11407083166564425062, 18189998238742408185, 4337638702446708282, 102153740646605557 }, + .{ 4112405898036935485, 924624216579956435, 14251108172073737125, 104153790666259019 }, + .{ 16996739107011444789, 10015944118339042475, 2395188869672266257, 106192999311487969 }, + .{ 4588314690421337879, 5339991768263654604, 15441007590670620066, 108272133262096356 }, + .{ 2286159977890359825, 14329706763185060248, 5980012964059367667, 110391974208576409 }, + .{ 9654767503237031099, 11293544302844823188, 11739932712678287805, 112553319146000238 }, + .{ 11362964448496095896, 7990659682315657680, 251480263940996374, 114756980673665505 }, + .{ 1423410421096377129, 14274395557581462179, 16553482793602208894, 117003787300607788 }, + .{ 2070444190619093137, 11517140404712147401, 11657844572835578076, 119294583757094535 }, + .{ 7648316884775828921, 15264332483297977688, 247182277434709002, 121630231312217685 }, + .{ 17410896758132241352, 10923914482914417070, 13976383996795783649, 124011608097704390 }, + .{ 9542674537907272703, 3079432708831728956, 14235189590642919676, 126439609438067572 }, + .{ 10364666969937261816, 8464573184892924210, 12758646866025101190, 128915148187220428 }, + .{ 14720354822146013883, 11480204489231511423, 7449876034836187038, 131439155071681461 }, + .{ 1692907053653558553, 17835392458598425233, 1754856712536736598, 134012579040499057 }, + .{ 5620591334531458755, 11361776175667106627, 13350215315297937856, 136636387622027174 }, + .{ 17455759733928092601, 10362573084069962561, 11246018728801810510, 139311567287686283 }, + .{ 2465404073814044982, 17694822665274381860, 1509954037718722697, 142039123822846312 }, + .{ 2152236053329638369, 11202280800589637091, 16388426812920420176, 72410041352485523 }, + .{ 17319024055671609028, 10944982848661280484, 2457150158022562661, 73827744744583080 }, + .{ 17511219308535248024, 5122059497846768077, 2089605804219668451, 75273205100637900 }, + .{ 10082673333144031533, 14429008783411894887, 12842832230171903890, 76746965869337783 }, + .{ 16196653406315961184, 10260180891682904501, 10537411930446752461, 78249581139456266 }, + .{ 15084422041749743389, 234835370106753111, 16662517110286225617, 79781615848172976 }, + .{ 8199644021067702606, 3787318116274991885, 7438130039325743106, 81343645993472659 }, + .{ 12039493937039359765, 9773822153580393709, 5945428874398357806, 82936258850702722 }, + .{ 984543865091303961, 7975107621689454830, 6556665988501773347, 84560053193370726 }, + .{ 9633317878125234244, 16099592426808915028, 9706674539190598200, 86215639518264828 }, + .{ 6860695058870476186, 4471839111886709592, 7828342285492709568, 87903640274981819 }, + .{ 14583324717644598331, 4496120889473451238, 5290040788305728466, 89624690099949049 }, + .{ 18093669366515003715, 12879506572606942994, 18005739787089675377, 91379436055028227 }, + .{ 17997493966862379937, 14646222655265145582, 10265023312844161858, 93168537870790806 }, + .{ 12283848109039722318, 11290258077250314935, 9878160025624946825, 94992668194556404 }, + .{ 8087752761883078164, 5262596608437575693, 11093553063763274413, 96852512843287537 }, + .{ 15027787746776840781, 12250273651168257752, 9290470558712181914, 98748771061435726 }, + .{ 15003915578366724489, 2937334162439764327, 5404085603526796602, 100682155783835929 }, + .{ 5225610465224746757, 14932114897406142027, 2774647558180708010, 102653393903748137 }, + .{ 17112957703385190360, 12069082008339002412, 3901112447086388439, 104663226546146909 }, + .{ 4062324464323300238, 3992768146772240329, 15757196565593695724, 106712409346361594 }, + .{ 5525364615810306701, 11855206026704935156, 11344868740897365300, 108801712734172003 }, + .{ 9274143661888462646, 4478365862348432381, 18010077872551661771, 110931922223466333 }, + .{ 12604141221930060148, 8930937759942591500, 9382183116147201338, 113103838707570263 }, + .{ 14513929377491886653, 1410646149696279084, 587092196850797612, 115318278760358235 }, + .{ 2226851524999454362, 7717102471110805679, 7187441550995571734, 117576074943260147 }, + .{ 5527526061344932763, 2347100676188369132, 16976241418824030445, 119878076118278875 }, + .{ 6088479778147221611, 17669593130014777580, 10991124207197663546, 122225147767136307 }, + .{ 11107734086759692041, 3391795220306863431, 17233960908859089158, 124618172316667879 }, + .{ 7913172514655155198, 17726879005381242552, 641069866244011540, 127058049470587962 }, + .{ 12596991768458713949, 15714785522479904446, 6035972567136116512, 129545696547750811 }, + .{ 16901996933781815980, 4275085211437148707, 14091642539965169063, 132082048827034281 }, + .{ 7524574627987869240, 15661204384239316051, 2444526454225712267, 134668059898975949 }, + .{ 8199251625090479942, 6803282222165044067, 16064817666437851504, 137304702024293857 }, + .{ 4453256673338111920, 15269922543084434181, 3139961729834750852, 139992966499426682 }, + .{ 15841763546372731299, 3013174075437671812, 4383755396295695606, 142733864029230733 }, + .{ 9771896230907310329, 4900659362437687569, 12386126719044266361, 72764212553486967 }, + .{ 9420455527449565190, 1859606122611023693, 6555040298902684281, 74188850200884818 }, + .{ 5146105983135678095, 2287300449992174951, 4325371679080264751, 75641380576797959 }, + .{ 11019359372592553360, 8422686425957443718, 7175176077944048210, 77122349788024458 }, + .{ 11005742969399620716, 4132174559240043701, 9372258443096612118, 78632314633490790 }, + .{ 8887589641394725840, 8029899502466543662, 14582206497241572853, 80171842813591127 }, + .{ 360247523705545899, 12568341805293354211, 14653258284762517866, 81741513143625247 }, + .{ 12314272731984275834, 4740745023227177044, 6141631472368337539, 83341915771415304 }, + .{ 441052047733984759, 7940090120939869826, 11750200619921094248, 84973652399183278 }, + .{ 3436657868127012749, 9187006432149937667, 16389726097323041290, 86637336509772529 }, + .{ 13490220260784534044, 15339072891382896702, 8846102360835316895, 88333593597298497 }, + .{ 4125672032094859833, 158347675704003277, 10592598512749774447, 90063061402315272 }, + .{ 12189928252974395775, 2386931199439295891, 7009030566469913276, 91826390151586454 }, + .{ 9256479608339282969, 2844900158963599229, 11148388908923225596, 93624242802550437 }, + .{ 11584393507658707408, 2863659090805147914, 9873421561981063551, 95457295292572042 }, + .{ 13984297296943171390, 1931468383973130608, 12905719743235082319, 97326236793074198 }, + .{ 5837045222254987499, 10213498696735864176, 14893951506257020749, 99231769968645227 }, +}; + +// Unfortunately, the results are sometimes off by one or two. We use an additional +// lookup table to store those cases and adjust the result. +const FLOAT128_POW5_ERRORS: [156]u64 = .{ + 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x9555596400000000, + 0x65a6569525565555, 0x4415551445449655, 0x5105015504144541, 0x65a69969a6965964, + 0x5054955969959656, 0x5105154515554145, 0x4055511051591555, 0x5500514455550115, + 0x0041140014145515, 0x1005440545511051, 0x0014405450411004, 0x0414440010500000, + 0x0044000440010040, 0x5551155000004001, 0x4554555454544114, 0x5150045544005441, + 0x0001111400054501, 0x6550955555554554, 0x1504159645559559, 0x4105055141454545, + 0x1411541410405454, 0x0415555044545555, 0x0014154115405550, 0x1540055040411445, + 0x0000000500000000, 0x5644000000000000, 0x1155555591596555, 0x0410440054569565, + 0x5145100010010005, 0x0555041405500150, 0x4141450455140450, 0x0000000144000140, + 0x5114004001105410, 0x4444100404005504, 0x0414014410001015, 0x5145055155555015, + 0x0141041444445540, 0x0000100451541414, 0x4105041104155550, 0x0500501150451145, + 0x1001050000004114, 0x5551504400141045, 0x5110545410151454, 0x0100001400004040, + 0x5040010111040000, 0x0140000150541100, 0x4400140400104110, 0x5011014405545004, + 0x0000000044155440, 0x0000000010000000, 0x1100401444440001, 0x0040401010055111, + 0x5155155551405454, 0x0444440015514411, 0x0054505054014101, 0x0451015441115511, + 0x1541411401140551, 0x4155104514445110, 0x4141145450145515, 0x5451445055155050, + 0x4400515554110054, 0x5111145104501151, 0x565a655455500501, 0x5565555555525955, + 0x0550511500405695, 0x4415504051054544, 0x6555595965555554, 0x0100915915555655, + 0x5540001510001001, 0x5450051414000544, 0x1405010555555551, 0x5555515555644155, + 0x5555055595496555, 0x5451045004415000, 0x5450510144040144, 0x5554155555556455, + 0x5051555495415555, 0x5555554555555545, 0x0000000010005455, 0x4000005000040000, + 0x5565555555555954, 0x5554559555555505, 0x9645545495552555, 0x4000400055955564, + 0x0040000000000001, 0x4004100100000000, 0x5540040440000411, 0x4565555955545644, + 0x1140659549651556, 0x0100000410010000, 0x5555515400004001, 0x5955545555155255, + 0x5151055545505556, 0x5051454510554515, 0x0501500050415554, 0x5044154005441005, + 0x1455445450550455, 0x0010144055144545, 0x0000401100000004, 0x1050145050000010, + 0x0415004554011540, 0x1000510100151150, 0x0100040400001144, 0x0000000000000000, + 0x0550004400000100, 0x0151145041451151, 0x0000400400005450, 0x0000100044010004, + 0x0100054100050040, 0x0504400005410010, 0x4011410445500105, 0x0000404000144411, + 0x0101504404500000, 0x0000005044400400, 0x0000000014000100, 0x0404440414000000, + 0x5554100410000140, 0x4555455544505555, 0x5454105055455455, 0x0115454155454015, + 0x4404110000045100, 0x4400001100101501, 0x6596955956966a94, 0x0040655955665965, + 0x5554144400100155, 0xa549495401011041, 0x5596555565955555, 0x5569965959549555, + 0x969565a655555456, 0x0000001000000000, 0x0000000040000140, 0x0000040100000000, + 0x1415454400000000, 0x5410415411454114, 0x0400040104000154, 0x0504045000000411, + 0x0000001000000010, 0x5554000000001040, 0x5549155551556595, 0x1455541055515555, + 0x0510555454554541, 0x9555555555540455, 0x6455456555556465, 0x4524565555654514, + 0x5554655255559545, 0x9555455441155556, 0x0000000051515555, 0x0010005040000550, + 0x5044044040000000, 0x1045040440010500, 0x0000400000040000, 0x0000000000000000, +}; + +const FLOAT128_POW5_INV_SPLIT: [89][4]u64 = .{ + .{ 0, 0, 0, 144115188075855872 }, + .{ 1573859546583440065, 2691002611772552616, 6763753280790178510, 141347765182270746 }, + .{ 12960290449513840412, 12345512957918226762, 18057899791198622765, 138633484706040742 }, + .{ 7615871757716765416, 9507132263365501332, 4879801712092008245, 135971326161092377 }, + .{ 7869961150745287587, 5804035291554591636, 8883897266325833928, 133360288657597085 }, + .{ 2942118023529634767, 15128191429820565086, 10638459445243230718, 130799390525667397 }, + .{ 14188759758411913794, 5362791266439207815, 8068821289119264054, 128287668946279217 }, + .{ 7183196927902545212, 1952291723540117099, 12075928209936341512, 125824179589281448 }, + .{ 5672588001402349748, 17892323620748423487, 9874578446960390364, 123407996258356868 }, + .{ 4442590541217566325, 4558254706293456445, 10343828952663182727, 121038210542800766 }, + .{ 3005560928406962566, 2082271027139057888, 13961184524927245081, 118713931475986426 }, + .{ 13299058168408384786, 17834349496131278595, 9029906103900731664, 116434285200389047 }, + .{ 5414878118283973035, 13079825470227392078, 17897304791683760280, 114198414639042157 }, + .{ 14609755883382484834, 14991702445765844156, 3269802549772755411, 112005479173303009 }, + .{ 15967774957605076027, 2511532636717499923, 16221038267832563171, 109854654326805788 }, + .{ 9269330061621627145, 3332501053426257392, 16223281189403734630, 107745131455483836 }, + .{ 16739559299223642282, 1873986623300664530, 6546709159471442872, 105676117443544318 }, + .{ 17116435360051202055, 1359075105581853924, 2038341371621886470, 103646834405281051 }, + .{ 17144715798009627550, 3201623802661132408, 9757551605154622431, 101656519392613377 }, + .{ 17580479792687825857, 6546633380567327312, 15099972427870912398, 99704424108241124 }, + .{ 9726477118325522902, 14578369026754005435, 11728055595254428803, 97789814624307808 }, + .{ 134593949518343635, 5715151379816901985, 1660163707976377376, 95911971106466306 }, + .{ 5515914027713859358, 7124354893273815720, 5548463282858794077, 94070187543243255 }, + .{ 6188403395862945512, 5681264392632320838, 15417410852121406654, 92263771480600430 }, + .{ 15908890877468271457, 10398888261125597540, 4817794962769172309, 90492043761593298 }, + .{ 1413077535082201005, 12675058125384151580, 7731426132303759597, 88754338271028867 }, + .{ 1486733163972670293, 11369385300195092554, 11610016711694864110, 87050001685026843 }, + .{ 8788596583757589684, 3978580923851924802, 9255162428306775812, 85378393225389919 }, + .{ 7203518319660962120, 15044736224407683725, 2488132019818199792, 83738884418690858 }, + .{ 4004175967662388707, 18236988667757575407, 15613100370957482671, 82130858859985791 }, + .{ 18371903370586036463, 53497579022921640, 16465963977267203307, 80553711981064899 }, + .{ 10170778323887491315, 1999668801648976001, 10209763593579456445, 79006850823153334 }, + .{ 17108131712433974546, 16825784443029944237, 2078700786753338945, 77489693813976938 }, + .{ 17221789422665858532, 12145427517550446164, 5391414622238668005, 76001670549108934 }, + .{ 4859588996898795878, 1715798948121313204, 3950858167455137171, 74542221577515387 }, + .{ 13513469241795711526, 631367850494860526, 10517278915021816160, 73110798191218799 }, + .{ 11757513142672073111, 2581974932255022228, 17498959383193606459, 143413724438001539 }, + .{ 14524355192525042817, 5640643347559376447, 1309659274756813016, 140659771648132296 }, + .{ 2765095348461978538, 11021111021896007722, 3224303603779962366, 137958702611185230 }, + .{ 12373410389187981037, 13679193545685856195, 11644609038462631561, 135309501808182158 }, + .{ 12813176257562780151, 3754199046160268020, 9954691079802960722, 132711173221007413 }, + .{ 17557452279667723458, 3237799193992485824, 17893947919029030695, 130162739957935629 }, + .{ 14634200999559435155, 4123869946105211004, 6955301747350769239, 127663243886350468 }, + .{ 2185352760627740240, 2864813346878886844, 13049218671329690184, 125211745272516185 }, + .{ 6143438674322183002, 10464733336980678750, 6982925169933978309, 122807322428266620 }, + .{ 1099509117817174576, 10202656147550524081, 754997032816608484, 120449071364478757 }, + .{ 2410631293559367023, 17407273750261453804, 15307291918933463037, 118136105451200587 }, + .{ 12224968375134586697, 1664436604907828062, 11506086230137787358, 115867555084305488 }, + .{ 3495926216898000888, 18392536965197424288, 10992889188570643156, 113642567358547782 }, + .{ 8744506286256259680, 3966568369496879937, 18342264969761820037, 111460305746896569 }, + .{ 7689600520560455039, 5254331190877624630, 9628558080573245556, 109319949786027263 }, + .{ 11862637625618819436, 3456120362318976488, 14690471063106001082, 107220694767852583 }, + .{ 5697330450030126444, 12424082405392918899, 358204170751754904, 105161751436977040 }, + .{ 11257457505097373622, 15373192700214208870, 671619062372033814, 103142345693961148 }, + .{ 16850355018477166700, 1913910419361963966, 4550257919755970531, 101161718304283822 }, + .{ 9670835567561997011, 10584031339132130638, 3060560222974851757, 99219124612893520 }, + .{ 7698686577353054710, 11689292838639130817, 11806331021588878241, 97313834264240819 }, + .{ 12233569599615692137, 3347791226108469959, 10333904326094451110, 95445130927687169 }, + .{ 13049400362825383933, 17142621313007799680, 3790542585289224168, 93612312028186576 }, + .{ 12430457242474442072, 5625077542189557960, 14765055286236672238, 91814688482138969 }, + .{ 4759444137752473128, 2230562561567025078, 4954443037339580076, 90051584438315940 }, + .{ 7246913525170274758, 8910297835195760709, 4015904029508858381, 88322337023761438 }, + .{ 12854430245836432067, 8135139748065431455, 11548083631386317976, 86626296094571907 }, + .{ 4848827254502687803, 4789491250196085625, 3988192420450664125, 84962823991462151 }, + .{ 7435538409611286684, 904061756819742353, 14598026519493048444, 83331295300025028 }, + .{ 11042616160352530997, 8948390828345326218, 10052651191118271927, 81731096615594853 }, + .{ 11059348291563778943, 11696515766184685544, 3783210511290897367, 80161626312626082 }, + .{ 7020010856491885826, 5025093219346041680, 8960210401638911765, 78622294318500592 }, + .{ 17732844474490699984, 7820866704994446502, 6088373186798844243, 77112521891678506 }, + .{ 688278527545590501, 3045610706602776618, 8684243536999567610, 75631741404109150 }, + .{ 2734573255120657297, 3903146411440697663, 9470794821691856713, 74179396127820347 }, + .{ 15996457521023071259, 4776627823451271680, 12394856457265744744, 72754940025605801 }, + .{ 13492065758834518331, 7390517611012222399, 1630485387832860230, 142715675091463768 }, + .{ 13665021627282055864, 9897834675523659302, 17907668136755296849, 139975126841173266 }, + .{ 9603773719399446181, 10771916301484339398, 10672699855989487527, 137287204938390542 }, + .{ 3630218541553511265, 8139010004241080614, 2876479648932814543, 134650898807055963 }, + .{ 8318835909686377084, 9525369258927993371, 2796120270400437057, 132065217277054270 }, + .{ 11190003059043290163, 12424345635599592110, 12539346395388933763, 129529188211565064 }, + .{ 8701968833973242276, 820569587086330727, 2315591597351480110, 127041858141569228 }, + .{ 5115113890115690487, 16906305245394587826, 9899749468931071388, 124602291907373862 }, + .{ 15543535488939245974, 10945189844466391399, 3553863472349432246, 122209572307020975 }, + .{ 7709257252608325038, 1191832167690640880, 15077137020234258537, 119862799751447719 }, + .{ 7541333244210021737, 9790054727902174575, 5160944773155322014, 117561091926268545 }, + .{ 12297384708782857832, 1281328873123467374, 4827925254630475769, 115303583460052092 }, + .{ 13243237906232367265, 15873887428139547641, 3607993172301799599, 113089425598968120 }, + .{ 11384616453739611114, 15184114243769211033, 13148448124803481057, 110917785887682141 }, + .{ 17727970963596660683, 1196965221832671990, 14537830463956404138, 108787847856377790 }, + .{ 17241367586707330931, 8880584684128262874, 11173506540726547818, 106698810713789254 }, + .{ 7184427196661305643, 14332510582433188173, 14230167953789677901, 104649889046128358 }, +}; + +const FLOAT128_POW5_INV_ERRORS: [154]u64 = .{ + 0x1144155514145504, 0x0000541555401141, 0x0000000000000000, 0x0154454000000000, + 0x4114105515544440, 0x0001001111500415, 0x4041411410011000, 0x5550114515155014, + 0x1404100041554551, 0x0515000450404410, 0x5054544401140004, 0x5155501005555105, + 0x1144141000105515, 0x0541500000500000, 0x1104105540444140, 0x4000015055514110, + 0x0054010450004005, 0x4155515404100005, 0x5155145045155555, 0x1511555515440558, + 0x5558544555515555, 0x0000000000000010, 0x5004000000000050, 0x1415510100000010, + 0x4545555444514500, 0x5155151555555551, 0x1441540144044554, 0x5150104045544400, + 0x5450545401444040, 0x5554455045501400, 0x4655155555555145, 0x1000010055455055, + 0x1000004000055004, 0x4455405104000005, 0x4500114504150545, 0x0000000014000000, + 0x5450000000000000, 0x5514551511445555, 0x4111501040555451, 0x4515445500054444, + 0x5101500104100441, 0x1545115155545055, 0x0000000000000000, 0x1554000000100000, + 0x5555545595551555, 0x5555051851455955, 0x5555555555555559, 0x0000400011001555, + 0x0000004400040000, 0x5455511555554554, 0x5614555544115445, 0x6455156145555155, + 0x5455855455415455, 0x5515555144555545, 0x0114400000145155, 0x0000051000450511, + 0x4455154554445100, 0x4554150141544455, 0x65955555559a5965, 0x5555555854559559, + 0x9569654559616595, 0x1040044040005565, 0x1010010500011044, 0x1554015545154540, + 0x4440555401545441, 0x1014441450550105, 0x4545400410504145, 0x5015111541040151, + 0x5145051154000410, 0x1040001044545044, 0x4001400000151410, 0x0540000044040000, + 0x0510555454411544, 0x0400054054141550, 0x1001041145001100, 0x0000000140000000, + 0x0000000014100000, 0x1544005454000140, 0x4050055505445145, 0x0011511104504155, + 0x5505544415045055, 0x1155154445515554, 0x0000000000004555, 0x0000000000000000, + 0x5101010510400004, 0x1514045044440400, 0x5515519555515555, 0x4554545441555545, + 0x1551055955551515, 0x0150000011505515, 0x0044005040400000, 0x0004001004010050, + 0x0000051004450414, 0x0114001101001144, 0x0401000001000001, 0x4500010001000401, + 0x0004100000005000, 0x0105000441101100, 0x0455455550454540, 0x5404050144105505, + 0x4101510540555455, 0x1055541411451555, 0x5451445110115505, 0x1154110010101545, + 0x1145140450054055, 0x5555565415551554, 0x1550559555555555, 0x5555541545045141, + 0x4555455450500100, 0x5510454545554555, 0x1510140115045455, 0x1001050040111510, + 0x5555454555555504, 0x9954155545515554, 0x6596656555555555, 0x0140410051555559, + 0x0011104010001544, 0x965669659a680501, 0x5655a55955556955, 0x4015111014404514, + 0x1414155554505145, 0x0540040011051404, 0x1010000000015005, 0x0010054050004410, + 0x5041104014000100, 0x4440010500100001, 0x1155510504545554, 0x0450151545115541, + 0x4000100400110440, 0x1004440010514440, 0x0000115050450000, 0x0545404455541500, + 0x1051051555505101, 0x5505144554544144, 0x4550545555515550, 0x0015400450045445, + 0x4514155400554415, 0x4555055051050151, 0x1511441450001014, 0x4544554510404414, + 0x4115115545545450, 0x5500541555551555, 0x5550010544155015, 0x0144414045545500, + 0x4154050001050150, 0x5550511111000145, 0x1114504055000151, 0x5104041101451040, + 0x0010501401051441, 0x0010501450504401, 0x4554585440044444, 0x5155555951450455, + 0x0040000400105555, 0x0000000000000001, +}; + +// zig fmt: on + +const builtin = @import("builtin"); + +fn check(comptime T: type, value: T, comptime expected: []const u8) !void { + const I = @Type(.{ .int = .{ .signedness = .unsigned, .bits = @bitSizeOf(T) } }); + + var buf: [6000]u8 = undefined; + const value_bits: I = @bitCast(value); + const s = try render(&buf, value, .{}); + try std.testing.expectEqualStrings(expected, s); + + if (T == f80 and builtin.target.os.tag == .windows and builtin.target.cpu.arch == .x86_64) return; + + const o = try std.fmt.parseFloat(T, s); + const o_bits: I = @bitCast(o); + + if (std.math.isNan(value)) { + try std.testing.expect(std.math.isNan(o)); + } else { + try std.testing.expectEqual(value_bits, o_bits); + } +} + +test "format f32" { + try check(f32, 0.0, "0e0"); + try check(f32, -0.0, "-0e0"); + try check(f32, 1.0, "1e0"); + try check(f32, -1.0, "-1e0"); + try check(f32, std.math.nan(f32), "nan"); + try check(f32, std.math.inf(f32), "inf"); + try check(f32, -std.math.inf(f32), "-inf"); + try check(f32, 1.1754944e-38, "1.1754944e-38"); + try check(f32, @bitCast(@as(u32, 0x7f7fffff)), "3.4028235e38"); + try check(f32, @bitCast(@as(u32, 1)), "1e-45"); + try check(f32, 3.355445E7, "3.355445e7"); + try check(f32, 8.999999e9, "9e9"); + try check(f32, 3.4366717e10, "3.436672e10"); + try check(f32, 3.0540412e5, "3.0540412e5"); + try check(f32, 8.0990312e3, "8.0990312e3"); + try check(f32, 2.4414062e-4, "2.4414062e-4"); + try check(f32, 2.4414062e-3, "2.4414062e-3"); + try check(f32, 4.3945312e-3, "4.3945312e-3"); + try check(f32, 6.3476562e-3, "6.3476562e-3"); + try check(f32, 4.7223665e21, "4.7223665e21"); + try check(f32, 8388608.0, "8.388608e6"); + try check(f32, 1.6777216e7, "1.6777216e7"); + try check(f32, 3.3554436e7, "3.3554436e7"); + try check(f32, 6.7131496e7, "6.7131496e7"); + try check(f32, 1.9310392e-38, "1.9310392e-38"); + try check(f32, -2.47e-43, "-2.47e-43"); + try check(f32, 1.993244e-38, "1.993244e-38"); + try check(f32, 4103.9003, "4.1039004e3"); + try check(f32, 5.3399997e9, "5.3399997e9"); + try check(f32, 6.0898e-39, "6.0898e-39"); + try check(f32, 0.0010310042, "1.0310042e-3"); + try check(f32, 2.8823261e17, "2.882326e17"); + try check(f32, 7.038531e-26, "7.038531e-26"); + try check(f32, 9.2234038e17, "9.223404e17"); + try check(f32, 6.7108872e7, "6.710887e7"); + try check(f32, 1.0e-44, "1e-44"); + try check(f32, 2.816025e14, "2.816025e14"); + try check(f32, 9.223372e18, "9.223372e18"); + try check(f32, 1.5846085e29, "1.5846086e29"); + try check(f32, 1.1811161e19, "1.1811161e19"); + try check(f32, 5.368709e18, "5.368709e18"); + try check(f32, 4.6143165e18, "4.6143166e18"); + try check(f32, 0.007812537, "7.812537e-3"); + try check(f32, 1.4e-45, "1e-45"); + try check(f32, 1.18697724e20, "1.18697725e20"); + try check(f32, 1.00014165e-36, "1.00014165e-36"); + try check(f32, 200.0, "2e2"); + try check(f32, 3.3554432e7, "3.3554432e7"); + + try check(f32, 1.0, "1e0"); + try check(f32, 1.2, "1.2e0"); + try check(f32, 1.23, "1.23e0"); + try check(f32, 1.234, "1.234e0"); + try check(f32, 1.2345, "1.2345e0"); + try check(f32, 1.23456, "1.23456e0"); + try check(f32, 1.234567, "1.234567e0"); + try check(f32, 1.2345678, "1.2345678e0"); + try check(f32, 1.23456735e-36, "1.23456735e-36"); +} + +test "format f64" { + try check(f64, 0.0, "0e0"); + try check(f64, -0.0, "-0e0"); + try check(f64, 1.0, "1e0"); + try check(f64, -1.0, "-1e0"); + try check(f64, std.math.nan(f64), "nan"); + try check(f64, std.math.inf(f64), "inf"); + try check(f64, -std.math.inf(f64), "-inf"); + try check(f64, 2.2250738585072014e-308, "2.2250738585072014e-308"); + try check(f64, @bitCast(@as(u64, 0x7fefffffffffffff)), "1.7976931348623157e308"); + try check(f64, @bitCast(@as(u64, 1)), "5e-324"); + try check(f64, 2.98023223876953125e-8, "2.9802322387695312e-8"); + try check(f64, -2.109808898695963e16, "-2.109808898695963e16"); + try check(f64, 4.940656e-318, "4.940656e-318"); + try check(f64, 1.18575755e-316, "1.18575755e-316"); + try check(f64, 2.989102097996e-312, "2.989102097996e-312"); + try check(f64, 9.0608011534336e15, "9.0608011534336e15"); + try check(f64, 4.708356024711512e18, "4.708356024711512e18"); + try check(f64, 9.409340012568248e18, "9.409340012568248e18"); + try check(f64, 1.2345678, "1.2345678e0"); + try check(f64, @bitCast(@as(u64, 0x4830f0cf064dd592)), "5.764607523034235e39"); + try check(f64, @bitCast(@as(u64, 0x4840f0cf064dd592)), "1.152921504606847e40"); + try check(f64, @bitCast(@as(u64, 0x4850f0cf064dd592)), "2.305843009213694e40"); + + try check(f64, 1, "1e0"); + try check(f64, 1.2, "1.2e0"); + try check(f64, 1.23, "1.23e0"); + try check(f64, 1.234, "1.234e0"); + try check(f64, 1.2345, "1.2345e0"); + try check(f64, 1.23456, "1.23456e0"); + try check(f64, 1.234567, "1.234567e0"); + try check(f64, 1.2345678, "1.2345678e0"); + try check(f64, 1.23456789, "1.23456789e0"); + try check(f64, 1.234567895, "1.234567895e0"); + try check(f64, 1.2345678901, "1.2345678901e0"); + try check(f64, 1.23456789012, "1.23456789012e0"); + try check(f64, 1.234567890123, "1.234567890123e0"); + try check(f64, 1.2345678901234, "1.2345678901234e0"); + try check(f64, 1.23456789012345, "1.23456789012345e0"); + try check(f64, 1.234567890123456, "1.234567890123456e0"); + try check(f64, 1.2345678901234567, "1.2345678901234567e0"); + + try check(f64, 4.294967294, "4.294967294e0"); + try check(f64, 4.294967295, "4.294967295e0"); + try check(f64, 4.294967296, "4.294967296e0"); + try check(f64, 4.294967297, "4.294967297e0"); + try check(f64, 4.294967298, "4.294967298e0"); +} + +test "format f80" { + try check(f80, 0.0, "0e0"); + try check(f80, -0.0, "-0e0"); + try check(f80, 1.0, "1e0"); + try check(f80, -1.0, "-1e0"); + try check(f80, std.math.nan(f80), "nan"); + try check(f80, std.math.inf(f80), "inf"); + try check(f80, -std.math.inf(f80), "-inf"); + + try check(f80, 2.2250738585072014e-308, "2.2250738585072014e-308"); + try check(f80, 2.98023223876953125e-8, "2.98023223876953125e-8"); + try check(f80, -2.109808898695963e16, "-2.109808898695963e16"); + try check(f80, 4.940656e-318, "4.940656e-318"); + try check(f80, 1.18575755e-316, "1.18575755e-316"); + try check(f80, 2.989102097996e-312, "2.989102097996e-312"); + try check(f80, 9.0608011534336e15, "9.0608011534336e15"); + try check(f80, 4.708356024711512e18, "4.708356024711512e18"); + try check(f80, 9.409340012568248e18, "9.409340012568248e18"); + try check(f80, 1.2345678, "1.2345678e0"); +} + +test "format f128" { + try check(f128, 0.0, "0e0"); + try check(f128, -0.0, "-0e0"); + try check(f128, 1.0, "1e0"); + try check(f128, -1.0, "-1e0"); + try check(f128, std.math.nan(f128), "nan"); + try check(f128, std.math.inf(f128), "inf"); + try check(f128, -std.math.inf(f128), "-inf"); + + try check(f128, 2.2250738585072014e-308, "2.2250738585072014e-308"); + try check(f128, 2.98023223876953125e-8, "2.98023223876953125e-8"); + try check(f128, -2.109808898695963e16, "-2.109808898695963e16"); + try check(f128, 4.940656e-318, "4.940656e-318"); + try check(f128, 1.18575755e-316, "1.18575755e-316"); + try check(f128, 2.989102097996e-312, "2.989102097996e-312"); + try check(f128, 9.0608011534336e15, "9.0608011534336e15"); + try check(f128, 4.708356024711512e18, "4.708356024711512e18"); + try check(f128, 9.409340012568248e18, "9.409340012568248e18"); + try check(f128, 1.2345678, "1.2345678e0"); +} + +test "format float to decimal with zero precision" { + try expectFmt("5", "{d:.0}", .{5}); + try expectFmt("6", "{d:.0}", .{6}); + try expectFmt("7", "{d:.0}", .{7}); + try expectFmt("8", "{d:.0}", .{8}); +} diff --git a/lib/std/fmt/format_float.zig b/lib/std/fmt/format_float.zig deleted file mode 100644 index 4c4c1a29229c4957d73ac7da9d5d98d221a9e1c5..0000000000000000000000000000000000000000 --- a/lib/std/fmt/format_float.zig +++ /dev/null @@ -1,1695 +0,0 @@ -//! This file implements the ryu floating point conversion algorithm: -//! https://dl.acm.org/doi/pdf/10.1145/3360595 - -const std = @import("std"); -const expectFmt = std.testing.expectFmt; - -const special_exponent = 0x7fffffff; - -/// Any buffer used for `format` must be at least this large. This is asserted. A runtime check will -/// additionally be performed if more bytes are required. -pub const min_buffer_size = 53; - -/// Returns the minimum buffer size needed to print every float of a specific type and format. -pub fn bufferSize(comptime mode: Format, comptime T: type) comptime_int { - comptime std.debug.assert(@typeInfo(T) == .float); - return switch (mode) { - .scientific => 53, - // Based on minimum subnormal values. - .decimal => switch (@bitSizeOf(T)) { - 16 => @max(15, min_buffer_size), - 32 => 55, - 64 => 347, - 80 => 4996, - 128 => 5011, - else => unreachable, - }, - }; -} - -pub const FormatError = error{ - BufferTooSmall, -}; - -pub const Format = enum { - scientific, - decimal, -}; - -pub const FormatOptions = struct { - mode: Format = .scientific, - precision: ?usize = null, -}; - -/// Format a floating-point value and write it to buffer. Returns a slice to the buffer containing -/// the string representation. -/// -/// Full precision is the default. Any full precision float can be reparsed with std.fmt.parseFloat -/// unambiguously. -/// -/// Scientific mode is recommended generally as the output is more compact and any type can be -/// written in full precision using a buffer of only `min_buffer_size`. -/// -/// When printing full precision decimals, use `bufferSize` to get the required space. It is -/// recommended to bound decimal output with a fixed precision to reduce the required buffer size. -pub fn formatFloat(buf: []u8, v_: anytype, options: FormatOptions) FormatError![]const u8 { - const v = switch (@TypeOf(v_)) { - // comptime_float internally is a f128; this preserves precision. - comptime_float => @as(f128, v_), - else => v_, - }; - - const T = @TypeOf(v); - comptime std.debug.assert(@typeInfo(T) == .float); - const I = @Type(.{ .int = .{ .signedness = .unsigned, .bits = @bitSizeOf(T) } }); - - const DT = if (@bitSizeOf(T) <= 64) u64 else u128; - const tables = switch (DT) { - u64 => if (@import("builtin").mode == .ReleaseSmall) &Backend64_TablesSmall else &Backend64_TablesFull, - u128 => &Backend128_Tables, - else => unreachable, - }; - - const has_explicit_leading_bit = std.math.floatMantissaBits(T) - std.math.floatFractionalBits(T) != 0; - const d = binaryToDecimal(DT, @as(I, @bitCast(v)), std.math.floatMantissaBits(T), std.math.floatExponentBits(T), has_explicit_leading_bit, tables); - - return switch (options.mode) { - .scientific => formatScientific(DT, buf, d, options.precision), - .decimal => formatDecimal(DT, buf, d, options.precision), - }; -} - -pub fn FloatDecimal(comptime T: type) type { - comptime std.debug.assert(T == u64 or T == u128); - return struct { - mantissa: T, - exponent: i32, - sign: bool, - }; -} - -fn copySpecialStr(buf: []u8, f: anytype) []const u8 { - if (f.sign) { - buf[0] = '-'; - } - const offset: usize = @intFromBool(f.sign); - if (f.mantissa != 0) { - @memcpy(buf[offset..][0..3], "nan"); - return buf[0 .. 3 + offset]; - } - @memcpy(buf[offset..][0..3], "inf"); - return buf[0 .. 3 + offset]; -} - -fn writeDecimal(buf: []u8, value: anytype, count: usize) void { - var i: usize = 0; - - while (i + 2 < count) : (i += 2) { - const c: u8 = @intCast(value.* % 100); - value.* /= 100; - const d = std.fmt.digits2(c); - buf[count - i - 1] = d[1]; - buf[count - i - 2] = d[0]; - } - - while (i < count) : (i += 1) { - const c: u8 = @intCast(value.* % 10); - value.* /= 10; - buf[count - i - 1] = '0' + c; - } -} - -fn isPowerOf10(n_: u128) bool { - var n = n_; - while (n != 0) : (n /= 10) { - if (n % 10 != 0) return false; - } - return true; -} - -const RoundMode = enum { - /// 1234.56 = precision 2 - decimal, - /// 1.23456e3 = precision 5 - scientific, -}; - -fn round(comptime T: type, f: FloatDecimal(T), mode: RoundMode, precision: usize) FloatDecimal(T) { - var round_digit: usize = 0; - var output = f.mantissa; - var exp = f.exponent; - const olength = decimalLength(output); - - switch (mode) { - .decimal => { - if (f.exponent > 0) { - round_digit = (olength - 1) + precision + @as(usize, @intCast(f.exponent)); - } else { - const min_exp_required = @as(usize, @intCast(-f.exponent)); - if (precision + olength > min_exp_required) { - round_digit = precision + olength - min_exp_required; - } - } - }, - .scientific => { - round_digit = 1 + precision; - }, - } - - if (round_digit < olength) { - var nlength = olength; - for (round_digit + 1..olength) |_| { - output /= 10; - exp += 1; - nlength -= 1; - } - - if (output % 10 >= 5) { - output /= 10; - output += 1; - exp += 1; - - // e.g. 9999 -> 10000 - if (isPowerOf10(output)) { - output /= 10; - exp += 1; - } - } - } - - return .{ - .mantissa = output, - .exponent = exp, - .sign = f.sign, - }; -} - -/// Write a FloatDecimal to a buffer in scientific form. -/// -/// The buffer provided must be greater than `min_buffer_size` in length. If no precision is -/// specified, this function will never return an error. If a precision is specified, up to -/// `8 + precision` bytes will be written to the buffer. An error will be returned if the content -/// will not fit. -/// -/// It is recommended to bound decimal formatting with an exact precision. -pub fn formatScientific(comptime T: type, buf: []u8, f_: FloatDecimal(T), precision: ?usize) FormatError![]const u8 { - std.debug.assert(buf.len >= min_buffer_size); - var f = f_; - - if (f.exponent == special_exponent) { - return copySpecialStr(buf, f); - } - - if (precision) |prec| { - f = round(T, f, .scientific, prec); - } - - var output = f.mantissa; - const olength = decimalLength(output); - - if (precision) |prec| { - // fixed bound: sign(1) + leading_digit(1) + point(1) + exp_sign(1) + exp_max(4) - const req_bytes = 8 + prec; - if (buf.len < req_bytes) { - return error.BufferTooSmall; - } - } - - // Step 5: Print the scientific representation - var index: usize = 0; - if (f.sign) { - buf[index] = '-'; - index += 1; - } - - // 1.12345 - writeDecimal(buf[index + 2 ..], &output, olength - 1); - buf[index] = '0' + @as(u8, @intCast(output % 10)); - buf[index + 1] = '.'; - index += 2; - const dp_index = index; - if (olength > 1) index += olength - 1 else index -= 1; - - if (precision) |prec| { - index += @intFromBool(olength == 1); - if (prec > olength - 1) { - const len = prec - (olength - 1); - @memset(buf[index..][0..len], '0'); - index += len; - } else { - index = dp_index + prec - @intFromBool(prec == 0); - } - } - - // e100 - buf[index] = 'e'; - index += 1; - var exp = f.exponent + @as(i32, @intCast(olength)) - 1; - if (exp < 0) { - buf[index] = '-'; - index += 1; - exp = -exp; - } - var uexp: u32 = @intCast(exp); - const elength = decimalLength(uexp); - writeDecimal(buf[index..], &uexp, elength); - index += elength; - - return buf[0..index]; -} - -/// Write a FloatDecimal to a buffer in decimal form. -/// -/// The buffer provided must be greater than `min_buffer_size` bytes in length. If no precision is -/// specified, this may still return an error. If precision is specified, `2 + precision` bytes will -/// always be written. -pub fn formatDecimal(comptime T: type, buf: []u8, f_: FloatDecimal(T), precision: ?usize) FormatError![]const u8 { - std.debug.assert(buf.len >= min_buffer_size); - var f = f_; - - if (f.exponent == special_exponent) { - return copySpecialStr(buf, f); - } - - if (precision) |prec| { - f = round(T, f, .decimal, prec); - } - - var output = f.mantissa; - const olength = decimalLength(output); - - // fixed bound: leading_digit(1) + point(1) - const req_bytes = if (f.exponent >= 0) - @as(usize, 2) + @abs(f.exponent) + olength + (precision orelse 0) - else - @as(usize, 2) + @max(@abs(f.exponent) + olength, precision orelse 0); - if (buf.len < req_bytes) { - return error.BufferTooSmall; - } - - // Step 5: Print the decimal representation - var index: usize = 0; - if (f.sign) { - buf[index] = '-'; - index += 1; - } - - const dp_offset = f.exponent + cast_i32(olength); - if (dp_offset <= 0) { - // 0.000001234 - buf[index] = '0'; - buf[index + 1] = '.'; - index += 2; - const dp_index = index; - - const dp_poffset: u32 = @intCast(-dp_offset); - @memset(buf[index..][0..dp_poffset], '0'); - index += dp_poffset; - writeDecimal(buf[index..], &output, olength); - index += olength; - - if (precision) |prec| { - const dp_written = index - dp_index; - if (prec > dp_written) { - @memset(buf[index..][0 .. prec - dp_written], '0'); - } - index = dp_index + prec - @intFromBool(prec == 0); - } - } else { - // 123456000 - const dp_uoffset: usize = @intCast(dp_offset); - if (dp_uoffset >= olength) { - writeDecimal(buf[index..], &output, olength); - index += olength; - @memset(buf[index..][0 .. dp_uoffset - olength], '0'); - index += dp_uoffset - olength; - - if (precision) |prec| { - if (prec != 0) { - buf[index] = '.'; - index += 1; - @memset(buf[index..][0..prec], '0'); - index += prec; - } - } - } else { - // 12345.6789 - writeDecimal(buf[index + dp_uoffset + 1 ..], &output, olength - dp_uoffset); - buf[index + dp_uoffset] = '.'; - const dp_index = index + dp_uoffset + 1; - writeDecimal(buf[index..], &output, dp_uoffset); - index += olength + 1; - - if (precision) |prec| { - const dp_written = olength - dp_uoffset; - if (prec > dp_written) { - @memset(buf[index..][0 .. prec - dp_written], '0'); - } - index = dp_index + prec - @intFromBool(prec == 0); - } - } - } - - return buf[0..index]; -} - -fn cast_i32(v: anytype) i32 { - return @intCast(v); -} - -/// Convert a binary float representation to decimal. -pub fn binaryToDecimal(comptime T: type, bits: T, mantissa_bits: std.math.Log2Int(T), exponent_bits: u5, explicit_leading_bit: bool, comptime tables: anytype) FloatDecimal(T) { - if (T != tables.T) { - @compileError("table type does not match backend type: " ++ @typeName(tables.T) ++ " != " ++ @typeName(T)); - } - - const bias = (@as(u32, 1) << (exponent_bits - 1)) - 1; - const ieee_sign = ((bits >> (mantissa_bits + exponent_bits)) & 1) != 0; - const ieee_mantissa = bits & ((@as(T, 1) << mantissa_bits) - 1); - const ieee_exponent: u32 = @intCast((bits >> mantissa_bits) & ((@as(T, 1) << exponent_bits) - 1)); - - if (ieee_exponent == 0 and ieee_mantissa == 0) { - return .{ - .mantissa = 0, - .exponent = 0, - .sign = ieee_sign, - }; - } - if (ieee_exponent == ((@as(u32, 1) << exponent_bits) - 1)) { - return .{ - .mantissa = if (explicit_leading_bit) ieee_mantissa & ((@as(T, 1) << (mantissa_bits - 1)) - 1) else ieee_mantissa, - .exponent = special_exponent, - .sign = ieee_sign, - }; - } - - var e2: i32 = undefined; - var m2: T = undefined; - if (explicit_leading_bit) { - if (ieee_exponent == 0) { - e2 = 1 - cast_i32(bias) - cast_i32(mantissa_bits) + 1 - 2; - } else { - e2 = cast_i32(ieee_exponent) - cast_i32(bias) - cast_i32(mantissa_bits) + 1 - 2; - } - m2 = ieee_mantissa; - } else { - if (ieee_exponent == 0) { - e2 = 1 - cast_i32(bias) - cast_i32(mantissa_bits) - 2; - m2 = ieee_mantissa; - } else { - e2 = cast_i32(ieee_exponent) - cast_i32(bias) - cast_i32(mantissa_bits) - 2; - m2 = (@as(T, 1) << mantissa_bits) | ieee_mantissa; - } - } - const even = (m2 & 1) == 0; - const accept_bounds = even; - - // Step 2: Determine the interval of legal decimal representations. - const mv = 4 * m2; - const mm_shift: u1 = @intFromBool((ieee_mantissa != if (explicit_leading_bit) (@as(T, 1) << (mantissa_bits - 1)) else 0) or (ieee_exponent == 0)); - - // Step 3: Convert to a decimal power base using 128-bit arithmetic. - var vr: T = undefined; - var vp: T = undefined; - var vm: T = undefined; - var e10: i32 = undefined; - var vm_is_trailing_zeros = false; - var vr_is_trailing_zeros = false; - if (e2 >= 0) { - const q: u32 = log10Pow2(@intCast(e2)) - @intFromBool(e2 > 3); - e10 = cast_i32(q); - const k: i32 = @intCast(tables.POW5_INV_BITCOUNT + pow5Bits(q) - 1); - const i: u32 = @intCast(-e2 + cast_i32(q) + k); - - const pow5 = tables.computeInvPow5(q); - vr = tables.mulShift(4 * m2, &pow5, i); - vp = tables.mulShift(4 * m2 + 2, &pow5, i); - vm = tables.mulShift(4 * m2 - 1 - mm_shift, &pow5, i); - - if (q <= tables.bound1) { - if (mv % 5 == 0) { - vr_is_trailing_zeros = multipleOfPowerOf5(mv, if (tables.adjust_q) q -% 1 else q); - } else if (accept_bounds) { - vm_is_trailing_zeros = multipleOfPowerOf5(mv - 1 - mm_shift, q); - } else { - vp -= @intFromBool(multipleOfPowerOf5(mv + 2, q)); - } - } - } else { - const q: u32 = log10Pow5(@intCast(-e2)) - @intFromBool(-e2 > 1); - e10 = cast_i32(q) + e2; - const i: i32 = -e2 - cast_i32(q); - const k: i32 = cast_i32(pow5Bits(@intCast(i))) - tables.POW5_BITCOUNT; - const j: u32 = @intCast(cast_i32(q) - k); - - const pow5 = tables.computePow5(@intCast(i)); - vr = tables.mulShift(4 * m2, &pow5, j); - vp = tables.mulShift(4 * m2 + 2, &pow5, j); - vm = tables.mulShift(4 * m2 - 1 - mm_shift, &pow5, j); - - if (q <= 1) { - vr_is_trailing_zeros = true; - if (accept_bounds) { - vm_is_trailing_zeros = mm_shift == 1; - } else { - vp -= 1; - } - } else if (q < tables.bound2) { - vr_is_trailing_zeros = multipleOfPowerOf2(mv, if (tables.adjust_q) q - 1 else q); - } - } - - // Step 4: Find the shortest decimal representation in the interval of legal representations. - var removed: u32 = 0; - var last_removed_digit: u8 = 0; - - while (vp / 10 > vm / 10) { - vm_is_trailing_zeros = vm_is_trailing_zeros and vm % 10 == 0; - vr_is_trailing_zeros = vr_is_trailing_zeros and last_removed_digit == 0; - last_removed_digit = @intCast(vr % 10); - vr /= 10; - vp /= 10; - vm /= 10; - removed += 1; - } - - if (vm_is_trailing_zeros) { - while (vm % 10 == 0) { - vr_is_trailing_zeros = vr_is_trailing_zeros and last_removed_digit == 0; - last_removed_digit = @intCast(vr % 10); - vr /= 10; - vp /= 10; - vm /= 10; - removed += 1; - } - } - - if (vr_is_trailing_zeros and (last_removed_digit == 5) and (vr % 2 == 0)) { - last_removed_digit = 4; - } - - return .{ - .mantissa = vr + @intFromBool((vr == vm and (!accept_bounds or !vm_is_trailing_zeros)) or last_removed_digit >= 5), - .exponent = e10 + cast_i32(removed), - .sign = ieee_sign, - }; -} - -fn decimalLength(v: anytype) u32 { - switch (@TypeOf(v)) { - u32, u64 => { - std.debug.assert(v < 100000000000000000); - if (v >= 10000000000000000) return 17; - if (v >= 1000000000000000) return 16; - if (v >= 100000000000000) return 15; - if (v >= 10000000000000) return 14; - if (v >= 1000000000000) return 13; - if (v >= 100000000000) return 12; - if (v >= 10000000000) return 11; - if (v >= 1000000000) return 10; - if (v >= 100000000) return 9; - if (v >= 10000000) return 8; - if (v >= 1000000) return 7; - if (v >= 100000) return 6; - if (v >= 10000) return 5; - if (v >= 1000) return 4; - if (v >= 100) return 3; - if (v >= 10) return 2; - return 1; - }, - u128 => { - const LARGEST_POW10 = (@as(u128, 5421010862427522170) << 64) | 687399551400673280; - var p10 = LARGEST_POW10; - var i: u32 = 39; - while (i > 0) : (i -= 1) { - if (v >= p10) return i; - p10 /= 10; - } - return 1; - }, - else => unreachable, - } -} - -// floor(log_10(2^e)) -fn log10Pow2(e: u32) u32 { - std.debug.assert(e <= 1 << 15); - return @intCast((@as(u64, @intCast(e)) * 169464822037455) >> 49); -} - -// floor(log_10(5^e)) -fn log10Pow5(e: u32) u32 { - std.debug.assert(e <= 1 << 15); - return @intCast((@as(u64, @intCast(e)) * 196742565691928) >> 48); -} - -// if (e == 0) 1 else ceil(log_2(5^e)) -fn pow5Bits(e: u32) u32 { - std.debug.assert(e <= 1 << 15); - return @intCast(((@as(u64, @intCast(e)) * 163391164108059) >> 46) + 1); -} - -fn pow5Factor(value_: anytype) u32 { - var count: u32 = 0; - var value = value_; - while (value > 0) : ({ - count += 1; - value /= 5; - }) { - if (value % 5 != 0) return count; - } - return 0; -} - -fn multipleOfPowerOf5(value: anytype, p: u32) bool { - const T = @TypeOf(value); - std.debug.assert(@typeInfo(T) == .int); - return pow5Factor(value) >= p; -} - -fn multipleOfPowerOf2(value: anytype, p: u32) bool { - const T = @TypeOf(value); - std.debug.assert(@typeInfo(T) == .int); - return (value & ((@as(T, 1) << @as(std.math.Log2Int(T), @intCast(p))) - 1)) == 0; -} - -fn mulShift128(m: u128, mul: *const [4]u64, j: u32) u128 { - std.debug.assert(j > 128); - const a: [2]u64 = .{ @truncate(m), @truncate(m >> 64) }; - const r = mul_128_256_shift(&a, mul, j, 0); - return (@as(u128, r[1]) << 64) | r[0]; -} - -fn mul_128_256_shift(a: *const [2]u64, b: *const [4]u64, shift: u32, corr: u32) [4]u64 { - std.debug.assert(shift > 0); - std.debug.assert(shift < 256); - - const b00 = @as(u128, a[0]) * b[0]; - const b01 = @as(u128, a[0]) * b[1]; - const b02 = @as(u128, a[0]) * b[2]; - const b03 = @as(u128, a[0]) * b[3]; - const b10 = @as(u128, a[1]) * b[0]; - const b11 = @as(u128, a[1]) * b[1]; - const b12 = @as(u128, a[1]) * b[2]; - const b13 = @as(u128, a[1]) * b[3]; - - const s0 = b00; - const s1 = b01 +% b10; - const c1: u128 = @intFromBool(s1 < b01); - const s2 = b02 +% b11; - const c2: u128 = @intFromBool(s2 < b02); - const s3 = b03 +% b12; - const c3: u128 = @intFromBool(s3 < b03); - - const p0 = s0 +% (s1 << 64); - const d0: u128 = @intFromBool(p0 < b00); - const q1 = s2 +% (s1 >> 64) +% (s3 << 64); - const d1: u128 = @intFromBool(q1 < s2); - const p1 = q1 +% (c1 << 64) +% d0; - const d2: u128 = @intFromBool(p1 < q1); - const p2 = b13 +% (s3 >> 64) +% c2 +% (c3 << 64) +% d1 +% d2; - - var r0: u128 = undefined; - var r1: u128 = undefined; - if (shift < 128) { - const cshift: u7 = @intCast(shift); - const sshift: u7 = @intCast(128 - shift); - r0 = corr +% ((p0 >> cshift) | (p1 << sshift)); - r1 = ((p1 >> cshift) | (p2 << sshift)) +% @intFromBool(r0 < corr); - } else if (shift == 128) { - r0 = corr +% p1; - r1 = p2 +% @intFromBool(r0 < corr); - } else { - const ashift: u7 = @intCast(shift - 128); - const sshift: u7 = @intCast(256 - shift); - r0 = corr +% ((p1 >> ashift) | (p2 << sshift)); - r1 = (p2 >> ashift) +% @intFromBool(r0 < corr); - } - - return .{ @truncate(r0), @truncate(r0 >> 64), @truncate(r1), @truncate(r1 >> 64) }; -} - -pub const Backend128_Tables = struct { - const T = u128; - const mulShift = mulShift128; - const POW5_INV_BITCOUNT = FLOAT128_POW5_INV_BITCOUNT; - const POW5_BITCOUNT = FLOAT128_POW5_BITCOUNT; - - const bound1 = 55; - const bound2 = 127; - const adjust_q = true; - - fn computePow5(i: u32) [4]u64 { - const base = i / FLOAT128_POW5_TABLE_SIZE; - const base2 = base * FLOAT128_POW5_TABLE_SIZE; - const mul = &FLOAT128_POW5_SPLIT[base]; - if (i == base2) { - return mul.*; - } else { - const offset = i - base2; - const m = &FLOAT128_POW5_TABLE[offset]; - const delta = pow5Bits(i) - pow5Bits(base2); - - const shift: u6 = @intCast(2 * (i % 32)); - const corr: u32 = @intCast((FLOAT128_POW5_ERRORS[i / 32] >> shift) & 3); - return mul_128_256_shift(m, mul, delta, corr); - } - } - - fn computeInvPow5(i: u32) [4]u64 { - const base = (i + FLOAT128_POW5_TABLE_SIZE - 1) / FLOAT128_POW5_TABLE_SIZE; - const base2 = base * FLOAT128_POW5_TABLE_SIZE; - const mul = &FLOAT128_POW5_INV_SPLIT[base]; // 1 / 5^base2 - if (i == base2) { - return .{ mul[0] + 1, mul[1], mul[2], mul[3] }; - } else { - const offset = base2 - i; - const m = &FLOAT128_POW5_TABLE[offset]; // 5^offset - const delta = pow5Bits(base2) - pow5Bits(i); - - const shift: u6 = @intCast(2 * (i % 32)); - const corr: u32 = @intCast(((FLOAT128_POW5_INV_ERRORS[i / 32] >> shift) & 3) + 1); - return mul_128_256_shift(m, mul, delta, corr); - } - } -}; - -fn mulShift64(m: u64, mul: *const [2]u64, j: u32) u64 { - std.debug.assert(j > 64); - const b0 = @as(u128, m) * mul[0]; - const b2 = @as(u128, m) * mul[1]; - - if (j < 128) { - const shift: u6 = @intCast(j - 64); - return @intCast(((b0 >> 64) + b2) >> shift); - } else { - return 0; - } -} - -pub const Backend64_TablesFull = struct { - const T = u64; - const mulShift = mulShift64; - const POW5_INV_BITCOUNT = FLOAT64_POW5_INV_BITCOUNT; - const POW5_BITCOUNT = FLOAT64_POW5_BITCOUNT; - - const bound1 = 21; - const bound2 = 63; - const adjust_q = false; - - fn computePow5(i: u32) [2]u64 { - return FLOAT64_POW5_SPLIT[i]; - } - - fn computeInvPow5(i: u32) [2]u64 { - return FLOAT64_POW5_INV_SPLIT[i]; - } -}; - -pub const Backend64_TablesSmall = struct { - const T = u64; - const mulShift = mulShift64; - const POW5_INV_BITCOUNT = FLOAT64_POW5_INV_BITCOUNT; - const POW5_BITCOUNT = FLOAT64_POW5_BITCOUNT; - - const bound1 = 21; - const bound2 = 63; - const adjust_q = false; - - fn computePow5(i: u32) [2]u64 { - const base = i / FLOAT64_POW5_TABLE_SIZE; - const base2 = base * FLOAT64_POW5_TABLE_SIZE; - const mul = &FLOAT64_POW5_SPLIT2[base]; - if (i == base2) { - return .{ mul[0], mul[1] }; - } else { - const offset = i - base2; - const m = FLOAT64_POW5_TABLE[offset]; - const b0 = @as(u128, m) * mul[0]; - const b2 = @as(u128, m) * mul[1]; - const delta: u7 = @intCast(pow5Bits(i) - pow5Bits(base2)); - const shift: u5 = @intCast((i % 16) << 1); - const shifted_sum = ((b0 >> delta) + (b2 << (64 - delta))) + 1 + ((FLOAT64_POW5_OFFSETS[i / 16] >> shift) & 3); - return .{ @truncate(shifted_sum), @truncate(shifted_sum >> 64) }; - } - } - - fn computeInvPow5(i: u32) [2]u64 { - const base = (i + FLOAT64_POW5_TABLE_SIZE - 1) / FLOAT64_POW5_TABLE_SIZE; - const base2 = base * FLOAT64_POW5_TABLE_SIZE; - const mul = &FLOAT64_POW5_INV_SPLIT2[base]; // 1 / 5^base2 - if (i == base2) { - return .{ mul[0], mul[1] }; - } else { - const offset = base2 - i; - const m = FLOAT64_POW5_TABLE[offset]; // 5^offset - const b0 = @as(u128, m) * (mul[0] - 1); - const b2 = @as(u128, m) * mul[1]; // 1/5^base2 * 5^offset = 1/5^(base2-offset) = 1/5^i - const delta: u7 = @intCast(pow5Bits(base2) - pow5Bits(i)); - const shift: u5 = @intCast((i % 16) << 1); - const shifted_sum = ((b0 >> delta) + (b2 << (64 - delta))) + 1 + ((FLOAT64_POW5_INV_OFFSETS[i / 16] >> shift) & 3); - return .{ @truncate(shifted_sum), @truncate(shifted_sum >> 64) }; - } - } -}; - -const FLOAT64_POW5_INV_BITCOUNT = 125; -const FLOAT64_POW5_BITCOUNT = 125; - -// zig fmt: off -// -// f64 small tables: 816 bytes - -const FLOAT64_POW5_TABLE_SIZE: comptime_int = FLOAT64_POW5_TABLE.len; - -const FLOAT64_POW5_TABLE: [26]u64 = .{ - 1, 5, - 25, 125, - 625, 3125, - 15625, 78125, - 390625, 1953125, - 9765625, 48828125, - 244140625, 1220703125, - 6103515625, 30517578125, - 152587890625, 762939453125, - 3814697265625, 19073486328125, - 95367431640625, 476837158203125, - 2384185791015625, 11920928955078125, - 59604644775390625, 298023223876953125, -}; - -const FLOAT64_POW5_SPLIT2: [13][2]u64 = .{ - .{ 0, 1152921504606846976 }, - .{ 0, 1490116119384765625 }, - .{ 1032610780636961552, 1925929944387235853 }, - .{ 7910200175544436838, 1244603055572228341 }, - .{ 16941905809032713930, 1608611746708759036 }, - .{ 13024893955298202172, 2079081953128979843 }, - .{ 6607496772837067824, 1343575221513417750 }, - .{ 17332926989895652603, 1736530273035216783 }, - .{ 13037379183483547984, 2244412773384604712 }, - .{ 1605989338741628675, 1450417759929778918 }, - .{ 9630225068416591280, 1874621017369538693 }, - .{ 665883850346957067, 1211445438634777304 }, - .{ 14931890668723713708, 1565756531257009982 } -}; - -const FLOAT64_POW5_OFFSETS: [21]u32 = .{ - 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x40000000, 0x59695995, 0x55545555, 0x56555515, - 0x41150504, 0x40555410, 0x44555145, 0x44504540, - 0x45555550, 0x40004000, 0x96440440, 0x55565565, - 0x54454045, 0x40154151, 0x55559155, 0x51405555, - 0x00000105, -}; - -const FLOAT64_POW5_INV_SPLIT2: [15][2]u64 = .{ - .{ 1, 2305843009213693952 }, - .{ 5955668970331000884, 1784059615882449851 }, - .{ 8982663654677661702, 1380349269358112757 }, - .{ 7286864317269821294, 2135987035920910082 }, - .{ 7005857020398200553, 1652639921975621497 }, - .{ 17965325103354776697, 1278668206209430417 }, - .{ 8928596168509315048, 1978643211784836272 }, - .{ 10075671573058298858, 1530901034580419511 }, - .{ 597001226353042382, 1184477304306571148 }, - .{ 1527430471115325346, 1832889850782397517 }, - .{ 12533209867169019542, 1418129833677084982 }, - .{ 5577825024675947042, 2194449627517475473 }, - .{ 11006974540203867551, 1697873161311732311 }, - .{ 10313493231639821582, 1313665730009899186 }, - .{ 12701016819766672773, 2032799256770390445 } -}; - -const FLOAT64_POW5_INV_OFFSETS: [19]u32 = .{ - 0x54544554, 0x04055545, 0x10041000, 0x00400414, - 0x40010000, 0x41155555, 0x00000454, 0x00010044, - 0x40000000, 0x44000041, 0x50454450, 0x55550054, - 0x51655554, 0x40004000, 0x01000001, 0x00010500, - 0x51515411, 0x05555554, 0x00000000, -}; - - -// zig fmt: off - -// f64 full tables: 10688 bytes - -const FLOAT64_POW5_SPLIT: [326][2]u64 = .{ - .{ 0, 1152921504606846976 }, .{ 0, 1441151880758558720 }, - .{ 0, 1801439850948198400 }, .{ 0, 2251799813685248000 }, - .{ 0, 1407374883553280000 }, .{ 0, 1759218604441600000 }, - .{ 0, 2199023255552000000 }, .{ 0, 1374389534720000000 }, - .{ 0, 1717986918400000000 }, .{ 0, 2147483648000000000 }, - .{ 0, 1342177280000000000 }, .{ 0, 1677721600000000000 }, - .{ 0, 2097152000000000000 }, .{ 0, 1310720000000000000 }, - .{ 0, 1638400000000000000 }, .{ 0, 2048000000000000000 }, - .{ 0, 1280000000000000000 }, .{ 0, 1600000000000000000 }, - .{ 0, 2000000000000000000 }, .{ 0, 1250000000000000000 }, - .{ 0, 1562500000000000000 }, .{ 0, 1953125000000000000 }, - .{ 0, 1220703125000000000 }, .{ 0, 1525878906250000000 }, - .{ 0, 1907348632812500000 }, .{ 0, 1192092895507812500 }, - .{ 0, 1490116119384765625 }, .{ 4611686018427387904, 1862645149230957031 }, - .{ 9799832789158199296, 1164153218269348144 }, .{ 12249790986447749120, 1455191522836685180 }, - .{ 15312238733059686400, 1818989403545856475 }, .{ 14528612397897220096, 2273736754432320594 }, - .{ 13692068767113150464, 1421085471520200371 }, .{ 12503399940464050176, 1776356839400250464 }, - .{ 15629249925580062720, 2220446049250313080 }, .{ 9768281203487539200, 1387778780781445675 }, - .{ 7598665485932036096, 1734723475976807094 }, .{ 274959820560269312, 2168404344971008868 }, - .{ 9395221924704944128, 1355252715606880542 }, .{ 2520655369026404352, 1694065894508600678 }, - .{ 12374191248137781248, 2117582368135750847 }, .{ 14651398557727195136, 1323488980084844279 }, - .{ 13702562178731606016, 1654361225106055349 }, .{ 3293144668132343808, 2067951531382569187 }, - .{ 18199116482078572544, 1292469707114105741 }, .{ 8913837547316051968, 1615587133892632177 }, - .{ 15753982952572452864, 2019483917365790221 }, .{ 12152082354571476992, 1262177448353618888 }, - .{ 15190102943214346240, 1577721810442023610 }, .{ 9764256642163156992, 1972152263052529513 }, - .{ 17631875447420442880, 1232595164407830945 }, .{ 8204786253993389888, 1540743955509788682 }, - .{ 1032610780636961552, 1925929944387235853 }, .{ 2951224747111794922, 1203706215242022408 }, - .{ 3689030933889743652, 1504632769052528010 }, .{ 13834660704216955373, 1880790961315660012 }, - .{ 17870034976990372916, 1175494350822287507 }, .{ 17725857702810578241, 1469367938527859384 }, - .{ 3710578054803671186, 1836709923159824231 }, .{ 26536550077201078, 2295887403949780289 }, - .{ 11545800389866720434, 1434929627468612680 }, .{ 14432250487333400542, 1793662034335765850 }, - .{ 8816941072311974870, 2242077542919707313 }, .{ 17039803216263454053, 1401298464324817070 }, - .{ 12076381983474541759, 1751623080406021338 }, .{ 5872105442488401391, 2189528850507526673 }, - .{ 15199280947623720629, 1368455531567204170 }, .{ 9775729147674874978, 1710569414459005213 }, - .{ 16831347453020981627, 2138211768073756516 }, .{ 1296220121283337709, 1336382355046097823 }, - .{ 15455333206886335848, 1670477943807622278 }, .{ 10095794471753144002, 2088097429759527848 }, - .{ 6309871544845715001, 1305060893599704905 }, .{ 12499025449484531656, 1631326116999631131 }, - .{ 11012095793428276666, 2039157646249538914 }, .{ 11494245889320060820, 1274473528905961821 }, - .{ 532749306367912313, 1593091911132452277 }, .{ 5277622651387278295, 1991364888915565346 }, - .{ 7910200175544436838, 1244603055572228341 }, .{ 14499436237857933952, 1555753819465285426 }, - .{ 8900923260467641632, 1944692274331606783 }, .{ 12480606065433357876, 1215432671457254239 }, - .{ 10989071563364309441, 1519290839321567799 }, .{ 9124653435777998898, 1899113549151959749 }, - .{ 8008751406574943263, 1186945968219974843 }, .{ 5399253239791291175, 1483682460274968554 }, - .{ 15972438586593889776, 1854603075343710692 }, .{ 759402079766405302, 1159126922089819183 }, - .{ 14784310654990170340, 1448908652612273978 }, .{ 9257016281882937117, 1811135815765342473 }, - .{ 16182956370781059300, 2263919769706678091 }, .{ 7808504722524468110, 1414949856066673807 }, - .{ 5148944884728197234, 1768687320083342259 }, .{ 1824495087482858639, 2210859150104177824 }, - .{ 1140309429676786649, 1381786968815111140 }, .{ 1425386787095983311, 1727233711018888925 }, - .{ 6393419502297367043, 2159042138773611156 }, .{ 13219259225790630210, 1349401336733506972 }, - .{ 16524074032238287762, 1686751670916883715 }, .{ 16043406521870471799, 2108439588646104644 }, - .{ 803757039314269066, 1317774742903815403 }, .{ 14839754354425000045, 1647218428629769253 }, - .{ 4714634887749086344, 2059023035787211567 }, .{ 9864175832484260821, 1286889397367007229 }, - .{ 16941905809032713930, 1608611746708759036 }, .{ 2730638187581340797, 2010764683385948796 }, - .{ 10930020904093113806, 1256727927116217997 }, .{ 18274212148543780162, 1570909908895272496 }, - .{ 4396021111970173586, 1963637386119090621 }, .{ 5053356204195052443, 1227273366324431638 }, - .{ 15540067292098591362, 1534091707905539547 }, .{ 14813398096695851299, 1917614634881924434 }, - .{ 13870059828862294966, 1198509146801202771 }, .{ 12725888767650480803, 1498136433501503464 }, - .{ 15907360959563101004, 1872670541876879330 }, .{ 14553786618154326031, 1170419088673049581 }, - .{ 4357175217410743827, 1463023860841311977 }, .{ 10058155040190817688, 1828779826051639971 }, - .{ 7961007781811134206, 2285974782564549964 }, .{ 14199001900486734687, 1428734239102843727 }, - .{ 13137066357181030455, 1785917798878554659 }, .{ 11809646928048900164, 2232397248598193324 }, - .{ 16604401366885338411, 1395248280373870827 }, .{ 16143815690179285109, 1744060350467338534 }, - .{ 10956397575869330579, 2180075438084173168 }, .{ 6847748484918331612, 1362547148802608230 }, - .{ 17783057643002690323, 1703183936003260287 }, .{ 17617136035325974999, 2128979920004075359 }, - .{ 17928239049719816230, 1330612450002547099 }, .{ 17798612793722382384, 1663265562503183874 }, - .{ 13024893955298202172, 2079081953128979843 }, .{ 5834715712847682405, 1299426220705612402 }, - .{ 16516766677914378815, 1624282775882015502 }, .{ 11422586310538197711, 2030353469852519378 }, - .{ 11750802462513761473, 1268970918657824611 }, .{ 10076817059714813937, 1586213648322280764 }, - .{ 12596021324643517422, 1982767060402850955 }, .{ 5566670318688504437, 1239229412751781847 }, - .{ 2346651879933242642, 1549036765939727309 }, .{ 7545000868343941206, 1936295957424659136 }, - .{ 4715625542714963254, 1210184973390411960 }, .{ 5894531928393704067, 1512731216738014950 }, - .{ 16591536947346905892, 1890914020922518687 }, .{ 17287239619732898039, 1181821263076574179 }, - .{ 16997363506238734644, 1477276578845717724 }, .{ 2799960309088866689, 1846595723557147156 }, - .{ 10973347230035317489, 1154122327223216972 }, .{ 13716684037544146861, 1442652909029021215 }, - .{ 12534169028502795672, 1803316136286276519 }, .{ 11056025267201106687, 2254145170357845649 }, - .{ 18439230838069161439, 1408840731473653530 }, .{ 13825666510731675991, 1761050914342066913 }, - .{ 3447025083132431277, 2201313642927583642 }, .{ 6766076695385157452, 1375821026829739776 }, - .{ 8457595869231446815, 1719776283537174720 }, .{ 10571994836539308519, 2149720354421468400 }, - .{ 6607496772837067824, 1343575221513417750 }, .{ 17482743002901110588, 1679469026891772187 }, - .{ 17241742735199000331, 2099336283614715234 }, .{ 15387775227926763111, 1312085177259197021 }, - .{ 5399660979626290177, 1640106471573996277 }, .{ 11361262242960250625, 2050133089467495346 }, - .{ 11712474920277544544, 1281333180917184591 }, .{ 10028907631919542777, 1601666476146480739 }, - .{ 7924448521472040567, 2002083095183100924 }, .{ 14176152362774801162, 1251301934489438077 }, - .{ 3885132398186337741, 1564127418111797597 }, .{ 9468101516160310080, 1955159272639746996 }, - .{ 15140935484454969608, 1221974545399841872 }, .{ 479425281859160394, 1527468181749802341 }, - .{ 5210967620751338397, 1909335227187252926 }, .{ 17091912818251750210, 1193334516992033078 }, - .{ 12141518985959911954, 1491668146240041348 }, .{ 15176898732449889943, 1864585182800051685 }, - .{ 11791404716994875166, 1165365739250032303 }, .{ 10127569877816206054, 1456707174062540379 }, - .{ 8047776328842869663, 1820883967578175474 }, .{ 836348374198811271, 2276104959472719343 }, - .{ 7440246761515338900, 1422565599670449589 }, .{ 13911994470321561530, 1778206999588061986 }, - .{ 8166621051047176104, 2222758749485077483 }, .{ 2798295147690791113, 1389224218428173427 }, - .{ 17332926989895652603, 1736530273035216783 }, .{ 17054472718942177850, 2170662841294020979 }, - .{ 8353202440125167204, 1356664275808763112 }, .{ 10441503050156459005, 1695830344760953890 }, - .{ 3828506775840797949, 2119787930951192363 }, .{ 86973725686804766, 1324867456844495227 }, - .{ 13943775212390669669, 1656084321055619033 }, .{ 3594660960206173375, 2070105401319523792 }, - .{ 2246663100128858359, 1293815875824702370 }, .{ 12031700912015848757, 1617269844780877962 }, - .{ 5816254103165035138, 2021587305976097453 }, .{ 5941001823691840913, 1263492066235060908 }, - .{ 7426252279614801142, 1579365082793826135 }, .{ 4671129331091113523, 1974206353492282669 }, - .{ 5225298841145639904, 1233878970932676668 }, .{ 6531623551432049880, 1542348713665845835 }, - .{ 3552843420862674446, 1927935892082307294 }, .{ 16055585193321335241, 1204959932551442058 }, - .{ 10846109454796893243, 1506199915689302573 }, .{ 18169322836923504458, 1882749894611628216 }, - .{ 11355826773077190286, 1176718684132267635 }, .{ 9583097447919099954, 1470898355165334544 }, - .{ 11978871809898874942, 1838622943956668180 }, .{ 14973589762373593678, 2298278679945835225 }, - .{ 2440964573842414192, 1436424174966147016 }, .{ 3051205717303017741, 1795530218707683770 }, - .{ 13037379183483547984, 2244412773384604712 }, .{ 8148361989677217490, 1402757983365377945 }, - .{ 14797138505523909766, 1753447479206722431 }, .{ 13884737113477499304, 2191809349008403039 }, - .{ 15595489723564518921, 1369880843130251899 }, .{ 14882676136028260747, 1712351053912814874 }, - .{ 9379973133180550126, 2140438817391018593 }, .{ 17391698254306313589, 1337774260869386620 }, - .{ 3292878744173340370, 1672217826086733276 }, .{ 4116098430216675462, 2090272282608416595 }, - .{ 266718509671728212, 1306420176630260372 }, .{ 333398137089660265, 1633025220787825465 }, - .{ 5028433689789463235, 2041281525984781831 }, .{ 10060300083759496378, 1275800953740488644 }, - .{ 12575375104699370472, 1594751192175610805 }, .{ 1884160825592049379, 1993438990219513507 }, - .{ 17318501580490888525, 1245899368887195941 }, .{ 7813068920331446945, 1557374211108994927 }, - .{ 5154650131986920777, 1946717763886243659 }, .{ 915813323278131534, 1216698602428902287 }, - .{ 14979824709379828129, 1520873253036127858 }, .{ 9501408849870009354, 1901091566295159823 }, - .{ 12855909558809837702, 1188182228934474889 }, .{ 2234828893230133415, 1485227786168093612 }, - .{ 2793536116537666769, 1856534732710117015 }, .{ 8663489100477123587, 1160334207943823134 }, - .{ 1605989338741628675, 1450417759929778918 }, .{ 11230858710281811652, 1813022199912223647 }, - .{ 9426887369424876662, 2266277749890279559 }, .{ 12809333633531629769, 1416423593681424724 }, - .{ 16011667041914537212, 1770529492101780905 }, .{ 6179525747111007803, 2213161865127226132 }, - .{ 13085575628799155685, 1383226165704516332 }, .{ 16356969535998944606, 1729032707130645415 }, - .{ 15834525901571292854, 2161290883913306769 }, .{ 2979049660840976177, 1350806802445816731 }, - .{ 17558870131333383934, 1688508503057270913 }, .{ 8113529608884566205, 2110635628821588642 }, - .{ 9682642023980241782, 1319147268013492901 }, .{ 16714988548402690132, 1648934085016866126 }, - .{ 11670363648648586857, 2061167606271082658 }, .{ 11905663298832754689, 1288229753919426661 }, - .{ 1047021068258779650, 1610287192399283327 }, .{ 15143834390605638274, 2012858990499104158 }, - .{ 4853210475701136017, 1258036869061940099 }, .{ 1454827076199032118, 1572546086327425124 }, - .{ 1818533845248790147, 1965682607909281405 }, .{ 3442426662494187794, 1228551629943300878 }, - .{ 13526405364972510550, 1535689537429126097 }, .{ 3072948650933474476, 1919611921786407622 }, - .{ 15755650962115585259, 1199757451116504763 }, .{ 15082877684217093670, 1499696813895630954 }, - .{ 9630225068416591280, 1874621017369538693 }, .{ 8324733676974063502, 1171638135855961683 }, - .{ 5794231077790191473, 1464547669819952104 }, .{ 7242788847237739342, 1830684587274940130 }, - .{ 18276858095901949986, 2288355734093675162 }, .{ 16034722328366106645, 1430222333808546976 }, - .{ 1596658836748081690, 1787777917260683721 }, .{ 6607509564362490017, 2234722396575854651 }, - .{ 1823850468512862308, 1396701497859909157 }, .{ 6891499104068465790, 1745876872324886446 }, - .{ 17837745916940358045, 2182346090406108057 }, .{ 4231062170446641922, 1363966306503817536 }, - .{ 5288827713058302403, 1704957883129771920 }, .{ 6611034641322878003, 2131197353912214900 }, - .{ 13355268687681574560, 1331998346195134312 }, .{ 16694085859601968200, 1664997932743917890 }, - .{ 11644235287647684442, 2081247415929897363 }, .{ 4971804045566108824, 1300779634956185852 }, - .{ 6214755056957636030, 1625974543695232315 }, .{ 3156757802769657134, 2032468179619040394 }, - .{ 6584659645158423613, 1270292612261900246 }, .{ 17454196593302805324, 1587865765327375307 }, - .{ 17206059723201118751, 1984832206659219134 }, .{ 6142101308573311315, 1240520129162011959 }, - .{ 3065940617289251240, 1550650161452514949 }, .{ 8444111790038951954, 1938312701815643686 }, - .{ 665883850346957067, 1211445438634777304 }, .{ 832354812933696334, 1514306798293471630 }, - .{ 10263815553021896226, 1892883497866839537 }, .{ 17944099766707154901, 1183052186166774710 }, - .{ 13206752671529167818, 1478815232708468388 }, .{ 16508440839411459773, 1848519040885585485 }, - .{ 12623618533845856310, 1155324400553490928 }, .{ 15779523167307320387, 1444155500691863660 }, - .{ 1277659885424598868, 1805194375864829576 }, .{ 1597074856780748586, 2256492969831036970 }, - .{ 5609857803915355770, 1410308106144398106 }, .{ 16235694291748970521, 1762885132680497632 }, - .{ 1847873790976661535, 2203606415850622041 }, .{ 12684136165428883219, 1377254009906638775 }, - .{ 11243484188358716120, 1721567512383298469 }, .{ 219297180166231438, 2151959390479123087 }, - .{ 7054589765244976505, 1344974619049451929 }, .{ 13429923224983608535, 1681218273811814911 }, - .{ 12175718012802122765, 2101522842264768639 }, .{ 14527352785642408584, 1313451776415480399 }, - .{ 13547504963625622826, 1641814720519350499 }, .{ 12322695186104640628, 2052268400649188124 }, - .{ 16925056528170176201, 1282667750405742577 }, .{ 7321262604930556539, 1603334688007178222 }, - .{ 18374950293017971482, 2004168360008972777 }, .{ 4566814905495150320, 1252605225005607986 }, - .{ 14931890668723713708, 1565756531257009982 }, .{ 9441491299049866327, 1957195664071262478 }, - .{ 1289246043478778550, 1223247290044539049 }, .{ 6223243572775861092, 1529059112555673811 }, - .{ 3167368447542438461, 1911323890694592264 }, .{ 1979605279714024038, 1194577431684120165 }, - .{ 7086192618069917952, 1493221789605150206 }, .{ 18081112809442173248, 1866527237006437757 }, - .{ 13606538515115052232, 1166579523129023598 }, .{ 7784801107039039482, 1458224403911279498 }, - .{ 507629346944023544, 1822780504889099373 }, .{ 5246222702107417334, 2278475631111374216 }, - .{ 3278889188817135834, 1424047269444608885 }, .{ 8710297504448807696, 1780059086805761106 } -}; - -const FLOAT64_POW5_INV_SPLIT: [342][2]u64 = .{ - .{ 1, 2305843009213693952 }, .{ 11068046444225730970, 1844674407370955161 }, - .{ 5165088340638674453, 1475739525896764129 }, .{ 7821419487252849886, 1180591620717411303 }, - .{ 8824922364862649494, 1888946593147858085 }, .{ 7059937891890119595, 1511157274518286468 }, - .{ 13026647942995916322, 1208925819614629174 }, .{ 9774590264567735146, 1934281311383406679 }, - .{ 11509021026396098440, 1547425049106725343 }, .{ 16585914450600699399, 1237940039285380274 }, - .{ 15469416676735388068, 1980704062856608439 }, .{ 16064882156130220778, 1584563250285286751 }, - .{ 9162556910162266299, 1267650600228229401 }, .{ 7281393426775805432, 2028240960365167042 }, - .{ 16893161185646375315, 1622592768292133633 }, .{ 2446482504291369283, 1298074214633706907 }, - .{ 7603720821608101175, 2076918743413931051 }, .{ 2393627842544570617, 1661534994731144841 }, - .{ 16672297533003297786, 1329227995784915872 }, .{ 11918280793837635165, 2126764793255865396 }, - .{ 5845275820328197809, 1701411834604692317 }, .{ 15744267100488289217, 1361129467683753853 }, - .{ 3054734472329800808, 2177807148294006166 }, .{ 17201182836831481939, 1742245718635204932 }, - .{ 6382248639981364905, 1393796574908163946 }, .{ 2832900194486363201, 2230074519853062314 }, - .{ 5955668970331000884, 1784059615882449851 }, .{ 1075186361522890384, 1427247692705959881 }, - .{ 12788344622662355584, 2283596308329535809 }, .{ 13920024512871794791, 1826877046663628647 }, - .{ 3757321980813615186, 1461501637330902918 }, .{ 10384555214134712795, 1169201309864722334 }, - .{ 5547241898389809503, 1870722095783555735 }, .{ 4437793518711847602, 1496577676626844588 }, - .{ 10928932444453298728, 1197262141301475670 }, .{ 17486291911125277965, 1915619426082361072 }, - .{ 6610335899416401726, 1532495540865888858 }, .{ 12666966349016942027, 1225996432692711086 }, - .{ 12888448528943286597, 1961594292308337738 }, .{ 17689456452638449924, 1569275433846670190 }, - .{ 14151565162110759939, 1255420347077336152 }, .{ 7885109000409574610, 2008672555323737844 }, - .{ 9997436015069570011, 1606938044258990275 }, .{ 7997948812055656009, 1285550435407192220 }, - .{ 12796718099289049614, 2056880696651507552 }, .{ 2858676849947419045, 1645504557321206042 }, - .{ 13354987924183666206, 1316403645856964833 }, .{ 17678631863951955605, 2106245833371143733 }, - .{ 3074859046935833515, 1684996666696914987 }, .{ 13527933681774397782, 1347997333357531989 }, - .{ 10576647446613305481, 2156795733372051183 }, .{ 15840015586774465031, 1725436586697640946 }, - .{ 8982663654677661702, 1380349269358112757 }, .{ 18061610662226169046, 2208558830972980411 }, - .{ 10759939715039024913, 1766847064778384329 }, .{ 12297300586773130254, 1413477651822707463 }, - .{ 15986332124095098083, 2261564242916331941 }, .{ 9099716884534168143, 1809251394333065553 }, - .{ 14658471137111155161, 1447401115466452442 }, .{ 4348079280205103483, 1157920892373161954 }, - .{ 14335624477811986218, 1852673427797059126 }, .{ 7779150767507678651, 1482138742237647301 }, - .{ 2533971799264232598, 1185710993790117841 }, .{ 15122401323048503126, 1897137590064188545 }, - .{ 12097921058438802501, 1517710072051350836 }, .{ 5988988032009131678, 1214168057641080669 }, - .{ 16961078480698431330, 1942668892225729070 }, .{ 13568862784558745064, 1554135113780583256 }, - .{ 7165741412905085728, 1243308091024466605 }, .{ 11465186260648137165, 1989292945639146568 }, - .{ 16550846638002330379, 1591434356511317254 }, .{ 16930026125143774626, 1273147485209053803 }, - .{ 4951948911778577463, 2037035976334486086 }, .{ 272210314680951647, 1629628781067588869 }, - .{ 3907117066486671641, 1303703024854071095 }, .{ 6251387306378674625, 2085924839766513752 }, - .{ 16069156289328670670, 1668739871813211001 }, .{ 9165976216721026213, 1334991897450568801 }, - .{ 7286864317269821294, 2135987035920910082 }, .{ 16897537898041588005, 1708789628736728065 }, - .{ 13518030318433270404, 1367031702989382452 }, .{ 6871453250525591353, 2187250724783011924 }, - .{ 9186511415162383406, 1749800579826409539 }, .{ 11038557946871817048, 1399840463861127631 }, - .{ 10282995085511086630, 2239744742177804210 }, .{ 8226396068408869304, 1791795793742243368 }, - .{ 13959814484210916090, 1433436634993794694 }, .{ 11267656730511734774, 2293498615990071511 }, - .{ 5324776569667477496, 1834798892792057209 }, .{ 7949170070475892320, 1467839114233645767 }, - .{ 17427382500606444826, 1174271291386916613 }, .{ 5747719112518849781, 1878834066219066582 }, - .{ 15666221734240810795, 1503067252975253265 }, .{ 12532977387392648636, 1202453802380202612 }, - .{ 5295368560860596524, 1923926083808324180 }, .{ 4236294848688477220, 1539140867046659344 }, - .{ 7078384693692692099, 1231312693637327475 }, .{ 11325415509908307358, 1970100309819723960 }, - .{ 9060332407926645887, 1576080247855779168 }, .{ 14626963555825137356, 1260864198284623334 }, - .{ 12335095245094488799, 2017382717255397335 }, .{ 9868076196075591040, 1613906173804317868 }, - .{ 15273158586344293478, 1291124939043454294 }, .{ 13369007293925138595, 2065799902469526871 }, - .{ 7005857020398200553, 1652639921975621497 }, .{ 16672732060544291412, 1322111937580497197 }, - .{ 11918976037903224966, 2115379100128795516 }, .{ 5845832015580669650, 1692303280103036413 }, - .{ 12055363241948356366, 1353842624082429130 }, .{ 841837113407818570, 2166148198531886609 }, - .{ 4362818505468165179, 1732918558825509287 }, .{ 14558301248600263113, 1386334847060407429 }, - .{ 12225235553534690011, 2218135755296651887 }, .{ 2401490813343931363, 1774508604237321510 }, - .{ 1921192650675145090, 1419606883389857208 }, .{ 17831303500047873437, 2271371013423771532 }, - .{ 6886345170554478103, 1817096810739017226 }, .{ 1819727321701672159, 1453677448591213781 }, - .{ 16213177116328979020, 1162941958872971024 }, .{ 14873036941900635463, 1860707134196753639 }, - .{ 15587778368262418694, 1488565707357402911 }, .{ 8780873879868024632, 1190852565885922329 }, - .{ 2981351763563108441, 1905364105417475727 }, .{ 13453127855076217722, 1524291284333980581 }, - .{ 7073153469319063855, 1219433027467184465 }, .{ 11317045550910502167, 1951092843947495144 }, - .{ 12742985255470312057, 1560874275157996115 }, .{ 10194388204376249646, 1248699420126396892 }, - .{ 1553625868034358140, 1997919072202235028 }, .{ 8621598323911307159, 1598335257761788022 }, - .{ 17965325103354776697, 1278668206209430417 }, .{ 13987124906400001422, 2045869129935088668 }, - .{ 121653480894270168, 1636695303948070935 }, .{ 97322784715416134, 1309356243158456748 }, - .{ 14913111714512307107, 2094969989053530796 }, .{ 8241140556867935363, 1675975991242824637 }, - .{ 17660958889720079260, 1340780792994259709 }, .{ 17189487779326395846, 2145249268790815535 }, - .{ 13751590223461116677, 1716199415032652428 }, .{ 18379969808252713988, 1372959532026121942 }, - .{ 14650556434236701088, 2196735251241795108 }, .{ 652398703163629901, 1757388200993436087 }, - .{ 11589965406756634890, 1405910560794748869 }, .{ 7475898206584884855, 2249456897271598191 }, - .{ 2291369750525997561, 1799565517817278553 }, .{ 9211793429904618695, 1439652414253822842 }, - .{ 18428218302589300235, 2303443862806116547 }, .{ 7363877012587619542, 1842755090244893238 }, - .{ 13269799239553916280, 1474204072195914590 }, .{ 10615839391643133024, 1179363257756731672 }, - .{ 2227947767661371545, 1886981212410770676 }, .{ 16539753473096738529, 1509584969928616540 }, - .{ 13231802778477390823, 1207667975942893232 }, .{ 6413489186596184024, 1932268761508629172 }, - .{ 16198837793502678189, 1545815009206903337 }, .{ 5580372605318321905, 1236652007365522670 }, - .{ 8928596168509315048, 1978643211784836272 }, .{ 18210923379033183008, 1582914569427869017 }, - .{ 7190041073742725760, 1266331655542295214 }, .{ 436019273762630246, 2026130648867672343 }, - .{ 7727513048493924843, 1620904519094137874 }, .{ 9871359253537050198, 1296723615275310299 }, - .{ 4726128361433549347, 2074757784440496479 }, .{ 7470251503888749801, 1659806227552397183 }, - .{ 13354898832594820487, 1327844982041917746 }, .{ 13989140502667892133, 2124551971267068394 }, - .{ 14880661216876224029, 1699641577013654715 }, .{ 11904528973500979224, 1359713261610923772 }, - .{ 4289851098633925465, 2175541218577478036 }, .{ 18189276137874781665, 1740432974861982428 }, - .{ 3483374466074094362, 1392346379889585943 }, .{ 1884050330976640656, 2227754207823337509 }, - .{ 5196589079523222848, 1782203366258670007 }, .{ 15225317707844309248, 1425762693006936005 }, - .{ 5913764258841343181, 2281220308811097609 }, .{ 8420360221814984868, 1824976247048878087 }, - .{ 17804334621677718864, 1459980997639102469 }, .{ 17932816512084085415, 1167984798111281975 }, - .{ 10245762345624985047, 1868775676978051161 }, .{ 4507261061758077715, 1495020541582440929 }, - .{ 7295157664148372495, 1196016433265952743 }, .{ 7982903447895485668, 1913626293225524389 }, - .{ 10075671573058298858, 1530901034580419511 }, .{ 4371188443704728763, 1224720827664335609 }, - .{ 14372599139411386667, 1959553324262936974 }, .{ 15187428126271019657, 1567642659410349579 }, - .{ 15839291315758726049, 1254114127528279663 }, .{ 3206773216762499739, 2006582604045247462 }, - .{ 13633465017635730761, 1605266083236197969 }, .{ 14596120828850494932, 1284212866588958375 }, - .{ 4907049252451240275, 2054740586542333401 }, .{ 236290587219081897, 1643792469233866721 }, - .{ 14946427728742906810, 1315033975387093376 }, .{ 16535586736504830250, 2104054360619349402 }, - .{ 5849771759720043554, 1683243488495479522 }, .{ 15747863852001765813, 1346594790796383617 }, - .{ 10439186904235184007, 2154551665274213788 }, .{ 15730047152871967852, 1723641332219371030 }, - .{ 12584037722297574282, 1378913065775496824 }, .{ 9066413911450387881, 2206260905240794919 }, - .{ 10942479943902220628, 1765008724192635935 }, .{ 8753983955121776503, 1412006979354108748 }, - .{ 10317025513452932081, 2259211166966573997 }, .{ 874922781278525018, 1807368933573259198 }, - .{ 8078635854506640661, 1445895146858607358 }, .{ 13841606313089133175, 1156716117486885886 }, - .{ 14767872471458792434, 1850745787979017418 }, .{ 746251532941302978, 1480596630383213935 }, - .{ 597001226353042382, 1184477304306571148 }, .{ 15712597221132509104, 1895163686890513836 }, - .{ 8880728962164096960, 1516130949512411069 }, .{ 10793931984473187891, 1212904759609928855 }, - .{ 17270291175157100626, 1940647615375886168 }, .{ 2748186495899949531, 1552518092300708935 }, - .{ 2198549196719959625, 1242014473840567148 }, .{ 18275073973719576693, 1987223158144907436 }, - .{ 10930710364233751031, 1589778526515925949 }, .{ 12433917106128911148, 1271822821212740759 }, - .{ 8826220925580526867, 2034916513940385215 }, .{ 7060976740464421494, 1627933211152308172 }, - .{ 16716827836597268165, 1302346568921846537 }, .{ 11989529279587987770, 2083754510274954460 }, - .{ 9591623423670390216, 1667003608219963568 }, .{ 15051996368420132820, 1333602886575970854 }, - .{ 13015147745246481542, 2133764618521553367 }, .{ 3033420566713364587, 1707011694817242694 }, - .{ 6116085268112601993, 1365609355853794155 }, .{ 9785736428980163188, 2184974969366070648 }, - .{ 15207286772667951197, 1747979975492856518 }, .{ 1097782973908629988, 1398383980394285215 }, - .{ 1756452758253807981, 2237414368630856344 }, .{ 5094511021344956708, 1789931494904685075 }, - .{ 4075608817075965366, 1431945195923748060 }, .{ 6520974107321544586, 2291112313477996896 }, - .{ 1527430471115325346, 1832889850782397517 }, .{ 12289990821117991246, 1466311880625918013 }, - .{ 17210690286378213644, 1173049504500734410 }, .{ 9090360384495590213, 1876879207201175057 }, - .{ 18340334751822203140, 1501503365760940045 }, .{ 14672267801457762512, 1201202692608752036 }, - .{ 16096930852848599373, 1921924308174003258 }, .{ 1809498238053148529, 1537539446539202607 }, - .{ 12515645034668249793, 1230031557231362085 }, .{ 1578287981759648052, 1968050491570179337 }, - .{ 12330676829633449412, 1574440393256143469 }, .{ 13553890278448669853, 1259552314604914775 }, - .{ 3239480371808320148, 2015283703367863641 }, .{ 17348979556414297411, 1612226962694290912 }, - .{ 6500486015647617283, 1289781570155432730 }, .{ 10400777625036187652, 2063650512248692368 }, - .{ 15699319729512770768, 1650920409798953894 }, .{ 16248804598352126938, 1320736327839163115 }, - .{ 7551343283653851484, 2113178124542660985 }, .{ 6041074626923081187, 1690542499634128788 }, - .{ 12211557331022285596, 1352433999707303030 }, .{ 1091747655926105338, 2163894399531684849 }, - .{ 4562746939482794594, 1731115519625347879 }, .{ 7339546366328145998, 1384892415700278303 }, - .{ 8053925371383123274, 2215827865120445285 }, .{ 6443140297106498619, 1772662292096356228 }, - .{ 12533209867169019542, 1418129833677084982 }, .{ 5295740528502789974, 2269007733883335972 }, - .{ 15304638867027962949, 1815206187106668777 }, .{ 4865013464138549713, 1452164949685335022 }, - .{ 14960057215536570740, 1161731959748268017 }, .{ 9178696285890871890, 1858771135597228828 }, - .{ 14721654658196518159, 1487016908477783062 }, .{ 4398626097073393881, 1189613526782226450 }, - .{ 7037801755317430209, 1903381642851562320 }, .{ 5630241404253944167, 1522705314281249856 }, - .{ 814844308661245011, 1218164251424999885 }, .{ 1303750893857992017, 1949062802279999816 }, - .{ 15800395974054034906, 1559250241823999852 }, .{ 5261619149759407279, 1247400193459199882 }, - .{ 12107939454356961969, 1995840309534719811 }, .{ 5997002748743659252, 1596672247627775849 }, - .{ 8486951013736837725, 1277337798102220679 }, .{ 2511075177753209390, 2043740476963553087 }, - .{ 13076906586428298482, 1634992381570842469 }, .{ 14150874083884549109, 1307993905256673975 }, - .{ 4194654460505726958, 2092790248410678361 }, .{ 18113118827372222859, 1674232198728542688 }, - .{ 3422448617672047318, 1339385758982834151 }, .{ 16543964232501006678, 2143017214372534641 }, - .{ 9545822571258895019, 1714413771498027713 }, .{ 15015355686490936662, 1371531017198422170 }, - .{ 5577825024675947042, 2194449627517475473 }, .{ 11840957649224578280, 1755559702013980378 }, - .{ 16851463748863483271, 1404447761611184302 }, .{ 12204946739213931940, 2247116418577894884 }, - .{ 13453306206113055875, 1797693134862315907 }, .{ 3383947335406624054, 1438154507889852726 }, - .{ 16482362180876329456, 2301047212623764361 }, .{ 9496540929959153242, 1840837770099011489 }, - .{ 11286581558709232917, 1472670216079209191 }, .{ 5339916432225476010, 1178136172863367353 }, - .{ 4854517476818851293, 1885017876581387765 }, .{ 3883613981455081034, 1508014301265110212 }, - .{ 14174937629389795797, 1206411441012088169 }, .{ 11611853762797942306, 1930258305619341071 }, - .{ 5600134195496443521, 1544206644495472857 }, .{ 15548153800622885787, 1235365315596378285 }, - .{ 6430302007287065643, 1976584504954205257 }, .{ 16212288050055383484, 1581267603963364205 }, - .{ 12969830440044306787, 1265014083170691364 }, .{ 9683682259845159889, 2024022533073106183 }, - .{ 15125643437359948558, 1619218026458484946 }, .{ 8411165935146048523, 1295374421166787957 }, - .{ 17147214310975587960, 2072599073866860731 }, .{ 10028422634038560045, 1658079259093488585 }, - .{ 8022738107230848036, 1326463407274790868 }, .{ 9147032156827446534, 2122341451639665389 }, - .{ 11006974540203867551, 1697873161311732311 }, .{ 5116230817421183718, 1358298529049385849 }, - .{ 15564666937357714594, 2173277646479017358 }, .{ 1383687105660440706, 1738622117183213887 }, - .{ 12174996128754083534, 1390897693746571109 }, .{ 8411947361780802685, 2225436309994513775 }, - .{ 6729557889424642148, 1780349047995611020 }, .{ 5383646311539713719, 1424279238396488816 }, - .{ 1235136468979721303, 2278846781434382106 }, .{ 15745504434151418335, 1823077425147505684 }, - .{ 16285752362063044992, 1458461940118004547 }, .{ 5649904260166615347, 1166769552094403638 }, - .{ 5350498001524674232, 1866831283351045821 }, .{ 591049586477829062, 1493465026680836657 }, - .{ 11540886113407994219, 1194772021344669325 }, .{ 18673707743239135, 1911635234151470921 }, - .{ 14772334225162232601, 1529308187321176736 }, .{ 8128518565387875758, 1223446549856941389 }, - .{ 1937583260394870242, 1957514479771106223 }, .{ 8928764237799716840, 1566011583816884978 }, - .{ 14521709019723594119, 1252809267053507982 }, .{ 8477339172590109297, 2004494827285612772 }, - .{ 17849917782297818407, 1603595861828490217 }, .{ 6901236596354434079, 1282876689462792174 }, - .{ 18420676183650915173, 2052602703140467478 }, .{ 3668494502695001169, 1642082162512373983 }, - .{ 10313493231639821582, 1313665730009899186 }, .{ 9122891541139893884, 2101865168015838698 }, - .{ 14677010862395735754, 1681492134412670958 }, .{ 673562245690857633, 1345193707530136767 } -}; - -// zig fmt: off -// -// f128 small tables: 9072 bytes - -const FLOAT128_POW5_INV_BITCOUNT = 249; -const FLOAT128_POW5_BITCOUNT = 249; -const FLOAT128_POW5_TABLE_SIZE: comptime_int = FLOAT128_POW5_TABLE.len; - -const FLOAT128_POW5_TABLE: [56][2]u64 = .{ - .{ 1, 0 }, - .{ 5, 0 }, - .{ 25, 0 }, - .{ 125, 0 }, - .{ 625, 0 }, - .{ 3125, 0 }, - .{ 15625, 0 }, - .{ 78125, 0 }, - .{ 390625, 0 }, - .{ 1953125, 0 }, - .{ 9765625, 0 }, - .{ 48828125, 0 }, - .{ 244140625, 0 }, - .{ 1220703125, 0 }, - .{ 6103515625, 0 }, - .{ 30517578125, 0 }, - .{ 152587890625, 0 }, - .{ 762939453125, 0 }, - .{ 3814697265625, 0 }, - .{ 19073486328125, 0 }, - .{ 95367431640625, 0 }, - .{ 476837158203125, 0 }, - .{ 2384185791015625, 0 }, - .{ 11920928955078125, 0 }, - .{ 59604644775390625, 0 }, - .{ 298023223876953125, 0 }, - .{ 1490116119384765625, 0 }, - .{ 7450580596923828125, 0 }, - .{ 359414837200037393, 2 }, - .{ 1797074186000186965, 10 }, - .{ 8985370930000934825, 50 }, - .{ 8033366502585570893, 252 }, - .{ 3273344365508751233, 1262 }, - .{ 16366721827543756165, 6310 }, - .{ 8046632842880574361, 31554 }, - .{ 3339676066983768573, 157772 }, - .{ 16698380334918842865, 788860 }, - .{ 9704925379756007861, 3944304 }, - .{ 11631138751360936073, 19721522 }, - .{ 2815461535676025517, 98607613 }, - .{ 14077307678380127585, 493038065 }, - .{ 15046306170771983077, 2465190328 }, - .{ 1444554559021708921, 12325951644 }, - .{ 7222772795108544605, 61629758220 }, - .{ 17667119901833171409, 308148791101 }, - .{ 14548623214327650581, 1540743955509 }, - .{ 17402883850509598057, 7703719777548 }, - .{ 13227442957709783821, 38518598887744 }, - .{ 10796982567420264257, 192592994438723 }, - .{ 17091424689682218053, 962964972193617 }, - .{ 11670147153572883801, 4814824860968089 }, - .{ 3010503546735764157, 24074124304840448 }, - .{ 15052517733678820785, 120370621524202240 }, - .{ 1475612373555897461, 601853107621011204 }, - .{ 7378061867779487305, 3009265538105056020 }, - .{ 18443565265187884909, 15046327690525280101 }, -}; - -const FLOAT128_POW5_SPLIT: [89][4]u64 = .{ - .{ 0, 0, 0, 72057594037927936 }, - .{ 0, 5206161169240293376, 4575641699882439235, 73468396926392969 }, - .{ 3360510775605221349, 6983200512169538081, 4325643253124434363, 74906821675075173 }, - .{ 11917660854915489451, 9652941469841108803, 946308467778435600, 76373409087490117 }, - .{ 1994853395185689235, 16102657350889591545, 6847013871814915412, 77868710555449746 }, - .{ 958415760277438274, 15059347134713823592, 7329070255463483331, 79393288266368765 }, - .{ 2065144883315240188, 7145278325844925976, 14718454754511147343, 80947715414629833 }, - .{ 8980391188862868935, 13709057401304208685, 8230434828742694591, 82532576417087045 }, - .{ 432148644612782575, 7960151582448466064, 12056089168559840552, 84148467132788711 }, - .{ 484109300864744403, 15010663910730448582, 16824949663447227068, 85795995087002057 }, - .{ 14793711725276144220, 16494403799991899904, 10145107106505865967, 87475779699624060 }, - .{ 15427548291869817042, 12330588654550505203, 13980791795114552342, 89188452518064298 }, - .{ 9979404135116626552, 13477446383271537499, 14459862802511591337, 90934657454687378 }, - .{ 12385121150303452775, 9097130814231585614, 6523855782339765207, 92715051028904201 }, - .{ 1822931022538209743, 16062974719797586441, 3619180286173516788, 94530302614003091 }, - .{ 12318611738248470829, 13330752208259324507, 10986694768744162601, 96381094688813589 }, - .{ 13684493829640282333, 7674802078297225834, 15208116197624593182, 98268123094297527 }, - .{ 5408877057066295332, 6470124174091971006, 15112713923117703147, 100192097295163851 }, - .{ 11407083166564425062, 18189998238742408185, 4337638702446708282, 102153740646605557 }, - .{ 4112405898036935485, 924624216579956435, 14251108172073737125, 104153790666259019 }, - .{ 16996739107011444789, 10015944118339042475, 2395188869672266257, 106192999311487969 }, - .{ 4588314690421337879, 5339991768263654604, 15441007590670620066, 108272133262096356 }, - .{ 2286159977890359825, 14329706763185060248, 5980012964059367667, 110391974208576409 }, - .{ 9654767503237031099, 11293544302844823188, 11739932712678287805, 112553319146000238 }, - .{ 11362964448496095896, 7990659682315657680, 251480263940996374, 114756980673665505 }, - .{ 1423410421096377129, 14274395557581462179, 16553482793602208894, 117003787300607788 }, - .{ 2070444190619093137, 11517140404712147401, 11657844572835578076, 119294583757094535 }, - .{ 7648316884775828921, 15264332483297977688, 247182277434709002, 121630231312217685 }, - .{ 17410896758132241352, 10923914482914417070, 13976383996795783649, 124011608097704390 }, - .{ 9542674537907272703, 3079432708831728956, 14235189590642919676, 126439609438067572 }, - .{ 10364666969937261816, 8464573184892924210, 12758646866025101190, 128915148187220428 }, - .{ 14720354822146013883, 11480204489231511423, 7449876034836187038, 131439155071681461 }, - .{ 1692907053653558553, 17835392458598425233, 1754856712536736598, 134012579040499057 }, - .{ 5620591334531458755, 11361776175667106627, 13350215315297937856, 136636387622027174 }, - .{ 17455759733928092601, 10362573084069962561, 11246018728801810510, 139311567287686283 }, - .{ 2465404073814044982, 17694822665274381860, 1509954037718722697, 142039123822846312 }, - .{ 2152236053329638369, 11202280800589637091, 16388426812920420176, 72410041352485523 }, - .{ 17319024055671609028, 10944982848661280484, 2457150158022562661, 73827744744583080 }, - .{ 17511219308535248024, 5122059497846768077, 2089605804219668451, 75273205100637900 }, - .{ 10082673333144031533, 14429008783411894887, 12842832230171903890, 76746965869337783 }, - .{ 16196653406315961184, 10260180891682904501, 10537411930446752461, 78249581139456266 }, - .{ 15084422041749743389, 234835370106753111, 16662517110286225617, 79781615848172976 }, - .{ 8199644021067702606, 3787318116274991885, 7438130039325743106, 81343645993472659 }, - .{ 12039493937039359765, 9773822153580393709, 5945428874398357806, 82936258850702722 }, - .{ 984543865091303961, 7975107621689454830, 6556665988501773347, 84560053193370726 }, - .{ 9633317878125234244, 16099592426808915028, 9706674539190598200, 86215639518264828 }, - .{ 6860695058870476186, 4471839111886709592, 7828342285492709568, 87903640274981819 }, - .{ 14583324717644598331, 4496120889473451238, 5290040788305728466, 89624690099949049 }, - .{ 18093669366515003715, 12879506572606942994, 18005739787089675377, 91379436055028227 }, - .{ 17997493966862379937, 14646222655265145582, 10265023312844161858, 93168537870790806 }, - .{ 12283848109039722318, 11290258077250314935, 9878160025624946825, 94992668194556404 }, - .{ 8087752761883078164, 5262596608437575693, 11093553063763274413, 96852512843287537 }, - .{ 15027787746776840781, 12250273651168257752, 9290470558712181914, 98748771061435726 }, - .{ 15003915578366724489, 2937334162439764327, 5404085603526796602, 100682155783835929 }, - .{ 5225610465224746757, 14932114897406142027, 2774647558180708010, 102653393903748137 }, - .{ 17112957703385190360, 12069082008339002412, 3901112447086388439, 104663226546146909 }, - .{ 4062324464323300238, 3992768146772240329, 15757196565593695724, 106712409346361594 }, - .{ 5525364615810306701, 11855206026704935156, 11344868740897365300, 108801712734172003 }, - .{ 9274143661888462646, 4478365862348432381, 18010077872551661771, 110931922223466333 }, - .{ 12604141221930060148, 8930937759942591500, 9382183116147201338, 113103838707570263 }, - .{ 14513929377491886653, 1410646149696279084, 587092196850797612, 115318278760358235 }, - .{ 2226851524999454362, 7717102471110805679, 7187441550995571734, 117576074943260147 }, - .{ 5527526061344932763, 2347100676188369132, 16976241418824030445, 119878076118278875 }, - .{ 6088479778147221611, 17669593130014777580, 10991124207197663546, 122225147767136307 }, - .{ 11107734086759692041, 3391795220306863431, 17233960908859089158, 124618172316667879 }, - .{ 7913172514655155198, 17726879005381242552, 641069866244011540, 127058049470587962 }, - .{ 12596991768458713949, 15714785522479904446, 6035972567136116512, 129545696547750811 }, - .{ 16901996933781815980, 4275085211437148707, 14091642539965169063, 132082048827034281 }, - .{ 7524574627987869240, 15661204384239316051, 2444526454225712267, 134668059898975949 }, - .{ 8199251625090479942, 6803282222165044067, 16064817666437851504, 137304702024293857 }, - .{ 4453256673338111920, 15269922543084434181, 3139961729834750852, 139992966499426682 }, - .{ 15841763546372731299, 3013174075437671812, 4383755396295695606, 142733864029230733 }, - .{ 9771896230907310329, 4900659362437687569, 12386126719044266361, 72764212553486967 }, - .{ 9420455527449565190, 1859606122611023693, 6555040298902684281, 74188850200884818 }, - .{ 5146105983135678095, 2287300449992174951, 4325371679080264751, 75641380576797959 }, - .{ 11019359372592553360, 8422686425957443718, 7175176077944048210, 77122349788024458 }, - .{ 11005742969399620716, 4132174559240043701, 9372258443096612118, 78632314633490790 }, - .{ 8887589641394725840, 8029899502466543662, 14582206497241572853, 80171842813591127 }, - .{ 360247523705545899, 12568341805293354211, 14653258284762517866, 81741513143625247 }, - .{ 12314272731984275834, 4740745023227177044, 6141631472368337539, 83341915771415304 }, - .{ 441052047733984759, 7940090120939869826, 11750200619921094248, 84973652399183278 }, - .{ 3436657868127012749, 9187006432149937667, 16389726097323041290, 86637336509772529 }, - .{ 13490220260784534044, 15339072891382896702, 8846102360835316895, 88333593597298497 }, - .{ 4125672032094859833, 158347675704003277, 10592598512749774447, 90063061402315272 }, - .{ 12189928252974395775, 2386931199439295891, 7009030566469913276, 91826390151586454 }, - .{ 9256479608339282969, 2844900158963599229, 11148388908923225596, 93624242802550437 }, - .{ 11584393507658707408, 2863659090805147914, 9873421561981063551, 95457295292572042 }, - .{ 13984297296943171390, 1931468383973130608, 12905719743235082319, 97326236793074198 }, - .{ 5837045222254987499, 10213498696735864176, 14893951506257020749, 99231769968645227 }, -}; - -// Unfortunately, the results are sometimes off by one or two. We use an additional -// lookup table to store those cases and adjust the result. -const FLOAT128_POW5_ERRORS: [156]u64 = .{ - 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x9555596400000000, - 0x65a6569525565555, 0x4415551445449655, 0x5105015504144541, 0x65a69969a6965964, - 0x5054955969959656, 0x5105154515554145, 0x4055511051591555, 0x5500514455550115, - 0x0041140014145515, 0x1005440545511051, 0x0014405450411004, 0x0414440010500000, - 0x0044000440010040, 0x5551155000004001, 0x4554555454544114, 0x5150045544005441, - 0x0001111400054501, 0x6550955555554554, 0x1504159645559559, 0x4105055141454545, - 0x1411541410405454, 0x0415555044545555, 0x0014154115405550, 0x1540055040411445, - 0x0000000500000000, 0x5644000000000000, 0x1155555591596555, 0x0410440054569565, - 0x5145100010010005, 0x0555041405500150, 0x4141450455140450, 0x0000000144000140, - 0x5114004001105410, 0x4444100404005504, 0x0414014410001015, 0x5145055155555015, - 0x0141041444445540, 0x0000100451541414, 0x4105041104155550, 0x0500501150451145, - 0x1001050000004114, 0x5551504400141045, 0x5110545410151454, 0x0100001400004040, - 0x5040010111040000, 0x0140000150541100, 0x4400140400104110, 0x5011014405545004, - 0x0000000044155440, 0x0000000010000000, 0x1100401444440001, 0x0040401010055111, - 0x5155155551405454, 0x0444440015514411, 0x0054505054014101, 0x0451015441115511, - 0x1541411401140551, 0x4155104514445110, 0x4141145450145515, 0x5451445055155050, - 0x4400515554110054, 0x5111145104501151, 0x565a655455500501, 0x5565555555525955, - 0x0550511500405695, 0x4415504051054544, 0x6555595965555554, 0x0100915915555655, - 0x5540001510001001, 0x5450051414000544, 0x1405010555555551, 0x5555515555644155, - 0x5555055595496555, 0x5451045004415000, 0x5450510144040144, 0x5554155555556455, - 0x5051555495415555, 0x5555554555555545, 0x0000000010005455, 0x4000005000040000, - 0x5565555555555954, 0x5554559555555505, 0x9645545495552555, 0x4000400055955564, - 0x0040000000000001, 0x4004100100000000, 0x5540040440000411, 0x4565555955545644, - 0x1140659549651556, 0x0100000410010000, 0x5555515400004001, 0x5955545555155255, - 0x5151055545505556, 0x5051454510554515, 0x0501500050415554, 0x5044154005441005, - 0x1455445450550455, 0x0010144055144545, 0x0000401100000004, 0x1050145050000010, - 0x0415004554011540, 0x1000510100151150, 0x0100040400001144, 0x0000000000000000, - 0x0550004400000100, 0x0151145041451151, 0x0000400400005450, 0x0000100044010004, - 0x0100054100050040, 0x0504400005410010, 0x4011410445500105, 0x0000404000144411, - 0x0101504404500000, 0x0000005044400400, 0x0000000014000100, 0x0404440414000000, - 0x5554100410000140, 0x4555455544505555, 0x5454105055455455, 0x0115454155454015, - 0x4404110000045100, 0x4400001100101501, 0x6596955956966a94, 0x0040655955665965, - 0x5554144400100155, 0xa549495401011041, 0x5596555565955555, 0x5569965959549555, - 0x969565a655555456, 0x0000001000000000, 0x0000000040000140, 0x0000040100000000, - 0x1415454400000000, 0x5410415411454114, 0x0400040104000154, 0x0504045000000411, - 0x0000001000000010, 0x5554000000001040, 0x5549155551556595, 0x1455541055515555, - 0x0510555454554541, 0x9555555555540455, 0x6455456555556465, 0x4524565555654514, - 0x5554655255559545, 0x9555455441155556, 0x0000000051515555, 0x0010005040000550, - 0x5044044040000000, 0x1045040440010500, 0x0000400000040000, 0x0000000000000000, -}; - -const FLOAT128_POW5_INV_SPLIT: [89][4]u64 = .{ - .{ 0, 0, 0, 144115188075855872 }, - .{ 1573859546583440065, 2691002611772552616, 6763753280790178510, 141347765182270746 }, - .{ 12960290449513840412, 12345512957918226762, 18057899791198622765, 138633484706040742 }, - .{ 7615871757716765416, 9507132263365501332, 4879801712092008245, 135971326161092377 }, - .{ 7869961150745287587, 5804035291554591636, 8883897266325833928, 133360288657597085 }, - .{ 2942118023529634767, 15128191429820565086, 10638459445243230718, 130799390525667397 }, - .{ 14188759758411913794, 5362791266439207815, 8068821289119264054, 128287668946279217 }, - .{ 7183196927902545212, 1952291723540117099, 12075928209936341512, 125824179589281448 }, - .{ 5672588001402349748, 17892323620748423487, 9874578446960390364, 123407996258356868 }, - .{ 4442590541217566325, 4558254706293456445, 10343828952663182727, 121038210542800766 }, - .{ 3005560928406962566, 2082271027139057888, 13961184524927245081, 118713931475986426 }, - .{ 13299058168408384786, 17834349496131278595, 9029906103900731664, 116434285200389047 }, - .{ 5414878118283973035, 13079825470227392078, 17897304791683760280, 114198414639042157 }, - .{ 14609755883382484834, 14991702445765844156, 3269802549772755411, 112005479173303009 }, - .{ 15967774957605076027, 2511532636717499923, 16221038267832563171, 109854654326805788 }, - .{ 9269330061621627145, 3332501053426257392, 16223281189403734630, 107745131455483836 }, - .{ 16739559299223642282, 1873986623300664530, 6546709159471442872, 105676117443544318 }, - .{ 17116435360051202055, 1359075105581853924, 2038341371621886470, 103646834405281051 }, - .{ 17144715798009627550, 3201623802661132408, 9757551605154622431, 101656519392613377 }, - .{ 17580479792687825857, 6546633380567327312, 15099972427870912398, 99704424108241124 }, - .{ 9726477118325522902, 14578369026754005435, 11728055595254428803, 97789814624307808 }, - .{ 134593949518343635, 5715151379816901985, 1660163707976377376, 95911971106466306 }, - .{ 5515914027713859358, 7124354893273815720, 5548463282858794077, 94070187543243255 }, - .{ 6188403395862945512, 5681264392632320838, 15417410852121406654, 92263771480600430 }, - .{ 15908890877468271457, 10398888261125597540, 4817794962769172309, 90492043761593298 }, - .{ 1413077535082201005, 12675058125384151580, 7731426132303759597, 88754338271028867 }, - .{ 1486733163972670293, 11369385300195092554, 11610016711694864110, 87050001685026843 }, - .{ 8788596583757589684, 3978580923851924802, 9255162428306775812, 85378393225389919 }, - .{ 7203518319660962120, 15044736224407683725, 2488132019818199792, 83738884418690858 }, - .{ 4004175967662388707, 18236988667757575407, 15613100370957482671, 82130858859985791 }, - .{ 18371903370586036463, 53497579022921640, 16465963977267203307, 80553711981064899 }, - .{ 10170778323887491315, 1999668801648976001, 10209763593579456445, 79006850823153334 }, - .{ 17108131712433974546, 16825784443029944237, 2078700786753338945, 77489693813976938 }, - .{ 17221789422665858532, 12145427517550446164, 5391414622238668005, 76001670549108934 }, - .{ 4859588996898795878, 1715798948121313204, 3950858167455137171, 74542221577515387 }, - .{ 13513469241795711526, 631367850494860526, 10517278915021816160, 73110798191218799 }, - .{ 11757513142672073111, 2581974932255022228, 17498959383193606459, 143413724438001539 }, - .{ 14524355192525042817, 5640643347559376447, 1309659274756813016, 140659771648132296 }, - .{ 2765095348461978538, 11021111021896007722, 3224303603779962366, 137958702611185230 }, - .{ 12373410389187981037, 13679193545685856195, 11644609038462631561, 135309501808182158 }, - .{ 12813176257562780151, 3754199046160268020, 9954691079802960722, 132711173221007413 }, - .{ 17557452279667723458, 3237799193992485824, 17893947919029030695, 130162739957935629 }, - .{ 14634200999559435155, 4123869946105211004, 6955301747350769239, 127663243886350468 }, - .{ 2185352760627740240, 2864813346878886844, 13049218671329690184, 125211745272516185 }, - .{ 6143438674322183002, 10464733336980678750, 6982925169933978309, 122807322428266620 }, - .{ 1099509117817174576, 10202656147550524081, 754997032816608484, 120449071364478757 }, - .{ 2410631293559367023, 17407273750261453804, 15307291918933463037, 118136105451200587 }, - .{ 12224968375134586697, 1664436604907828062, 11506086230137787358, 115867555084305488 }, - .{ 3495926216898000888, 18392536965197424288, 10992889188570643156, 113642567358547782 }, - .{ 8744506286256259680, 3966568369496879937, 18342264969761820037, 111460305746896569 }, - .{ 7689600520560455039, 5254331190877624630, 9628558080573245556, 109319949786027263 }, - .{ 11862637625618819436, 3456120362318976488, 14690471063106001082, 107220694767852583 }, - .{ 5697330450030126444, 12424082405392918899, 358204170751754904, 105161751436977040 }, - .{ 11257457505097373622, 15373192700214208870, 671619062372033814, 103142345693961148 }, - .{ 16850355018477166700, 1913910419361963966, 4550257919755970531, 101161718304283822 }, - .{ 9670835567561997011, 10584031339132130638, 3060560222974851757, 99219124612893520 }, - .{ 7698686577353054710, 11689292838639130817, 11806331021588878241, 97313834264240819 }, - .{ 12233569599615692137, 3347791226108469959, 10333904326094451110, 95445130927687169 }, - .{ 13049400362825383933, 17142621313007799680, 3790542585289224168, 93612312028186576 }, - .{ 12430457242474442072, 5625077542189557960, 14765055286236672238, 91814688482138969 }, - .{ 4759444137752473128, 2230562561567025078, 4954443037339580076, 90051584438315940 }, - .{ 7246913525170274758, 8910297835195760709, 4015904029508858381, 88322337023761438 }, - .{ 12854430245836432067, 8135139748065431455, 11548083631386317976, 86626296094571907 }, - .{ 4848827254502687803, 4789491250196085625, 3988192420450664125, 84962823991462151 }, - .{ 7435538409611286684, 904061756819742353, 14598026519493048444, 83331295300025028 }, - .{ 11042616160352530997, 8948390828345326218, 10052651191118271927, 81731096615594853 }, - .{ 11059348291563778943, 11696515766184685544, 3783210511290897367, 80161626312626082 }, - .{ 7020010856491885826, 5025093219346041680, 8960210401638911765, 78622294318500592 }, - .{ 17732844474490699984, 7820866704994446502, 6088373186798844243, 77112521891678506 }, - .{ 688278527545590501, 3045610706602776618, 8684243536999567610, 75631741404109150 }, - .{ 2734573255120657297, 3903146411440697663, 9470794821691856713, 74179396127820347 }, - .{ 15996457521023071259, 4776627823451271680, 12394856457265744744, 72754940025605801 }, - .{ 13492065758834518331, 7390517611012222399, 1630485387832860230, 142715675091463768 }, - .{ 13665021627282055864, 9897834675523659302, 17907668136755296849, 139975126841173266 }, - .{ 9603773719399446181, 10771916301484339398, 10672699855989487527, 137287204938390542 }, - .{ 3630218541553511265, 8139010004241080614, 2876479648932814543, 134650898807055963 }, - .{ 8318835909686377084, 9525369258927993371, 2796120270400437057, 132065217277054270 }, - .{ 11190003059043290163, 12424345635599592110, 12539346395388933763, 129529188211565064 }, - .{ 8701968833973242276, 820569587086330727, 2315591597351480110, 127041858141569228 }, - .{ 5115113890115690487, 16906305245394587826, 9899749468931071388, 124602291907373862 }, - .{ 15543535488939245974, 10945189844466391399, 3553863472349432246, 122209572307020975 }, - .{ 7709257252608325038, 1191832167690640880, 15077137020234258537, 119862799751447719 }, - .{ 7541333244210021737, 9790054727902174575, 5160944773155322014, 117561091926268545 }, - .{ 12297384708782857832, 1281328873123467374, 4827925254630475769, 115303583460052092 }, - .{ 13243237906232367265, 15873887428139547641, 3607993172301799599, 113089425598968120 }, - .{ 11384616453739611114, 15184114243769211033, 13148448124803481057, 110917785887682141 }, - .{ 17727970963596660683, 1196965221832671990, 14537830463956404138, 108787847856377790 }, - .{ 17241367586707330931, 8880584684128262874, 11173506540726547818, 106698810713789254 }, - .{ 7184427196661305643, 14332510582433188173, 14230167953789677901, 104649889046128358 }, -}; - -const FLOAT128_POW5_INV_ERRORS: [154]u64 = .{ - 0x1144155514145504, 0x0000541555401141, 0x0000000000000000, 0x0154454000000000, - 0x4114105515544440, 0x0001001111500415, 0x4041411410011000, 0x5550114515155014, - 0x1404100041554551, 0x0515000450404410, 0x5054544401140004, 0x5155501005555105, - 0x1144141000105515, 0x0541500000500000, 0x1104105540444140, 0x4000015055514110, - 0x0054010450004005, 0x4155515404100005, 0x5155145045155555, 0x1511555515440558, - 0x5558544555515555, 0x0000000000000010, 0x5004000000000050, 0x1415510100000010, - 0x4545555444514500, 0x5155151555555551, 0x1441540144044554, 0x5150104045544400, - 0x5450545401444040, 0x5554455045501400, 0x4655155555555145, 0x1000010055455055, - 0x1000004000055004, 0x4455405104000005, 0x4500114504150545, 0x0000000014000000, - 0x5450000000000000, 0x5514551511445555, 0x4111501040555451, 0x4515445500054444, - 0x5101500104100441, 0x1545115155545055, 0x0000000000000000, 0x1554000000100000, - 0x5555545595551555, 0x5555051851455955, 0x5555555555555559, 0x0000400011001555, - 0x0000004400040000, 0x5455511555554554, 0x5614555544115445, 0x6455156145555155, - 0x5455855455415455, 0x5515555144555545, 0x0114400000145155, 0x0000051000450511, - 0x4455154554445100, 0x4554150141544455, 0x65955555559a5965, 0x5555555854559559, - 0x9569654559616595, 0x1040044040005565, 0x1010010500011044, 0x1554015545154540, - 0x4440555401545441, 0x1014441450550105, 0x4545400410504145, 0x5015111541040151, - 0x5145051154000410, 0x1040001044545044, 0x4001400000151410, 0x0540000044040000, - 0x0510555454411544, 0x0400054054141550, 0x1001041145001100, 0x0000000140000000, - 0x0000000014100000, 0x1544005454000140, 0x4050055505445145, 0x0011511104504155, - 0x5505544415045055, 0x1155154445515554, 0x0000000000004555, 0x0000000000000000, - 0x5101010510400004, 0x1514045044440400, 0x5515519555515555, 0x4554545441555545, - 0x1551055955551515, 0x0150000011505515, 0x0044005040400000, 0x0004001004010050, - 0x0000051004450414, 0x0114001101001144, 0x0401000001000001, 0x4500010001000401, - 0x0004100000005000, 0x0105000441101100, 0x0455455550454540, 0x5404050144105505, - 0x4101510540555455, 0x1055541411451555, 0x5451445110115505, 0x1154110010101545, - 0x1145140450054055, 0x5555565415551554, 0x1550559555555555, 0x5555541545045141, - 0x4555455450500100, 0x5510454545554555, 0x1510140115045455, 0x1001050040111510, - 0x5555454555555504, 0x9954155545515554, 0x6596656555555555, 0x0140410051555559, - 0x0011104010001544, 0x965669659a680501, 0x5655a55955556955, 0x4015111014404514, - 0x1414155554505145, 0x0540040011051404, 0x1010000000015005, 0x0010054050004410, - 0x5041104014000100, 0x4440010500100001, 0x1155510504545554, 0x0450151545115541, - 0x4000100400110440, 0x1004440010514440, 0x0000115050450000, 0x0545404455541500, - 0x1051051555505101, 0x5505144554544144, 0x4550545555515550, 0x0015400450045445, - 0x4514155400554415, 0x4555055051050151, 0x1511441450001014, 0x4544554510404414, - 0x4115115545545450, 0x5500541555551555, 0x5550010544155015, 0x0144414045545500, - 0x4154050001050150, 0x5550511111000145, 0x1114504055000151, 0x5104041101451040, - 0x0010501401051441, 0x0010501450504401, 0x4554585440044444, 0x5155555951450455, - 0x0040000400105555, 0x0000000000000001, -}; - -// zig fmt: on - -const builtin = @import("builtin"); - -fn check(comptime T: type, value: T, comptime expected: []const u8) !void { - const I = @Type(.{ .int = .{ .signedness = .unsigned, .bits = @bitSizeOf(T) } }); - - var buf: [6000]u8 = undefined; - const value_bits: I = @bitCast(value); - const s = try formatFloat(&buf, value, .{}); - try std.testing.expectEqualStrings(expected, s); - - if (T == f80 and builtin.target.os.tag == .windows and builtin.target.cpu.arch == .x86_64) return; - - const o = try std.fmt.parseFloat(T, s); - const o_bits: I = @bitCast(o); - - if (std.math.isNan(value)) { - try std.testing.expect(std.math.isNan(o)); - } else { - try std.testing.expectEqual(value_bits, o_bits); - } -} - -test "format f32" { - try check(f32, 0.0, "0e0"); - try check(f32, -0.0, "-0e0"); - try check(f32, 1.0, "1e0"); - try check(f32, -1.0, "-1e0"); - try check(f32, std.math.nan(f32), "nan"); - try check(f32, std.math.inf(f32), "inf"); - try check(f32, -std.math.inf(f32), "-inf"); - try check(f32, 1.1754944e-38, "1.1754944e-38"); - try check(f32, @bitCast(@as(u32, 0x7f7fffff)), "3.4028235e38"); - try check(f32, @bitCast(@as(u32, 1)), "1e-45"); - try check(f32, 3.355445E7, "3.355445e7"); - try check(f32, 8.999999e9, "9e9"); - try check(f32, 3.4366717e10, "3.436672e10"); - try check(f32, 3.0540412e5, "3.0540412e5"); - try check(f32, 8.0990312e3, "8.0990312e3"); - try check(f32, 2.4414062e-4, "2.4414062e-4"); - try check(f32, 2.4414062e-3, "2.4414062e-3"); - try check(f32, 4.3945312e-3, "4.3945312e-3"); - try check(f32, 6.3476562e-3, "6.3476562e-3"); - try check(f32, 4.7223665e21, "4.7223665e21"); - try check(f32, 8388608.0, "8.388608e6"); - try check(f32, 1.6777216e7, "1.6777216e7"); - try check(f32, 3.3554436e7, "3.3554436e7"); - try check(f32, 6.7131496e7, "6.7131496e7"); - try check(f32, 1.9310392e-38, "1.9310392e-38"); - try check(f32, -2.47e-43, "-2.47e-43"); - try check(f32, 1.993244e-38, "1.993244e-38"); - try check(f32, 4103.9003, "4.1039004e3"); - try check(f32, 5.3399997e9, "5.3399997e9"); - try check(f32, 6.0898e-39, "6.0898e-39"); - try check(f32, 0.0010310042, "1.0310042e-3"); - try check(f32, 2.8823261e17, "2.882326e17"); - try check(f32, 7.038531e-26, "7.038531e-26"); - try check(f32, 9.2234038e17, "9.223404e17"); - try check(f32, 6.7108872e7, "6.710887e7"); - try check(f32, 1.0e-44, "1e-44"); - try check(f32, 2.816025e14, "2.816025e14"); - try check(f32, 9.223372e18, "9.223372e18"); - try check(f32, 1.5846085e29, "1.5846086e29"); - try check(f32, 1.1811161e19, "1.1811161e19"); - try check(f32, 5.368709e18, "5.368709e18"); - try check(f32, 4.6143165e18, "4.6143166e18"); - try check(f32, 0.007812537, "7.812537e-3"); - try check(f32, 1.4e-45, "1e-45"); - try check(f32, 1.18697724e20, "1.18697725e20"); - try check(f32, 1.00014165e-36, "1.00014165e-36"); - try check(f32, 200.0, "2e2"); - try check(f32, 3.3554432e7, "3.3554432e7"); - - try check(f32, 1.0, "1e0"); - try check(f32, 1.2, "1.2e0"); - try check(f32, 1.23, "1.23e0"); - try check(f32, 1.234, "1.234e0"); - try check(f32, 1.2345, "1.2345e0"); - try check(f32, 1.23456, "1.23456e0"); - try check(f32, 1.234567, "1.234567e0"); - try check(f32, 1.2345678, "1.2345678e0"); - try check(f32, 1.23456735e-36, "1.23456735e-36"); -} - -test "format f64" { - try check(f64, 0.0, "0e0"); - try check(f64, -0.0, "-0e0"); - try check(f64, 1.0, "1e0"); - try check(f64, -1.0, "-1e0"); - try check(f64, std.math.nan(f64), "nan"); - try check(f64, std.math.inf(f64), "inf"); - try check(f64, -std.math.inf(f64), "-inf"); - try check(f64, 2.2250738585072014e-308, "2.2250738585072014e-308"); - try check(f64, @bitCast(@as(u64, 0x7fefffffffffffff)), "1.7976931348623157e308"); - try check(f64, @bitCast(@as(u64, 1)), "5e-324"); - try check(f64, 2.98023223876953125e-8, "2.9802322387695312e-8"); - try check(f64, -2.109808898695963e16, "-2.109808898695963e16"); - try check(f64, 4.940656e-318, "4.940656e-318"); - try check(f64, 1.18575755e-316, "1.18575755e-316"); - try check(f64, 2.989102097996e-312, "2.989102097996e-312"); - try check(f64, 9.0608011534336e15, "9.0608011534336e15"); - try check(f64, 4.708356024711512e18, "4.708356024711512e18"); - try check(f64, 9.409340012568248e18, "9.409340012568248e18"); - try check(f64, 1.2345678, "1.2345678e0"); - try check(f64, @bitCast(@as(u64, 0x4830f0cf064dd592)), "5.764607523034235e39"); - try check(f64, @bitCast(@as(u64, 0x4840f0cf064dd592)), "1.152921504606847e40"); - try check(f64, @bitCast(@as(u64, 0x4850f0cf064dd592)), "2.305843009213694e40"); - - try check(f64, 1, "1e0"); - try check(f64, 1.2, "1.2e0"); - try check(f64, 1.23, "1.23e0"); - try check(f64, 1.234, "1.234e0"); - try check(f64, 1.2345, "1.2345e0"); - try check(f64, 1.23456, "1.23456e0"); - try check(f64, 1.234567, "1.234567e0"); - try check(f64, 1.2345678, "1.2345678e0"); - try check(f64, 1.23456789, "1.23456789e0"); - try check(f64, 1.234567895, "1.234567895e0"); - try check(f64, 1.2345678901, "1.2345678901e0"); - try check(f64, 1.23456789012, "1.23456789012e0"); - try check(f64, 1.234567890123, "1.234567890123e0"); - try check(f64, 1.2345678901234, "1.2345678901234e0"); - try check(f64, 1.23456789012345, "1.23456789012345e0"); - try check(f64, 1.234567890123456, "1.234567890123456e0"); - try check(f64, 1.2345678901234567, "1.2345678901234567e0"); - - try check(f64, 4.294967294, "4.294967294e0"); - try check(f64, 4.294967295, "4.294967295e0"); - try check(f64, 4.294967296, "4.294967296e0"); - try check(f64, 4.294967297, "4.294967297e0"); - try check(f64, 4.294967298, "4.294967298e0"); -} - -test "format f80" { - try check(f80, 0.0, "0e0"); - try check(f80, -0.0, "-0e0"); - try check(f80, 1.0, "1e0"); - try check(f80, -1.0, "-1e0"); - try check(f80, std.math.nan(f80), "nan"); - try check(f80, std.math.inf(f80), "inf"); - try check(f80, -std.math.inf(f80), "-inf"); - - try check(f80, 2.2250738585072014e-308, "2.2250738585072014e-308"); - try check(f80, 2.98023223876953125e-8, "2.98023223876953125e-8"); - try check(f80, -2.109808898695963e16, "-2.109808898695963e16"); - try check(f80, 4.940656e-318, "4.940656e-318"); - try check(f80, 1.18575755e-316, "1.18575755e-316"); - try check(f80, 2.989102097996e-312, "2.989102097996e-312"); - try check(f80, 9.0608011534336e15, "9.0608011534336e15"); - try check(f80, 4.708356024711512e18, "4.708356024711512e18"); - try check(f80, 9.409340012568248e18, "9.409340012568248e18"); - try check(f80, 1.2345678, "1.2345678e0"); -} - -test "format f128" { - try check(f128, 0.0, "0e0"); - try check(f128, -0.0, "-0e0"); - try check(f128, 1.0, "1e0"); - try check(f128, -1.0, "-1e0"); - try check(f128, std.math.nan(f128), "nan"); - try check(f128, std.math.inf(f128), "inf"); - try check(f128, -std.math.inf(f128), "-inf"); - - try check(f128, 2.2250738585072014e-308, "2.2250738585072014e-308"); - try check(f128, 2.98023223876953125e-8, "2.98023223876953125e-8"); - try check(f128, -2.109808898695963e16, "-2.109808898695963e16"); - try check(f128, 4.940656e-318, "4.940656e-318"); - try check(f128, 1.18575755e-316, "1.18575755e-316"); - try check(f128, 2.989102097996e-312, "2.989102097996e-312"); - try check(f128, 9.0608011534336e15, "9.0608011534336e15"); - try check(f128, 4.708356024711512e18, "4.708356024711512e18"); - try check(f128, 9.409340012568248e18, "9.409340012568248e18"); - try check(f128, 1.2345678, "1.2345678e0"); -} - -test "format float to decimal with zero precision" { - try expectFmt("5", "{d:.0}", .{5}); - try expectFmt("6", "{d:.0}", .{6}); - try expectFmt("7", "{d:.0}", .{7}); - try expectFmt("8", "{d:.0}", .{8}); -} diff --git a/lib/std/fs/File.zig b/lib/std/fs/File.zig index 30b98cddf091eab677d30259a17e29d6ec18e7c3..47b94497d29c9ec7cce6893271e2bbc957c6a493 100644 --- a/lib/std/fs/File.zig +++ b/lib/std/fs/File.zig @@ -1587,12 +1587,112 @@ pub fn reader(file: File) Reader { return .{ .context = file }; } -pub const Writer = io.Writer(File, WriteError, write); +pub fn writer(file: File) std.io.Writer { + return .{ + .context = interface.handleToOpaque(file.handle), + .vtable = &.{ + .writev = interface.writev, + .writeFile = interface.writeFile, + }, + }; +} -pub fn writer(file: File) Writer { - return .{ .context = file }; +pub fn unbufferedWriter(file: File) std.io.BufferedWriter { + return .{ + .buffer = &.{}, + .unbuffered_writer = writer(file), + }; } +const interface = struct { + /// Number of slices to store on the stack, when trying to send as many byte + /// vectors through the underlying write calls as possible. + const max_buffers_len = 16; + + fn writev(context: *anyopaque, data: []const []const u8) anyerror!usize { + const file = opaqueToHandle(context); + + if (is_windows) { + // TODO improve this to use WriteFileScatter + if (data.len == 0) return 0; + const first = data[0]; + return windows.WriteFile(file, first.base[0..first.len], null); + } + + var iovecs_buffer: [max_buffers_len]std.posix.iovec_const = undefined; + const iovecs = iovecs_buffer[0..@min(iovecs_buffer.len, data.len)]; + for (iovecs, data[0..iovecs.len]) |*v, d| v.* = .{ .base = d.ptr, .len = d.len }; + return std.posix.writev(file, iovecs); + } + + fn writeFile( + context: *anyopaque, + in_file: std.fs.File, + in_offset: u64, + in_len: std.io.Writer.VTable.FileLen, + headers_and_trailers: []const []const u8, + headers_len: usize, + ) anyerror!usize { + const out_fd = opaqueToHandle(context); + const in_fd = in_file.handle; + const len_int = switch (in_len) { + .zero => return interface.writev(context, headers_and_trailers), + .entire_file => 0, + else => in_len.int(), + }; + var iovecs_buffer: [max_buffers_len]std.posix.iovec_const = undefined; + const iovecs = iovecs_buffer[0..@min(iovecs_buffer.len, headers_and_trailers.len)]; + for (iovecs, headers_and_trailers[0..iovecs.len]) |*v, d| v.* = .{ .base = d.ptr, .len = d.len }; + const headers = iovecs[0..@min(headers_len, iovecs.len)]; + const trailers = iovecs[headers.len..]; + const flags = 0; + return posix.sendfile(out_fd, in_fd, in_offset, len_int, headers, trailers, flags) catch |err| switch (err) { + error.Unseekable, + error.FastOpenAlreadyInProgress, + error.MessageTooBig, + error.FileDescriptorNotASocket, + error.NetworkUnreachable, + error.NetworkSubsystemFailed, + => return writeFileUnseekable(out_fd, in_fd, in_offset, in_len, headers_and_trailers, headers_len), + + else => |e| return e, + }; + } + + fn writeFileUnseekable( + out_fd: Handle, + in_fd: Handle, + in_offset: u64, + in_len: std.io.Writer.VTable.FileLen, + headers_and_trailers: []const []const u8, + headers_len: usize, + ) anyerror!usize { + _ = out_fd; + _ = in_fd; + _ = in_offset; + _ = in_len; + _ = headers_and_trailers; + _ = headers_len; + @panic("TODO writeFileUnseekable"); + } + + fn handleToOpaque(handle: File.Handle) *anyopaque { + return switch (@typeInfo(Handle)) { + .pointer => @ptrCast(handle), + .int => @ptrFromInt(@as(u32, @bitCast(handle))), + else => @compileError("unhandled"), + }; + } + + fn opaqueToHandle(userdata: *anyopaque) Handle { + return switch (@typeInfo(Handle)) { + .pointer => @ptrCast(userdata), + .int => @intCast(@intFromPtr(userdata)), + else => @compileError("unhandled"), + }; + } +}; + pub const SeekableStream = io.SeekableStream( File, SeekError, diff --git a/lib/std/io.zig b/lib/std/io.zig index 597b8d5ec1e173b3552b9a8a5f639018645e672d..619ac8c9e64cc64c47ca8763cdc979f14e987a2e 100644 --- a/lib/std/io.zig +++ b/lib/std/io.zig @@ -336,7 +336,7 @@ pub fn GenericWriter( return @errorCast(self.any().writeStructEndian(value, endian)); } - pub inline fn any(self: *const Self) AnyWriter { + pub inline fn any(self: *const Self) Writer { return .{ .context = @ptrCast(&self.context), .writeFn = typeErasedWriteFn, @@ -351,26 +351,23 @@ pub fn GenericWriter( } /// Deprecated; consider switching to `AnyReader` or use `GenericReader` -/// to use previous API. +/// to use previous API. To be removed after 0.14.0 is tagged. pub const Reader = GenericReader; -/// Deprecated; consider switching to `AnyWriter` or use `GenericWriter` -/// to use previous API. -pub const Writer = GenericWriter; +pub const Writer = @import("io/Writer.zig"); pub const AnyReader = @import("io/Reader.zig"); -pub const AnyWriter = @import("io/Writer.zig"); +/// Deprecated; to be removed after 0.14.0 is tagged. +pub const AnyWriter = Writer; pub const SeekableStream = @import("io/seekable_stream.zig").SeekableStream; -pub const BufferedWriter = @import("io/buffered_writer.zig").BufferedWriter; -pub const bufferedWriter = @import("io/buffered_writer.zig").bufferedWriter; +pub const BufferedWriter = @import("io/BufferedWriter.zig"); pub const BufferedReader = @import("io/buffered_reader.zig").BufferedReader; pub const bufferedReader = @import("io/buffered_reader.zig").bufferedReader; pub const bufferedReaderSize = @import("io/buffered_reader.zig").bufferedReaderSize; -pub const FixedBufferStream = @import("io/fixed_buffer_stream.zig").FixedBufferStream; -pub const fixedBufferStream = @import("io/fixed_buffer_stream.zig").fixedBufferStream; +pub const FixedBufferStream = @import("io/FixedBufferStream.zig"); pub const CWriter = @import("io/c_writer.zig").CWriter; pub const cWriter = @import("io/c_writer.zig").cWriter; @@ -378,8 +375,7 @@ pub const cWriter = @import("io/c_writer.zig").cWriter; pub const LimitedReader = @import("io/limited_reader.zig").LimitedReader; pub const limitedReader = @import("io/limited_reader.zig").limitedReader; -pub const CountingWriter = @import("io/counting_writer.zig").CountingWriter; -pub const countingWriter = @import("io/counting_writer.zig").countingWriter; +pub const CountingWriter = @import("io/CountingWriter.zig"); pub const CountingReader = @import("io/counting_reader.zig").CountingReader; pub const countingReader = @import("io/counting_reader.zig").countingReader; @@ -404,17 +400,42 @@ pub const StreamSource = @import("io/stream_source.zig").StreamSource; pub const tty = @import("io/tty.zig"); -/// A Writer that doesn't write to anything. -pub const null_writer: NullWriter = .{ .context = {} }; +/// A `Writer` that discards all data. +pub const null_writer: Writer = .{ + .context = undefined, + .vtable = &.{ + .writev = null_writev, + .writeFile = null_writeFile, + }, +}; -pub const NullWriter = Writer(void, error{}, dummyWrite); -fn dummyWrite(context: void, data: []const u8) error{}!usize { +fn null_writev(context: *anyopaque, data: []const []const u8) anyerror!usize { _ = context; - return data.len; + var n: usize = 0; + for (data) |bytes| n += bytes.len; + return n; +} + +fn null_writeFile( + context: *anyopaque, + file: std.fs.File, + offset: u64, + len: Writer.VTable.FileLen, + headers_and_trailers: []const []const u8, + headers_len: usize, +) anyerror!usize { + _ = context; + _ = offset; + _ = headers_len; + _ = file; + if (len == .entire_file) return error.Unimplemented; + var n: usize = 0; + for (headers_and_trailers) |bytes| n += bytes.len; + return len.int() + n; } test null_writer { - null_writer.writeAll("yay" ** 10) catch |err| switch (err) {}; + try null_writer.writeAll("yay"); } pub fn poll( @@ -820,16 +841,15 @@ pub fn PollFiles(comptime StreamEnum: type) type { test { _ = AnyReader; - _ = AnyWriter; + _ = Writer; + _ = CountingWriter; + _ = FixedBufferStream; _ = @import("io/bit_reader.zig"); _ = @import("io/bit_writer.zig"); _ = @import("io/buffered_atomic_file.zig"); _ = @import("io/buffered_reader.zig"); - _ = @import("io/buffered_writer.zig"); _ = @import("io/c_writer.zig"); - _ = @import("io/counting_writer.zig"); _ = @import("io/counting_reader.zig"); - _ = @import("io/fixed_buffer_stream.zig"); _ = @import("io/seekable_stream.zig"); _ = @import("io/stream_source.zig"); _ = @import("io/test.zig"); diff --git a/lib/std/io/BufferedWriter.zig b/lib/std/io/BufferedWriter.zig new file mode 100644 index 0000000000000000000000000000000000000000..e60b79ecedff72c648981035280d9e0cf0c17ccd --- /dev/null +++ b/lib/std/io/BufferedWriter.zig @@ -0,0 +1,1494 @@ +const std = @import("../std.zig"); +const BufferedWriter = @This(); +const assert = std.debug.assert; +const native_endian = @import("builtin").target.cpu.arch.endian(); +const Writer = std.io.Writer; +const testing = std.testing; + +/// Underlying stream to send bytes to. +unbuffered_writer: Writer, +/// User-provided storage that must outlive this `BufferedWriter`. +/// +/// If this has length zero, the writer is unbuffered, and `flush` is a no-op. +buffer: []u8, +/// Marks the end of `buffer` - before this are buffered bytes, after this is +/// undefined. +end: usize = 0, + +/// Number of slices to store on the stack, when trying to send as many byte +/// vectors through the underlying write calls as possible. +pub const max_buffers_len = 8; + +const passthru_vtable: Writer.VTable = .{ + .writev = passthru_writev, + .writeFile = passthru_writeFile, +}; + +const fixed_vtable: Writer.VTable = .{ + .writev = fixed_writev, + .writeFile = fixed_writeFile, +}; + +pub fn writer(bw: *BufferedWriter) Writer { + return .{ + .context = bw, + .vtable = &passthru_vtable, + }; +} + +/// Replaces the `BufferedWriter` with a new one that writes to `buffer` and +/// returns `error.NoSpaceLeft` when it is full. +pub fn initFixed(bw: *BufferedWriter, buffer: []u8) void { + bw.* = .{ + .unbuffered_writer = .{ + .context = bw, + .vtable = &fixed_vtable, + }, + .buffer = buffer, + }; +} + +/// This function is available when using `initFixed`. +pub fn getWritten(bw: *const BufferedWriter) []u8 { + assert(bw.unbuffered_writer.vtable == &fixed_vtable); + return bw.buffer[0..bw.end]; +} + +/// This function is available when using `initFixed`. +pub fn reset(bw: *BufferedWriter) void { + assert(bw.unbuffered_writer.vtable == &fixed_vtable); + bw.end = 0; +} + +pub fn flush(bw: *BufferedWriter) anyerror!void { + try bw.unbuffered_writer.writeAll(bw.buffer[0..bw.end]); + bw.end = 0; +} + +/// The `data` parameter is mutable because this function needs to mutate the +/// fields in order to handle partial writes from `Writer.VTable.writev`. +pub fn writevAll(bw: *BufferedWriter, data: []const []const u8) anyerror!void { + var i: usize = 0; + while (true) { + var n = try writev(bw, data[i..]); + while (n >= data[i].len) { + n -= data[i].len; + i += 1; + if (i >= data.len) return; + } + data[i] = data[i][n..]; + } +} + +pub fn writev(bw: *BufferedWriter, data: []const []const u8) anyerror!usize { + return passthru_writev(bw, data); +} + +fn passthru_writev(context: *anyopaque, data: []const []const u8) anyerror!usize { + const bw: *BufferedWriter = @alignCast(@ptrCast(context)); + const buffer = bw.buffer; + const start_end = bw.end; + var end = bw.end; + for (data, 0..) |bytes, i| { + const new_end = end + bytes.len; + if (new_end <= buffer.len) { + @branchHint(.likely); + @memcpy(buffer[end..new_end], bytes); + end = new_end; + continue; + } + var buffers: [max_buffers_len][]const u8 = undefined; + buffers[0] = buffer[0..end]; + const remaining_data = data[i..]; + const remaining_buffers = buffers[1..]; + const len: usize = @min(remaining_data.len, remaining_buffers.len); + @memcpy(remaining_buffers[0..len], remaining_data[0..len]); + const n = try bw.unbuffered_writer.writev(buffers[0 .. len + 1]); + if (n < end) { + @branchHint(.unlikely); + const remainder = buffer[n..end]; + std.mem.copyForwards(u8, buffer[0..remainder.len], remainder); + bw.end = remainder.len; + return end - start_end; + } + bw.end = 0; + return n - start_end; + } + bw.end = end; + return end - start_end; +} + +fn fixed_writev(context: *anyopaque, data: []const []const u8) anyerror!usize { + const bw: *BufferedWriter = @alignCast(@ptrCast(context)); + // When this function is called it means the buffer got full, so it's time + // to return an error. However, we still need to make sure all of the + // available buffer has been used. + const first = data[0]; + const dest = bw.buffer[bw.end..]; + @memcpy(dest, first[0..dest.len]); + return error.NoSpaceLeft; +} + +pub fn write(bw: *BufferedWriter, bytes: []const u8) anyerror!usize { + const buffer = bw.buffer; + const end = bw.end; + const new_end = end + bytes.len; + if (new_end > buffer.len) { + var data: [2][]const u8 = .{ buffer[0..end], bytes }; + const n = try bw.unbuffered_writer.writev(&data); + if (n < end) { + @branchHint(.unlikely); + const remainder = buffer[n..end]; + std.mem.copyForwards(u8, buffer[0..remainder.len], remainder); + bw.end = remainder.len; + return 0; + } + bw.end = 0; + return n - end; + } + @memcpy(buffer[end..new_end], bytes); + bw.end = new_end; + return bytes.len; +} + +/// This function is provided by the `Writer`, however it is +/// duplicated here so that `bw` can be passed to `std.fmt.format` directly, +/// avoiding one indirect function call. +pub fn writeAll(bw: *BufferedWriter, bytes: []const u8) anyerror!void { + var index: usize = 0; + while (index < bytes.len) index += try write(bw, bytes[index..]); +} + +pub fn print(bw: *BufferedWriter, comptime format: []const u8, args: anytype) anyerror!void { + return std.fmt.format(bw, format, args); +} + +pub fn writeByte(bw: *BufferedWriter, byte: u8) anyerror!void { + const buffer = bw.buffer; + const end = bw.end; + if (end == buffer.len) { + @branchHint(.unlikely); + var buffers: [2][]const u8 = .{ buffer, &.{byte} }; + while (true) { + const n = try bw.unbuffered_writer.writev(&buffers); + if (n == 0) { + @branchHint(.unlikely); + continue; + } else if (n >= buffer.len) { + @branchHint(.likely); + if (n > buffer.len) { + @branchHint(.likely); + bw.end = 0; + return; + } else { + buffer[0] = byte; + bw.end = 1; + return; + } + } + const remainder = buffer[n..]; + std.mem.copyForwards(u8, buffer[0..remainder.len], remainder); + buffer[remainder.len] = byte; + bw.end = remainder.len + 1; + return; + } + } + buffer[end] = byte; + bw.end = end + 1; +} + +/// Writes the same byte many times, performing the underlying write call as +/// many times as necessary. +pub fn splatByteAll(bw: *BufferedWriter, byte: u8, n: usize) anyerror!void { + var remaining: usize = n; + while (remaining > 0) remaining -= try splatByte(bw, byte, remaining); +} + +/// Writes the same byte many times, allowing short writes. +/// +/// Does maximum of one underlying `Writer.VTable.writev`. +pub fn splatByte(bw: *BufferedWriter, byte: u8, n: usize) anyerror!usize { + const buffer = bw.buffer; + const end = bw.end; + + const new_end = end + n; + if (new_end <= buffer.len) { + @memset(buffer[end..][0..n], byte); + bw.end = new_end; + return n; + } + + if (n <= buffer.len) { + const written = try bw.unbuffered_writer.write(buffer[0..end]); + if (written < end) { + @branchHint(.unlikely); + const remainder = buffer[written..end]; + std.mem.copyForwards(u8, buffer[0..remainder.len], remainder); + bw.end = remainder.len; + return 0; + } + @memset(buffer[0..n], byte); + bw.end = n; + return n; + } + + // First try to use only the unused buffer region, to make an attempt for a + // single `writev`. + const free_space = buffer[end..]; + var remaining = n - free_space.len; + @memset(free_space, byte); + var buffers: [max_buffers_len][]const u8 = undefined; + buffers[0] = buffer; + var buffer_i: usize = 1; + while (remaining > free_space.len and buffer_i < buffers.len) { + buffers[buffer_i] = free_space; + buffer_i += 1; + remaining -= free_space.len; + } + if (remaining > 0 and buffer_i < buffers.len) { + buffers[buffer_i] = free_space[0..remaining]; + buffer_i += 1; + const written = try bw.unbuffered_writer.writev(buffers[0..buffer_i]); + if (written < end) { + @branchHint(.unlikely); + const remainder = buffer[written..end]; + std.mem.copyForwards(u8, buffer[0..remainder.len], remainder); + bw.end = remainder.len; + return 0; + } + bw.end = 0; + return written - end; + } + + const written = try bw.unbuffered_writer.writev(buffers[0..buffer_i]); + if (written < end) { + @branchHint(.unlikely); + const remainder = buffer[written..end]; + std.mem.copyForwards(u8, buffer[0..remainder.len], remainder); + bw.end = remainder.len; + return 0; + } + + bw.end = 0; + return written - end; +} + +/// Writes the same slice many times, performing the underlying write call as +/// many times as necessary. +pub fn splatBytesAll(bw: *BufferedWriter, bytes: []const u8, n: usize) anyerror!void { + var remaining: usize = n * bytes.len; + while (remaining > 0) remaining -= try splatBytes(bw, bytes, remaining); +} + +/// Writes the same slice many times, allowing short writes. +/// +/// Does maximum of one underlying `Writer.VTable.writev`. +pub fn splatBytes(bw: *BufferedWriter, bytes: []const u8, n: usize) anyerror!usize { + const buffer = bw.buffer; + const start_end = bw.end; + var end = start_end; + var remaining = n; + while (remaining > 0 and end + bytes.len <= buffer.len) { + @memcpy(buffer[end..][0..bytes.len], bytes); + end += bytes.len; + remaining -= 1; + } + + if (remaining == 0) { + bw.end = end; + return end - start_end; + } + + var buffers: [max_buffers_len][]const u8 = undefined; + var buffer_i: usize = 1; + buffers[0] = buffer[0..end]; + const remaining_buffers = buffers[1..]; + const buffers_len: usize = @min(remaining, remaining_buffers.len); + @memset(remaining_buffers[0..buffers_len], bytes); + remaining -= buffers_len; + buffer_i += buffers_len; + + const written = try bw.unbuffered_writer.writev(buffers[0..buffer_i]); + if (written < end) { + @branchHint(.unlikely); + const remainder = buffer[written..end]; + std.mem.copyForwards(u8, buffer[0..remainder.len], remainder); + bw.end = remainder.len; + return end - start_end; + } + bw.end = 0; + return written - start_end; +} + +/// Asserts the `buffer` was initialized with a capacity of at least `@sizeOf(T)` bytes. +pub inline fn writeInt(bw: *BufferedWriter, comptime T: type, value: T, endian: std.builtin.Endian) anyerror!void { + var bytes: [@divExact(@typeInfo(T).int.bits, 8)]u8 = undefined; + std.mem.writeInt(std.math.ByteAlignedInt(@TypeOf(value)), &bytes, value, endian); + return bw.writeAll(&bytes); +} + +pub fn writeStruct(bw: *BufferedWriter, value: anytype) anyerror!void { + // Only extern and packed structs have defined in-memory layout. + comptime assert(@typeInfo(@TypeOf(value)).@"struct".layout != .auto); + return bw.writeAll(std.mem.asBytes(&value)); +} + +pub fn writeStructEndian(bw: *BufferedWriter, value: anytype, endian: std.builtin.Endian) anyerror!void { + // TODO: make sure this value is not a reference type + if (native_endian == endian) { + return bw.writeStruct(value); + } else { + var copy = value; + std.mem.byteSwapAllFields(@TypeOf(value), ©); + return bw.writeStruct(copy); + } +} + +pub fn writeFile( + bw: *BufferedWriter, + file: std.fs.File, + offset: u64, + len: Writer.VTable.FileLen, + headers_and_trailers: []const []const u8, + headers_len: usize, +) anyerror!usize { + return passthru_writeFile(bw, file, offset, len, headers_and_trailers, headers_len); +} + +fn passthru_writeFile( + context: *anyopaque, + file: std.fs.File, + offset: u64, + len: Writer.VTable.FileLen, + headers_and_trailers: []const []const u8, + headers_len: usize, +) anyerror!usize { + const bw: *BufferedWriter = @alignCast(@ptrCast(context)); + const buffer = bw.buffer; + const start_end = bw.end; + const headers = headers_and_trailers[0..headers_len]; + const trailers = headers_and_trailers[headers_len..]; + var buffers: [max_buffers_len][]const u8 = undefined; + var end = start_end; + for (headers, 0..) |header, i| { + const new_end = end + header.len; + if (new_end <= buffer.len) { + @branchHint(.likely); + @memcpy(buffer[end..new_end], header); + end = new_end; + continue; + } + buffers[0] = buffer[0..end]; + const remaining_headers = headers[i..]; + const remaining_buffers = buffers[1..]; + const buffers_len: usize = @min(remaining_headers.len, remaining_buffers.len); + @memcpy(remaining_buffers[0..buffers_len], remaining_headers[0..buffers_len]); + if (buffers_len >= remaining_headers.len) { + // Made it past the headers, so we can call `writeFile`. + const remaining_buffers_for_trailers = remaining_buffers[buffers_len..]; + const send_trailers_len: usize = @min(trailers.len, remaining_buffers_for_trailers.len); + @memcpy(remaining_buffers_for_trailers[0..send_trailers_len], trailers[0..send_trailers_len]); + const send_headers_len = 1 + buffers_len; + const send_buffers = buffers[0 .. send_headers_len + send_trailers_len]; + const n = try bw.unbuffered_writer.writeFile(file, offset, len, send_buffers, send_headers_len); + if (n < end) { + @branchHint(.unlikely); + const remainder = buffer[n..end]; + std.mem.copyForwards(u8, buffer[0..remainder.len], remainder); + bw.end = remainder.len; + return end - start_end; + } + bw.end = 0; + return n - start_end; + } + // Have not made it past the headers yet; must call `writev`. + const n = try bw.unbuffered_writer.writev(buffers[0 .. buffers_len + 1]); + if (n < end) { + @branchHint(.unlikely); + const remainder = buffer[n..end]; + std.mem.copyForwards(u8, buffer[0..remainder.len], remainder); + bw.end = remainder.len; + return end - start_end; + } + bw.end = 0; + return n - start_end; + } + // All headers written to buffer. + buffers[0] = buffer[0..end]; + const remaining_buffers = buffers[1..]; + const send_trailers_len: usize = @min(trailers.len, remaining_buffers.len); + @memcpy(remaining_buffers[0..send_trailers_len], trailers[0..send_trailers_len]); + const send_headers_len = 1; + const send_buffers = buffers[0 .. send_headers_len + send_trailers_len]; + const n = try bw.unbuffered_writer.writeFile(file, offset, len, send_buffers, send_headers_len); + if (n < end) { + @branchHint(.unlikely); + const remainder = buffer[n..end]; + std.mem.copyForwards(u8, buffer[0..remainder.len], remainder); + bw.end = remainder.len; + return end - start_end; + } + bw.end = 0; + return n - start_end; +} + +pub const WriteFileOptions = struct { + offset: u64 = 0, + /// If the size of the source file is known, it is likely that passing the + /// size here will save one syscall. + len: Writer.VTable.FileLen = .entire_file, + /// Headers and trailers must be passed together so that in case `len` is + /// zero, they can be forwarded directly to `Writer.VTable.writev`. + /// + /// The parameter is mutable because this function needs to mutate the + /// fields in order to handle partial writes from `Writer.VTable.writeFile`. + headers_and_trailers: [][]const u8 = &.{}, + /// The number of trailers is inferred from `headers_and_trailers.len - + /// headers_len`. + headers_len: usize = 0, +}; + +pub fn writeFileAll(bw: *BufferedWriter, file: std.fs.File, options: WriteFileOptions) anyerror!void { + const headers_and_trailers = options.headers_and_trailers; + const headers = headers_and_trailers[0..options.headers_len]; + var len = options.len; + var i: usize = 0; + var offset = options.offset; + if (len == .zero) return writevAll(bw, headers_and_trailers[i..]); + while (i < headers_and_trailers.len) { + var n = try writeFile(bw, file, offset, len, headers_and_trailers[i..], headers.len - i); + while (i < headers.len and n >= headers[i].len) { + n -= headers[i].len; + i += 1; + } + if (i < headers.len) { + headers[i] = headers[i][n..]; + continue; + } + if (n >= len.int()) { + n -= len.int(); + while (n >= headers_and_trailers[i].len) { + n -= headers_and_trailers[i].len; + i += 1; + if (i >= headers_and_trailers.len) return; + } + headers_and_trailers[i] = headers_and_trailers[i][n..]; + return writevAll(bw, headers_and_trailers[i..]); + } + offset += n; + len = if (len == .entire_file) .entire_file else .init(len.int() - n); + } +} + +fn fixed_writeFile( + context: *anyopaque, + file: std.fs.File, + offset: u64, + len: Writer.VTable.FileLen, + headers_and_trailers: []const []const u8, + headers_len: usize, +) anyerror!usize { + _ = context; + _ = file; + _ = offset; + _ = len; + _ = headers_and_trailers; + _ = headers_len; + return error.Unimplemented; +} + +pub fn alignBuffer( + bw: *BufferedWriter, + buffer: []const u8, + width: usize, + alignment: std.fmt.Alignment, + fill: u8, +) anyerror!void { + const padding = if (buffer.len < width) width - buffer.len else 0; + if (padding == 0) { + @branchHint(.likely); + return bw.writeAll(buffer); + } + switch (alignment) { + .left => { + try bw.writeAll(buffer); + try bw.splatByteAll(fill, padding); + }, + .center => { + const left_padding = padding / 2; + const right_padding = (padding + 1) / 2; + try bw.splatByteAll(fill, left_padding); + try bw.writeAll(buffer); + try bw.splatByteAll(fill, right_padding); + }, + .right => { + try bw.splatByteAll(fill, padding); + try bw.writeAll(buffer); + }, + } +} + +pub fn alignBufferOptions(bw: *BufferedWriter, buffer: []const u8, options: std.fmt.Options) anyerror!void { + return alignBuffer(bw, buffer, options.width orelse buffer.len, options.alignment, options.fill); +} + +pub fn printAddress(bw: *BufferedWriter, value: anytype) anyerror!void { + const T = @TypeOf(value); + + switch (@typeInfo(T)) { + .pointer => |info| { + try bw.writeAll(@typeName(info.child) ++ "@"); + if (info.size == .slice) + try printIntOptions(bw, @intFromPtr(value.ptr), 16, .lower, .{}) + else + try printIntOptions(bw, @intFromPtr(value), 16, .lower, .{}); + return; + }, + .optional => |info| { + if (@typeInfo(info.child) == .pointer) { + try bw.writeAll(@typeName(info.child) ++ "@"); + try printIntOptions(bw, @intFromPtr(value), 16, .lower, .{}); + return; + } + }, + else => {}, + } + + @compileError("cannot format non-pointer type " ++ @typeName(T) ++ " with * specifier"); +} + +pub fn printValue( + bw: *BufferedWriter, + comptime fmt: []const u8, + options: std.fmt.Options, + value: anytype, + max_depth: usize, +) anyerror!void { + const T = @TypeOf(value); + const actual_fmt = comptime if (std.mem.eql(u8, fmt, ANY)) + defaultFormatString(T) + else if (fmt.len != 0 and (fmt[0] == '?' or fmt[0] == '!')) switch (@typeInfo(T)) { + .optional, .error_union => fmt, + else => stripOptionalOrErrorUnionSpec(fmt), + } else fmt; + + if (comptime std.mem.eql(u8, actual_fmt, "*")) { + return printAddress(bw, value); + } + + if (std.meta.hasMethod(T, "format")) { + if (fmt.len == 0) { + // @deprecated() + // After 0.14.0 is tagged, uncomment this next line: + //@compileError("ambiguous format string; specify {f} to call print method, or {any} to skip it"); + return value.format(fmt, options, bw); + } else if (fmt[0] == 'f') { + return value.format(fmt[1..], options, bw); + } + } + + switch (@typeInfo(T)) { + .float, .comptime_float => return printFloat(bw, actual_fmt, options, value), + .int, .comptime_int => return printInt(bw, actual_fmt, options, value), + .bool => { + if (actual_fmt.len != 0) invalidFmtError(fmt, value); + return alignBufferOptions(bw, if (value) "true" else "false", options); + }, + .void => { + if (actual_fmt.len != 0) invalidFmtError(fmt, value); + return alignBufferOptions(bw, "void", options); + }, + .optional => { + if (actual_fmt.len == 0 or actual_fmt[0] != '?') + @compileError("cannot print optional without a specifier (i.e. {?} or {any})"); + const remaining_fmt = comptime stripOptionalOrErrorUnionSpec(actual_fmt); + if (value) |payload| { + return printValue(bw, remaining_fmt, options, payload, max_depth); + } else { + return alignBufferOptions(bw, "null", options); + } + }, + .error_union => { + if (actual_fmt.len == 0 or actual_fmt[0] != '!') + @compileError("cannot format error union without a specifier (i.e. {!} or {any})"); + const remaining_fmt = comptime stripOptionalOrErrorUnionSpec(actual_fmt); + if (value) |payload| { + return printValue(bw, remaining_fmt, options, payload, max_depth); + } else |err| { + return printValue(bw, "", options, err, max_depth); + } + }, + .error_set => { + if (actual_fmt.len != 0) invalidFmtError(fmt, value); + try bw.writeAll("error."); + return bw.writeAll(@errorName(value)); + }, + .@"enum" => |enumInfo| { + try bw.writeAll(@typeName(T)); + if (enumInfo.is_exhaustive) { + if (actual_fmt.len != 0) invalidFmtError(fmt, value); + try bw.writeAll("."); + try bw.writeAll(@tagName(value)); + return; + } + + // Use @tagName only if value is one of known fields + @setEvalBranchQuota(3 * enumInfo.fields.len); + inline for (enumInfo.fields) |enumField| { + if (@intFromEnum(value) == enumField.value) { + try bw.writeAll("."); + try bw.writeAll(@tagName(value)); + return; + } + } + + try bw.writeByte('('); + try printValue(bw, actual_fmt, options, @intFromEnum(value), max_depth); + try bw.writeByte(')'); + }, + .@"union" => |info| { + if (actual_fmt.len != 0) invalidFmtError(fmt, value); + try bw.writeAll(@typeName(T)); + if (max_depth == 0) { + return bw.writeAll("{ ... }"); + } + if (info.tag_type) |UnionTagType| { + try bw.writeAll("{ ."); + try bw.writeAll(@tagName(@as(UnionTagType, value))); + try bw.writeAll(" = "); + inline for (info.fields) |u_field| { + if (value == @field(UnionTagType, u_field.name)) { + try printValue(bw, ANY, options, @field(value, u_field.name), max_depth - 1); + } + } + try bw.writeAll(" }"); + } else { + try bw.writeByte('@'); + try bw.printIntOptions(@intFromPtr(&value), 16, .lower); + } + }, + .@"struct" => |info| { + if (actual_fmt.len != 0) invalidFmtError(fmt, value); + if (info.is_tuple) { + // Skip the type and field names when formatting tuples. + if (max_depth == 0) { + return bw.writeAll("{ ... }"); + } + try bw.writeAll("{"); + inline for (info.fields, 0..) |f, i| { + if (i == 0) { + try bw.writeAll(" "); + } else { + try bw.writeAll(", "); + } + try printValue(bw, ANY, options, @field(value, f.name), max_depth - 1); + } + return bw.writeAll(" }"); + } + try bw.writeAll(@typeName(T)); + if (max_depth == 0) { + return bw.writeAll("{ ... }"); + } + try bw.writeAll("{"); + inline for (info.fields, 0..) |f, i| { + if (i == 0) { + try bw.writeAll(" ."); + } else { + try bw.writeAll(", ."); + } + try bw.writeAll(f.name); + try bw.writeAll(" = "); + try printValue(bw, ANY, options, @field(value, f.name), max_depth - 1); + } + try bw.writeAll(" }"); + }, + .pointer => |ptr_info| switch (ptr_info.size) { + .one => switch (@typeInfo(ptr_info.child)) { + .array, .@"enum", .@"union", .@"struct" => { + return printValue(bw, actual_fmt, options, value.*, max_depth); + }, + else => { + const buffers: [2][]const u8 = .{ @typeName(ptr_info.child), "@" }; + try writevAll(bw, &buffers); + try printIntOptions(bw, @intFromPtr(value), 16, .lower); + }, + }, + .many, .c => { + if (actual_fmt.len == 0) + @compileError("cannot format pointer without a specifier (i.e. {s} or {*})"); + if (ptr_info.sentinel() != null) { + return printValue(bw, actual_fmt, options, std.mem.span(value), max_depth); + } + if (actual_fmt[0] == 's' and ptr_info.child == u8) { + return alignBufferOptions(bw, std.mem.span(value), options); + } + invalidFmtError(fmt, value); + }, + .slice => { + if (actual_fmt.len == 0) + @compileError("cannot format slice without a specifier (i.e. {s} or {any})"); + if (max_depth == 0) { + return bw.writeAll("{ ... }"); + } + if (actual_fmt[0] == 's' and ptr_info.child == u8) { + return alignBufferOptions(bw, value, options); + } + try bw.writeAll("{ "); + for (value, 0..) |elem, i| { + try printValue(bw, actual_fmt, options, elem, max_depth - 1); + if (i != value.len - 1) { + try bw.writeAll(", "); + } + } + try bw.writeAll(" }"); + }, + }, + .array => |info| { + if (actual_fmt.len == 0) + @compileError("cannot format array without a specifier (i.e. {s} or {any})"); + if (max_depth == 0) { + return bw.writeAll("{ ... }"); + } + if (actual_fmt[0] == 's' and info.child == u8) { + return alignBufferOptions(bw, &value, options); + } + try bw.writeAll("{ "); + for (value, 0..) |elem, i| { + try printValue(bw, actual_fmt, options, elem, max_depth - 1); + if (i < value.len - 1) { + try bw.writeAll(", "); + } + } + try bw.writeAll(" }"); + }, + .vector => |info| { + if (max_depth == 0) { + return bw.writeAll("{ ... }"); + } + try bw.writeAll("{ "); + var i: usize = 0; + while (i < info.len) : (i += 1) { + try printValue(bw, actual_fmt, options, value[i], max_depth - 1); + if (i < info.len - 1) { + try bw.writeAll(", "); + } + } + try bw.writeAll(" }"); + }, + .@"fn" => @compileError("unable to format function body type, use '*const " ++ @typeName(T) ++ "' for a function pointer type"), + .type => { + if (actual_fmt.len != 0) invalidFmtError(fmt, value); + return alignBufferOptions(bw, @typeName(value), options); + }, + .enum_literal => { + if (actual_fmt.len != 0) invalidFmtError(fmt, value); + const buffer = [_]u8{'.'} ++ @tagName(value); + return alignBufferOptions(bw, buffer, options); + }, + .null => { + if (actual_fmt.len != 0) invalidFmtError(fmt, value); + return alignBufferOptions(bw, "null", options); + }, + else => @compileError("unable to format type '" ++ @typeName(T) ++ "'"), + } +} + +pub fn printInt( + bw: *BufferedWriter, + comptime fmt: []const u8, + options: std.fmt.Options, + value: anytype, +) anyerror!void { + comptime var base = 10; + comptime var case: std.fmt.Case = .lower; + + const int_value = if (@TypeOf(value) == comptime_int) blk: { + const Int = std.math.IntFittingRange(value, value); + break :blk @as(Int, value); + } else value; + + if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "d")) { + base = 10; + case = .lower; + } else if (comptime std.mem.eql(u8, fmt, "c")) { + if (@typeInfo(@TypeOf(int_value)).int.bits <= 8) { + return printAsciiChar(bw, @as(u8, int_value), options); + } else { + @compileError("cannot print integer that is larger than 8 bits as an ASCII character"); + } + } else if (comptime std.mem.eql(u8, fmt, "u")) { + if (@typeInfo(@TypeOf(int_value)).int.bits <= 21) { + return printUnicodeCodepoint(bw, @as(u21, int_value), options); + } else { + @compileError("cannot print integer that is larger than 21 bits as an UTF-8 sequence"); + } + } else if (comptime std.mem.eql(u8, fmt, "b")) { + base = 2; + case = .lower; + } else if (comptime std.mem.eql(u8, fmt, "x")) { + base = 16; + case = .lower; + } else if (comptime std.mem.eql(u8, fmt, "X")) { + base = 16; + case = .upper; + } else if (comptime std.mem.eql(u8, fmt, "o")) { + base = 8; + case = .lower; + } else { + invalidFmtError(fmt, value); + } + + return printIntOptions(bw, int_value, base, case, options); +} + +pub fn printAsciiChar(bw: *BufferedWriter, c: u8, options: std.fmt.Options) anyerror!void { + return alignBufferOptions(bw, @as(*const [1]u8, &c), options); +} + +pub fn printAscii(bw: *BufferedWriter, bytes: []const u8, options: std.fmt.Options) anyerror!void { + return alignBufferOptions(bw, bytes, options); +} + +pub fn printUnicodeCodepoint(bw: *BufferedWriter, c: u21, options: std.fmt.Options) anyerror!void { + var buf: [4]u8 = undefined; + const len = try std.unicode.utf8Encode(c, &buf); + return alignBufferOptions(bw, buf[0..len], options); +} + +pub fn printIntOptions( + bw: *BufferedWriter, + value: anytype, + base: u8, + case: std.fmt.Case, + options: std.fmt.Options, +) anyerror!void { + assert(base >= 2); + + const int_value = if (@TypeOf(value) == comptime_int) blk: { + const Int = std.math.IntFittingRange(value, value); + break :blk @as(Int, value); + } else value; + + const value_info = @typeInfo(@TypeOf(int_value)).int; + + // The type must have the same size as `base` or be wider in order for the + // division to work + const min_int_bits = comptime @max(value_info.bits, 8); + const MinInt = std.meta.Int(.unsigned, min_int_bits); + + const abs_value = @abs(int_value); + // The worst case in terms of space needed is base 2, plus 1 for the sign + var buf: [1 + @max(@as(comptime_int, value_info.bits), 1)]u8 = undefined; + + var a: MinInt = abs_value; + var index: usize = buf.len; + + if (base == 10) { + while (a >= 100) : (a = @divTrunc(a, 100)) { + index -= 2; + buf[index..][0..2].* = std.fmt.digits2(@intCast(a % 100)); + } + + if (a < 10) { + index -= 1; + buf[index] = '0' + @as(u8, @intCast(a)); + } else { + index -= 2; + buf[index..][0..2].* = std.fmt.digits2(@intCast(a)); + } + } else { + while (true) { + const digit = a % base; + index -= 1; + buf[index] = std.fmt.digitToChar(@intCast(digit), case); + a /= base; + if (a == 0) break; + } + } + + if (value_info.signedness == .signed) { + if (value < 0) { + // Negative integer + index -= 1; + buf[index] = '-'; + } else if (options.width == null or options.width.? == 0) { + // Positive integer, omit the plus sign + } else { + // Positive integer + index -= 1; + buf[index] = '+'; + } + } + + return alignBufferOptions(bw, buf[index..], options); +} + +pub fn printFloat( + bw: *BufferedWriter, + comptime fmt: []const u8, + options: std.fmt.Options, + value: anytype, +) anyerror!void { + var buf: [std.fmt.float.bufferSize(.decimal, f64)]u8 = undefined; + + if (fmt.len > 1) invalidFmtError(fmt, value); + switch (if (fmt.len == 0) 'e' else fmt[0]) { + 'e' => { + const s = std.fmt.float.render(&buf, value, .{ .mode = .scientific, .precision = options.precision }) catch |err| switch (err) { + error.BufferTooSmall => "(float)", + }; + return alignBufferOptions(bw, s, options); + }, + 'd' => { + const s = std.fmt.float.render(&buf, value, .{ .mode = .decimal, .precision = options.precision }) catch |err| switch (err) { + error.BufferTooSmall => "(float)", + }; + return alignBufferOptions(bw, s, options); + }, + 'x' => { + var sub_bw: BufferedWriter = undefined; + sub_bw.initFixed(&buf); + sub_bw.printFloatHexadecimal(value, options) catch unreachable; + return alignBufferOptions(bw, sub_bw.getWritten(), options); + }, + else => invalidFmtError(fmt, value), + } +} + +pub fn printFloatHexadecimal(bw: *BufferedWriter, value: anytype, opt_precision: ?usize) anyerror!void { + if (std.math.signbit(value)) try bw.writeByte('-'); + if (std.math.isNan(value)) return bw.writeAll("nan"); + if (std.math.isInf(value)) return bw.writeAll("inf"); + + const T = @TypeOf(value); + const TU = std.meta.Int(.unsigned, @bitSizeOf(T)); + + const mantissa_bits = std.math.floatMantissaBits(T); + const fractional_bits = std.math.floatFractionalBits(T); + const exponent_bits = std.math.floatExponentBits(T); + const mantissa_mask = (1 << mantissa_bits) - 1; + const exponent_mask = (1 << exponent_bits) - 1; + const exponent_bias = (1 << (exponent_bits - 1)) - 1; + + const as_bits: TU = @bitCast(value); + var mantissa = as_bits & mantissa_mask; + var exponent: i32 = @as(u16, @truncate((as_bits >> mantissa_bits) & exponent_mask)); + + const is_denormal = exponent == 0 and mantissa != 0; + const is_zero = exponent == 0 and mantissa == 0; + + if (is_zero) { + // Handle this case here to simplify the logic below. + try bw.writeAll("0x0"); + if (opt_precision) |precision| { + if (precision > 0) { + try bw.writeAll("."); + try bw.splatByteAll('0', precision); + } + } else { + try bw.writeAll(".0"); + } + try bw.writeAll("p0"); + return; + } + + if (is_denormal) { + // Adjust the exponent for printing. + exponent += 1; + } else { + if (fractional_bits == mantissa_bits) + mantissa |= 1 << fractional_bits; // Add the implicit integer bit. + } + + const mantissa_digits = (fractional_bits + 3) / 4; + // Fill in zeroes to round the fraction width to a multiple of 4. + mantissa <<= mantissa_digits * 4 - fractional_bits; + + if (opt_precision) |precision| { + // Round if needed. + if (precision < mantissa_digits) { + // We always have at least 4 extra bits. + var extra_bits = (mantissa_digits - precision) * 4; + // The result LSB is the Guard bit, we need two more (Round and + // Sticky) to round the value. + while (extra_bits > 2) { + mantissa = (mantissa >> 1) | (mantissa & 1); + extra_bits -= 1; + } + // Round to nearest, tie to even. + mantissa |= @intFromBool(mantissa & 0b100 != 0); + mantissa += 1; + // Drop the excess bits. + mantissa >>= 2; + // Restore the alignment. + mantissa <<= @as(std.math.Log2Int(TU), @intCast((mantissa_digits - precision) * 4)); + + const overflow = mantissa & (1 << 1 + mantissa_digits * 4) != 0; + // Prefer a normalized result in case of overflow. + if (overflow) { + mantissa >>= 1; + exponent += 1; + } + } + } + + // +1 for the decimal part. + var buf: [1 + mantissa_digits]u8 = undefined; + assert(std.fmt.printInt(&buf, mantissa, 16, .lower, .{ .fill = '0', .width = 1 + mantissa_digits }) == buf.len); + + try bw.writeAll("0x"); + try bw.writeByte(buf[0]); + const trimmed = std.mem.trimRight(u8, buf[1..], "0"); + if (opt_precision) |precision| { + if (precision > 0) try bw.writeAll("."); + } else if (trimmed.len > 0) { + try bw.writeAll("."); + } + try bw.writeAll(trimmed); + // Add trailing zeros if explicitly requested. + if (opt_precision) |precision| if (precision > 0) { + if (precision > trimmed.len) + try bw.writeByteNTimes('0', precision - trimmed.len); + }; + try bw.writeAll("p"); + try printIntOptions(bw, exponent - exponent_bias, 10, .lower, .{}); +} + +pub const ByteSizeUnits = enum { + /// This formatter represents the number as multiple of 1000 and uses the SI + /// measurement units (kB, MB, GB, ...). + decimal, + /// This formatter represents the number as multiple of 1024 and uses the IEC + /// measurement units (KiB, MiB, GiB, ...). + binary, +}; + +/// Format option `precision` is ignored when `value` is less than 1kB +pub fn printByteSize( + bw: *std.io.BufferedWriter, + value: u64, + units: ByteSizeUnits, + options: std.fmt.Options, +) anyerror!void { + if (value == 0) return alignBufferOptions(bw, "0B", options); + // The worst case in terms of space needed is 32 bytes + 3 for the suffix. + var buf: [std.fmt.float.min_buffer_size + 3]u8 = undefined; + + const mags_si = " kMGTPEZY"; + const mags_iec = " KMGTPEZY"; + + const log2 = std.math.log2(value); + const base = switch (units) { + .decimal => 1000, + .binary => 1024, + }; + const magnitude = switch (units) { + .decimal => @min(log2 / comptime std.math.log2(1000), mags_si.len - 1), + .binary => @min(log2 / 10, mags_iec.len - 1), + else => unreachable, + }; + const new_value = std.math.lossyCast(f64, value) / std.math.pow(f64, std.math.lossyCast(f64, base), std.math.lossyCast(f64, magnitude)); + const suffix = switch (units) { + .decimal => mags_si[magnitude], + .binary => mags_iec[magnitude], + else => unreachable, + }; + + const s = switch (magnitude) { + 0 => buf[0..std.fmt.printInt(&buf, value, 10, .lower, .{})], + else => std.fmt.float.render(&buf, new_value, .{ .mode = .decimal, .precision = options.precision }) catch |err| switch (err) { + error.BufferTooSmall => unreachable, + }, + }; + + var i: usize = s.len; + if (suffix == ' ') { + buf[i] = 'B'; + i += 1; + } else switch (units) { + .decimal => { + buf[i..][0..2].* = [_]u8{ suffix, 'B' }; + i += 2; + }, + .binary => { + buf[i..][0..3].* = [_]u8{ suffix, 'i', 'B' }; + i += 3; + }, + else => unreachable, + } + + return alignBufferOptions(buf[0..i], options, bw); +} + +// This ANY const is a workaround for: https://github.com/ziglang/zig/issues/7948 +const ANY = "any"; + +fn defaultFormatString(comptime T: type) [:0]const u8 { + switch (@typeInfo(T)) { + .array, .vector => return ANY, + .pointer => |ptr_info| switch (ptr_info.size) { + .one => switch (@typeInfo(ptr_info.child)) { + .array => return ANY, + else => {}, + }, + .many, .c => return "*", + .slice => return ANY, + }, + .optional => |info| return "?" ++ defaultFormatString(info.child), + .error_union => |info| return "!" ++ defaultFormatString(info.payload), + else => {}, + } + return ""; +} + +fn stripOptionalOrErrorUnionSpec(comptime fmt: []const u8) []const u8 { + return if (std.mem.eql(u8, fmt[1..], ANY)) + ANY + else + fmt[1..]; +} + +pub fn invalidFmtError(comptime fmt: []const u8, value: anytype) noreturn { + @compileError("invalid format string '" ++ fmt ++ "' for type '" ++ @typeName(@TypeOf(value)) ++ "'"); +} + +pub fn printDurationSigned(bw: *BufferedWriter, ns: i64) anyerror!void { + if (ns < 0) try bw.writeByte('-'); + return printDurationUnsigned(bw, @abs(ns)); +} + +pub fn printDurationUnsigned(bw: *BufferedWriter, ns: u64) anyerror!void { + var ns_remaining = ns; + inline for (.{ + .{ .ns = 365 * std.time.ns_per_day, .sep = 'y' }, + .{ .ns = std.time.ns_per_week, .sep = 'w' }, + .{ .ns = std.time.ns_per_day, .sep = 'd' }, + .{ .ns = std.time.ns_per_hour, .sep = 'h' }, + .{ .ns = std.time.ns_per_min, .sep = 'm' }, + }) |unit| { + if (ns_remaining >= unit.ns) { + const units = ns_remaining / unit.ns; + try bw.printIntOptions(units, 10, .lower, .{}); + try bw.writeByte(unit.sep); + ns_remaining -= units * unit.ns; + if (ns_remaining == 0) return; + } + } + + inline for (.{ + .{ .ns = std.time.ns_per_s, .sep = "s" }, + .{ .ns = std.time.ns_per_ms, .sep = "ms" }, + .{ .ns = std.time.ns_per_us, .sep = "us" }, + }) |unit| { + const kunits = ns_remaining * 1000 / unit.ns; + if (kunits >= 1000) { + try bw.printIntOptions(kunits / 1000, 10, .lower, .{}); + const frac = kunits % 1000; + if (frac > 0) { + // Write up to 3 decimal places + var decimal_buf = [_]u8{ '.', 0, 0, 0 }; + assert(printInt(decimal_buf[1..], frac, 10, .lower, .{ .fill = '0', .width = 3 }) == 3); + var end: usize = 4; + while (end > 1) : (end -= 1) { + if (decimal_buf[end - 1] != '0') break; + } + try bw.writeAll(decimal_buf[0..end]); + } + return bw.writeAll(unit.sep); + } + } + + try printIntOptions(bw, ns_remaining, 10, .lower, .{}); + try bw.writeAll("ns"); +} + +/// Writes number of nanoseconds according to its signed magnitude: +/// `[#y][#w][#d][#h][#m]#[.###][n|u|m]s` +/// `nanoseconds` must be an integer that coerces into `u64` or `i64`. +pub fn printDuration(bw: *BufferedWriter, nanoseconds: anytype, options: std.fmt.Options) anyerror!void { + // worst case: "-XXXyXXwXXdXXhXXmXX.XXXs".len = 24 + var buf: [24]u8 = undefined; + var sub_bw: BufferedWriter = undefined; + sub_bw.initFixed(&buf); + switch (@typeInfo(@TypeOf(nanoseconds)).int.signedness) { + .signed => sub_bw.printDurationSigned(nanoseconds, options) catch unreachable, + .unsigned => sub_bw.printDurationUnsigned(nanoseconds, options) catch unreachable, + } + return alignBufferOptions(bw, sub_bw.getWritten(), options); +} + +pub fn printHex(bw: *BufferedWriter, bytes: []const u8, case: std.fmt.Case) anyerror!void { + const charset = switch (case) { + .upper => "0123456789ABCDEF", + .lower => "0123456789abcdef", + }; + for (bytes) |c| { + try writeByte(bw, charset[c >> 4]); + try writeByte(bw, charset[c & 15]); + } +} + +test "formatValue max_depth" { + const Vec2 = struct { + const SelfType = @This(); + x: f32, + y: f32, + + pub fn format( + self: SelfType, + comptime fmt: []const u8, + options: std.fmt.Options, + bw: *BufferedWriter, + ) anyerror!void { + _ = options; + if (fmt.len == 0) { + return bw.print("({d:.3},{d:.3})", .{ self.x, self.y }); + } else { + @compileError("unknown format string: '" ++ fmt ++ "'"); + } + } + }; + const E = enum { + One, + Two, + Three, + }; + const TU = union(enum) { + const SelfType = @This(); + float: f32, + int: u32, + ptr: ?*SelfType, + }; + const S = struct { + const SelfType = @This(); + a: ?*SelfType, + tu: TU, + e: E, + vec: Vec2, + }; + + var inst = S{ + .a = null, + .tu = TU{ .ptr = null }, + .e = E.Two, + .vec = Vec2{ .x = 10.2, .y = 2.22 }, + }; + inst.a = &inst; + inst.tu.ptr = &inst.tu; + + var buf: [1000]u8 = undefined; + var bw: BufferedWriter = undefined; + bw.initFixed(&buf); + try bw.printValue("", .{}, inst, 0); + try testing.expectEqualStrings("io.BufferedWriter.test.printValue max_depth.S{ ... }", bw.getWritten()); + + bw.reset(); + try bw.printValue("", .{}, inst, 1); + try testing.expectEqualStrings("io.BufferedWriter.test.printValue max_depth.S{ .a = io.BufferedWriter.test.printValue max_depth.S{ ... }, .tu = io.BufferedWriter.test.printValue max_depth.TU{ ... }, .e = io.BufferedWriter.test.printValue max_depth.E.Two, .vec = (10.200,2.220) }", bw.getWritten()); + + bw.reset(); + try bw.printValue("", .{}, inst, 2); + try testing.expectEqualStrings("io.BufferedWriter.test.printValue max_depth.S{ .a = io.BufferedWriter.test.printValue max_depth.S{ .a = io.BufferedWriter.test.printValue max_depth.S{ ... }, .tu = io.BufferedWriter.test.printValue max_depth.TU{ ... }, .e = io.BufferedWriter.test.printValue max_depth.E.Two, .vec = (10.200,2.220) }, .tu = io.BufferedWriter.test.printValue max_depth.TU{ .ptr = io.BufferedWriter.test.printValue max_depth.TU{ ... } }, .e = io.BufferedWriter.test.printValue max_depth.E.Two, .vec = (10.200,2.220) }", bw.getWritten()); + + bw.reset(); + try bw.printValue("", .{}, inst, 3); + try testing.expectEqualStrings("io.BufferedWriter.test.printValue max_depth.S{ .a = io.BufferedWriter.test.printValue max_depth.S{ .a = io.BufferedWriter.test.printValue max_depth.S{ .a = io.BufferedWriter.test.printValue max_depth.S{ ... }, .tu = io.BufferedWriter.test.printValue max_depth.TU{ ... }, .e = io.BufferedWriter.test.printValue max_depth.E.Two, .vec = (10.200,2.220) }, .tu = io.BufferedWriter.test.printValue max_depth.TU{ .ptr = io.BufferedWriter.test.printValue max_depth.TU{ ... } }, .e = io.BufferedWriter.test.printValue max_depth.E.Two, .vec = (10.200,2.220) }, .tu = io.BufferedWriter.test.printValue max_depth.TU{ .ptr = io.BufferedWriter.test.printValue max_depth.TU{ .ptr = io.BufferedWriter.test.printValue max_depth.TU{ ... } } }, .e = io.BufferedWriter.test.printValue max_depth.E.Two, .vec = (10.200,2.220) }", bw.getWritten()); + + const vec: @Vector(4, i32) = .{ 1, 2, 3, 4 }; + bw.reset(); + try bw.printValue("", .{}, vec, 0); + try testing.expectEqualStrings("{ ... }", bw.getWritten()); + + bw.reset(); + try bw.printValue("", .{}, vec, 1); + try testing.expectEqualStrings("{ 1, 2, 3, 4 }", bw.getWritten()); +} + +test printDuration { + testDurationCase("0ns", 0); + testDurationCase("1ns", 1); + testDurationCase("999ns", std.time.ns_per_us - 1); + testDurationCase("1us", std.time.ns_per_us); + testDurationCase("1.45us", 1450); + testDurationCase("1.5us", 3 * std.time.ns_per_us / 2); + testDurationCase("14.5us", 14500); + testDurationCase("145us", 145000); + testDurationCase("999.999us", std.time.ns_per_ms - 1); + testDurationCase("1ms", std.time.ns_per_ms + 1); + testDurationCase("1.5ms", 3 * std.time.ns_per_ms / 2); + testDurationCase("1.11ms", 1110000); + testDurationCase("1.111ms", 1111000); + testDurationCase("1.111ms", 1111100); + testDurationCase("999.999ms", std.time.ns_per_s - 1); + testDurationCase("1s", std.time.ns_per_s); + testDurationCase("59.999s", std.time.ns_per_min - 1); + testDurationCase("1m", std.time.ns_per_min); + testDurationCase("1h", std.time.ns_per_hour); + testDurationCase("1d", std.time.ns_per_day); + testDurationCase("1w", std.time.ns_per_week); + testDurationCase("1y", 365 * std.time.ns_per_day); + testDurationCase("1y52w23h59m59.999s", 730 * std.time.ns_per_day - 1); // 365d = 52w1 + testDurationCase("1y1h1.001s", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + std.time.ns_per_ms); + testDurationCase("1y1h1s", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + 999 * std.time.ns_per_us); + testDurationCase("1y1h999.999us", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms - 1); + testDurationCase("1y1h1ms", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms); + testDurationCase("1y1h1ms", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms + 1); + testDurationCase("1y1m999ns", 365 * std.time.ns_per_day + std.time.ns_per_min + 999); + testDurationCase("584y49w23h34m33.709s", std.math.maxInt(u64)); + + testing.expectFmt("=======0ns", "{D:=>10}", .{0}); + testing.expectFmt("1ns=======", "{D:=<10}", .{1}); + testing.expectFmt(" 999ns ", "{D:^10}", .{std.time.ns_per_us - 1}); +} + +test printDurationSigned { + testDurationCaseSigned("0ns", 0); + testDurationCaseSigned("1ns", 1); + testDurationCaseSigned("-1ns", -(1)); + testDurationCaseSigned("999ns", std.time.ns_per_us - 1); + testDurationCaseSigned("-999ns", -(std.time.ns_per_us - 1)); + testDurationCaseSigned("1us", std.time.ns_per_us); + testDurationCaseSigned("-1us", -(std.time.ns_per_us)); + testDurationCaseSigned("1.45us", 1450); + testDurationCaseSigned("-1.45us", -(1450)); + testDurationCaseSigned("1.5us", 3 * std.time.ns_per_us / 2); + testDurationCaseSigned("-1.5us", -(3 * std.time.ns_per_us / 2)); + testDurationCaseSigned("14.5us", 14500); + testDurationCaseSigned("-14.5us", -(14500)); + testDurationCaseSigned("145us", 145000); + testDurationCaseSigned("-145us", -(145000)); + testDurationCaseSigned("999.999us", std.time.ns_per_ms - 1); + testDurationCaseSigned("-999.999us", -(std.time.ns_per_ms - 1)); + testDurationCaseSigned("1ms", std.time.ns_per_ms + 1); + testDurationCaseSigned("-1ms", -(std.time.ns_per_ms + 1)); + testDurationCaseSigned("1.5ms", 3 * std.time.ns_per_ms / 2); + testDurationCaseSigned("-1.5ms", -(3 * std.time.ns_per_ms / 2)); + testDurationCaseSigned("1.11ms", 1110000); + testDurationCaseSigned("-1.11ms", -(1110000)); + testDurationCaseSigned("1.111ms", 1111000); + testDurationCaseSigned("-1.111ms", -(1111000)); + testDurationCaseSigned("1.111ms", 1111100); + testDurationCaseSigned("-1.111ms", -(1111100)); + testDurationCaseSigned("999.999ms", std.time.ns_per_s - 1); + testDurationCaseSigned("-999.999ms", -(std.time.ns_per_s - 1)); + testDurationCaseSigned("1s", std.time.ns_per_s); + testDurationCaseSigned("-1s", -(std.time.ns_per_s)); + testDurationCaseSigned("59.999s", std.time.ns_per_min - 1); + testDurationCaseSigned("-59.999s", -(std.time.ns_per_min - 1)); + testDurationCaseSigned("1m", std.time.ns_per_min); + testDurationCaseSigned("-1m", -(std.time.ns_per_min)); + testDurationCaseSigned("1h", std.time.ns_per_hour); + testDurationCaseSigned("-1h", -(std.time.ns_per_hour)); + testDurationCaseSigned("1d", std.time.ns_per_day); + testDurationCaseSigned("-1d", -(std.time.ns_per_day)); + testDurationCaseSigned("1w", std.time.ns_per_week); + testDurationCaseSigned("-1w", -(std.time.ns_per_week)); + testDurationCaseSigned("1y", 365 * std.time.ns_per_day); + testDurationCaseSigned("-1y", -(365 * std.time.ns_per_day)); + testDurationCaseSigned("1y52w23h59m59.999s", 730 * std.time.ns_per_day - 1); // 365d = 52w1d + testDurationCaseSigned("-1y52w23h59m59.999s", -(730 * std.time.ns_per_day - 1)); // 365d = 52w1d + testDurationCaseSigned("1y1h1.001s", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + std.time.ns_per_ms); + testDurationCaseSigned("-1y1h1.001s", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + std.time.ns_per_ms)); + testDurationCaseSigned("1y1h1s", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + 999 * std.time.ns_per_us); + testDurationCaseSigned("-1y1h1s", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_s + 999 * std.time.ns_per_us)); + testDurationCaseSigned("1y1h999.999us", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms - 1); + testDurationCaseSigned("-1y1h999.999us", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms - 1)); + testDurationCaseSigned("1y1h1ms", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms); + testDurationCaseSigned("-1y1h1ms", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms)); + testDurationCaseSigned("1y1h1ms", 365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms + 1); + testDurationCaseSigned("-1y1h1ms", -(365 * std.time.ns_per_day + std.time.ns_per_hour + std.time.ns_per_ms + 1)); + testDurationCaseSigned("1y1m999ns", 365 * std.time.ns_per_day + std.time.ns_per_min + 999); + testDurationCaseSigned("-1y1m999ns", -(365 * std.time.ns_per_day + std.time.ns_per_min + 999)); + testDurationCaseSigned("292y24w3d23h47m16.854s", std.math.maxInt(i64)); + testDurationCaseSigned("-292y24w3d23h47m16.854s", std.math.minInt(i64) + 1); + testDurationCaseSigned("-292y24w3d23h47m16.854s", std.math.minInt(i64)); + + testing.expectFmt("=======0ns", "{s:=>10}", .{0}); + testing.expectFmt("1ns=======", "{s:=<10}", .{1}); + testing.expectFmt("-1ns======", "{s:=<10}", .{-(1)}); + testing.expectFmt(" -999ns ", "{s:^10}", .{-(std.time.ns_per_us - 1)}); +} + +fn testDurationCase(expected: []const u8, input: u64) !void { + var buf: [24]u8 = undefined; + var bw: BufferedWriter = undefined; + bw.initFixed(&buf); + try bw.printDurationUnsigned(input); + try testing.expectEqualStrings(expected, bw.getWritten()); +} + +fn testDurationCaseSigned(expected: []const u8, input: i64) !void { + var buf: [24]u8 = undefined; + var bw: BufferedWriter = undefined; + bw.initFixed(&buf); + try bw.printDurationSigned(input); + try testing.expectEqualStrings(expected, bw.getWritten()); +} + +test printIntOptions { + try testPrintIntCase("-1", @as(i1, -1), 10, .lower, .{}); + + try testPrintIntCase("-101111000110000101001110", @as(i32, -12345678), 2, .lower, .{}); + try testPrintIntCase("-12345678", @as(i32, -12345678), 10, .lower, .{}); + try testPrintIntCase("-bc614e", @as(i32, -12345678), 16, .lower, .{}); + try testPrintIntCase("-BC614E", @as(i32, -12345678), 16, .upper, .{}); + + try testPrintIntCase("12345678", @as(u32, 12345678), 10, .upper, .{}); + + try testPrintIntCase(" 666", @as(u32, 666), 10, .lower, .{ .width = 6 }); + try testPrintIntCase(" 1234", @as(u32, 0x1234), 16, .lower, .{ .width = 6 }); + try testPrintIntCase("1234", @as(u32, 0x1234), 16, .lower, .{ .width = 1 }); + + try testPrintIntCase("+42", @as(i32, 42), 10, .lower, .{ .width = 3 }); + try testPrintIntCase("-42", @as(i32, -42), 10, .lower, .{ .width = 3 }); +} + +test "printInt with comptime_int" { + var buf: [20]u8 = undefined; + var bw: BufferedWriter = undefined; + bw.initFixed(&buf); + try bw.printInt(@as(comptime_int, 123456789123456789), "", .{}); + try std.testing.expectEqualStrings("123456789123456789", bw.getWritten()); +} + +test "printFloat with comptime_float" { + var buf: [20]u8 = undefined; + var bw: BufferedWriter = undefined; + bw.initFixed(&buf); + try bw.printFloat("", .{}, @as(comptime_float, 1.0)); + try std.testing.expectEqualStrings(bw.getWritten(), "1e0"); + try std.testing.expectFmt("1e0", "{}", .{1.0}); +} + +fn testPrintIntCase(expected: []const u8, value: anytype, base: u8, case: std.fmt.Case, options: std.fmt.Options) !void { + var buffer: [100]u8 = undefined; + var bw: BufferedWriter = undefined; + bw.initFixed(&buffer); + bw.printIntOptions(value, base, case, options); + try testing.expectEqualStrings(expected, bw.getWritten()); +} + +test printByteSize { + try testing.expectFmt("file size: 42B\n", "file size: {B}\n", .{42}); + try testing.expectFmt("file size: 42B\n", "file size: {Bi}\n", .{42}); + try testing.expectFmt("file size: 63MB\n", "file size: {B}\n", .{63 * 1000 * 1000}); + try testing.expectFmt("file size: 63MiB\n", "file size: {Bi}\n", .{63 * 1024 * 1024}); + try testing.expectFmt("file size: 42B\n", "file size: {B:.2}\n", .{42}); + try testing.expectFmt("file size: 42B\n", "file size: {B:>9.2}\n", .{42}); + try testing.expectFmt("file size: 66.06MB\n", "file size: {B:.2}\n", .{63 * 1024 * 1024}); + try testing.expectFmt("file size: 60.08MiB\n", "file size: {Bi:.2}\n", .{63 * 1000 * 1000}); + try testing.expectFmt("file size: =66.06MB=\n", "file size: {B:=^9.2}\n", .{63 * 1024 * 1024}); + try testing.expectFmt("file size: 66.06MB\n", "file size: {B: >9.2}\n", .{63 * 1024 * 1024}); + try testing.expectFmt("file size: 66.06MB \n", "file size: {B: <9.2}\n", .{63 * 1024 * 1024}); + try testing.expectFmt("file size: 0.01844674407370955ZB\n", "file size: {B}\n", .{std.math.maxInt(u64)}); +} + +test "bytes.hex" { + const some_bytes = "\xCA\xFE\xBA\xBE"; + try std.testing.expectFmt("lowercase: cafebabe\n", "lowercase: {x}\n", .{some_bytes}); + try std.testing.expectFmt("uppercase: CAFEBABE\n", "uppercase: {X}\n", .{some_bytes}); + try std.testing.expectFmt("uppercase: CAFE\n", "uppercase: {X}\n", .{some_bytes[0..2]}); + try std.testing.expectFmt("lowercase: babe\n", "lowercase: {x}\n", .{some_bytes[2..]}); + const bytes_with_zeros = "\x00\x0E\xBA\xBE"; + try std.testing.expectFmt("lowercase: 000ebabe\n", "lowercase: {x}\n", .{bytes_with_zeros}); +} diff --git a/lib/std/io/CountingWriter.zig b/lib/std/io/CountingWriter.zig new file mode 100644 index 0000000000000000000000000000000000000000..cc4e2ee00e65e362f555a2bf6eb627f287ef6aa5 --- /dev/null +++ b/lib/std/io/CountingWriter.zig @@ -0,0 +1,56 @@ +const std = @import("../std.zig"); +const CountingWriter = @This(); +const assert = std.debug.assert; +const native_endian = @import("builtin").target.cpu.arch.endian(); +const Writer = std.io.Writer; +const testing = std.testing; + +/// Underlying stream to passthrough bytes to. +child_writer: Writer, +bytes_written: u64 = 0, + +pub fn writer(cw: *CountingWriter) Writer { + return .{ + .context = cw, + .vtable = &.{ + .writev = passthru_writev, + .writeFile = passthru_writeFile, + }, + }; +} + +pub fn unbufferedWriter(cw: *CountingWriter) std.io.BufferedWriter { + return .{ + .buffer = &.{}, + .unbuffered_writer = writer(cw), + }; +} + +fn passthru_writev(context: *anyopaque, data: []const []const u8) anyerror!usize { + const cw: *CountingWriter = @alignCast(@ptrCast(context)); + const n = try cw.child_writer.writev(data); + cw.bytes_written += n; + return n; +} + +fn passthru_writeFile( + context: *anyopaque, + file: std.fs.File, + offset: u64, + len: Writer.VTable.FileLen, + headers_and_trailers: []const []const u8, + headers_len: usize, +) anyerror!usize { + const cw: *CountingWriter = @alignCast(@ptrCast(context)); + const n = try cw.child_writer.writeFile(file, offset, len, headers_and_trailers, headers_len); + cw.bytes_written += n; + return n; +} + +test CountingWriter { + var cw: CountingWriter = .{ .child_writer = std.io.null_writer }; + var bw = cw.unbufferedWriter(); + const bytes = "yay"; + try bw.writeAll(bytes); + try testing.expect(cw.bytes_written == bytes.len); +} diff --git a/lib/std/io/FixedBufferStream.zig b/lib/std/io/FixedBufferStream.zig new file mode 100644 index 0000000000000000000000000000000000000000..8038204e18e0445d7805f8b737d3ecdc28a06f10 --- /dev/null +++ b/lib/std/io/FixedBufferStream.zig @@ -0,0 +1,148 @@ +//! This turns a const byte buffer into an `io.Reader`, or `io.SeekableStream`. + +const std = @import("../std.zig"); +const io = std.io; +const testing = std.testing; +const mem = std.mem; +const assert = std.debug.assert; +const FixedBufferStream = @This(); + +buffer: []const u8, +pos: usize = 0, + +pub const ReadError = error{}; +pub const SeekError = error{}; +pub const GetSeekPosError = error{}; + +pub const Reader = io.Reader(*Self, ReadError, read); + +pub const SeekableStream = io.SeekableStream( + *Self, + SeekError, + GetSeekPosError, + seekTo, + seekBy, + getPos, + getEndPos, +); + +const Self = @This(); + +pub fn reader(self: *Self) Reader { + return .{ .context = self }; +} + +pub fn seekableStream(self: *Self) SeekableStream { + return .{ .context = self }; +} + +pub fn read(self: *Self, dest: []u8) ReadError!usize { + const size = @min(dest.len, self.buffer.len - self.pos); + const end = self.pos + size; + + @memcpy(dest[0..size], self.buffer[self.pos..end]); + self.pos = end; + + return size; +} + +pub fn seekTo(self: *Self, pos: u64) SeekError!void { + self.pos = @min(std.math.lossyCast(usize, pos), self.buffer.len); +} + +pub fn seekBy(self: *Self, amt: i64) SeekError!void { + if (amt < 0) { + const abs_amt = @abs(amt); + const abs_amt_usize = std.math.cast(usize, abs_amt) orelse std.math.maxInt(usize); + if (abs_amt_usize > self.pos) { + self.pos = 0; + } else { + self.pos -= abs_amt_usize; + } + } else { + const amt_usize = std.math.cast(usize, amt) orelse std.math.maxInt(usize); + const new_pos = std.math.add(usize, self.pos, amt_usize) catch std.math.maxInt(usize); + self.pos = @min(self.buffer.len, new_pos); + } +} + +pub fn getEndPos(self: *Self) GetSeekPosError!u64 { + return self.buffer.len; +} + +pub fn getPos(self: *Self) GetSeekPosError!u64 { + return self.pos; +} + +pub fn getWritten(self: Self) []const u8 { + return self.buffer[0..self.pos]; +} + +pub fn reset(self: *Self) void { + self.pos = 0; +} + +test "output" { + var buf: [255]u8 = undefined; + var fbs: FixedBufferStream = .{ .buffer = &buf }; + const stream = fbs.writer(); + + try stream.print("{s}{s}!", .{ "Hello", "World" }); + try testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten()); +} + +test "output at comptime" { + comptime { + var buf: [255]u8 = undefined; + var fbs: FixedBufferStream = .{ .buffer = &buf }; + const stream = fbs.writer(); + + try stream.print("{s}{s}!", .{ "Hello", "World" }); + try testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten()); + } +} + +test "output 2" { + var buffer: [10]u8 = undefined; + var fbs: FixedBufferStream = .{ .buffer = &buffer }; + + try fbs.writer().writeAll("Hello"); + try testing.expect(mem.eql(u8, fbs.getWritten(), "Hello")); + + try fbs.writer().writeAll("world"); + try testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld")); + + try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("!")); + try testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld")); + + fbs.reset(); + try testing.expect(fbs.getWritten().len == 0); + + try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("Hello world!")); + try testing.expect(mem.eql(u8, fbs.getWritten(), "Hello worl")); + + try fbs.seekTo((try fbs.getEndPos()) + 1); + try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("H")); +} + +test "input" { + const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7 }; + var fbs: FixedBufferStream = .{ .buffer = &bytes }; + + var dest: [4]u8 = undefined; + + var amt_read = try fbs.reader().read(&dest); + try testing.expect(amt_read == 4); + try testing.expect(mem.eql(u8, dest[0..4], bytes[0..4])); + + amt_read = try fbs.reader().read(&dest); + try testing.expect(amt_read == 3); + try testing.expect(mem.eql(u8, dest[0..3], bytes[4..7])); + + amt_read = try fbs.reader().read(&dest); + try testing.expect(amt_read == 0); + + try fbs.seekTo((try fbs.getEndPos()) + 1); + amt_read = try fbs.reader().read(&dest); + try testing.expect(amt_read == 0); +} diff --git a/lib/std/io/Writer.zig b/lib/std/io/Writer.zig index 26d4f88def8044f5d27900fb45999c088898b79e..d0b0b28f82ad6f56eacc515f02e5b7cfd485fc8b 100644 --- a/lib/std/io/Writer.zig +++ b/lib/std/io/Writer.zig @@ -1,83 +1,100 @@ const std = @import("../std.zig"); const assert = std.debug.assert; -const mem = std.mem; -const native_endian = @import("builtin").target.cpu.arch.endian(); +const Writer = @This(); -context: *const anyopaque, -writeFn: *const fn (context: *const anyopaque, bytes: []const u8) anyerror!usize, +context: *anyopaque, +vtable: *const VTable, -const Self = @This(); -pub const Error = anyerror; +pub const VTable = struct { + /// Each slice in `data` is written in order. + /// + /// Number of bytes actually written is returned. + /// + /// Number of bytes returned may be zero, which does not mean + /// end-of-stream. A subsequent call may return nonzero, or may signal end + /// of stream via an error. + writev: *const fn (context: *anyopaque, data: []const []const u8) anyerror!usize, -pub fn write(self: Self, bytes: []const u8) anyerror!usize { - return self.writeFn(self.context, bytes); + /// Writes contents from an open file. `headers` are written first, then `len` + /// bytes of `file` starting from `offset`, then `trailers`. + /// + /// Number of bytes actually written is returned, which may lie within + /// headers, the file, trailers, or anywhere in between. + /// + /// Number of bytes returned may be zero, which does not mean + /// end-of-stream. A subsequent call may return nonzero, or may signal end + /// of stream via an error. + writeFile: *const fn ( + context: *anyopaque, + file: std.fs.File, + offset: u64, + /// When zero, it means copy until the end of the file is reached. + len: FileLen, + /// Headers and trailers must be passed together so that in case `len` is + /// zero, they can be forwarded directly to `VTable.writev`. + headers_and_trailers: []const []const u8, + headers_len: usize, + ) anyerror!usize, + + pub const FileLen = enum(u64) { + zero = 0, + entire_file = std.math.maxInt(u64), + _, + + pub fn init(integer: u64) FileLen { + const result: FileLen = @enumFromInt(integer); + assert(result != .none); + return result; + } + + pub fn int(len: FileLen) u64 { + return @intFromEnum(len); + } + }; +}; + +pub fn writev(w: Writer, data: []const []const u8) anyerror!usize { + return w.vtable.writev(w.context, data); +} + +pub fn writeFile( + w: Writer, + file: std.fs.File, + offset: u64, + len: VTable.FileLen, + headers_and_trailers: []const []const u8, + headers_len: usize, +) anyerror!usize { + return w.vtable.writeFile(w.context, file, offset, len, headers_and_trailers, headers_len); +} + +pub fn write(w: Writer, bytes: []const u8) anyerror!usize { + const single: [1][]const u8 = .{bytes}; + return w.vtable.writev(w.context, &single); } -pub fn writeAll(self: Self, bytes: []const u8) anyerror!void { +pub fn writeAll(w: Writer, bytes: []const u8) anyerror!void { var index: usize = 0; - while (index != bytes.len) { - index += try self.write(bytes[index..]); - } + while (index < bytes.len) index += try write(w, bytes[index..]); } -pub fn print(self: Self, comptime format: []const u8, args: anytype) anyerror!void { - return std.fmt.format(self, format, args); -} - -pub fn writeByte(self: Self, byte: u8) anyerror!void { - const array = [1]u8{byte}; - return self.writeAll(&array); -} - -pub fn writeByteNTimes(self: Self, byte: u8, n: usize) anyerror!void { - var bytes: [256]u8 = undefined; - @memset(bytes[0..], byte); - - var remaining: usize = n; - while (remaining > 0) { - const to_write = @min(remaining, bytes.len); - try self.writeAll(bytes[0..to_write]); - remaining -= to_write; - } -} +///// Directly calls `writeAll` many times to render the formatted text. To +///// enable buffering, call `std.io.BufferedWriter.print` instead. +//pub fn unbufferedPrint(w: Writer, comptime format: []const u8, args: anytype) anyerror!void { +// return std.fmt.format(w, format, args); +//} -pub fn writeBytesNTimes(self: Self, bytes: []const u8, n: usize) anyerror!void { +/// The `data` parameter is mutable because this function needs to mutate the +/// fields in order to handle partial writes from `VTable.writev`. +pub fn writevAll(w: Writer, data: [][]const u8) anyerror!void { var i: usize = 0; - while (i < n) : (i += 1) { - try self.writeAll(bytes); - } -} - -pub inline fn writeInt(self: Self, comptime T: type, value: T, endian: std.builtin.Endian) anyerror!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); -} - -pub fn writeStruct(self: Self, value: anytype) anyerror!void { - // Only extern and packed structs have defined in-memory layout. - comptime assert(@typeInfo(@TypeOf(value)).@"struct".layout != .auto); - return self.writeAll(mem.asBytes(&value)); -} - -pub fn writeStructEndian(self: Self, value: anytype, endian: std.builtin.Endian) anyerror!void { - // TODO: make sure this value is not a reference type - if (native_endian == endian) { - return self.writeStruct(value); - } else { - var copy = value; - mem.byteSwapAllFields(@TypeOf(value), ©); - return self.writeStruct(copy); - } -} - -pub fn writeFile(self: Self, file: std.fs.File) anyerror!void { - // TODO: figure out how to adjust std lib abstractions so that this ends up - // doing sendfile or maybe even copy_file_range under the right conditions. - var buf: [4000]u8 = undefined; while (true) { - const n = try file.readAll(&buf); - try self.writeAll(buf[0..n]); - if (n < buf.len) return; + var n = try w.vtable.writev(w.context, data[i..]); + while (n >= data[i].len) { + n -= data[i].len; + i += 1; + if (i >= data.len) return; + } + data[i] = data[i][n..]; } } diff --git a/lib/std/io/buffered_writer.zig b/lib/std/io/buffered_writer.zig deleted file mode 100644 index 906d6cce4926033cbcea2d662426e5fe72dbd089..0000000000000000000000000000000000000000 --- a/lib/std/io/buffered_writer.zig +++ /dev/null @@ -1,43 +0,0 @@ -const std = @import("../std.zig"); - -const io = std.io; -const mem = std.mem; - -pub fn BufferedWriter(comptime buffer_size: usize, comptime WriterType: type) type { - return struct { - unbuffered_writer: WriterType, - buf: [buffer_size]u8 = undefined, - end: usize = 0, - - pub const Error = WriterType.Error; - pub const Writer = io.Writer(*Self, Error, write); - - const Self = @This(); - - pub fn flush(self: *Self) !void { - try self.unbuffered_writer.writeAll(self.buf[0..self.end]); - self.end = 0; - } - - pub fn writer(self: *Self) Writer { - return .{ .context = self }; - } - - pub fn write(self: *Self, bytes: []const u8) Error!usize { - if (self.end + bytes.len > self.buf.len) { - try self.flush(); - if (bytes.len > self.buf.len) - return self.unbuffered_writer.write(bytes); - } - - const new_end = self.end + bytes.len; - @memcpy(self.buf[self.end..new_end], bytes); - self.end = new_end; - return bytes.len; - } - }; -} - -pub fn bufferedWriter(underlying_stream: anytype) BufferedWriter(4096, @TypeOf(underlying_stream)) { - return .{ .unbuffered_writer = underlying_stream }; -} diff --git a/lib/std/io/counting_writer.zig b/lib/std/io/counting_writer.zig deleted file mode 100644 index 9043e1a47c17dfbf67559ade1793584cc9ae9d1a..0000000000000000000000000000000000000000 --- a/lib/std/io/counting_writer.zig +++ /dev/null @@ -1,39 +0,0 @@ -const std = @import("../std.zig"); -const io = std.io; -const testing = std.testing; - -/// A Writer that counts how many bytes has been written to it. -pub fn CountingWriter(comptime WriterType: type) type { - return struct { - bytes_written: u64, - child_stream: WriterType, - - pub const Error = WriterType.Error; - pub const Writer = io.Writer(*Self, Error, write); - - const Self = @This(); - - pub fn write(self: *Self, bytes: []const u8) Error!usize { - const amt = try self.child_stream.write(bytes); - self.bytes_written += amt; - return amt; - } - - pub fn writer(self: *Self) Writer { - return .{ .context = self }; - } - }; -} - -pub fn countingWriter(child_stream: anytype) CountingWriter(@TypeOf(child_stream)) { - return .{ .bytes_written = 0, .child_stream = child_stream }; -} - -test CountingWriter { - var counting_stream = countingWriter(std.io.null_writer); - const stream = counting_stream.writer(); - - const bytes = "yay" ** 100; - stream.writeAll(bytes) catch unreachable; - try testing.expect(counting_stream.bytes_written == bytes.len); -} diff --git a/lib/std/io/fixed_buffer_stream.zig b/lib/std/io/fixed_buffer_stream.zig deleted file mode 100644 index bfc25eb6ac54246103ad9b41d18b5ff6a1c9df64..0000000000000000000000000000000000000000 --- a/lib/std/io/fixed_buffer_stream.zig +++ /dev/null @@ -1,198 +0,0 @@ -const std = @import("../std.zig"); -const io = std.io; -const testing = std.testing; -const mem = std.mem; -const assert = std.debug.assert; - -/// This turns a byte buffer into an `io.Writer`, `io.Reader`, or `io.SeekableStream`. -/// If the supplied byte buffer is const, then `io.Writer` is not available. -pub fn FixedBufferStream(comptime Buffer: type) type { - return struct { - /// `Buffer` is either a `[]u8` or `[]const u8`. - buffer: Buffer, - pos: usize, - - pub const ReadError = error{}; - pub const WriteError = error{NoSpaceLeft}; - pub const SeekError = error{}; - pub const GetSeekPosError = error{}; - - pub const Reader = io.Reader(*Self, ReadError, read); - pub const Writer = io.Writer(*Self, WriteError, write); - - pub const SeekableStream = io.SeekableStream( - *Self, - SeekError, - GetSeekPosError, - seekTo, - seekBy, - getPos, - getEndPos, - ); - - const Self = @This(); - - pub fn reader(self: *Self) Reader { - return .{ .context = self }; - } - - pub fn writer(self: *Self) Writer { - return .{ .context = self }; - } - - pub fn seekableStream(self: *Self) SeekableStream { - return .{ .context = self }; - } - - pub fn read(self: *Self, dest: []u8) ReadError!usize { - const size = @min(dest.len, self.buffer.len - self.pos); - const end = self.pos + size; - - @memcpy(dest[0..size], self.buffer[self.pos..end]); - self.pos = end; - - return size; - } - - /// If the returned number of bytes written is less than requested, the - /// buffer is full. Returns `error.NoSpaceLeft` when no bytes would be written. - /// Note: `error.NoSpaceLeft` matches the corresponding error from - /// `std.fs.File.WriteError`. - pub fn write(self: *Self, bytes: []const u8) WriteError!usize { - if (bytes.len == 0) return 0; - if (self.pos >= self.buffer.len) return error.NoSpaceLeft; - - const n = @min(self.buffer.len - self.pos, bytes.len); - @memcpy(self.buffer[self.pos..][0..n], bytes[0..n]); - self.pos += n; - - if (n == 0) return error.NoSpaceLeft; - - return n; - } - - pub fn seekTo(self: *Self, pos: u64) SeekError!void { - self.pos = @min(std.math.lossyCast(usize, pos), self.buffer.len); - } - - pub fn seekBy(self: *Self, amt: i64) SeekError!void { - if (amt < 0) { - const abs_amt = @abs(amt); - const abs_amt_usize = std.math.cast(usize, abs_amt) orelse std.math.maxInt(usize); - if (abs_amt_usize > self.pos) { - self.pos = 0; - } else { - self.pos -= abs_amt_usize; - } - } else { - const amt_usize = std.math.cast(usize, amt) orelse std.math.maxInt(usize); - const new_pos = std.math.add(usize, self.pos, amt_usize) catch std.math.maxInt(usize); - self.pos = @min(self.buffer.len, new_pos); - } - } - - pub fn getEndPos(self: *Self) GetSeekPosError!u64 { - return self.buffer.len; - } - - pub fn getPos(self: *Self) GetSeekPosError!u64 { - return self.pos; - } - - pub fn getWritten(self: Self) Buffer { - return self.buffer[0..self.pos]; - } - - pub fn reset(self: *Self) void { - self.pos = 0; - } - }; -} - -pub fn fixedBufferStream(buffer: anytype) FixedBufferStream(Slice(@TypeOf(buffer))) { - return .{ .buffer = buffer, .pos = 0 }; -} - -fn Slice(comptime T: type) type { - switch (@typeInfo(T)) { - .pointer => |ptr_info| { - var new_ptr_info = ptr_info; - switch (ptr_info.size) { - .slice => {}, - .one => switch (@typeInfo(ptr_info.child)) { - .array => |info| new_ptr_info.child = info.child, - else => @compileError("invalid type given to fixedBufferStream"), - }, - else => @compileError("invalid type given to fixedBufferStream"), - } - new_ptr_info.size = .slice; - return @Type(.{ .pointer = new_ptr_info }); - }, - else => @compileError("invalid type given to fixedBufferStream"), - } -} - -test "output" { - var buf: [255]u8 = undefined; - var fbs = fixedBufferStream(&buf); - const stream = fbs.writer(); - - try stream.print("{s}{s}!", .{ "Hello", "World" }); - try testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten()); -} - -test "output at comptime" { - comptime { - var buf: [255]u8 = undefined; - var fbs = fixedBufferStream(&buf); - const stream = fbs.writer(); - - try stream.print("{s}{s}!", .{ "Hello", "World" }); - try testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten()); - } -} - -test "output 2" { - var buffer: [10]u8 = undefined; - var fbs = fixedBufferStream(&buffer); - - try fbs.writer().writeAll("Hello"); - try testing.expect(mem.eql(u8, fbs.getWritten(), "Hello")); - - try fbs.writer().writeAll("world"); - try testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld")); - - try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("!")); - try testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld")); - - fbs.reset(); - try testing.expect(fbs.getWritten().len == 0); - - try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("Hello world!")); - try testing.expect(mem.eql(u8, fbs.getWritten(), "Hello worl")); - - try fbs.seekTo((try fbs.getEndPos()) + 1); - try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("H")); -} - -test "input" { - const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7 }; - var fbs = fixedBufferStream(&bytes); - - var dest: [4]u8 = undefined; - - var read = try fbs.reader().read(&dest); - try testing.expect(read == 4); - try testing.expect(mem.eql(u8, dest[0..4], bytes[0..4])); - - read = try fbs.reader().read(&dest); - try testing.expect(read == 3); - try testing.expect(mem.eql(u8, dest[0..3], bytes[4..7])); - - read = try fbs.reader().read(&dest); - try testing.expect(read == 0); - - try fbs.seekTo((try fbs.getEndPos()) + 1); - read = try fbs.reader().read(&dest); - try testing.expect(read == 0); -} diff --git a/lib/std/log.zig b/lib/std/log.zig index 3479766678679fed173faead4f3fae2d50bba348..32d471fa40f899b68a3f5f815a16dcdca2d17f80 100644 --- a/lib/std/log.zig +++ b/lib/std/log.zig @@ -148,14 +148,15 @@ pub fn defaultLog( ) void { const level_txt = comptime message_level.asText(); const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; - const stderr = std.io.getStdErr().writer(); - var bw = std.io.bufferedWriter(stderr); - const writer = bw.writer(); - + var buffer: [1024]u8 = undefined; + var bw: std.io.BufferedWriter = .{ + .unbuffered_writer = std.io.getStdErr().writer(), + .buffer = &buffer, + }; std.debug.lockStdErr(); defer std.debug.unlockStdErr(); nosuspend { - writer.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return; + bw.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return; bw.flush() catch return; } } diff --git a/lib/std/os/uefi.zig b/lib/std/os/uefi.zig index c362f707c6bc47eac79e602bf45dbe14b41fe622..e437e2f66e5d72d7434201acd38e3a361d4f98b5 100644 --- a/lib/std/os/uefi.zig +++ b/lib/std/os/uefi.zig @@ -67,19 +67,17 @@ pub const Guid = extern struct { ) !void { _ = options; if (f.len == 0) { - const fmt = std.fmt.fmtSliceHexLower; - const time_low = @byteSwap(self.time_low); const time_mid = @byteSwap(self.time_mid); const time_high_and_version = @byteSwap(self.time_high_and_version); - return std.fmt.format(writer, "{:0>8}-{:0>4}-{:0>4}-{:0>2}{:0>2}-{:0>12}", .{ - fmt(std.mem.asBytes(&time_low)), - fmt(std.mem.asBytes(&time_mid)), - fmt(std.mem.asBytes(&time_high_and_version)), - fmt(std.mem.asBytes(&self.clock_seq_high_and_reserved)), - fmt(std.mem.asBytes(&self.clock_seq_low)), - fmt(std.mem.asBytes(&self.node)), + return std.fmt.format(writer, "{x:0>8}-{x:0>4}-{x:0>4}-{x:0>2}{x:0>2}-{x:0>12}", .{ + std.mem.asBytes(&time_low), + std.mem.asBytes(&time_mid), + std.mem.asBytes(&time_high_and_version), + std.mem.asBytes(&self.clock_seq_high_and_reserved), + std.mem.asBytes(&self.clock_seq_low), + std.mem.asBytes(&self.node), }); } else { std.fmt.invalidFmtError(f, self);