Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/aes/aesni.zig
const std = @import("../../std.zig"); const builtin = @import("builtin"); const mem = std.mem; const debug = std.debug; const Vector = std.meta.Vector; const BlockVec = Vector(2, u64); /// A single AES block. pub const Block = struct { pub const block_length: usize = 16; /// Internal representation of a block. repr: BlockVec, /// Convert a byte sequence into an internal representation. pub inline fn fromBytes(bytes: *const [16]u8) Block { const repr = mem.bytesToValue(BlockVec, bytes); return Block{ .repr = repr }; } /// Convert the internal representation of a block into a byte sequence. pub inline fn toBytes(block: Block) [16]u8 { return mem.toBytes(block.repr); } /// XOR the block with a byte sequence. pub inline fn xorBytes(block: Block, bytes: *const [16]u8) [16]u8 { const x = block.repr ^ fromBytes(bytes).repr; return mem.toBytes(x); } /// Encrypt a block with a round key. pub inline fn encrypt(block: Block, round_key: Block) Block { return Block{ .repr = asm ( \\ vaesenc %[rk], %[in], %[out] : [out] "=x" (-> BlockVec), : [in] "x" (block.repr), [rk] "x" (round_key.repr), ), }; } /// Encrypt a block with the last round key. pub inline fn encryptLast(block: Block, round_key: Block) Block { return Block{ .repr = asm ( \\ vaesenclast %[rk], %[in], %[out] : [out] "=x" (-> BlockVec), : [in] "x" (block.repr), [rk] "x" (round_key.repr), ), }; } /// Decrypt a block with a round key. pub inline fn decrypt(block: Block, inv_round_key: Block) Block { return Block{ .repr = asm ( \\ vaesdec %[rk], %[in], %[out] : [out] "=x" (-> BlockVec), : [in] "x" (block.repr), [rk] "x" (inv_round_key.repr), ), }; } /// Decrypt a block with the last round key. pub inline fn decryptLast(block: Block, inv_round_key: Block) Block { return Block{ .repr = asm ( \\ vaesdeclast %[rk], %[in], %[out] : [out] "=x" (-> BlockVec), : [in] "x" (block.repr), [rk] "x" (inv_round_key.repr), ), }; } /// Apply the bitwise XOR operation to the content of two blocks. pub inline fn xorBlocks(block1: Block, block2: Block) Block { return Block{ .repr = block1.repr ^ block2.repr }; } /// Apply the bitwise AND operation to the content of two blocks. pub inline fn andBlocks(block1: Block, block2: Block) Block { return Block{ .repr = block1.repr & block2.repr }; } /// Apply the bitwise OR operation to the content of two blocks. pub inline fn orBlocks(block1: Block, block2: Block) Block { return Block{ .repr = block1.repr | block2.repr }; } /// Perform operations on multiple blocks in parallel. pub const parallel = struct { const cpu = std.Target.x86.cpu; /// The recommended number of AES encryption/decryption to perform in parallel for the chosen implementation. pub const optimal_parallel_blocks = switch (builtin.cpu.model) { &cpu.westmere => 6, &cpu.sandybridge, &cpu.ivybridge => 8, &cpu.haswell, &cpu.broadwell => 7, &cpu.cannonlake, &cpu.skylake, &cpu.skylake_avx512 => 4, &cpu.icelake_client, &cpu.icelake_server => 6, &cpu.znver1, &cpu.znver2 => 8, else => 8, }; /// Encrypt multiple blocks in parallel, each their own round key. pub inline fn encryptParallel(comptime count: usize, blocks: [count]Block, round_keys: [count]Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].encrypt(round_keys[i]); } return out; } /// Decrypt multiple blocks in parallel, each their own round key. pub inline fn decryptParallel(comptime count: usize, blocks: [count]Block, round_keys: [count]Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].decrypt(round_keys[i]); } return out; } /// Encrypt multiple blocks in parallel with the same round key. pub inline fn encryptWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].encrypt(round_key); } return out; } /// Decrypt multiple blocks in parallel with the same round key. pub inline fn decryptWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].decrypt(round_key); } return out; } /// Encrypt multiple blocks in parallel with the same last round key. pub inline fn encryptLastWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].encryptLast(round_key); } return out; } /// Decrypt multiple blocks in parallel with the same last round key. pub inline fn decryptLastWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].decryptLast(round_key); } return out; } }; }; fn KeySchedule(comptime Aes: type) type { std.debug.assert(Aes.rounds == 10 or Aes.rounds == 14); const rounds = Aes.rounds; return struct { const Self = @This(); round_keys: [rounds + 1]Block, fn drc(comptime second: bool, comptime rc: u8, t: BlockVec, tx: BlockVec) BlockVec { var s: BlockVec = undefined; var ts: BlockVec = undefined; return asm ( \\ vaeskeygenassist %[rc], %[t], %[s] \\ vpslldq $4, %[tx], %[ts] \\ vpxor %[ts], %[tx], %[r] \\ vpslldq $8, %[r], %[ts] \\ vpxor %[ts], %[r], %[r] \\ vpshufd %[mask], %[s], %[ts] \\ vpxor %[ts], %[r], %[r] : [r] "=&x" (-> BlockVec), [s] "=&x" (s), [ts] "=&x" (ts), : [rc] "n" (rc), [t] "x" (t), [tx] "x" (tx), [mask] "n" (@as(u8, if (second) 0xaa else 0xff)), ); } fn expand128(t1: *Block) Self { var round_keys: [11]Block = undefined; const rcs = [_]u8{ 1, 2, 4, 8, 16, 32, 64, 128, 27, 54 }; inline for (rcs, 0..) |rc, round| { round_keys[round] = t1.*; t1.repr = drc(false, rc, t1.repr, t1.repr); } round_keys[rcs.len] = t1.*; return Self{ .round_keys = round_keys }; } fn expand256(t1: *Block, t2: *Block) Self { var round_keys: [15]Block = undefined; const rcs = [_]u8{ 1, 2, 4, 8, 16, 32 }; round_keys[0] = t1.*; inline for (rcs, 0..) |rc, round| { round_keys[round * 2 + 1] = t2.*; t1.repr = drc(false, rc, t2.repr, t1.repr); round_keys[round * 2 + 2] = t1.*; t2.repr = drc(true, rc, t1.repr, t2.repr); } round_keys[rcs.len * 2 + 1] = t2.*; t1.repr = drc(false, 64, t2.repr, t1.repr); round_keys[rcs.len * 2 + 2] = t1.*; return Self{ .round_keys = round_keys }; } /// Invert the key schedule. pub fn invert(key_schedule: Self) Self { const round_keys = &key_schedule.round_keys; var inv_round_keys: [rounds + 1]Block = undefined; inv_round_keys[0] = round_keys[rounds]; comptime var i = 1; inline while (i < rounds) : (i += 1) { inv_round_keys[i] = Block{ .repr = asm ( \\ vaesimc %[rk], %[inv_rk] : [inv_rk] "=x" (-> BlockVec), : [rk] "x" (round_keys[rounds - i].repr), ), }; } inv_round_keys[rounds] = round_keys[0]; return Self{ .round_keys = inv_round_keys }; } }; } /// A context to perform encryption using the standard AES key schedule. pub fn AesEncryptCtx(comptime Aes: type) type { std.debug.assert(Aes.key_bits == 128 or Aes.key_bits == 256); const rounds = Aes.rounds; return struct { const Self = @This(); pub const block = Aes.block; pub const block_length = block.block_length; key_schedule: KeySchedule(Aes), /// Create a new encryption context with the given key. pub fn init(key: [Aes.key_bits / 8]u8) Self { var t1 = Block.fromBytes(key[0..16]); const key_schedule = if (Aes.key_bits == 128) ks: { break :ks KeySchedule(Aes).expand128(&t1); } else ks: { var t2 = Block.fromBytes(key[16..32]); break :ks KeySchedule(Aes).expand256(&t1, &t2); }; return Self{ .key_schedule = key_schedule, }; } /// Encrypt a single block. pub fn encrypt(ctx: Self, dst: *[16]u8, src: *const [16]u8) void { const round_keys = ctx.key_schedule.round_keys; var t = Block.fromBytes(src).xorBlocks(round_keys[0]); comptime var i = 1; inline while (i < rounds) : (i += 1) { t = t.encrypt(round_keys[i]); } t = t.encryptLast(round_keys[rounds]); dst.* = t.toBytes(); } /// Encrypt+XOR a single block. pub fn xor(ctx: Self, dst: *[16]u8, src: *const [16]u8, counter: [16]u8) void { const round_keys = ctx.key_schedule.round_keys; var t = Block.fromBytes(&counter).xorBlocks(round_keys[0]); comptime var i = 1; inline while (i < rounds) : (i += 1) { t = t.encrypt(round_keys[i]); } t = t.encryptLast(round_keys[rounds]); dst.* = t.xorBytes(src); } /// Encrypt multiple blocks, possibly leveraging parallelization. pub fn encryptWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8) void { const round_keys = ctx.key_schedule.round_keys; var ts: [count]Block = undefined; comptime var j = 0; inline while (j < count) : (j += 1) { ts[j] = Block.fromBytes(src[j * 16 .. j * 16 + 16][0..16]).xorBlocks(round_keys[0]); } comptime var i = 1; inline while (i < rounds) : (i += 1) { ts = Block.parallel.encryptWide(count, ts, round_keys[i]); } ts = Block.parallel.encryptLastWide(count, ts, round_keys[i]); j = 0; inline while (j < count) : (j += 1) { dst[16 * j .. 16 * j + 16].* = ts[j].toBytes(); } } /// Encrypt+XOR multiple blocks, possibly leveraging parallelization. pub fn xorWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8, counters: [16 * count]u8) void { const round_keys = ctx.key_schedule.round_keys; var ts: [count]Block = undefined; comptime var j = 0; inline while (j < count) : (j += 1) { ts[j] = Block.fromBytes(counters[j * 16 .. j * 16 + 16][0..16]).xorBlocks(round_keys[0]); } comptime var i = 1; inline while (i < rounds) : (i += 1) { ts = Block.parallel.encryptWide(count, ts, round_keys[i]); } ts = Block.parallel.encryptLastWide(count, ts, round_keys[i]); j = 0; inline while (j < count) : (j += 1) { dst[16 * j .. 16 * j + 16].* = ts[j].xorBytes(src[16 * j .. 16 * j + 16]); } } }; } /// A context to perform decryption using the standard AES key schedule. pub fn AesDecryptCtx(comptime Aes: type) type { std.debug.assert(Aes.key_bits == 128 or Aes.key_bits == 256); const rounds = Aes.rounds; return struct { const Self = @This(); pub const block = Aes.block; pub const block_length = block.block_length; key_schedule: KeySchedule(Aes), /// Create a decryption context from an existing encryption context. pub fn initFromEnc(ctx: AesEncryptCtx(Aes)) Self { return Self{ .key_schedule = ctx.key_schedule.invert(), }; } /// Create a new decryption context with the given key. pub fn init(key: [Aes.key_bits / 8]u8) Self { const enc_ctx = AesEncryptCtx(Aes).init(key); return initFromEnc(enc_ctx); } /// Decrypt a single block. pub fn decrypt(ctx: Self, dst: *[16]u8, src: *const [16]u8) void { const inv_round_keys = ctx.key_schedule.round_keys; var t = Block.fromBytes(src).xorBlocks(inv_round_keys[0]); comptime var i = 1; inline while (i < rounds) : (i += 1) { t = t.decrypt(inv_round_keys[i]); } t = t.decryptLast(inv_round_keys[rounds]); dst.* = t.toBytes(); } /// Decrypt multiple blocks, possibly leveraging parallelization. pub fn decryptWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8) void { const inv_round_keys = ctx.key_schedule.round_keys; var ts: [count]Block = undefined; comptime var j = 0; inline while (j < count) : (j += 1) { ts[j] = Block.fromBytes(src[j * 16 .. j * 16 + 16][0..16]).xorBlocks(inv_round_keys[0]); } comptime var i = 1; inline while (i < rounds) : (i += 1) { ts = Block.parallel.decryptWide(count, ts, inv_round_keys[i]); } ts = Block.parallel.decryptLastWide(count, ts, inv_round_keys[i]); j = 0; inline while (j < count) : (j += 1) { dst[16 * j .. 16 * j + 16].* = ts[j].toBytes(); } } }; } /// AES-128 with the standard key schedule. pub const Aes128 = struct { pub const key_bits: usize = 128; pub const rounds = ((key_bits - 64) / 32 + 8); pub const block = Block; /// Create a new context for encryption. pub fn initEnc(key: [key_bits / 8]u8) AesEncryptCtx(Aes128) { return AesEncryptCtx(Aes128).init(key); } /// Create a new context for decryption. pub fn initDec(key: [key_bits / 8]u8) AesDecryptCtx(Aes128) { return AesDecryptCtx(Aes128).init(key); } }; /// AES-256 with the standard key schedule. pub const Aes256 = struct { pub const key_bits: usize = 256; pub const rounds = ((key_bits - 64) / 32 + 8); pub const block = Block; /// Create a new context for encryption. pub fn initEnc(key: [key_bits / 8]u8) AesEncryptCtx(Aes256) { return AesEncryptCtx(Aes256).init(key); } /// Create a new context for decryption. pub fn initDec(key: [key_bits / 8]u8) AesDecryptCtx(Aes256) { return AesDecryptCtx(Aes256).init(key); } };
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves/tests.zig
const std = @import("std"); const fmt = std.fmt; const testing = std.testing; const P256 = @import("p256.zig").P256; test "p256 ECDH key exchange" { const dha = P256.scalar.random(.Little); const dhb = P256.scalar.random(.Little); const dhA = try P256.basePoint.mul(dha, .Little); const dhB = try P256.basePoint.mul(dhb, .Little); const shareda = try dhA.mul(dhb, .Little); const sharedb = try dhB.mul(dha, .Little); try testing.expect(shareda.equivalent(sharedb)); } test "p256 point from affine coordinates" { const xh = "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"; const yh = "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"; var xs: [32]u8 = undefined; _ = try fmt.hexToBytes(&xs, xh); var ys: [32]u8 = undefined; _ = try fmt.hexToBytes(&ys, yh); var p = try P256.fromSerializedAffineCoordinates(xs, ys, .Big); try testing.expect(p.equivalent(P256.basePoint)); } test "p256 test vectors" { const expected = [_][]const u8{ "0000000000000000000000000000000000000000000000000000000000000000", "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", "7cf27b188d034f7e8a52380304b51ac3c08969e277f21b35a60b48fc47669978", "5ecbe4d1a6330a44c8f7ef951d4bf165e6c6b721efada985fb41661bc6e7fd6c", "e2534a3532d08fbba02dde659ee62bd0031fe2db785596ef509302446b030852", "51590b7a515140d2d784c85608668fdfef8c82fd1f5be52421554a0dc3d033ed", "b01a172a76a4602c92d3242cb897dde3024c740debb215b4c6b0aae93c2291a9", "8e533b6fa0bf7b4625bb30667c01fb607ef9f8b8a80fef5b300628703187b2a3", "62d9779dbee9b0534042742d3ab54cadc1d238980fce97dbb4dd9dc1db6fb393", "ea68d7b6fedf0b71878938d51d71f8729e0acb8c2c6df8b3d79e8a4b90949ee0", }; var p = P256.identityElement; for (expected) |xh| { const x = p.affineCoordinates().x; p = p.add(P256.basePoint); var xs: [32]u8 = undefined; _ = try fmt.hexToBytes(&xs, xh); try testing.expectEqualSlices(u8, &x.toBytes(.Big), &xs); } } test "p256 test vectors - doubling" { const expected = [_][]const u8{ "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", "7cf27b188d034f7e8a52380304b51ac3c08969e277f21b35a60b48fc47669978", "e2534a3532d08fbba02dde659ee62bd0031fe2db785596ef509302446b030852", "62d9779dbee9b0534042742d3ab54cadc1d238980fce97dbb4dd9dc1db6fb393", }; var p = P256.basePoint; for (expected) |xh| { const x = p.affineCoordinates().x; p = p.dbl(); var xs: [32]u8 = undefined; _ = try fmt.hexToBytes(&xs, xh); try testing.expectEqualSlices(u8, &x.toBytes(.Big), &xs); } } test "p256 compressed sec1 encoding/decoding" { const p = P256.random(); const s = p.toCompressedSec1(); const q = try P256.fromSec1(&s); try testing.expect(p.equivalent(q)); } test "p256 uncompressed sec1 encoding/decoding" { const p = P256.random(); const s = p.toUncompressedSec1(); const q = try P256.fromSec1(&s); try testing.expect(p.equivalent(q)); } test "p256 public key is the neutral element" { const n = P256.scalar.Scalar.zero.toBytes(.Little); const p = P256.random(); try testing.expectError(error.IdentityElement, p.mul(n, .Little)); } test "p256 public key is the neutral element (public verification)" { const n = P256.scalar.Scalar.zero.toBytes(.Little); const p = P256.random(); try testing.expectError(error.IdentityElement, p.mulPublic(n, .Little)); } test "p256 field element non-canonical encoding" { const s = [_]u8{0xff} ** 32; try testing.expectError(error.NonCanonical, P256.Fe.fromBytes(s, .Little)); } test "p256 neutral element decoding" { try testing.expectError(error.InvalidEncoding, P256.fromAffineCoordinates(.{ .x = P256.Fe.zero, .y = P256.Fe.zero })); const p = try P256.fromAffineCoordinates(.{ .x = P256.Fe.zero, .y = P256.Fe.one }); try testing.expectError(error.IdentityElement, p.rejectIdentity()); } test "p256 double base multiplication" { const p1 = P256.basePoint; const p2 = P256.basePoint.dbl(); const s1 = [_]u8{0x01} ** 32; const s2 = [_]u8{0x02} ** 32; const pr1 = try P256.mulDoubleBasePublic(p1, s1, p2, s2, .Little); const pr2 = (try p1.mul(s1, .Little)).add(try p2.mul(s2, .Little)); try testing.expect(pr1.equivalent(pr2)); } test "p256 scalar inverse" { const expected = "3b549196a13c898a6f6e84dfb3a22c40a8b9b17fb88e408ea674e451cd01d0a6"; var out: [32]u8 = undefined; _ = try std.fmt.hexToBytes(&out, expected); const scalar = try P256.scalar.Scalar.fromBytes(.{ 0x94, 0xa1, 0xbb, 0xb1, 0x4b, 0x90, 0x6a, 0x61, 0xa2, 0x80, 0xf2, 0x45, 0xf9, 0xe9, 0x3c, 0x7f, 0x3b, 0x4a, 0x62, 0x47, 0x82, 0x4f, 0x5d, 0x33, 0xb9, 0x67, 0x07, 0x87, 0x64, 0x2a, 0x68, 0xde, }, .Big); const inverse = scalar.invert(); try std.testing.expectEqualSlices(u8, &out, &inverse.toBytes(.Big)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves/p256.zig
const std = @import("std"); const crypto = std.crypto; const mem = std.mem; const meta = std.meta; const EncodingError = crypto.errors.EncodingError; const IdentityElementError = crypto.errors.IdentityElementError; const NonCanonicalError = crypto.errors.NonCanonicalError; const NotSquareError = crypto.errors.NotSquareError; /// Group operations over P256. pub const P256 = struct { /// The underlying prime field. pub const Fe = @import("p256/field.zig").Fe; /// Field arithmetic mod the order of the main subgroup. pub const scalar = @import("p256/scalar.zig"); x: Fe, y: Fe, z: Fe = Fe.one, is_base: bool = false, /// The P256 base point. pub const basePoint = P256{ .x = Fe.fromInt(48439561293906451759052585252797914202762949526041747995844080717082404635286) catch unreachable, .y = Fe.fromInt(36134250956749795798585127919587881956611106672985015071877198253568414405109) catch unreachable, .z = Fe.one, .is_base = true, }; /// The P256 neutral element. pub const identityElement = P256{ .x = Fe.zero, .y = Fe.one, .z = Fe.zero }; pub const B = Fe.fromInt(41058363725152142129326129780047268409114441015993725554835256314039467401291) catch unreachable; /// Reject the neutral element. pub fn rejectIdentity(p: P256) IdentityElementError!void { if (p.x.isZero()) { return error.IdentityElement; } } /// Create a point from affine coordinates after checking that they match the curve equation. pub fn fromAffineCoordinates(p: AffineCoordinates) EncodingError!P256 { const x = p.x; const y = p.y; const x3AxB = x.sq().mul(x).sub(x).sub(x).sub(x).add(B); const yy = y.sq(); const on_curve = @intFromBool(x3AxB.equivalent(yy)); const is_identity = @intFromBool(x.equivalent(AffineCoordinates.identityElement.x)) & @intFromBool(y.equivalent(AffineCoordinates.identityElement.y)); if ((on_curve | is_identity) == 0) { return error.InvalidEncoding; } var ret = P256{ .x = x, .y = y, .z = Fe.one }; ret.z.cMov(P256.identityElement.z, is_identity); return ret; } /// Create a point from serialized affine coordinates. pub fn fromSerializedAffineCoordinates(xs: [32]u8, ys: [32]u8, endian: std.builtin.Endian) (NonCanonicalError || EncodingError)!P256 { const x = try Fe.fromBytes(xs, endian); const y = try Fe.fromBytes(ys, endian); return fromAffineCoordinates(.{ .x = x, .y = y }); } /// Recover the Y coordinate from the X coordinate. pub fn recoverY(x: Fe, is_odd: bool) NotSquareError!Fe { const x3AxB = x.sq().mul(x).sub(x).sub(x).sub(x).add(B); var y = try x3AxB.sqrt(); const yn = y.neg(); y.cMov(yn, @intFromBool(is_odd) ^ @intFromBool(y.isOdd())); return y; } /// Deserialize a SEC1-encoded point. pub fn fromSec1(s: []const u8) (EncodingError || NotSquareError || NonCanonicalError)!P256 { if (s.len < 1) return error.InvalidEncoding; const encoding_type = s[0]; const encoded = s[1..]; switch (encoding_type) { 0 => { if (encoded.len != 0) return error.InvalidEncoding; return P256.identityElement; }, 2, 3 => { if (encoded.len != 32) return error.InvalidEncoding; const x = try Fe.fromBytes(encoded[0..32].*, .Big); const y_is_odd = (encoding_type == 3); const y = try recoverY(x, y_is_odd); return P256{ .x = x, .y = y }; }, 4 => { if (encoded.len != 64) return error.InvalidEncoding; const x = try Fe.fromBytes(encoded[0..32].*, .Big); const y = try Fe.fromBytes(encoded[32..64].*, .Big); return P256.fromAffineCoordinates(.{ .x = x, .y = y }); }, else => return error.InvalidEncoding, } } /// Serialize a point using the compressed SEC-1 format. pub fn toCompressedSec1(p: P256) [33]u8 { var out: [33]u8 = undefined; const xy = p.affineCoordinates(); out[0] = if (xy.y.isOdd()) 3 else 2; mem.copy(u8, out[1..], &xy.x.toBytes(.Big)); return out; } /// Serialize a point using the uncompressed SEC-1 format. pub fn toUncompressedSec1(p: P256) [65]u8 { var out: [65]u8 = undefined; out[0] = 4; const xy = p.affineCoordinates(); mem.copy(u8, out[1..33], &xy.x.toBytes(.Big)); mem.copy(u8, out[33..65], &xy.y.toBytes(.Big)); return out; } /// Return a random point. pub fn random() P256 { const n = scalar.random(.Little); return basePoint.mul(n, .Little) catch unreachable; } /// Flip the sign of the X coordinate. pub fn neg(p: P256) P256 { return .{ .x = p.x, .y = p.y.neg(), .z = p.z }; } /// Double a P256 point. // Algorithm 6 from https://eprint.iacr.org/2015/1060.pdf pub fn dbl(p: P256) P256 { var t0 = p.x.sq(); var t1 = p.y.sq(); var t2 = p.z.sq(); var t3 = p.x.mul(p.y); t3 = t3.dbl(); var Z3 = p.x.mul(p.z); Z3 = Z3.add(Z3); var Y3 = B.mul(t2); Y3 = Y3.sub(Z3); var X3 = Y3.dbl(); Y3 = X3.add(Y3); X3 = t1.sub(Y3); Y3 = t1.add(Y3); Y3 = X3.mul(Y3); X3 = X3.mul(t3); t3 = t2.dbl(); t2 = t2.add(t3); Z3 = B.mul(Z3); Z3 = Z3.sub(t2); Z3 = Z3.sub(t0); t3 = Z3.dbl(); Z3 = Z3.add(t3); t3 = t0.dbl(); t0 = t3.add(t0); t0 = t0.sub(t2); t0 = t0.mul(Z3); Y3 = Y3.add(t0); t0 = p.y.mul(p.z); t0 = t0.dbl(); Z3 = t0.mul(Z3); X3 = X3.sub(Z3); Z3 = t0.mul(t1); Z3 = Z3.dbl().dbl(); return .{ .x = X3, .y = Y3, .z = Z3, }; } /// Add P256 points, the second being specified using affine coordinates. // Algorithm 5 from https://eprint.iacr.org/2015/1060.pdf pub fn addMixed(p: P256, q: AffineCoordinates) P256 { var t0 = p.x.mul(q.x); var t1 = p.y.mul(q.y); var t3 = q.x.add(q.y); var t4 = p.x.add(p.y); t3 = t3.mul(t4); t4 = t0.add(t1); t3 = t3.sub(t4); t4 = q.y.mul(p.z); t4 = t4.add(p.y); var Y3 = q.x.mul(p.z); Y3 = Y3.add(p.x); var Z3 = B.mul(p.z); var X3 = Y3.sub(Z3); Z3 = X3.dbl(); X3 = X3.add(Z3); Z3 = t1.sub(X3); X3 = t1.add(X3); Y3 = B.mul(Y3); t1 = p.z.dbl(); var t2 = t1.add(p.z); Y3 = Y3.sub(t2); Y3 = Y3.sub(t0); t1 = Y3.dbl(); Y3 = t1.add(Y3); t1 = t0.dbl(); t0 = t1.add(t0); t0 = t0.sub(t2); t1 = t4.mul(Y3); t2 = t0.mul(Y3); Y3 = X3.mul(Z3); Y3 = Y3.add(t2); X3 = t3.mul(X3); X3 = X3.sub(t1); Z3 = t4.mul(Z3); t1 = t3.mul(t0); Z3 = Z3.add(t1); var ret = P256{ .x = X3, .y = Y3, .z = Z3, }; ret.cMov(p, @intFromBool(q.x.isZero())); return ret; } /// Add P256 points. // Algorithm 4 from https://eprint.iacr.org/2015/1060.pdf pub fn add(p: P256, q: P256) P256 { var t0 = p.x.mul(q.x); var t1 = p.y.mul(q.y); var t2 = p.z.mul(q.z); var t3 = p.x.add(p.y); var t4 = q.x.add(q.y); t3 = t3.mul(t4); t4 = t0.add(t1); t3 = t3.sub(t4); t4 = p.y.add(p.z); var X3 = q.y.add(q.z); t4 = t4.mul(X3); X3 = t1.add(t2); t4 = t4.sub(X3); X3 = p.x.add(p.z); var Y3 = q.x.add(q.z); X3 = X3.mul(Y3); Y3 = t0.add(t2); Y3 = X3.sub(Y3); var Z3 = B.mul(t2); X3 = Y3.sub(Z3); Z3 = X3.dbl(); X3 = X3.add(Z3); Z3 = t1.sub(X3); X3 = t1.add(X3); Y3 = B.mul(Y3); t1 = t2.dbl(); t2 = t1.add(t2); Y3 = Y3.sub(t2); Y3 = Y3.sub(t0); t1 = Y3.dbl(); Y3 = t1.add(Y3); t1 = t0.dbl(); t0 = t1.add(t0); t0 = t0.sub(t2); t1 = t4.mul(Y3); t2 = t0.mul(Y3); Y3 = X3.mul(Z3); Y3 = Y3.add(t2); X3 = t3.mul(X3); X3 = X3.sub(t1); Z3 = t4.mul(Z3); t1 = t3.mul(t0); Z3 = Z3.add(t1); return .{ .x = X3, .y = Y3, .z = Z3, }; } /// Subtract P256 points. pub fn sub(p: P256, q: P256) P256 { return p.add(q.neg()); } /// Subtract P256 points, the second being specified using affine coordinates. pub fn subMixed(p: P256, q: AffineCoordinates) P256 { return p.addMixed(q.neg()); } /// Return affine coordinates. pub fn affineCoordinates(p: P256) AffineCoordinates { const zinv = p.z.invert(); var ret = AffineCoordinates{ .x = p.x.mul(zinv), .y = p.y.mul(zinv), }; ret.cMov(AffineCoordinates.identityElement, @intFromBool(p.x.isZero())); return ret; } /// Return true if both coordinate sets represent the same point. pub fn equivalent(a: P256, b: P256) bool { if (a.sub(b).rejectIdentity()) { return false; } else |_| { return true; } } fn cMov(p: *P256, a: P256, c: u1) void { p.x.cMov(a.x, c); p.y.cMov(a.y, c); p.z.cMov(a.z, c); } fn pcSelect(comptime n: usize, pc: *const [n]P256, b: u8) P256 { var t = P256.identityElement; comptime var i: u8 = 1; inline while (i < pc.len) : (i += 1) { t.cMov(pc[i], @as(u1, @truncate((@as(usize, b ^ i) -% 1) >> 8))); } return t; } fn slide(s: [32]u8) [2 * 32 + 1]i8 { var e: [2 * 32 + 1]i8 = undefined; for (s, 0..) |x, i| { e[i * 2 + 0] = @as(i8, @as(u4, @truncate(x))); e[i * 2 + 1] = @as(i8, @as(u4, @truncate(x >> 4))); } // Now, e[0..63] is between 0 and 15, e[63] is between 0 and 7 var carry: i8 = 0; for (e[0..64]) |*x| { x.* += carry; carry = (x.* + 8) >> 4; x.* -= carry * 16; std.debug.assert(x.* >= -8 and x.* <= 8); } e[64] = carry; // Now, e[*] is between -8 and 8, including e[64] std.debug.assert(carry >= -8 and carry <= 8); return e; } fn pcMul(pc: *const [9]P256, s: [32]u8, comptime vartime: bool) IdentityElementError!P256 { std.debug.assert(vartime); const e = slide(s); var q = P256.identityElement; var pos = e.len - 1; while (true) : (pos -= 1) { const slot = e[pos]; if (slot > 0) { q = q.add(pc[@as(usize, @intCast(slot))]); } else if (slot < 0) { q = q.sub(pc[@as(usize, @intCast(-slot))]); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } fn pcMul16(pc: *const [16]P256, s: [32]u8, comptime vartime: bool) IdentityElementError!P256 { var q = P256.identityElement; var pos: usize = 252; while (true) : (pos -= 4) { const slot = @as(u4, @truncate((s[pos >> 3] >> @as(u3, @truncate(pos))))); if (vartime) { if (slot != 0) { q = q.add(pc[slot]); } } else { q = q.add(pcSelect(16, pc, slot)); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } fn precompute(p: P256, comptime count: usize) [1 + count]P256 { var pc: [1 + count]P256 = undefined; pc[0] = P256.identityElement; pc[1] = p; var i: usize = 2; while (i <= count) : (i += 1) { pc[i] = if (i % 2 == 0) pc[i / 2].dbl() else pc[i - 1].add(p); } return pc; } const basePointPc = pc: { @setEvalBranchQuota(50000); break :pc precompute(P256.basePoint, 15); }; /// Multiply an elliptic curve point by a scalar. /// Return error.IdentityElement if the result is the identity element. pub fn mul(p: P256, s_: [32]u8, endian: std.builtin.Endian) IdentityElementError!P256 { const s = if (endian == .Little) s_ else Fe.orderSwap(s_); if (p.is_base) { return pcMul16(&basePointPc, s, false); } try p.rejectIdentity(); const pc = precompute(p, 15); return pcMul16(&pc, s, false); } /// Multiply an elliptic curve point by a *PUBLIC* scalar *IN VARIABLE TIME* /// This can be used for signature verification. pub fn mulPublic(p: P256, s_: [32]u8, endian: std.builtin.Endian) IdentityElementError!P256 { const s = if (endian == .Little) s_ else Fe.orderSwap(s_); if (p.is_base) { return pcMul16(&basePointPc, s, true); } try p.rejectIdentity(); const pc = precompute(p, 8); return pcMul(&pc, s, true); } /// Double-base multiplication of public parameters - Compute (p1*s1)+(p2*s2) *IN VARIABLE TIME* /// This can be used for signature verification. pub fn mulDoubleBasePublic(p1: P256, s1_: [32]u8, p2: P256, s2_: [32]u8, endian: std.builtin.Endian) IdentityElementError!P256 { const s1 = if (endian == .Little) s1_ else Fe.orderSwap(s1_); const s2 = if (endian == .Little) s2_ else Fe.orderSwap(s2_); try p1.rejectIdentity(); var pc1_array: [9]P256 = undefined; const pc1 = if (p1.is_base) basePointPc[0..9] else pc: { pc1_array = precompute(p1, 8); break :pc &pc1_array; }; try p2.rejectIdentity(); var pc2_array: [9]P256 = undefined; const pc2 = if (p2.is_base) basePointPc[0..9] else pc: { pc2_array = precompute(p2, 8); break :pc &pc2_array; }; const e1 = slide(s1); const e2 = slide(s2); var q = P256.identityElement; var pos: usize = 2 * 32 - 1; while (true) : (pos -= 1) { const slot1 = e1[pos]; if (slot1 > 0) { q = q.add(pc1[@as(usize, @intCast(slot1))]); } else if (slot1 < 0) { q = q.sub(pc1[@as(usize, @intCast(-slot1))]); } const slot2 = e2[pos]; if (slot2 > 0) { q = q.add(pc2[@as(usize, @intCast(slot2))]); } else if (slot2 < 0) { q = q.sub(pc2[@as(usize, @intCast(-slot2))]); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } }; /// A point in affine coordinates. pub const AffineCoordinates = struct { x: P256.Fe, y: P256.Fe, /// Identity element in affine coordinates. pub const identityElement = AffineCoordinates{ .x = P256.identityElement.x, .y = P256.identityElement.y }; fn cMov(p: *AffineCoordinates, a: AffineCoordinates, c: u1) void { p.x.cMov(a.x, c); p.y.cMov(a.y, c); } }; test "p256" { _ = @import("tests.zig"); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves/common.zig
const std = @import("std"); const crypto = std.crypto; const debug = std.debug; const mem = std.mem; const meta = std.meta; const NonCanonicalError = crypto.errors.NonCanonicalError; const NotSquareError = crypto.errors.NotSquareError; /// Parameters to create a finite field type. pub const FieldParams = struct { fiat: type, field_order: comptime_int, field_bits: comptime_int, saturated_bits: comptime_int, encoded_length: comptime_int, }; /// A field element, internally stored in Montgomery domain. pub fn Field(comptime params: FieldParams) type { const fiat = params.fiat; const MontgomeryDomainFieldElement = fiat.MontgomeryDomainFieldElement; const NonMontgomeryDomainFieldElement = fiat.NonMontgomeryDomainFieldElement; return struct { const Fe = @This(); limbs: MontgomeryDomainFieldElement, /// Field size. pub const field_order = params.field_order; /// Number of bits to represent the set of all elements. pub const field_bits = params.field_bits; /// Number of bits that can be saturated without overflowing. pub const saturated_bits = params.saturated_bits; /// Number of bytes required to encode an element. pub const encoded_length = params.encoded_length; /// Zero. pub const zero: Fe = Fe{ .limbs = mem.zeroes(MontgomeryDomainFieldElement) }; /// One. pub const one = one: { var fe: Fe = undefined; fiat.setOne(&fe.limbs); break :one fe; }; /// Reject non-canonical encodings of an element. pub fn rejectNonCanonical(s_: [encoded_length]u8, endian: std.builtin.Endian) NonCanonicalError!void { var s = if (endian == .Little) s_ else orderSwap(s_); const field_order_s = comptime fos: { var fos: [encoded_length]u8 = undefined; mem.writeIntLittle(std.meta.Int(.unsigned, encoded_length * 8), &fos, field_order); break :fos fos; }; if (crypto.utils.timingSafeCompare(u8, &s, &field_order_s, .Little) != .lt) { return error.NonCanonical; } } /// Swap the endianness of an encoded element. pub fn orderSwap(s: [encoded_length]u8) [encoded_length]u8 { var t = s; for (s, 0..) |x, i| t[t.len - 1 - i] = x; return t; } /// Unpack a field element. pub fn fromBytes(s_: [encoded_length]u8, endian: std.builtin.Endian) NonCanonicalError!Fe { var s = if (endian == .Little) s_ else orderSwap(s_); try rejectNonCanonical(s, .Little); var limbs_z: NonMontgomeryDomainFieldElement = undefined; fiat.fromBytes(&limbs_z, s); var limbs: MontgomeryDomainFieldElement = undefined; fiat.toMontgomery(&limbs, limbs_z); return Fe{ .limbs = limbs }; } /// Pack a field element. pub fn toBytes(fe: Fe, endian: std.builtin.Endian) [encoded_length]u8 { var limbs_z: NonMontgomeryDomainFieldElement = undefined; fiat.fromMontgomery(&limbs_z, fe.limbs); var s: [encoded_length]u8 = undefined; fiat.toBytes(&s, limbs_z); return if (endian == .Little) s else orderSwap(s); } /// Element as an integer. pub const IntRepr = meta.Int(.unsigned, params.field_bits); /// Create a field element from an integer. pub fn fromInt(comptime x: IntRepr) NonCanonicalError!Fe { var s: [encoded_length]u8 = undefined; mem.writeIntLittle(IntRepr, &s, x); return fromBytes(s, .Little); } /// Return the field element as an integer. pub fn toInt(fe: Fe) IntRepr { const s = fe.toBytes(.Little); return mem.readIntLittle(IntRepr, &s); } /// Return true if the field element is zero. pub fn isZero(fe: Fe) bool { var z: @TypeOf(fe.limbs[0]) = undefined; fiat.nonzero(&z, fe.limbs); return z == 0; } /// Return true if both field elements are equivalent. pub fn equivalent(a: Fe, b: Fe) bool { return a.sub(b).isZero(); } /// Return true if the element is odd. pub fn isOdd(fe: Fe) bool { const s = fe.toBytes(.Little); return @as(u1, @truncate(s[0])) != 0; } /// Conditonally replace a field element with `a` if `c` is positive. pub fn cMov(fe: *Fe, a: Fe, c: u1) void { fiat.selectznz(&fe.limbs, c, fe.limbs, a.limbs); } /// Add field elements. pub fn add(a: Fe, b: Fe) Fe { var fe: Fe = undefined; fiat.add(&fe.limbs, a.limbs, b.limbs); return fe; } /// Subtract field elements. pub fn sub(a: Fe, b: Fe) Fe { var fe: Fe = undefined; fiat.sub(&fe.limbs, a.limbs, b.limbs); return fe; } /// Double a field element. pub fn dbl(a: Fe) Fe { var fe: Fe = undefined; fiat.add(&fe.limbs, a.limbs, a.limbs); return fe; } /// Multiply field elements. pub fn mul(a: Fe, b: Fe) Fe { var fe: Fe = undefined; fiat.mul(&fe.limbs, a.limbs, b.limbs); return fe; } /// Square a field element. pub fn sq(a: Fe) Fe { var fe: Fe = undefined; fiat.square(&fe.limbs, a.limbs); return fe; } /// Square a field element n times. fn sqn(a: Fe, comptime n: comptime_int) Fe { var i: usize = 0; var fe = a; while (i < n) : (i += 1) { fe = fe.sq(); } return fe; } /// Compute a^n. pub fn pow(a: Fe, comptime T: type, comptime n: T) Fe { var fe = one; var x: T = n; var t = a; while (true) { if (@as(u1, @truncate(x)) != 0) fe = fe.mul(t); x >>= 1; if (x == 0) break; t = t.sq(); } return fe; } /// Negate a field element. pub fn neg(a: Fe) Fe { var fe: Fe = undefined; fiat.opp(&fe.limbs, a.limbs); return fe; } /// Return the inverse of a field element, or 0 if a=0. // Field inversion from https://eprint.iacr.org/2021/549.pdf pub fn invert(a: Fe) Fe { const iterations = (49 * field_bits + 57) / 17; const Limbs = @TypeOf(a.limbs); const Word = @TypeOf(a.limbs[0]); const XLimbs = [a.limbs.len + 1]Word; var d: Word = 1; var f: XLimbs = undefined; fiat.msat(&f); var g: XLimbs = undefined; fiat.fromMontgomery(g[0..a.limbs.len], a.limbs); g[g.len - 1] = 0; var r: Limbs = undefined; fiat.setOne(&r); var v = mem.zeroes(Limbs); var precomp: Limbs = undefined; fiat.divstepPrecomp(&precomp); var out1: Word = undefined; var out2: XLimbs = undefined; var out3: XLimbs = undefined; var out4: Limbs = undefined; var out5: Limbs = undefined; var i: usize = 0; while (i < iterations - iterations % 2) : (i += 2) { fiat.divstep(&out1, &out2, &out3, &out4, &out5, d, f, g, v, r); fiat.divstep(&d, &f, &g, &v, &r, out1, out2, out3, out4, out5); } if (iterations % 2 != 0) { fiat.divstep(&out1, &out2, &out3, &out4, &out5, d, f, g, v, r); mem.copy(Word, &v, &out4); mem.copy(Word, &f, &out2); } var v_opp: Limbs = undefined; fiat.opp(&v_opp, v); fiat.selectznz(&v, @as(u1, @truncate(f[f.len - 1] >> (meta.bitCount(Word) - 1))), v, v_opp); var fe: Fe = undefined; fiat.mul(&fe.limbs, v, precomp); return fe; } /// Return true if the field element is a square. pub fn isSquare(x2: Fe) bool { if (field_order == 115792089210356248762697446949407573530086143415290314195533631308867097853951) { const t110 = x2.mul(x2.sq()).sq(); const t111 = x2.mul(t110); const t111111 = t111.mul(x2.mul(t110).sqn(3)); const x15 = t111111.sqn(6).mul(t111111).sqn(3).mul(t111); const x16 = x15.sq().mul(x2); const x53 = x16.sqn(16).mul(x16).sqn(15); const x47 = x15.mul(x53); const ls = x47.mul(((x53.sqn(17).mul(x2)).sqn(143).mul(x47)).sqn(47)).sq().mul(x2); return ls.equivalent(Fe.one); } else { const ls = x2.pow(std.meta.Int(.unsigned, field_bits), (field_order - 1) / 2); // Legendre symbol return ls.equivalent(Fe.one); } } // x=x2^((field_order+1)/4) w/ field order=3 (mod 4). fn uncheckedSqrt(x2: Fe) Fe { comptime debug.assert(field_order % 4 == 3); if (field_order == 115792089210356248762697446949407573530086143415290314195533631308867097853951) { const t11 = x2.mul(x2.sq()); const t1111 = t11.mul(t11.sqn(2)); const t11111111 = t1111.mul(t1111.sqn(4)); const x16 = t11111111.sqn(8).mul(t11111111); return x16.sqn(16).mul(x16).sqn(32).mul(x2).sqn(96).mul(x2).sqn(94); } else { return x2.pow(std.meta.Int(.unsigned, field_bits), (field_order + 1) / 4); } } /// Compute the square root of `x2`, returning `error.NotSquare` if `x2` was not a square. pub fn sqrt(x2: Fe) NotSquareError!Fe { const x = x2.uncheckedSqrt(); if (x.sq().equivalent(x2)) { return x; } return error.NotSquare; } }; }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves/p256/p256_scalar_64.zig
// Autogenerated: 'src/ExtractionOCaml/word_by_word_montgomery' --lang Zig --internal-static --public-function-case camelCase --private-function-case camelCase --public-type-case UpperCamelCase --private-type-case UpperCamelCase --no-prefix-fiat --package-name p256-scalar '' 64 115792089210356248762697446949407573529996955224135760342422259061068512044369 mul square add sub opp from_montgomery to_montgomery nonzero selectznz to_bytes from_bytes one msat divstep divstep_precomp // curve description (via package name): p256-scalar // machine_wordsize = 64 (from "64") // requested operations: mul, square, add, sub, opp, from_montgomery, to_montgomery, nonzero, selectznz, to_bytes, from_bytes, one, msat, divstep, divstep_precomp // m = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 (from "115792089210356248762697446949407573529996955224135760342422259061068512044369") // // NOTE: In addition to the bounds specified above each function, all // functions synthesized for this Montgomery arithmetic require the // input to be strictly less than the prime modulus (m), and also // require the input to be in the unique saturated representation. // All functions also ensure that these two properties are true of // return values. // // Computed values: // eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) // bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) // twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in // if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 const std = @import("std"); const mode = @import("builtin").mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels // The type MontgomeryDomainFieldElement is a field element in the Montgomery domain. // Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub const MontgomeryDomainFieldElement = [4]u64; // The type NonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain. // Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub const NonMontgomeryDomainFieldElement = [4]u64; /// The function addcarryxU64 is an addition with carry. /// /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^64 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] inline fn addcarryxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const ov1 = @addWithOverflow(arg2, arg3); const ov2 = @addWithOverflow(ov1[0], arg1); out1.* = ov2[0]; out2.* = ov1[1] | ov2[1]; } /// The function subborrowxU64 is a subtraction with borrow. /// /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^64 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] inline fn subborrowxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const ov1 = @subWithOverflow(arg2, arg3); const ov2 = @subWithOverflow(ov1[0], arg1); out1.* = ov2[0]; out2.* = ov1[1] | ov2[1]; } /// The function mulxU64 is a multiplication, returning the full double-width result. /// /// Postconditions: /// out1 = (arg1 * arg2) mod 2^64 /// out2 = ⌊arg1 * arg2 / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0xffffffffffffffff] inline fn mulxU64(out1: *u64, out2: *u64, arg1: u64, arg2: u64) void { @setRuntimeSafety(mode == .Debug); const x = @as(u128, arg1) * @as(u128, arg2); out1.* = @as(u64, @truncate(x)); out2.* = @as(u64, @truncate(x >> 64)); } /// The function cmovznzU64 is a single-word conditional move. /// /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] inline fn cmovznzU64(out1: *u64, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const mask = 0 -% @as(u64, arg1); out1.* = (mask & arg3) | ((~mask) & arg2); } /// The function mul multiplies two field elements in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// pub fn mul(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; mulxU64(&x5, &x6, x4, (arg2[3])); var x7: u64 = undefined; var x8: u64 = undefined; mulxU64(&x7, &x8, x4, (arg2[2])); var x9: u64 = undefined; var x10: u64 = undefined; mulxU64(&x9, &x10, x4, (arg2[1])); var x11: u64 = undefined; var x12: u64 = undefined; mulxU64(&x11, &x12, x4, (arg2[0])); var x13: u64 = undefined; var x14: u1 = undefined; addcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; addcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; addcarryxU64(&x17, &x18, x16, x8, x5); const x19 = (@as(u64, x18) + x6); var x20: u64 = undefined; var x21: u64 = undefined; mulxU64(&x20, &x21, x11, 0xccd1c8aaee00bc4f); var x22: u64 = undefined; var x23: u64 = undefined; mulxU64(&x22, &x23, x20, 0xffffffff00000000); var x24: u64 = undefined; var x25: u64 = undefined; mulxU64(&x24, &x25, x20, 0xffffffffffffffff); var x26: u64 = undefined; var x27: u64 = undefined; mulxU64(&x26, &x27, x20, 0xbce6faada7179e84); var x28: u64 = undefined; var x29: u64 = undefined; mulxU64(&x28, &x29, x20, 0xf3b9cac2fc632551); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, 0x0, x29, x26); var x32: u64 = undefined; var x33: u1 = undefined; addcarryxU64(&x32, &x33, x31, x27, x24); var x34: u64 = undefined; var x35: u1 = undefined; addcarryxU64(&x34, &x35, x33, x25, x22); const x36 = (@as(u64, x35) + x23); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, 0x0, x11, x28); var x39: u64 = undefined; var x40: u1 = undefined; addcarryxU64(&x39, &x40, x38, x13, x30); var x41: u64 = undefined; var x42: u1 = undefined; addcarryxU64(&x41, &x42, x40, x15, x32); var x43: u64 = undefined; var x44: u1 = undefined; addcarryxU64(&x43, &x44, x42, x17, x34); var x45: u64 = undefined; var x46: u1 = undefined; addcarryxU64(&x45, &x46, x44, x19, x36); var x47: u64 = undefined; var x48: u64 = undefined; mulxU64(&x47, &x48, x1, (arg2[3])); var x49: u64 = undefined; var x50: u64 = undefined; mulxU64(&x49, &x50, x1, (arg2[2])); var x51: u64 = undefined; var x52: u64 = undefined; mulxU64(&x51, &x52, x1, (arg2[1])); var x53: u64 = undefined; var x54: u64 = undefined; mulxU64(&x53, &x54, x1, (arg2[0])); var x55: u64 = undefined; var x56: u1 = undefined; addcarryxU64(&x55, &x56, 0x0, x54, x51); var x57: u64 = undefined; var x58: u1 = undefined; addcarryxU64(&x57, &x58, x56, x52, x49); var x59: u64 = undefined; var x60: u1 = undefined; addcarryxU64(&x59, &x60, x58, x50, x47); const x61 = (@as(u64, x60) + x48); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, 0x0, x39, x53); var x64: u64 = undefined; var x65: u1 = undefined; addcarryxU64(&x64, &x65, x63, x41, x55); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, x65, x43, x57); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, x67, x45, x59); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, x69, @as(u64, x46), x61); var x72: u64 = undefined; var x73: u64 = undefined; mulxU64(&x72, &x73, x62, 0xccd1c8aaee00bc4f); var x74: u64 = undefined; var x75: u64 = undefined; mulxU64(&x74, &x75, x72, 0xffffffff00000000); var x76: u64 = undefined; var x77: u64 = undefined; mulxU64(&x76, &x77, x72, 0xffffffffffffffff); var x78: u64 = undefined; var x79: u64 = undefined; mulxU64(&x78, &x79, x72, 0xbce6faada7179e84); var x80: u64 = undefined; var x81: u64 = undefined; mulxU64(&x80, &x81, x72, 0xf3b9cac2fc632551); var x82: u64 = undefined; var x83: u1 = undefined; addcarryxU64(&x82, &x83, 0x0, x81, x78); var x84: u64 = undefined; var x85: u1 = undefined; addcarryxU64(&x84, &x85, x83, x79, x76); var x86: u64 = undefined; var x87: u1 = undefined; addcarryxU64(&x86, &x87, x85, x77, x74); const x88 = (@as(u64, x87) + x75); var x89: u64 = undefined; var x90: u1 = undefined; addcarryxU64(&x89, &x90, 0x0, x62, x80); var x91: u64 = undefined; var x92: u1 = undefined; addcarryxU64(&x91, &x92, x90, x64, x82); var x93: u64 = undefined; var x94: u1 = undefined; addcarryxU64(&x93, &x94, x92, x66, x84); var x95: u64 = undefined; var x96: u1 = undefined; addcarryxU64(&x95, &x96, x94, x68, x86); var x97: u64 = undefined; var x98: u1 = undefined; addcarryxU64(&x97, &x98, x96, x70, x88); const x99 = (@as(u64, x98) + @as(u64, x71)); var x100: u64 = undefined; var x101: u64 = undefined; mulxU64(&x100, &x101, x2, (arg2[3])); var x102: u64 = undefined; var x103: u64 = undefined; mulxU64(&x102, &x103, x2, (arg2[2])); var x104: u64 = undefined; var x105: u64 = undefined; mulxU64(&x104, &x105, x2, (arg2[1])); var x106: u64 = undefined; var x107: u64 = undefined; mulxU64(&x106, &x107, x2, (arg2[0])); var x108: u64 = undefined; var x109: u1 = undefined; addcarryxU64(&x108, &x109, 0x0, x107, x104); var x110: u64 = undefined; var x111: u1 = undefined; addcarryxU64(&x110, &x111, x109, x105, x102); var x112: u64 = undefined; var x113: u1 = undefined; addcarryxU64(&x112, &x113, x111, x103, x100); const x114 = (@as(u64, x113) + x101); var x115: u64 = undefined; var x116: u1 = undefined; addcarryxU64(&x115, &x116, 0x0, x91, x106); var x117: u64 = undefined; var x118: u1 = undefined; addcarryxU64(&x117, &x118, x116, x93, x108); var x119: u64 = undefined; var x120: u1 = undefined; addcarryxU64(&x119, &x120, x118, x95, x110); var x121: u64 = undefined; var x122: u1 = undefined; addcarryxU64(&x121, &x122, x120, x97, x112); var x123: u64 = undefined; var x124: u1 = undefined; addcarryxU64(&x123, &x124, x122, x99, x114); var x125: u64 = undefined; var x126: u64 = undefined; mulxU64(&x125, &x126, x115, 0xccd1c8aaee00bc4f); var x127: u64 = undefined; var x128: u64 = undefined; mulxU64(&x127, &x128, x125, 0xffffffff00000000); var x129: u64 = undefined; var x130: u64 = undefined; mulxU64(&x129, &x130, x125, 0xffffffffffffffff); var x131: u64 = undefined; var x132: u64 = undefined; mulxU64(&x131, &x132, x125, 0xbce6faada7179e84); var x133: u64 = undefined; var x134: u64 = undefined; mulxU64(&x133, &x134, x125, 0xf3b9cac2fc632551); var x135: u64 = undefined; var x136: u1 = undefined; addcarryxU64(&x135, &x136, 0x0, x134, x131); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, x136, x132, x129); var x139: u64 = undefined; var x140: u1 = undefined; addcarryxU64(&x139, &x140, x138, x130, x127); const x141 = (@as(u64, x140) + x128); var x142: u64 = undefined; var x143: u1 = undefined; addcarryxU64(&x142, &x143, 0x0, x115, x133); var x144: u64 = undefined; var x145: u1 = undefined; addcarryxU64(&x144, &x145, x143, x117, x135); var x146: u64 = undefined; var x147: u1 = undefined; addcarryxU64(&x146, &x147, x145, x119, x137); var x148: u64 = undefined; var x149: u1 = undefined; addcarryxU64(&x148, &x149, x147, x121, x139); var x150: u64 = undefined; var x151: u1 = undefined; addcarryxU64(&x150, &x151, x149, x123, x141); const x152 = (@as(u64, x151) + @as(u64, x124)); var x153: u64 = undefined; var x154: u64 = undefined; mulxU64(&x153, &x154, x3, (arg2[3])); var x155: u64 = undefined; var x156: u64 = undefined; mulxU64(&x155, &x156, x3, (arg2[2])); var x157: u64 = undefined; var x158: u64 = undefined; mulxU64(&x157, &x158, x3, (arg2[1])); var x159: u64 = undefined; var x160: u64 = undefined; mulxU64(&x159, &x160, x3, (arg2[0])); var x161: u64 = undefined; var x162: u1 = undefined; addcarryxU64(&x161, &x162, 0x0, x160, x157); var x163: u64 = undefined; var x164: u1 = undefined; addcarryxU64(&x163, &x164, x162, x158, x155); var x165: u64 = undefined; var x166: u1 = undefined; addcarryxU64(&x165, &x166, x164, x156, x153); const x167 = (@as(u64, x166) + x154); var x168: u64 = undefined; var x169: u1 = undefined; addcarryxU64(&x168, &x169, 0x0, x144, x159); var x170: u64 = undefined; var x171: u1 = undefined; addcarryxU64(&x170, &x171, x169, x146, x161); var x172: u64 = undefined; var x173: u1 = undefined; addcarryxU64(&x172, &x173, x171, x148, x163); var x174: u64 = undefined; var x175: u1 = undefined; addcarryxU64(&x174, &x175, x173, x150, x165); var x176: u64 = undefined; var x177: u1 = undefined; addcarryxU64(&x176, &x177, x175, x152, x167); var x178: u64 = undefined; var x179: u64 = undefined; mulxU64(&x178, &x179, x168, 0xccd1c8aaee00bc4f); var x180: u64 = undefined; var x181: u64 = undefined; mulxU64(&x180, &x181, x178, 0xffffffff00000000); var x182: u64 = undefined; var x183: u64 = undefined; mulxU64(&x182, &x183, x178, 0xffffffffffffffff); var x184: u64 = undefined; var x185: u64 = undefined; mulxU64(&x184, &x185, x178, 0xbce6faada7179e84); var x186: u64 = undefined; var x187: u64 = undefined; mulxU64(&x186, &x187, x178, 0xf3b9cac2fc632551); var x188: u64 = undefined; var x189: u1 = undefined; addcarryxU64(&x188, &x189, 0x0, x187, x184); var x190: u64 = undefined; var x191: u1 = undefined; addcarryxU64(&x190, &x191, x189, x185, x182); var x192: u64 = undefined; var x193: u1 = undefined; addcarryxU64(&x192, &x193, x191, x183, x180); const x194 = (@as(u64, x193) + x181); var x195: u64 = undefined; var x196: u1 = undefined; addcarryxU64(&x195, &x196, 0x0, x168, x186); var x197: u64 = undefined; var x198: u1 = undefined; addcarryxU64(&x197, &x198, x196, x170, x188); var x199: u64 = undefined; var x200: u1 = undefined; addcarryxU64(&x199, &x200, x198, x172, x190); var x201: u64 = undefined; var x202: u1 = undefined; addcarryxU64(&x201, &x202, x200, x174, x192); var x203: u64 = undefined; var x204: u1 = undefined; addcarryxU64(&x203, &x204, x202, x176, x194); const x205 = (@as(u64, x204) + @as(u64, x177)); var x206: u64 = undefined; var x207: u1 = undefined; subborrowxU64(&x206, &x207, 0x0, x197, 0xf3b9cac2fc632551); var x208: u64 = undefined; var x209: u1 = undefined; subborrowxU64(&x208, &x209, x207, x199, 0xbce6faada7179e84); var x210: u64 = undefined; var x211: u1 = undefined; subborrowxU64(&x210, &x211, x209, x201, 0xffffffffffffffff); var x212: u64 = undefined; var x213: u1 = undefined; subborrowxU64(&x212, &x213, x211, x203, 0xffffffff00000000); var x214: u64 = undefined; var x215: u1 = undefined; subborrowxU64(&x214, &x215, x213, x205, @as(u64, 0x0)); var x216: u64 = undefined; cmovznzU64(&x216, x215, x206, x197); var x217: u64 = undefined; cmovznzU64(&x217, x215, x208, x199); var x218: u64 = undefined; cmovznzU64(&x218, x215, x210, x201); var x219: u64 = undefined; cmovznzU64(&x219, x215, x212, x203); out1[0] = x216; out1[1] = x217; out1[2] = x218; out1[3] = x219; } /// The function square squares a field element in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m /// 0 ≤ eval out1 < m /// pub fn square(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; mulxU64(&x5, &x6, x4, (arg1[3])); var x7: u64 = undefined; var x8: u64 = undefined; mulxU64(&x7, &x8, x4, (arg1[2])); var x9: u64 = undefined; var x10: u64 = undefined; mulxU64(&x9, &x10, x4, (arg1[1])); var x11: u64 = undefined; var x12: u64 = undefined; mulxU64(&x11, &x12, x4, (arg1[0])); var x13: u64 = undefined; var x14: u1 = undefined; addcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; addcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; addcarryxU64(&x17, &x18, x16, x8, x5); const x19 = (@as(u64, x18) + x6); var x20: u64 = undefined; var x21: u64 = undefined; mulxU64(&x20, &x21, x11, 0xccd1c8aaee00bc4f); var x22: u64 = undefined; var x23: u64 = undefined; mulxU64(&x22, &x23, x20, 0xffffffff00000000); var x24: u64 = undefined; var x25: u64 = undefined; mulxU64(&x24, &x25, x20, 0xffffffffffffffff); var x26: u64 = undefined; var x27: u64 = undefined; mulxU64(&x26, &x27, x20, 0xbce6faada7179e84); var x28: u64 = undefined; var x29: u64 = undefined; mulxU64(&x28, &x29, x20, 0xf3b9cac2fc632551); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, 0x0, x29, x26); var x32: u64 = undefined; var x33: u1 = undefined; addcarryxU64(&x32, &x33, x31, x27, x24); var x34: u64 = undefined; var x35: u1 = undefined; addcarryxU64(&x34, &x35, x33, x25, x22); const x36 = (@as(u64, x35) + x23); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, 0x0, x11, x28); var x39: u64 = undefined; var x40: u1 = undefined; addcarryxU64(&x39, &x40, x38, x13, x30); var x41: u64 = undefined; var x42: u1 = undefined; addcarryxU64(&x41, &x42, x40, x15, x32); var x43: u64 = undefined; var x44: u1 = undefined; addcarryxU64(&x43, &x44, x42, x17, x34); var x45: u64 = undefined; var x46: u1 = undefined; addcarryxU64(&x45, &x46, x44, x19, x36); var x47: u64 = undefined; var x48: u64 = undefined; mulxU64(&x47, &x48, x1, (arg1[3])); var x49: u64 = undefined; var x50: u64 = undefined; mulxU64(&x49, &x50, x1, (arg1[2])); var x51: u64 = undefined; var x52: u64 = undefined; mulxU64(&x51, &x52, x1, (arg1[1])); var x53: u64 = undefined; var x54: u64 = undefined; mulxU64(&x53, &x54, x1, (arg1[0])); var x55: u64 = undefined; var x56: u1 = undefined; addcarryxU64(&x55, &x56, 0x0, x54, x51); var x57: u64 = undefined; var x58: u1 = undefined; addcarryxU64(&x57, &x58, x56, x52, x49); var x59: u64 = undefined; var x60: u1 = undefined; addcarryxU64(&x59, &x60, x58, x50, x47); const x61 = (@as(u64, x60) + x48); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, 0x0, x39, x53); var x64: u64 = undefined; var x65: u1 = undefined; addcarryxU64(&x64, &x65, x63, x41, x55); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, x65, x43, x57); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, x67, x45, x59); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, x69, @as(u64, x46), x61); var x72: u64 = undefined; var x73: u64 = undefined; mulxU64(&x72, &x73, x62, 0xccd1c8aaee00bc4f); var x74: u64 = undefined; var x75: u64 = undefined; mulxU64(&x74, &x75, x72, 0xffffffff00000000); var x76: u64 = undefined; var x77: u64 = undefined; mulxU64(&x76, &x77, x72, 0xffffffffffffffff); var x78: u64 = undefined; var x79: u64 = undefined; mulxU64(&x78, &x79, x72, 0xbce6faada7179e84); var x80: u64 = undefined; var x81: u64 = undefined; mulxU64(&x80, &x81, x72, 0xf3b9cac2fc632551); var x82: u64 = undefined; var x83: u1 = undefined; addcarryxU64(&x82, &x83, 0x0, x81, x78); var x84: u64 = undefined; var x85: u1 = undefined; addcarryxU64(&x84, &x85, x83, x79, x76); var x86: u64 = undefined; var x87: u1 = undefined; addcarryxU64(&x86, &x87, x85, x77, x74); const x88 = (@as(u64, x87) + x75); var x89: u64 = undefined; var x90: u1 = undefined; addcarryxU64(&x89, &x90, 0x0, x62, x80); var x91: u64 = undefined; var x92: u1 = undefined; addcarryxU64(&x91, &x92, x90, x64, x82); var x93: u64 = undefined; var x94: u1 = undefined; addcarryxU64(&x93, &x94, x92, x66, x84); var x95: u64 = undefined; var x96: u1 = undefined; addcarryxU64(&x95, &x96, x94, x68, x86); var x97: u64 = undefined; var x98: u1 = undefined; addcarryxU64(&x97, &x98, x96, x70, x88); const x99 = (@as(u64, x98) + @as(u64, x71)); var x100: u64 = undefined; var x101: u64 = undefined; mulxU64(&x100, &x101, x2, (arg1[3])); var x102: u64 = undefined; var x103: u64 = undefined; mulxU64(&x102, &x103, x2, (arg1[2])); var x104: u64 = undefined; var x105: u64 = undefined; mulxU64(&x104, &x105, x2, (arg1[1])); var x106: u64 = undefined; var x107: u64 = undefined; mulxU64(&x106, &x107, x2, (arg1[0])); var x108: u64 = undefined; var x109: u1 = undefined; addcarryxU64(&x108, &x109, 0x0, x107, x104); var x110: u64 = undefined; var x111: u1 = undefined; addcarryxU64(&x110, &x111, x109, x105, x102); var x112: u64 = undefined; var x113: u1 = undefined; addcarryxU64(&x112, &x113, x111, x103, x100); const x114 = (@as(u64, x113) + x101); var x115: u64 = undefined; var x116: u1 = undefined; addcarryxU64(&x115, &x116, 0x0, x91, x106); var x117: u64 = undefined; var x118: u1 = undefined; addcarryxU64(&x117, &x118, x116, x93, x108); var x119: u64 = undefined; var x120: u1 = undefined; addcarryxU64(&x119, &x120, x118, x95, x110); var x121: u64 = undefined; var x122: u1 = undefined; addcarryxU64(&x121, &x122, x120, x97, x112); var x123: u64 = undefined; var x124: u1 = undefined; addcarryxU64(&x123, &x124, x122, x99, x114); var x125: u64 = undefined; var x126: u64 = undefined; mulxU64(&x125, &x126, x115, 0xccd1c8aaee00bc4f); var x127: u64 = undefined; var x128: u64 = undefined; mulxU64(&x127, &x128, x125, 0xffffffff00000000); var x129: u64 = undefined; var x130: u64 = undefined; mulxU64(&x129, &x130, x125, 0xffffffffffffffff); var x131: u64 = undefined; var x132: u64 = undefined; mulxU64(&x131, &x132, x125, 0xbce6faada7179e84); var x133: u64 = undefined; var x134: u64 = undefined; mulxU64(&x133, &x134, x125, 0xf3b9cac2fc632551); var x135: u64 = undefined; var x136: u1 = undefined; addcarryxU64(&x135, &x136, 0x0, x134, x131); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, x136, x132, x129); var x139: u64 = undefined; var x140: u1 = undefined; addcarryxU64(&x139, &x140, x138, x130, x127); const x141 = (@as(u64, x140) + x128); var x142: u64 = undefined; var x143: u1 = undefined; addcarryxU64(&x142, &x143, 0x0, x115, x133); var x144: u64 = undefined; var x145: u1 = undefined; addcarryxU64(&x144, &x145, x143, x117, x135); var x146: u64 = undefined; var x147: u1 = undefined; addcarryxU64(&x146, &x147, x145, x119, x137); var x148: u64 = undefined; var x149: u1 = undefined; addcarryxU64(&x148, &x149, x147, x121, x139); var x150: u64 = undefined; var x151: u1 = undefined; addcarryxU64(&x150, &x151, x149, x123, x141); const x152 = (@as(u64, x151) + @as(u64, x124)); var x153: u64 = undefined; var x154: u64 = undefined; mulxU64(&x153, &x154, x3, (arg1[3])); var x155: u64 = undefined; var x156: u64 = undefined; mulxU64(&x155, &x156, x3, (arg1[2])); var x157: u64 = undefined; var x158: u64 = undefined; mulxU64(&x157, &x158, x3, (arg1[1])); var x159: u64 = undefined; var x160: u64 = undefined; mulxU64(&x159, &x160, x3, (arg1[0])); var x161: u64 = undefined; var x162: u1 = undefined; addcarryxU64(&x161, &x162, 0x0, x160, x157); var x163: u64 = undefined; var x164: u1 = undefined; addcarryxU64(&x163, &x164, x162, x158, x155); var x165: u64 = undefined; var x166: u1 = undefined; addcarryxU64(&x165, &x166, x164, x156, x153); const x167 = (@as(u64, x166) + x154); var x168: u64 = undefined; var x169: u1 = undefined; addcarryxU64(&x168, &x169, 0x0, x144, x159); var x170: u64 = undefined; var x171: u1 = undefined; addcarryxU64(&x170, &x171, x169, x146, x161); var x172: u64 = undefined; var x173: u1 = undefined; addcarryxU64(&x172, &x173, x171, x148, x163); var x174: u64 = undefined; var x175: u1 = undefined; addcarryxU64(&x174, &x175, x173, x150, x165); var x176: u64 = undefined; var x177: u1 = undefined; addcarryxU64(&x176, &x177, x175, x152, x167); var x178: u64 = undefined; var x179: u64 = undefined; mulxU64(&x178, &x179, x168, 0xccd1c8aaee00bc4f); var x180: u64 = undefined; var x181: u64 = undefined; mulxU64(&x180, &x181, x178, 0xffffffff00000000); var x182: u64 = undefined; var x183: u64 = undefined; mulxU64(&x182, &x183, x178, 0xffffffffffffffff); var x184: u64 = undefined; var x185: u64 = undefined; mulxU64(&x184, &x185, x178, 0xbce6faada7179e84); var x186: u64 = undefined; var x187: u64 = undefined; mulxU64(&x186, &x187, x178, 0xf3b9cac2fc632551); var x188: u64 = undefined; var x189: u1 = undefined; addcarryxU64(&x188, &x189, 0x0, x187, x184); var x190: u64 = undefined; var x191: u1 = undefined; addcarryxU64(&x190, &x191, x189, x185, x182); var x192: u64 = undefined; var x193: u1 = undefined; addcarryxU64(&x192, &x193, x191, x183, x180); const x194 = (@as(u64, x193) + x181); var x195: u64 = undefined; var x196: u1 = undefined; addcarryxU64(&x195, &x196, 0x0, x168, x186); var x197: u64 = undefined; var x198: u1 = undefined; addcarryxU64(&x197, &x198, x196, x170, x188); var x199: u64 = undefined; var x200: u1 = undefined; addcarryxU64(&x199, &x200, x198, x172, x190); var x201: u64 = undefined; var x202: u1 = undefined; addcarryxU64(&x201, &x202, x200, x174, x192); var x203: u64 = undefined; var x204: u1 = undefined; addcarryxU64(&x203, &x204, x202, x176, x194); const x205 = (@as(u64, x204) + @as(u64, x177)); var x206: u64 = undefined; var x207: u1 = undefined; subborrowxU64(&x206, &x207, 0x0, x197, 0xf3b9cac2fc632551); var x208: u64 = undefined; var x209: u1 = undefined; subborrowxU64(&x208, &x209, x207, x199, 0xbce6faada7179e84); var x210: u64 = undefined; var x211: u1 = undefined; subborrowxU64(&x210, &x211, x209, x201, 0xffffffffffffffff); var x212: u64 = undefined; var x213: u1 = undefined; subborrowxU64(&x212, &x213, x211, x203, 0xffffffff00000000); var x214: u64 = undefined; var x215: u1 = undefined; subborrowxU64(&x214, &x215, x213, x205, @as(u64, 0x0)); var x216: u64 = undefined; cmovznzU64(&x216, x215, x206, x197); var x217: u64 = undefined; cmovznzU64(&x217, x215, x208, x199); var x218: u64 = undefined; cmovznzU64(&x218, x215, x210, x201); var x219: u64 = undefined; cmovznzU64(&x219, x215, x212, x203); out1[0] = x216; out1[1] = x217; out1[2] = x218; out1[3] = x219; } /// The function add adds two field elements in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// pub fn add(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; addcarryxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u64 = undefined; var x4: u1 = undefined; addcarryxU64(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u64 = undefined; var x6: u1 = undefined; addcarryxU64(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u64 = undefined; var x8: u1 = undefined; addcarryxU64(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u64 = undefined; var x10: u1 = undefined; subborrowxU64(&x9, &x10, 0x0, x1, 0xf3b9cac2fc632551); var x11: u64 = undefined; var x12: u1 = undefined; subborrowxU64(&x11, &x12, x10, x3, 0xbce6faada7179e84); var x13: u64 = undefined; var x14: u1 = undefined; subborrowxU64(&x13, &x14, x12, x5, 0xffffffffffffffff); var x15: u64 = undefined; var x16: u1 = undefined; subborrowxU64(&x15, &x16, x14, x7, 0xffffffff00000000); var x17: u64 = undefined; var x18: u1 = undefined; subborrowxU64(&x17, &x18, x16, @as(u64, x8), @as(u64, 0x0)); var x19: u64 = undefined; cmovznzU64(&x19, x18, x9, x1); var x20: u64 = undefined; cmovznzU64(&x20, x18, x11, x3); var x21: u64 = undefined; cmovznzU64(&x21, x18, x13, x5); var x22: u64 = undefined; cmovznzU64(&x22, x18, x15, x7); out1[0] = x19; out1[1] = x20; out1[2] = x21; out1[3] = x22; } /// The function sub subtracts two field elements in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// pub fn sub(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; subborrowxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u64 = undefined; var x4: u1 = undefined; subborrowxU64(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u64 = undefined; var x6: u1 = undefined; subborrowxU64(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u64 = undefined; var x8: u1 = undefined; subborrowxU64(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u64 = undefined; cmovznzU64(&x9, x8, @as(u64, 0x0), 0xffffffffffffffff); var x10: u64 = undefined; var x11: u1 = undefined; addcarryxU64(&x10, &x11, 0x0, x1, (x9 & 0xf3b9cac2fc632551)); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, x11, x3, (x9 & 0xbce6faada7179e84)); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, x5, x9); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, x7, (x9 & 0xffffffff00000000)); out1[0] = x10; out1[1] = x12; out1[2] = x14; out1[3] = x16; } /// The function opp negates a field element in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m /// 0 ≤ eval out1 < m /// pub fn opp(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; subborrowxU64(&x1, &x2, 0x0, @as(u64, 0x0), (arg1[0])); var x3: u64 = undefined; var x4: u1 = undefined; subborrowxU64(&x3, &x4, x2, @as(u64, 0x0), (arg1[1])); var x5: u64 = undefined; var x6: u1 = undefined; subborrowxU64(&x5, &x6, x4, @as(u64, 0x0), (arg1[2])); var x7: u64 = undefined; var x8: u1 = undefined; subborrowxU64(&x7, &x8, x6, @as(u64, 0x0), (arg1[3])); var x9: u64 = undefined; cmovznzU64(&x9, x8, @as(u64, 0x0), 0xffffffffffffffff); var x10: u64 = undefined; var x11: u1 = undefined; addcarryxU64(&x10, &x11, 0x0, x1, (x9 & 0xf3b9cac2fc632551)); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, x11, x3, (x9 & 0xbce6faada7179e84)); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, x5, x9); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, x7, (x9 & 0xffffffff00000000)); out1[0] = x10; out1[1] = x12; out1[2] = x14; out1[3] = x16; } /// The function fromMontgomery translates a field element out of the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m /// 0 ≤ eval out1 < m /// pub fn fromMontgomery(out1: *NonMontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[0]); var x2: u64 = undefined; var x3: u64 = undefined; mulxU64(&x2, &x3, x1, 0xccd1c8aaee00bc4f); var x4: u64 = undefined; var x5: u64 = undefined; mulxU64(&x4, &x5, x2, 0xffffffff00000000); var x6: u64 = undefined; var x7: u64 = undefined; mulxU64(&x6, &x7, x2, 0xffffffffffffffff); var x8: u64 = undefined; var x9: u64 = undefined; mulxU64(&x8, &x9, x2, 0xbce6faada7179e84); var x10: u64 = undefined; var x11: u64 = undefined; mulxU64(&x10, &x11, x2, 0xf3b9cac2fc632551); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, 0x0, x11, x8); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, x9, x6); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, x7, x4); var x18: u64 = undefined; var x19: u1 = undefined; addcarryxU64(&x18, &x19, 0x0, x1, x10); var x20: u64 = undefined; var x21: u1 = undefined; addcarryxU64(&x20, &x21, x19, @as(u64, 0x0), x12); var x22: u64 = undefined; var x23: u1 = undefined; addcarryxU64(&x22, &x23, x21, @as(u64, 0x0), x14); var x24: u64 = undefined; var x25: u1 = undefined; addcarryxU64(&x24, &x25, x23, @as(u64, 0x0), x16); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, 0x0, x20, (arg1[1])); var x28: u64 = undefined; var x29: u1 = undefined; addcarryxU64(&x28, &x29, x27, x22, @as(u64, 0x0)); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, x29, x24, @as(u64, 0x0)); var x32: u64 = undefined; var x33: u64 = undefined; mulxU64(&x32, &x33, x26, 0xccd1c8aaee00bc4f); var x34: u64 = undefined; var x35: u64 = undefined; mulxU64(&x34, &x35, x32, 0xffffffff00000000); var x36: u64 = undefined; var x37: u64 = undefined; mulxU64(&x36, &x37, x32, 0xffffffffffffffff); var x38: u64 = undefined; var x39: u64 = undefined; mulxU64(&x38, &x39, x32, 0xbce6faada7179e84); var x40: u64 = undefined; var x41: u64 = undefined; mulxU64(&x40, &x41, x32, 0xf3b9cac2fc632551); var x42: u64 = undefined; var x43: u1 = undefined; addcarryxU64(&x42, &x43, 0x0, x41, x38); var x44: u64 = undefined; var x45: u1 = undefined; addcarryxU64(&x44, &x45, x43, x39, x36); var x46: u64 = undefined; var x47: u1 = undefined; addcarryxU64(&x46, &x47, x45, x37, x34); var x48: u64 = undefined; var x49: u1 = undefined; addcarryxU64(&x48, &x49, 0x0, x26, x40); var x50: u64 = undefined; var x51: u1 = undefined; addcarryxU64(&x50, &x51, x49, x28, x42); var x52: u64 = undefined; var x53: u1 = undefined; addcarryxU64(&x52, &x53, x51, x30, x44); var x54: u64 = undefined; var x55: u1 = undefined; addcarryxU64(&x54, &x55, x53, (@as(u64, x31) + (@as(u64, x25) + (@as(u64, x17) + x5))), x46); var x56: u64 = undefined; var x57: u1 = undefined; addcarryxU64(&x56, &x57, 0x0, x50, (arg1[2])); var x58: u64 = undefined; var x59: u1 = undefined; addcarryxU64(&x58, &x59, x57, x52, @as(u64, 0x0)); var x60: u64 = undefined; var x61: u1 = undefined; addcarryxU64(&x60, &x61, x59, x54, @as(u64, 0x0)); var x62: u64 = undefined; var x63: u64 = undefined; mulxU64(&x62, &x63, x56, 0xccd1c8aaee00bc4f); var x64: u64 = undefined; var x65: u64 = undefined; mulxU64(&x64, &x65, x62, 0xffffffff00000000); var x66: u64 = undefined; var x67: u64 = undefined; mulxU64(&x66, &x67, x62, 0xffffffffffffffff); var x68: u64 = undefined; var x69: u64 = undefined; mulxU64(&x68, &x69, x62, 0xbce6faada7179e84); var x70: u64 = undefined; var x71: u64 = undefined; mulxU64(&x70, &x71, x62, 0xf3b9cac2fc632551); var x72: u64 = undefined; var x73: u1 = undefined; addcarryxU64(&x72, &x73, 0x0, x71, x68); var x74: u64 = undefined; var x75: u1 = undefined; addcarryxU64(&x74, &x75, x73, x69, x66); var x76: u64 = undefined; var x77: u1 = undefined; addcarryxU64(&x76, &x77, x75, x67, x64); var x78: u64 = undefined; var x79: u1 = undefined; addcarryxU64(&x78, &x79, 0x0, x56, x70); var x80: u64 = undefined; var x81: u1 = undefined; addcarryxU64(&x80, &x81, x79, x58, x72); var x82: u64 = undefined; var x83: u1 = undefined; addcarryxU64(&x82, &x83, x81, x60, x74); var x84: u64 = undefined; var x85: u1 = undefined; addcarryxU64(&x84, &x85, x83, (@as(u64, x61) + (@as(u64, x55) + (@as(u64, x47) + x35))), x76); var x86: u64 = undefined; var x87: u1 = undefined; addcarryxU64(&x86, &x87, 0x0, x80, (arg1[3])); var x88: u64 = undefined; var x89: u1 = undefined; addcarryxU64(&x88, &x89, x87, x82, @as(u64, 0x0)); var x90: u64 = undefined; var x91: u1 = undefined; addcarryxU64(&x90, &x91, x89, x84, @as(u64, 0x0)); var x92: u64 = undefined; var x93: u64 = undefined; mulxU64(&x92, &x93, x86, 0xccd1c8aaee00bc4f); var x94: u64 = undefined; var x95: u64 = undefined; mulxU64(&x94, &x95, x92, 0xffffffff00000000); var x96: u64 = undefined; var x97: u64 = undefined; mulxU64(&x96, &x97, x92, 0xffffffffffffffff); var x98: u64 = undefined; var x99: u64 = undefined; mulxU64(&x98, &x99, x92, 0xbce6faada7179e84); var x100: u64 = undefined; var x101: u64 = undefined; mulxU64(&x100, &x101, x92, 0xf3b9cac2fc632551); var x102: u64 = undefined; var x103: u1 = undefined; addcarryxU64(&x102, &x103, 0x0, x101, x98); var x104: u64 = undefined; var x105: u1 = undefined; addcarryxU64(&x104, &x105, x103, x99, x96); var x106: u64 = undefined; var x107: u1 = undefined; addcarryxU64(&x106, &x107, x105, x97, x94); var x108: u64 = undefined; var x109: u1 = undefined; addcarryxU64(&x108, &x109, 0x0, x86, x100); var x110: u64 = undefined; var x111: u1 = undefined; addcarryxU64(&x110, &x111, x109, x88, x102); var x112: u64 = undefined; var x113: u1 = undefined; addcarryxU64(&x112, &x113, x111, x90, x104); var x114: u64 = undefined; var x115: u1 = undefined; addcarryxU64(&x114, &x115, x113, (@as(u64, x91) + (@as(u64, x85) + (@as(u64, x77) + x65))), x106); const x116 = (@as(u64, x115) + (@as(u64, x107) + x95)); var x117: u64 = undefined; var x118: u1 = undefined; subborrowxU64(&x117, &x118, 0x0, x110, 0xf3b9cac2fc632551); var x119: u64 = undefined; var x120: u1 = undefined; subborrowxU64(&x119, &x120, x118, x112, 0xbce6faada7179e84); var x121: u64 = undefined; var x122: u1 = undefined; subborrowxU64(&x121, &x122, x120, x114, 0xffffffffffffffff); var x123: u64 = undefined; var x124: u1 = undefined; subborrowxU64(&x123, &x124, x122, x116, 0xffffffff00000000); var x125: u64 = undefined; var x126: u1 = undefined; subborrowxU64(&x125, &x126, x124, @as(u64, 0x0), @as(u64, 0x0)); var x127: u64 = undefined; cmovznzU64(&x127, x126, x117, x110); var x128: u64 = undefined; cmovznzU64(&x128, x126, x119, x112); var x129: u64 = undefined; cmovznzU64(&x129, x126, x121, x114); var x130: u64 = undefined; cmovznzU64(&x130, x126, x123, x116); out1[0] = x127; out1[1] = x128; out1[2] = x129; out1[3] = x130; } /// The function toMontgomery translates a field element into the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = eval arg1 mod m /// 0 ≤ eval out1 < m /// pub fn toMontgomery(out1: *MontgomeryDomainFieldElement, arg1: NonMontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; mulxU64(&x5, &x6, x4, 0x66e12d94f3d95620); var x7: u64 = undefined; var x8: u64 = undefined; mulxU64(&x7, &x8, x4, 0x2845b2392b6bec59); var x9: u64 = undefined; var x10: u64 = undefined; mulxU64(&x9, &x10, x4, 0x4699799c49bd6fa6); var x11: u64 = undefined; var x12: u64 = undefined; mulxU64(&x11, &x12, x4, 0x83244c95be79eea2); var x13: u64 = undefined; var x14: u1 = undefined; addcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; addcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; addcarryxU64(&x17, &x18, x16, x8, x5); var x19: u64 = undefined; var x20: u64 = undefined; mulxU64(&x19, &x20, x11, 0xccd1c8aaee00bc4f); var x21: u64 = undefined; var x22: u64 = undefined; mulxU64(&x21, &x22, x19, 0xffffffff00000000); var x23: u64 = undefined; var x24: u64 = undefined; mulxU64(&x23, &x24, x19, 0xffffffffffffffff); var x25: u64 = undefined; var x26: u64 = undefined; mulxU64(&x25, &x26, x19, 0xbce6faada7179e84); var x27: u64 = undefined; var x28: u64 = undefined; mulxU64(&x27, &x28, x19, 0xf3b9cac2fc632551); var x29: u64 = undefined; var x30: u1 = undefined; addcarryxU64(&x29, &x30, 0x0, x28, x25); var x31: u64 = undefined; var x32: u1 = undefined; addcarryxU64(&x31, &x32, x30, x26, x23); var x33: u64 = undefined; var x34: u1 = undefined; addcarryxU64(&x33, &x34, x32, x24, x21); var x35: u64 = undefined; var x36: u1 = undefined; addcarryxU64(&x35, &x36, 0x0, x11, x27); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, x36, x13, x29); var x39: u64 = undefined; var x40: u1 = undefined; addcarryxU64(&x39, &x40, x38, x15, x31); var x41: u64 = undefined; var x42: u1 = undefined; addcarryxU64(&x41, &x42, x40, x17, x33); var x43: u64 = undefined; var x44: u1 = undefined; addcarryxU64(&x43, &x44, x42, (@as(u64, x18) + x6), (@as(u64, x34) + x22)); var x45: u64 = undefined; var x46: u64 = undefined; mulxU64(&x45, &x46, x1, 0x66e12d94f3d95620); var x47: u64 = undefined; var x48: u64 = undefined; mulxU64(&x47, &x48, x1, 0x2845b2392b6bec59); var x49: u64 = undefined; var x50: u64 = undefined; mulxU64(&x49, &x50, x1, 0x4699799c49bd6fa6); var x51: u64 = undefined; var x52: u64 = undefined; mulxU64(&x51, &x52, x1, 0x83244c95be79eea2); var x53: u64 = undefined; var x54: u1 = undefined; addcarryxU64(&x53, &x54, 0x0, x52, x49); var x55: u64 = undefined; var x56: u1 = undefined; addcarryxU64(&x55, &x56, x54, x50, x47); var x57: u64 = undefined; var x58: u1 = undefined; addcarryxU64(&x57, &x58, x56, x48, x45); var x59: u64 = undefined; var x60: u1 = undefined; addcarryxU64(&x59, &x60, 0x0, x37, x51); var x61: u64 = undefined; var x62: u1 = undefined; addcarryxU64(&x61, &x62, x60, x39, x53); var x63: u64 = undefined; var x64: u1 = undefined; addcarryxU64(&x63, &x64, x62, x41, x55); var x65: u64 = undefined; var x66: u1 = undefined; addcarryxU64(&x65, &x66, x64, x43, x57); var x67: u64 = undefined; var x68: u64 = undefined; mulxU64(&x67, &x68, x59, 0xccd1c8aaee00bc4f); var x69: u64 = undefined; var x70: u64 = undefined; mulxU64(&x69, &x70, x67, 0xffffffff00000000); var x71: u64 = undefined; var x72: u64 = undefined; mulxU64(&x71, &x72, x67, 0xffffffffffffffff); var x73: u64 = undefined; var x74: u64 = undefined; mulxU64(&x73, &x74, x67, 0xbce6faada7179e84); var x75: u64 = undefined; var x76: u64 = undefined; mulxU64(&x75, &x76, x67, 0xf3b9cac2fc632551); var x77: u64 = undefined; var x78: u1 = undefined; addcarryxU64(&x77, &x78, 0x0, x76, x73); var x79: u64 = undefined; var x80: u1 = undefined; addcarryxU64(&x79, &x80, x78, x74, x71); var x81: u64 = undefined; var x82: u1 = undefined; addcarryxU64(&x81, &x82, x80, x72, x69); var x83: u64 = undefined; var x84: u1 = undefined; addcarryxU64(&x83, &x84, 0x0, x59, x75); var x85: u64 = undefined; var x86: u1 = undefined; addcarryxU64(&x85, &x86, x84, x61, x77); var x87: u64 = undefined; var x88: u1 = undefined; addcarryxU64(&x87, &x88, x86, x63, x79); var x89: u64 = undefined; var x90: u1 = undefined; addcarryxU64(&x89, &x90, x88, x65, x81); var x91: u64 = undefined; var x92: u1 = undefined; addcarryxU64(&x91, &x92, x90, ((@as(u64, x66) + @as(u64, x44)) + (@as(u64, x58) + x46)), (@as(u64, x82) + x70)); var x93: u64 = undefined; var x94: u64 = undefined; mulxU64(&x93, &x94, x2, 0x66e12d94f3d95620); var x95: u64 = undefined; var x96: u64 = undefined; mulxU64(&x95, &x96, x2, 0x2845b2392b6bec59); var x97: u64 = undefined; var x98: u64 = undefined; mulxU64(&x97, &x98, x2, 0x4699799c49bd6fa6); var x99: u64 = undefined; var x100: u64 = undefined; mulxU64(&x99, &x100, x2, 0x83244c95be79eea2); var x101: u64 = undefined; var x102: u1 = undefined; addcarryxU64(&x101, &x102, 0x0, x100, x97); var x103: u64 = undefined; var x104: u1 = undefined; addcarryxU64(&x103, &x104, x102, x98, x95); var x105: u64 = undefined; var x106: u1 = undefined; addcarryxU64(&x105, &x106, x104, x96, x93); var x107: u64 = undefined; var x108: u1 = undefined; addcarryxU64(&x107, &x108, 0x0, x85, x99); var x109: u64 = undefined; var x110: u1 = undefined; addcarryxU64(&x109, &x110, x108, x87, x101); var x111: u64 = undefined; var x112: u1 = undefined; addcarryxU64(&x111, &x112, x110, x89, x103); var x113: u64 = undefined; var x114: u1 = undefined; addcarryxU64(&x113, &x114, x112, x91, x105); var x115: u64 = undefined; var x116: u64 = undefined; mulxU64(&x115, &x116, x107, 0xccd1c8aaee00bc4f); var x117: u64 = undefined; var x118: u64 = undefined; mulxU64(&x117, &x118, x115, 0xffffffff00000000); var x119: u64 = undefined; var x120: u64 = undefined; mulxU64(&x119, &x120, x115, 0xffffffffffffffff); var x121: u64 = undefined; var x122: u64 = undefined; mulxU64(&x121, &x122, x115, 0xbce6faada7179e84); var x123: u64 = undefined; var x124: u64 = undefined; mulxU64(&x123, &x124, x115, 0xf3b9cac2fc632551); var x125: u64 = undefined; var x126: u1 = undefined; addcarryxU64(&x125, &x126, 0x0, x124, x121); var x127: u64 = undefined; var x128: u1 = undefined; addcarryxU64(&x127, &x128, x126, x122, x119); var x129: u64 = undefined; var x130: u1 = undefined; addcarryxU64(&x129, &x130, x128, x120, x117); var x131: u64 = undefined; var x132: u1 = undefined; addcarryxU64(&x131, &x132, 0x0, x107, x123); var x133: u64 = undefined; var x134: u1 = undefined; addcarryxU64(&x133, &x134, x132, x109, x125); var x135: u64 = undefined; var x136: u1 = undefined; addcarryxU64(&x135, &x136, x134, x111, x127); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, x136, x113, x129); var x139: u64 = undefined; var x140: u1 = undefined; addcarryxU64(&x139, &x140, x138, ((@as(u64, x114) + @as(u64, x92)) + (@as(u64, x106) + x94)), (@as(u64, x130) + x118)); var x141: u64 = undefined; var x142: u64 = undefined; mulxU64(&x141, &x142, x3, 0x66e12d94f3d95620); var x143: u64 = undefined; var x144: u64 = undefined; mulxU64(&x143, &x144, x3, 0x2845b2392b6bec59); var x145: u64 = undefined; var x146: u64 = undefined; mulxU64(&x145, &x146, x3, 0x4699799c49bd6fa6); var x147: u64 = undefined; var x148: u64 = undefined; mulxU64(&x147, &x148, x3, 0x83244c95be79eea2); var x149: u64 = undefined; var x150: u1 = undefined; addcarryxU64(&x149, &x150, 0x0, x148, x145); var x151: u64 = undefined; var x152: u1 = undefined; addcarryxU64(&x151, &x152, x150, x146, x143); var x153: u64 = undefined; var x154: u1 = undefined; addcarryxU64(&x153, &x154, x152, x144, x141); var x155: u64 = undefined; var x156: u1 = undefined; addcarryxU64(&x155, &x156, 0x0, x133, x147); var x157: u64 = undefined; var x158: u1 = undefined; addcarryxU64(&x157, &x158, x156, x135, x149); var x159: u64 = undefined; var x160: u1 = undefined; addcarryxU64(&x159, &x160, x158, x137, x151); var x161: u64 = undefined; var x162: u1 = undefined; addcarryxU64(&x161, &x162, x160, x139, x153); var x163: u64 = undefined; var x164: u64 = undefined; mulxU64(&x163, &x164, x155, 0xccd1c8aaee00bc4f); var x165: u64 = undefined; var x166: u64 = undefined; mulxU64(&x165, &x166, x163, 0xffffffff00000000); var x167: u64 = undefined; var x168: u64 = undefined; mulxU64(&x167, &x168, x163, 0xffffffffffffffff); var x169: u64 = undefined; var x170: u64 = undefined; mulxU64(&x169, &x170, x163, 0xbce6faada7179e84); var x171: u64 = undefined; var x172: u64 = undefined; mulxU64(&x171, &x172, x163, 0xf3b9cac2fc632551); var x173: u64 = undefined; var x174: u1 = undefined; addcarryxU64(&x173, &x174, 0x0, x172, x169); var x175: u64 = undefined; var x176: u1 = undefined; addcarryxU64(&x175, &x176, x174, x170, x167); var x177: u64 = undefined; var x178: u1 = undefined; addcarryxU64(&x177, &x178, x176, x168, x165); var x179: u64 = undefined; var x180: u1 = undefined; addcarryxU64(&x179, &x180, 0x0, x155, x171); var x181: u64 = undefined; var x182: u1 = undefined; addcarryxU64(&x181, &x182, x180, x157, x173); var x183: u64 = undefined; var x184: u1 = undefined; addcarryxU64(&x183, &x184, x182, x159, x175); var x185: u64 = undefined; var x186: u1 = undefined; addcarryxU64(&x185, &x186, x184, x161, x177); var x187: u64 = undefined; var x188: u1 = undefined; addcarryxU64(&x187, &x188, x186, ((@as(u64, x162) + @as(u64, x140)) + (@as(u64, x154) + x142)), (@as(u64, x178) + x166)); var x189: u64 = undefined; var x190: u1 = undefined; subborrowxU64(&x189, &x190, 0x0, x181, 0xf3b9cac2fc632551); var x191: u64 = undefined; var x192: u1 = undefined; subborrowxU64(&x191, &x192, x190, x183, 0xbce6faada7179e84); var x193: u64 = undefined; var x194: u1 = undefined; subborrowxU64(&x193, &x194, x192, x185, 0xffffffffffffffff); var x195: u64 = undefined; var x196: u1 = undefined; subborrowxU64(&x195, &x196, x194, x187, 0xffffffff00000000); var x197: u64 = undefined; var x198: u1 = undefined; subborrowxU64(&x197, &x198, x196, @as(u64, x188), @as(u64, 0x0)); var x199: u64 = undefined; cmovznzU64(&x199, x198, x189, x181); var x200: u64 = undefined; cmovznzU64(&x200, x198, x191, x183); var x201: u64 = undefined; cmovznzU64(&x201, x198, x193, x185); var x202: u64 = undefined; cmovznzU64(&x202, x198, x195, x187); out1[0] = x199; out1[1] = x200; out1[2] = x201; out1[3] = x202; } /// The function nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] pub fn nonzero(out1: *u64, arg1: [4]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | (arg1[3])))); out1.* = x1; } /// The function selectznz is a multi-limb conditional select. /// /// Postconditions: /// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn selectznz(out1: *[4]u64, arg1: u1, arg2: [4]u64, arg3: [4]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; cmovznzU64(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u64 = undefined; cmovznzU64(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u64 = undefined; cmovznzU64(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u64 = undefined; cmovznzU64(&x4, arg1, (arg2[3]), (arg3[3])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; } /// The function toBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] pub fn toBytes(out1: *[32]u8, arg1: [4]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[3]); const x2 = (arg1[2]); const x3 = (arg1[1]); const x4 = (arg1[0]); const x5 = @as(u8, @truncate((x4 & @as(u64, 0xff)))); const x6 = (x4 >> 8); const x7 = @as(u8, @truncate((x6 & @as(u64, 0xff)))); const x8 = (x6 >> 8); const x9 = @as(u8, @truncate((x8 & @as(u64, 0xff)))); const x10 = (x8 >> 8); const x11 = @as(u8, @truncate((x10 & @as(u64, 0xff)))); const x12 = (x10 >> 8); const x13 = @as(u8, @truncate((x12 & @as(u64, 0xff)))); const x14 = (x12 >> 8); const x15 = @as(u8, @truncate((x14 & @as(u64, 0xff)))); const x16 = (x14 >> 8); const x17 = @as(u8, @truncate((x16 & @as(u64, 0xff)))); const x18 = @as(u8, @truncate((x16 >> 8))); const x19 = @as(u8, @truncate((x3 & @as(u64, 0xff)))); const x20 = (x3 >> 8); const x21 = @as(u8, @truncate((x20 & @as(u64, 0xff)))); const x22 = (x20 >> 8); const x23 = @as(u8, @truncate((x22 & @as(u64, 0xff)))); const x24 = (x22 >> 8); const x25 = @as(u8, @truncate((x24 & @as(u64, 0xff)))); const x26 = (x24 >> 8); const x27 = @as(u8, @truncate((x26 & @as(u64, 0xff)))); const x28 = (x26 >> 8); const x29 = @as(u8, @truncate((x28 & @as(u64, 0xff)))); const x30 = (x28 >> 8); const x31 = @as(u8, @truncate((x30 & @as(u64, 0xff)))); const x32 = @as(u8, @truncate((x30 >> 8))); const x33 = @as(u8, @truncate((x2 & @as(u64, 0xff)))); const x34 = (x2 >> 8); const x35 = @as(u8, @truncate((x34 & @as(u64, 0xff)))); const x36 = (x34 >> 8); const x37 = @as(u8, @truncate((x36 & @as(u64, 0xff)))); const x38 = (x36 >> 8); const x39 = @as(u8, @truncate((x38 & @as(u64, 0xff)))); const x40 = (x38 >> 8); const x41 = @as(u8, @truncate((x40 & @as(u64, 0xff)))); const x42 = (x40 >> 8); const x43 = @as(u8, @truncate((x42 & @as(u64, 0xff)))); const x44 = (x42 >> 8); const x45 = @as(u8, @truncate((x44 & @as(u64, 0xff)))); const x46 = @as(u8, @truncate((x44 >> 8))); const x47 = @as(u8, @truncate((x1 & @as(u64, 0xff)))); const x48 = (x1 >> 8); const x49 = @as(u8, @truncate((x48 & @as(u64, 0xff)))); const x50 = (x48 >> 8); const x51 = @as(u8, @truncate((x50 & @as(u64, 0xff)))); const x52 = (x50 >> 8); const x53 = @as(u8, @truncate((x52 & @as(u64, 0xff)))); const x54 = (x52 >> 8); const x55 = @as(u8, @truncate((x54 & @as(u64, 0xff)))); const x56 = (x54 >> 8); const x57 = @as(u8, @truncate((x56 & @as(u64, 0xff)))); const x58 = (x56 >> 8); const x59 = @as(u8, @truncate((x58 & @as(u64, 0xff)))); const x60 = @as(u8, @truncate((x58 >> 8))); out1[0] = x5; out1[1] = x7; out1[2] = x9; out1[3] = x11; out1[4] = x13; out1[5] = x15; out1[6] = x17; out1[7] = x18; out1[8] = x19; out1[9] = x21; out1[10] = x23; out1[11] = x25; out1[12] = x27; out1[13] = x29; out1[14] = x31; out1[15] = x32; out1[16] = x33; out1[17] = x35; out1[18] = x37; out1[19] = x39; out1[20] = x41; out1[21] = x43; out1[22] = x45; out1[23] = x46; out1[24] = x47; out1[25] = x49; out1[26] = x51; out1[27] = x53; out1[28] = x55; out1[29] = x57; out1[30] = x59; out1[31] = x60; } /// The function fromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. /// /// Preconditions: /// 0 ≤ bytes_eval arg1 < m /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fromBytes(out1: *[4]u64, arg1: [32]u8) void { @setRuntimeSafety(mode == .Debug); const x1 = (@as(u64, (arg1[31])) << 56); const x2 = (@as(u64, (arg1[30])) << 48); const x3 = (@as(u64, (arg1[29])) << 40); const x4 = (@as(u64, (arg1[28])) << 32); const x5 = (@as(u64, (arg1[27])) << 24); const x6 = (@as(u64, (arg1[26])) << 16); const x7 = (@as(u64, (arg1[25])) << 8); const x8 = (arg1[24]); const x9 = (@as(u64, (arg1[23])) << 56); const x10 = (@as(u64, (arg1[22])) << 48); const x11 = (@as(u64, (arg1[21])) << 40); const x12 = (@as(u64, (arg1[20])) << 32); const x13 = (@as(u64, (arg1[19])) << 24); const x14 = (@as(u64, (arg1[18])) << 16); const x15 = (@as(u64, (arg1[17])) << 8); const x16 = (arg1[16]); const x17 = (@as(u64, (arg1[15])) << 56); const x18 = (@as(u64, (arg1[14])) << 48); const x19 = (@as(u64, (arg1[13])) << 40); const x20 = (@as(u64, (arg1[12])) << 32); const x21 = (@as(u64, (arg1[11])) << 24); const x22 = (@as(u64, (arg1[10])) << 16); const x23 = (@as(u64, (arg1[9])) << 8); const x24 = (arg1[8]); const x25 = (@as(u64, (arg1[7])) << 56); const x26 = (@as(u64, (arg1[6])) << 48); const x27 = (@as(u64, (arg1[5])) << 40); const x28 = (@as(u64, (arg1[4])) << 32); const x29 = (@as(u64, (arg1[3])) << 24); const x30 = (@as(u64, (arg1[2])) << 16); const x31 = (@as(u64, (arg1[1])) << 8); const x32 = (arg1[0]); const x33 = (x31 + @as(u64, x32)); const x34 = (x30 + x33); const x35 = (x29 + x34); const x36 = (x28 + x35); const x37 = (x27 + x36); const x38 = (x26 + x37); const x39 = (x25 + x38); const x40 = (x23 + @as(u64, x24)); const x41 = (x22 + x40); const x42 = (x21 + x41); const x43 = (x20 + x42); const x44 = (x19 + x43); const x45 = (x18 + x44); const x46 = (x17 + x45); const x47 = (x15 + @as(u64, x16)); const x48 = (x14 + x47); const x49 = (x13 + x48); const x50 = (x12 + x49); const x51 = (x11 + x50); const x52 = (x10 + x51); const x53 = (x9 + x52); const x54 = (x7 + @as(u64, x8)); const x55 = (x6 + x54); const x56 = (x5 + x55); const x57 = (x4 + x56); const x58 = (x3 + x57); const x59 = (x2 + x58); const x60 = (x1 + x59); out1[0] = x39; out1[1] = x46; out1[2] = x53; out1[3] = x60; } /// The function setOne returns the field element one in the Montgomery domain. /// /// Postconditions: /// eval (from_montgomery out1) mod m = 1 mod m /// 0 ≤ eval out1 < m /// pub fn setOne(out1: *MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0xc46353d039cdaaf; out1[1] = 0x4319055258e8617b; out1[2] = @as(u64, 0x0); out1[3] = 0xffffffff; } /// The function msat returns the saturated representation of the prime modulus. /// /// Postconditions: /// twos_complement_eval out1 = m /// 0 ≤ eval out1 < m /// /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn msat(out1: *[5]u64) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0xf3b9cac2fc632551; out1[1] = 0xbce6faada7179e84; out1[2] = 0xffffffffffffffff; out1[3] = 0xffffffff00000000; out1[4] = @as(u64, 0x0); } /// The function divstep computes a divstep. /// /// Preconditions: /// 0 ≤ eval arg4 < m /// 0 ≤ eval arg5 < m /// Postconditions: /// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) /// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) /// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) /// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) /// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) /// 0 ≤ eval out5 < m /// 0 ≤ eval out5 < m /// 0 ≤ eval out2 < m /// 0 ≤ eval out3 < m /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn divstep(out1: *u64, out2: *[5]u64, out3: *[5]u64, out4: *[4]u64, out5: *[4]u64, arg1: u64, arg2: [5]u64, arg3: [5]u64, arg4: [4]u64, arg5: [4]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; addcarryxU64(&x1, &x2, 0x0, (~arg1), @as(u64, 0x1)); const x3 = @as(u1, @truncate((x1 >> 63))) & @as(u1, @truncate(((arg3[0]) & @as(u64, 0x1)))); var x4: u64 = undefined; var x5: u1 = undefined; addcarryxU64(&x4, &x5, 0x0, (~arg1), @as(u64, 0x1)); var x6: u64 = undefined; cmovznzU64(&x6, x3, arg1, x4); var x7: u64 = undefined; cmovznzU64(&x7, x3, (arg2[0]), (arg3[0])); var x8: u64 = undefined; cmovznzU64(&x8, x3, (arg2[1]), (arg3[1])); var x9: u64 = undefined; cmovznzU64(&x9, x3, (arg2[2]), (arg3[2])); var x10: u64 = undefined; cmovznzU64(&x10, x3, (arg2[3]), (arg3[3])); var x11: u64 = undefined; cmovznzU64(&x11, x3, (arg2[4]), (arg3[4])); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, 0x0, @as(u64, 0x1), (~(arg2[0]))); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, @as(u64, 0x0), (~(arg2[1]))); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, @as(u64, 0x0), (~(arg2[2]))); var x18: u64 = undefined; var x19: u1 = undefined; addcarryxU64(&x18, &x19, x17, @as(u64, 0x0), (~(arg2[3]))); var x20: u64 = undefined; var x21: u1 = undefined; addcarryxU64(&x20, &x21, x19, @as(u64, 0x0), (~(arg2[4]))); var x22: u64 = undefined; cmovznzU64(&x22, x3, (arg3[0]), x12); var x23: u64 = undefined; cmovznzU64(&x23, x3, (arg3[1]), x14); var x24: u64 = undefined; cmovznzU64(&x24, x3, (arg3[2]), x16); var x25: u64 = undefined; cmovznzU64(&x25, x3, (arg3[3]), x18); var x26: u64 = undefined; cmovznzU64(&x26, x3, (arg3[4]), x20); var x27: u64 = undefined; cmovznzU64(&x27, x3, (arg4[0]), (arg5[0])); var x28: u64 = undefined; cmovznzU64(&x28, x3, (arg4[1]), (arg5[1])); var x29: u64 = undefined; cmovznzU64(&x29, x3, (arg4[2]), (arg5[2])); var x30: u64 = undefined; cmovznzU64(&x30, x3, (arg4[3]), (arg5[3])); var x31: u64 = undefined; var x32: u1 = undefined; addcarryxU64(&x31, &x32, 0x0, x27, x27); var x33: u64 = undefined; var x34: u1 = undefined; addcarryxU64(&x33, &x34, x32, x28, x28); var x35: u64 = undefined; var x36: u1 = undefined; addcarryxU64(&x35, &x36, x34, x29, x29); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, x36, x30, x30); var x39: u64 = undefined; var x40: u1 = undefined; subborrowxU64(&x39, &x40, 0x0, x31, 0xf3b9cac2fc632551); var x41: u64 = undefined; var x42: u1 = undefined; subborrowxU64(&x41, &x42, x40, x33, 0xbce6faada7179e84); var x43: u64 = undefined; var x44: u1 = undefined; subborrowxU64(&x43, &x44, x42, x35, 0xffffffffffffffff); var x45: u64 = undefined; var x46: u1 = undefined; subborrowxU64(&x45, &x46, x44, x37, 0xffffffff00000000); var x47: u64 = undefined; var x48: u1 = undefined; subborrowxU64(&x47, &x48, x46, @as(u64, x38), @as(u64, 0x0)); const x49 = (arg4[3]); const x50 = (arg4[2]); const x51 = (arg4[1]); const x52 = (arg4[0]); var x53: u64 = undefined; var x54: u1 = undefined; subborrowxU64(&x53, &x54, 0x0, @as(u64, 0x0), x52); var x55: u64 = undefined; var x56: u1 = undefined; subborrowxU64(&x55, &x56, x54, @as(u64, 0x0), x51); var x57: u64 = undefined; var x58: u1 = undefined; subborrowxU64(&x57, &x58, x56, @as(u64, 0x0), x50); var x59: u64 = undefined; var x60: u1 = undefined; subborrowxU64(&x59, &x60, x58, @as(u64, 0x0), x49); var x61: u64 = undefined; cmovznzU64(&x61, x60, @as(u64, 0x0), 0xffffffffffffffff); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, 0x0, x53, (x61 & 0xf3b9cac2fc632551)); var x64: u64 = undefined; var x65: u1 = undefined; addcarryxU64(&x64, &x65, x63, x55, (x61 & 0xbce6faada7179e84)); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, x65, x57, x61); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, x67, x59, (x61 & 0xffffffff00000000)); var x70: u64 = undefined; cmovznzU64(&x70, x3, (arg5[0]), x62); var x71: u64 = undefined; cmovznzU64(&x71, x3, (arg5[1]), x64); var x72: u64 = undefined; cmovznzU64(&x72, x3, (arg5[2]), x66); var x73: u64 = undefined; cmovznzU64(&x73, x3, (arg5[3]), x68); const x74 = @as(u1, @truncate((x22 & @as(u64, 0x1)))); var x75: u64 = undefined; cmovznzU64(&x75, x74, @as(u64, 0x0), x7); var x76: u64 = undefined; cmovznzU64(&x76, x74, @as(u64, 0x0), x8); var x77: u64 = undefined; cmovznzU64(&x77, x74, @as(u64, 0x0), x9); var x78: u64 = undefined; cmovznzU64(&x78, x74, @as(u64, 0x0), x10); var x79: u64 = undefined; cmovznzU64(&x79, x74, @as(u64, 0x0), x11); var x80: u64 = undefined; var x81: u1 = undefined; addcarryxU64(&x80, &x81, 0x0, x22, x75); var x82: u64 = undefined; var x83: u1 = undefined; addcarryxU64(&x82, &x83, x81, x23, x76); var x84: u64 = undefined; var x85: u1 = undefined; addcarryxU64(&x84, &x85, x83, x24, x77); var x86: u64 = undefined; var x87: u1 = undefined; addcarryxU64(&x86, &x87, x85, x25, x78); var x88: u64 = undefined; var x89: u1 = undefined; addcarryxU64(&x88, &x89, x87, x26, x79); var x90: u64 = undefined; cmovznzU64(&x90, x74, @as(u64, 0x0), x27); var x91: u64 = undefined; cmovznzU64(&x91, x74, @as(u64, 0x0), x28); var x92: u64 = undefined; cmovznzU64(&x92, x74, @as(u64, 0x0), x29); var x93: u64 = undefined; cmovznzU64(&x93, x74, @as(u64, 0x0), x30); var x94: u64 = undefined; var x95: u1 = undefined; addcarryxU64(&x94, &x95, 0x0, x70, x90); var x96: u64 = undefined; var x97: u1 = undefined; addcarryxU64(&x96, &x97, x95, x71, x91); var x98: u64 = undefined; var x99: u1 = undefined; addcarryxU64(&x98, &x99, x97, x72, x92); var x100: u64 = undefined; var x101: u1 = undefined; addcarryxU64(&x100, &x101, x99, x73, x93); var x102: u64 = undefined; var x103: u1 = undefined; subborrowxU64(&x102, &x103, 0x0, x94, 0xf3b9cac2fc632551); var x104: u64 = undefined; var x105: u1 = undefined; subborrowxU64(&x104, &x105, x103, x96, 0xbce6faada7179e84); var x106: u64 = undefined; var x107: u1 = undefined; subborrowxU64(&x106, &x107, x105, x98, 0xffffffffffffffff); var x108: u64 = undefined; var x109: u1 = undefined; subborrowxU64(&x108, &x109, x107, x100, 0xffffffff00000000); var x110: u64 = undefined; var x111: u1 = undefined; subborrowxU64(&x110, &x111, x109, @as(u64, x101), @as(u64, 0x0)); var x112: u64 = undefined; var x113: u1 = undefined; addcarryxU64(&x112, &x113, 0x0, x6, @as(u64, 0x1)); const x114 = ((x80 >> 1) | ((x82 << 63) & 0xffffffffffffffff)); const x115 = ((x82 >> 1) | ((x84 << 63) & 0xffffffffffffffff)); const x116 = ((x84 >> 1) | ((x86 << 63) & 0xffffffffffffffff)); const x117 = ((x86 >> 1) | ((x88 << 63) & 0xffffffffffffffff)); const x118 = ((x88 & 0x8000000000000000) | (x88 >> 1)); var x119: u64 = undefined; cmovznzU64(&x119, x48, x39, x31); var x120: u64 = undefined; cmovznzU64(&x120, x48, x41, x33); var x121: u64 = undefined; cmovznzU64(&x121, x48, x43, x35); var x122: u64 = undefined; cmovznzU64(&x122, x48, x45, x37); var x123: u64 = undefined; cmovznzU64(&x123, x111, x102, x94); var x124: u64 = undefined; cmovznzU64(&x124, x111, x104, x96); var x125: u64 = undefined; cmovznzU64(&x125, x111, x106, x98); var x126: u64 = undefined; cmovznzU64(&x126, x111, x108, x100); out1.* = x112; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out3[0] = x114; out3[1] = x115; out3[2] = x116; out3[3] = x117; out3[4] = x118; out4[0] = x119; out4[1] = x120; out4[2] = x121; out4[3] = x122; out5[0] = x123; out5[1] = x124; out5[2] = x125; out5[3] = x126; } /// The function divstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). /// /// Postconditions: /// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if ⌊log2 m⌋ + 1 < 46 then ⌊(49 * (⌊log2 m⌋ + 1) + 80) / 17⌋ else ⌊(49 * (⌊log2 m⌋ + 1) + 57) / 17⌋) /// 0 ≤ eval out1 < m /// /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn divstepPrecomp(out1: *[4]u64) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0xd739262fb7fcfbb5; out1[1] = 0x8ac6f75d20074414; out1[2] = 0xc67428bfb5e3c256; out1[3] = 0x444962f2eda7aedf; }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves/p256/field.zig
const std = @import("std"); const common = @import("../common.zig"); const Field = common.Field; pub const Fe = Field(.{ .fiat = @import("p256_64.zig"), .field_order = 115792089210356248762697446949407573530086143415290314195533631308867097853951, .field_bits = 256, .saturated_bits = 255, .encoded_length = 32, });
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves/p256/p256_64.zig
// Autogenerated: 'src/ExtractionOCaml/word_by_word_montgomery' --lang Zig --internal-static --public-function-case camelCase --private-function-case camelCase --public-type-case UpperCamelCase --private-type-case UpperCamelCase --no-prefix-fiat --package-name p256 '' 64 '2^256 - 2^224 + 2^192 + 2^96 - 1' mul square add sub opp from_montgomery to_montgomery nonzero selectznz to_bytes from_bytes one msat divstep divstep_precomp // curve description (via package name): p256 // machine_wordsize = 64 (from "64") // requested operations: mul, square, add, sub, opp, from_montgomery, to_montgomery, nonzero, selectznz, to_bytes, from_bytes, one, msat, divstep, divstep_precomp // m = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff (from "2^256 - 2^224 + 2^192 + 2^96 - 1") // // NOTE: In addition to the bounds specified above each function, all // functions synthesized for this Montgomery arithmetic require the // input to be strictly less than the prime modulus (m), and also // require the input to be in the unique saturated representation. // All functions also ensure that these two properties are true of // return values. // // Computed values: // eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) // bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) // twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in // if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 const std = @import("std"); const mode = @import("builtin").mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels // The type MontgomeryDomainFieldElement is a field element in the Montgomery domain. // Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub const MontgomeryDomainFieldElement = [4]u64; // The type NonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain. // Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub const NonMontgomeryDomainFieldElement = [4]u64; /// The function addcarryxU64 is an addition with carry. /// /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^64 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] inline fn addcarryxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const ov1 = @addWithOverflow(arg2, arg3); const ov2 = @addWithOverflow(ov1[0], arg1); out1.* = ov2[0]; out2.* = ov1[1] | ov2[1]; } /// The function subborrowxU64 is a subtraction with borrow. /// /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^64 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] inline fn subborrowxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const ov1 = @subWithOverflow(arg2, arg3); const ov2 = @subWithOverflow(ov1[0], arg1); out1.* = ov2[0]; out2.* = ov1[1] | ov2[1]; } /// The function mulxU64 is a multiplication, returning the full double-width result. /// /// Postconditions: /// out1 = (arg1 * arg2) mod 2^64 /// out2 = ⌊arg1 * arg2 / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0xffffffffffffffff] inline fn mulxU64(out1: *u64, out2: *u64, arg1: u64, arg2: u64) void { @setRuntimeSafety(mode == .Debug); const x = @as(u128, arg1) * @as(u128, arg2); out1.* = @as(u64, @truncate(x)); out2.* = @as(u64, @truncate(x >> 64)); } /// The function cmovznzU64 is a single-word conditional move. /// /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] inline fn cmovznzU64(out1: *u64, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const mask = 0 -% @as(u64, arg1); out1.* = (mask & arg3) | ((~mask) & arg2); } /// The function mul multiplies two field elements in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// pub fn mul(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; mulxU64(&x5, &x6, x4, (arg2[3])); var x7: u64 = undefined; var x8: u64 = undefined; mulxU64(&x7, &x8, x4, (arg2[2])); var x9: u64 = undefined; var x10: u64 = undefined; mulxU64(&x9, &x10, x4, (arg2[1])); var x11: u64 = undefined; var x12: u64 = undefined; mulxU64(&x11, &x12, x4, (arg2[0])); var x13: u64 = undefined; var x14: u1 = undefined; addcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; addcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; addcarryxU64(&x17, &x18, x16, x8, x5); const x19 = (@as(u64, x18) + x6); var x20: u64 = undefined; var x21: u64 = undefined; mulxU64(&x20, &x21, x11, 0xffffffff00000001); var x22: u64 = undefined; var x23: u64 = undefined; mulxU64(&x22, &x23, x11, 0xffffffff); var x24: u64 = undefined; var x25: u64 = undefined; mulxU64(&x24, &x25, x11, 0xffffffffffffffff); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, 0x0, x25, x22); const x28 = (@as(u64, x27) + x23); var x29: u64 = undefined; var x30: u1 = undefined; addcarryxU64(&x29, &x30, 0x0, x11, x24); var x31: u64 = undefined; var x32: u1 = undefined; addcarryxU64(&x31, &x32, x30, x13, x26); var x33: u64 = undefined; var x34: u1 = undefined; addcarryxU64(&x33, &x34, x32, x15, x28); var x35: u64 = undefined; var x36: u1 = undefined; addcarryxU64(&x35, &x36, x34, x17, x20); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, x36, x19, x21); var x39: u64 = undefined; var x40: u64 = undefined; mulxU64(&x39, &x40, x1, (arg2[3])); var x41: u64 = undefined; var x42: u64 = undefined; mulxU64(&x41, &x42, x1, (arg2[2])); var x43: u64 = undefined; var x44: u64 = undefined; mulxU64(&x43, &x44, x1, (arg2[1])); var x45: u64 = undefined; var x46: u64 = undefined; mulxU64(&x45, &x46, x1, (arg2[0])); var x47: u64 = undefined; var x48: u1 = undefined; addcarryxU64(&x47, &x48, 0x0, x46, x43); var x49: u64 = undefined; var x50: u1 = undefined; addcarryxU64(&x49, &x50, x48, x44, x41); var x51: u64 = undefined; var x52: u1 = undefined; addcarryxU64(&x51, &x52, x50, x42, x39); const x53 = (@as(u64, x52) + x40); var x54: u64 = undefined; var x55: u1 = undefined; addcarryxU64(&x54, &x55, 0x0, x31, x45); var x56: u64 = undefined; var x57: u1 = undefined; addcarryxU64(&x56, &x57, x55, x33, x47); var x58: u64 = undefined; var x59: u1 = undefined; addcarryxU64(&x58, &x59, x57, x35, x49); var x60: u64 = undefined; var x61: u1 = undefined; addcarryxU64(&x60, &x61, x59, x37, x51); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, x61, @as(u64, x38), x53); var x64: u64 = undefined; var x65: u64 = undefined; mulxU64(&x64, &x65, x54, 0xffffffff00000001); var x66: u64 = undefined; var x67: u64 = undefined; mulxU64(&x66, &x67, x54, 0xffffffff); var x68: u64 = undefined; var x69: u64 = undefined; mulxU64(&x68, &x69, x54, 0xffffffffffffffff); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, 0x0, x69, x66); const x72 = (@as(u64, x71) + x67); var x73: u64 = undefined; var x74: u1 = undefined; addcarryxU64(&x73, &x74, 0x0, x54, x68); var x75: u64 = undefined; var x76: u1 = undefined; addcarryxU64(&x75, &x76, x74, x56, x70); var x77: u64 = undefined; var x78: u1 = undefined; addcarryxU64(&x77, &x78, x76, x58, x72); var x79: u64 = undefined; var x80: u1 = undefined; addcarryxU64(&x79, &x80, x78, x60, x64); var x81: u64 = undefined; var x82: u1 = undefined; addcarryxU64(&x81, &x82, x80, x62, x65); const x83 = (@as(u64, x82) + @as(u64, x63)); var x84: u64 = undefined; var x85: u64 = undefined; mulxU64(&x84, &x85, x2, (arg2[3])); var x86: u64 = undefined; var x87: u64 = undefined; mulxU64(&x86, &x87, x2, (arg2[2])); var x88: u64 = undefined; var x89: u64 = undefined; mulxU64(&x88, &x89, x2, (arg2[1])); var x90: u64 = undefined; var x91: u64 = undefined; mulxU64(&x90, &x91, x2, (arg2[0])); var x92: u64 = undefined; var x93: u1 = undefined; addcarryxU64(&x92, &x93, 0x0, x91, x88); var x94: u64 = undefined; var x95: u1 = undefined; addcarryxU64(&x94, &x95, x93, x89, x86); var x96: u64 = undefined; var x97: u1 = undefined; addcarryxU64(&x96, &x97, x95, x87, x84); const x98 = (@as(u64, x97) + x85); var x99: u64 = undefined; var x100: u1 = undefined; addcarryxU64(&x99, &x100, 0x0, x75, x90); var x101: u64 = undefined; var x102: u1 = undefined; addcarryxU64(&x101, &x102, x100, x77, x92); var x103: u64 = undefined; var x104: u1 = undefined; addcarryxU64(&x103, &x104, x102, x79, x94); var x105: u64 = undefined; var x106: u1 = undefined; addcarryxU64(&x105, &x106, x104, x81, x96); var x107: u64 = undefined; var x108: u1 = undefined; addcarryxU64(&x107, &x108, x106, x83, x98); var x109: u64 = undefined; var x110: u64 = undefined; mulxU64(&x109, &x110, x99, 0xffffffff00000001); var x111: u64 = undefined; var x112: u64 = undefined; mulxU64(&x111, &x112, x99, 0xffffffff); var x113: u64 = undefined; var x114: u64 = undefined; mulxU64(&x113, &x114, x99, 0xffffffffffffffff); var x115: u64 = undefined; var x116: u1 = undefined; addcarryxU64(&x115, &x116, 0x0, x114, x111); const x117 = (@as(u64, x116) + x112); var x118: u64 = undefined; var x119: u1 = undefined; addcarryxU64(&x118, &x119, 0x0, x99, x113); var x120: u64 = undefined; var x121: u1 = undefined; addcarryxU64(&x120, &x121, x119, x101, x115); var x122: u64 = undefined; var x123: u1 = undefined; addcarryxU64(&x122, &x123, x121, x103, x117); var x124: u64 = undefined; var x125: u1 = undefined; addcarryxU64(&x124, &x125, x123, x105, x109); var x126: u64 = undefined; var x127: u1 = undefined; addcarryxU64(&x126, &x127, x125, x107, x110); const x128 = (@as(u64, x127) + @as(u64, x108)); var x129: u64 = undefined; var x130: u64 = undefined; mulxU64(&x129, &x130, x3, (arg2[3])); var x131: u64 = undefined; var x132: u64 = undefined; mulxU64(&x131, &x132, x3, (arg2[2])); var x133: u64 = undefined; var x134: u64 = undefined; mulxU64(&x133, &x134, x3, (arg2[1])); var x135: u64 = undefined; var x136: u64 = undefined; mulxU64(&x135, &x136, x3, (arg2[0])); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, 0x0, x136, x133); var x139: u64 = undefined; var x140: u1 = undefined; addcarryxU64(&x139, &x140, x138, x134, x131); var x141: u64 = undefined; var x142: u1 = undefined; addcarryxU64(&x141, &x142, x140, x132, x129); const x143 = (@as(u64, x142) + x130); var x144: u64 = undefined; var x145: u1 = undefined; addcarryxU64(&x144, &x145, 0x0, x120, x135); var x146: u64 = undefined; var x147: u1 = undefined; addcarryxU64(&x146, &x147, x145, x122, x137); var x148: u64 = undefined; var x149: u1 = undefined; addcarryxU64(&x148, &x149, x147, x124, x139); var x150: u64 = undefined; var x151: u1 = undefined; addcarryxU64(&x150, &x151, x149, x126, x141); var x152: u64 = undefined; var x153: u1 = undefined; addcarryxU64(&x152, &x153, x151, x128, x143); var x154: u64 = undefined; var x155: u64 = undefined; mulxU64(&x154, &x155, x144, 0xffffffff00000001); var x156: u64 = undefined; var x157: u64 = undefined; mulxU64(&x156, &x157, x144, 0xffffffff); var x158: u64 = undefined; var x159: u64 = undefined; mulxU64(&x158, &x159, x144, 0xffffffffffffffff); var x160: u64 = undefined; var x161: u1 = undefined; addcarryxU64(&x160, &x161, 0x0, x159, x156); const x162 = (@as(u64, x161) + x157); var x163: u64 = undefined; var x164: u1 = undefined; addcarryxU64(&x163, &x164, 0x0, x144, x158); var x165: u64 = undefined; var x166: u1 = undefined; addcarryxU64(&x165, &x166, x164, x146, x160); var x167: u64 = undefined; var x168: u1 = undefined; addcarryxU64(&x167, &x168, x166, x148, x162); var x169: u64 = undefined; var x170: u1 = undefined; addcarryxU64(&x169, &x170, x168, x150, x154); var x171: u64 = undefined; var x172: u1 = undefined; addcarryxU64(&x171, &x172, x170, x152, x155); const x173 = (@as(u64, x172) + @as(u64, x153)); var x174: u64 = undefined; var x175: u1 = undefined; subborrowxU64(&x174, &x175, 0x0, x165, 0xffffffffffffffff); var x176: u64 = undefined; var x177: u1 = undefined; subborrowxU64(&x176, &x177, x175, x167, 0xffffffff); var x178: u64 = undefined; var x179: u1 = undefined; subborrowxU64(&x178, &x179, x177, x169, @as(u64, 0x0)); var x180: u64 = undefined; var x181: u1 = undefined; subborrowxU64(&x180, &x181, x179, x171, 0xffffffff00000001); var x182: u64 = undefined; var x183: u1 = undefined; subborrowxU64(&x182, &x183, x181, x173, @as(u64, 0x0)); var x184: u64 = undefined; cmovznzU64(&x184, x183, x174, x165); var x185: u64 = undefined; cmovznzU64(&x185, x183, x176, x167); var x186: u64 = undefined; cmovznzU64(&x186, x183, x178, x169); var x187: u64 = undefined; cmovznzU64(&x187, x183, x180, x171); out1[0] = x184; out1[1] = x185; out1[2] = x186; out1[3] = x187; } /// The function square squares a field element in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m /// 0 ≤ eval out1 < m /// pub fn square(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; mulxU64(&x5, &x6, x4, (arg1[3])); var x7: u64 = undefined; var x8: u64 = undefined; mulxU64(&x7, &x8, x4, (arg1[2])); var x9: u64 = undefined; var x10: u64 = undefined; mulxU64(&x9, &x10, x4, (arg1[1])); var x11: u64 = undefined; var x12: u64 = undefined; mulxU64(&x11, &x12, x4, (arg1[0])); var x13: u64 = undefined; var x14: u1 = undefined; addcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; addcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; addcarryxU64(&x17, &x18, x16, x8, x5); const x19 = (@as(u64, x18) + x6); var x20: u64 = undefined; var x21: u64 = undefined; mulxU64(&x20, &x21, x11, 0xffffffff00000001); var x22: u64 = undefined; var x23: u64 = undefined; mulxU64(&x22, &x23, x11, 0xffffffff); var x24: u64 = undefined; var x25: u64 = undefined; mulxU64(&x24, &x25, x11, 0xffffffffffffffff); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, 0x0, x25, x22); const x28 = (@as(u64, x27) + x23); var x29: u64 = undefined; var x30: u1 = undefined; addcarryxU64(&x29, &x30, 0x0, x11, x24); var x31: u64 = undefined; var x32: u1 = undefined; addcarryxU64(&x31, &x32, x30, x13, x26); var x33: u64 = undefined; var x34: u1 = undefined; addcarryxU64(&x33, &x34, x32, x15, x28); var x35: u64 = undefined; var x36: u1 = undefined; addcarryxU64(&x35, &x36, x34, x17, x20); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, x36, x19, x21); var x39: u64 = undefined; var x40: u64 = undefined; mulxU64(&x39, &x40, x1, (arg1[3])); var x41: u64 = undefined; var x42: u64 = undefined; mulxU64(&x41, &x42, x1, (arg1[2])); var x43: u64 = undefined; var x44: u64 = undefined; mulxU64(&x43, &x44, x1, (arg1[1])); var x45: u64 = undefined; var x46: u64 = undefined; mulxU64(&x45, &x46, x1, (arg1[0])); var x47: u64 = undefined; var x48: u1 = undefined; addcarryxU64(&x47, &x48, 0x0, x46, x43); var x49: u64 = undefined; var x50: u1 = undefined; addcarryxU64(&x49, &x50, x48, x44, x41); var x51: u64 = undefined; var x52: u1 = undefined; addcarryxU64(&x51, &x52, x50, x42, x39); const x53 = (@as(u64, x52) + x40); var x54: u64 = undefined; var x55: u1 = undefined; addcarryxU64(&x54, &x55, 0x0, x31, x45); var x56: u64 = undefined; var x57: u1 = undefined; addcarryxU64(&x56, &x57, x55, x33, x47); var x58: u64 = undefined; var x59: u1 = undefined; addcarryxU64(&x58, &x59, x57, x35, x49); var x60: u64 = undefined; var x61: u1 = undefined; addcarryxU64(&x60, &x61, x59, x37, x51); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, x61, @as(u64, x38), x53); var x64: u64 = undefined; var x65: u64 = undefined; mulxU64(&x64, &x65, x54, 0xffffffff00000001); var x66: u64 = undefined; var x67: u64 = undefined; mulxU64(&x66, &x67, x54, 0xffffffff); var x68: u64 = undefined; var x69: u64 = undefined; mulxU64(&x68, &x69, x54, 0xffffffffffffffff); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, 0x0, x69, x66); const x72 = (@as(u64, x71) + x67); var x73: u64 = undefined; var x74: u1 = undefined; addcarryxU64(&x73, &x74, 0x0, x54, x68); var x75: u64 = undefined; var x76: u1 = undefined; addcarryxU64(&x75, &x76, x74, x56, x70); var x77: u64 = undefined; var x78: u1 = undefined; addcarryxU64(&x77, &x78, x76, x58, x72); var x79: u64 = undefined; var x80: u1 = undefined; addcarryxU64(&x79, &x80, x78, x60, x64); var x81: u64 = undefined; var x82: u1 = undefined; addcarryxU64(&x81, &x82, x80, x62, x65); const x83 = (@as(u64, x82) + @as(u64, x63)); var x84: u64 = undefined; var x85: u64 = undefined; mulxU64(&x84, &x85, x2, (arg1[3])); var x86: u64 = undefined; var x87: u64 = undefined; mulxU64(&x86, &x87, x2, (arg1[2])); var x88: u64 = undefined; var x89: u64 = undefined; mulxU64(&x88, &x89, x2, (arg1[1])); var x90: u64 = undefined; var x91: u64 = undefined; mulxU64(&x90, &x91, x2, (arg1[0])); var x92: u64 = undefined; var x93: u1 = undefined; addcarryxU64(&x92, &x93, 0x0, x91, x88); var x94: u64 = undefined; var x95: u1 = undefined; addcarryxU64(&x94, &x95, x93, x89, x86); var x96: u64 = undefined; var x97: u1 = undefined; addcarryxU64(&x96, &x97, x95, x87, x84); const x98 = (@as(u64, x97) + x85); var x99: u64 = undefined; var x100: u1 = undefined; addcarryxU64(&x99, &x100, 0x0, x75, x90); var x101: u64 = undefined; var x102: u1 = undefined; addcarryxU64(&x101, &x102, x100, x77, x92); var x103: u64 = undefined; var x104: u1 = undefined; addcarryxU64(&x103, &x104, x102, x79, x94); var x105: u64 = undefined; var x106: u1 = undefined; addcarryxU64(&x105, &x106, x104, x81, x96); var x107: u64 = undefined; var x108: u1 = undefined; addcarryxU64(&x107, &x108, x106, x83, x98); var x109: u64 = undefined; var x110: u64 = undefined; mulxU64(&x109, &x110, x99, 0xffffffff00000001); var x111: u64 = undefined; var x112: u64 = undefined; mulxU64(&x111, &x112, x99, 0xffffffff); var x113: u64 = undefined; var x114: u64 = undefined; mulxU64(&x113, &x114, x99, 0xffffffffffffffff); var x115: u64 = undefined; var x116: u1 = undefined; addcarryxU64(&x115, &x116, 0x0, x114, x111); const x117 = (@as(u64, x116) + x112); var x118: u64 = undefined; var x119: u1 = undefined; addcarryxU64(&x118, &x119, 0x0, x99, x113); var x120: u64 = undefined; var x121: u1 = undefined; addcarryxU64(&x120, &x121, x119, x101, x115); var x122: u64 = undefined; var x123: u1 = undefined; addcarryxU64(&x122, &x123, x121, x103, x117); var x124: u64 = undefined; var x125: u1 = undefined; addcarryxU64(&x124, &x125, x123, x105, x109); var x126: u64 = undefined; var x127: u1 = undefined; addcarryxU64(&x126, &x127, x125, x107, x110); const x128 = (@as(u64, x127) + @as(u64, x108)); var x129: u64 = undefined; var x130: u64 = undefined; mulxU64(&x129, &x130, x3, (arg1[3])); var x131: u64 = undefined; var x132: u64 = undefined; mulxU64(&x131, &x132, x3, (arg1[2])); var x133: u64 = undefined; var x134: u64 = undefined; mulxU64(&x133, &x134, x3, (arg1[1])); var x135: u64 = undefined; var x136: u64 = undefined; mulxU64(&x135, &x136, x3, (arg1[0])); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, 0x0, x136, x133); var x139: u64 = undefined; var x140: u1 = undefined; addcarryxU64(&x139, &x140, x138, x134, x131); var x141: u64 = undefined; var x142: u1 = undefined; addcarryxU64(&x141, &x142, x140, x132, x129); const x143 = (@as(u64, x142) + x130); var x144: u64 = undefined; var x145: u1 = undefined; addcarryxU64(&x144, &x145, 0x0, x120, x135); var x146: u64 = undefined; var x147: u1 = undefined; addcarryxU64(&x146, &x147, x145, x122, x137); var x148: u64 = undefined; var x149: u1 = undefined; addcarryxU64(&x148, &x149, x147, x124, x139); var x150: u64 = undefined; var x151: u1 = undefined; addcarryxU64(&x150, &x151, x149, x126, x141); var x152: u64 = undefined; var x153: u1 = undefined; addcarryxU64(&x152, &x153, x151, x128, x143); var x154: u64 = undefined; var x155: u64 = undefined; mulxU64(&x154, &x155, x144, 0xffffffff00000001); var x156: u64 = undefined; var x157: u64 = undefined; mulxU64(&x156, &x157, x144, 0xffffffff); var x158: u64 = undefined; var x159: u64 = undefined; mulxU64(&x158, &x159, x144, 0xffffffffffffffff); var x160: u64 = undefined; var x161: u1 = undefined; addcarryxU64(&x160, &x161, 0x0, x159, x156); const x162 = (@as(u64, x161) + x157); var x163: u64 = undefined; var x164: u1 = undefined; addcarryxU64(&x163, &x164, 0x0, x144, x158); var x165: u64 = undefined; var x166: u1 = undefined; addcarryxU64(&x165, &x166, x164, x146, x160); var x167: u64 = undefined; var x168: u1 = undefined; addcarryxU64(&x167, &x168, x166, x148, x162); var x169: u64 = undefined; var x170: u1 = undefined; addcarryxU64(&x169, &x170, x168, x150, x154); var x171: u64 = undefined; var x172: u1 = undefined; addcarryxU64(&x171, &x172, x170, x152, x155); const x173 = (@as(u64, x172) + @as(u64, x153)); var x174: u64 = undefined; var x175: u1 = undefined; subborrowxU64(&x174, &x175, 0x0, x165, 0xffffffffffffffff); var x176: u64 = undefined; var x177: u1 = undefined; subborrowxU64(&x176, &x177, x175, x167, 0xffffffff); var x178: u64 = undefined; var x179: u1 = undefined; subborrowxU64(&x178, &x179, x177, x169, @as(u64, 0x0)); var x180: u64 = undefined; var x181: u1 = undefined; subborrowxU64(&x180, &x181, x179, x171, 0xffffffff00000001); var x182: u64 = undefined; var x183: u1 = undefined; subborrowxU64(&x182, &x183, x181, x173, @as(u64, 0x0)); var x184: u64 = undefined; cmovznzU64(&x184, x183, x174, x165); var x185: u64 = undefined; cmovznzU64(&x185, x183, x176, x167); var x186: u64 = undefined; cmovznzU64(&x186, x183, x178, x169); var x187: u64 = undefined; cmovznzU64(&x187, x183, x180, x171); out1[0] = x184; out1[1] = x185; out1[2] = x186; out1[3] = x187; } /// The function add adds two field elements in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// pub fn add(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; addcarryxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u64 = undefined; var x4: u1 = undefined; addcarryxU64(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u64 = undefined; var x6: u1 = undefined; addcarryxU64(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u64 = undefined; var x8: u1 = undefined; addcarryxU64(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u64 = undefined; var x10: u1 = undefined; subborrowxU64(&x9, &x10, 0x0, x1, 0xffffffffffffffff); var x11: u64 = undefined; var x12: u1 = undefined; subborrowxU64(&x11, &x12, x10, x3, 0xffffffff); var x13: u64 = undefined; var x14: u1 = undefined; subborrowxU64(&x13, &x14, x12, x5, @as(u64, 0x0)); var x15: u64 = undefined; var x16: u1 = undefined; subborrowxU64(&x15, &x16, x14, x7, 0xffffffff00000001); var x17: u64 = undefined; var x18: u1 = undefined; subborrowxU64(&x17, &x18, x16, @as(u64, x8), @as(u64, 0x0)); var x19: u64 = undefined; cmovznzU64(&x19, x18, x9, x1); var x20: u64 = undefined; cmovznzU64(&x20, x18, x11, x3); var x21: u64 = undefined; cmovznzU64(&x21, x18, x13, x5); var x22: u64 = undefined; cmovznzU64(&x22, x18, x15, x7); out1[0] = x19; out1[1] = x20; out1[2] = x21; out1[3] = x22; } /// The function sub subtracts two field elements in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// pub fn sub(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; subborrowxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u64 = undefined; var x4: u1 = undefined; subborrowxU64(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u64 = undefined; var x6: u1 = undefined; subborrowxU64(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u64 = undefined; var x8: u1 = undefined; subborrowxU64(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u64 = undefined; cmovznzU64(&x9, x8, @as(u64, 0x0), 0xffffffffffffffff); var x10: u64 = undefined; var x11: u1 = undefined; addcarryxU64(&x10, &x11, 0x0, x1, x9); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, x11, x3, (x9 & 0xffffffff)); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, x5, @as(u64, 0x0)); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, x7, (x9 & 0xffffffff00000001)); out1[0] = x10; out1[1] = x12; out1[2] = x14; out1[3] = x16; } /// The function opp negates a field element in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m /// 0 ≤ eval out1 < m /// pub fn opp(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; subborrowxU64(&x1, &x2, 0x0, @as(u64, 0x0), (arg1[0])); var x3: u64 = undefined; var x4: u1 = undefined; subborrowxU64(&x3, &x4, x2, @as(u64, 0x0), (arg1[1])); var x5: u64 = undefined; var x6: u1 = undefined; subborrowxU64(&x5, &x6, x4, @as(u64, 0x0), (arg1[2])); var x7: u64 = undefined; var x8: u1 = undefined; subborrowxU64(&x7, &x8, x6, @as(u64, 0x0), (arg1[3])); var x9: u64 = undefined; cmovznzU64(&x9, x8, @as(u64, 0x0), 0xffffffffffffffff); var x10: u64 = undefined; var x11: u1 = undefined; addcarryxU64(&x10, &x11, 0x0, x1, x9); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, x11, x3, (x9 & 0xffffffff)); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, x5, @as(u64, 0x0)); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, x7, (x9 & 0xffffffff00000001)); out1[0] = x10; out1[1] = x12; out1[2] = x14; out1[3] = x16; } /// The function fromMontgomery translates a field element out of the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m /// 0 ≤ eval out1 < m /// pub fn fromMontgomery(out1: *NonMontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[0]); var x2: u64 = undefined; var x3: u64 = undefined; mulxU64(&x2, &x3, x1, 0xffffffff00000001); var x4: u64 = undefined; var x5: u64 = undefined; mulxU64(&x4, &x5, x1, 0xffffffff); var x6: u64 = undefined; var x7: u64 = undefined; mulxU64(&x6, &x7, x1, 0xffffffffffffffff); var x8: u64 = undefined; var x9: u1 = undefined; addcarryxU64(&x8, &x9, 0x0, x7, x4); var x10: u64 = undefined; var x11: u1 = undefined; addcarryxU64(&x10, &x11, 0x0, x1, x6); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, x11, @as(u64, 0x0), x8); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, 0x0, x12, (arg1[1])); var x16: u64 = undefined; var x17: u64 = undefined; mulxU64(&x16, &x17, x14, 0xffffffff00000001); var x18: u64 = undefined; var x19: u64 = undefined; mulxU64(&x18, &x19, x14, 0xffffffff); var x20: u64 = undefined; var x21: u64 = undefined; mulxU64(&x20, &x21, x14, 0xffffffffffffffff); var x22: u64 = undefined; var x23: u1 = undefined; addcarryxU64(&x22, &x23, 0x0, x21, x18); var x24: u64 = undefined; var x25: u1 = undefined; addcarryxU64(&x24, &x25, 0x0, x14, x20); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, x25, (@as(u64, x15) + (@as(u64, x13) + (@as(u64, x9) + x5))), x22); var x28: u64 = undefined; var x29: u1 = undefined; addcarryxU64(&x28, &x29, x27, x2, (@as(u64, x23) + x19)); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, x29, x3, x16); var x32: u64 = undefined; var x33: u1 = undefined; addcarryxU64(&x32, &x33, 0x0, x26, (arg1[2])); var x34: u64 = undefined; var x35: u1 = undefined; addcarryxU64(&x34, &x35, x33, x28, @as(u64, 0x0)); var x36: u64 = undefined; var x37: u1 = undefined; addcarryxU64(&x36, &x37, x35, x30, @as(u64, 0x0)); var x38: u64 = undefined; var x39: u64 = undefined; mulxU64(&x38, &x39, x32, 0xffffffff00000001); var x40: u64 = undefined; var x41: u64 = undefined; mulxU64(&x40, &x41, x32, 0xffffffff); var x42: u64 = undefined; var x43: u64 = undefined; mulxU64(&x42, &x43, x32, 0xffffffffffffffff); var x44: u64 = undefined; var x45: u1 = undefined; addcarryxU64(&x44, &x45, 0x0, x43, x40); var x46: u64 = undefined; var x47: u1 = undefined; addcarryxU64(&x46, &x47, 0x0, x32, x42); var x48: u64 = undefined; var x49: u1 = undefined; addcarryxU64(&x48, &x49, x47, x34, x44); var x50: u64 = undefined; var x51: u1 = undefined; addcarryxU64(&x50, &x51, x49, x36, (@as(u64, x45) + x41)); var x52: u64 = undefined; var x53: u1 = undefined; addcarryxU64(&x52, &x53, x51, (@as(u64, x37) + (@as(u64, x31) + x17)), x38); var x54: u64 = undefined; var x55: u1 = undefined; addcarryxU64(&x54, &x55, 0x0, x48, (arg1[3])); var x56: u64 = undefined; var x57: u1 = undefined; addcarryxU64(&x56, &x57, x55, x50, @as(u64, 0x0)); var x58: u64 = undefined; var x59: u1 = undefined; addcarryxU64(&x58, &x59, x57, x52, @as(u64, 0x0)); var x60: u64 = undefined; var x61: u64 = undefined; mulxU64(&x60, &x61, x54, 0xffffffff00000001); var x62: u64 = undefined; var x63: u64 = undefined; mulxU64(&x62, &x63, x54, 0xffffffff); var x64: u64 = undefined; var x65: u64 = undefined; mulxU64(&x64, &x65, x54, 0xffffffffffffffff); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, 0x0, x65, x62); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, 0x0, x54, x64); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, x69, x56, x66); var x72: u64 = undefined; var x73: u1 = undefined; addcarryxU64(&x72, &x73, x71, x58, (@as(u64, x67) + x63)); var x74: u64 = undefined; var x75: u1 = undefined; addcarryxU64(&x74, &x75, x73, (@as(u64, x59) + (@as(u64, x53) + x39)), x60); const x76 = (@as(u64, x75) + x61); var x77: u64 = undefined; var x78: u1 = undefined; subborrowxU64(&x77, &x78, 0x0, x70, 0xffffffffffffffff); var x79: u64 = undefined; var x80: u1 = undefined; subborrowxU64(&x79, &x80, x78, x72, 0xffffffff); var x81: u64 = undefined; var x82: u1 = undefined; subborrowxU64(&x81, &x82, x80, x74, @as(u64, 0x0)); var x83: u64 = undefined; var x84: u1 = undefined; subborrowxU64(&x83, &x84, x82, x76, 0xffffffff00000001); var x85: u64 = undefined; var x86: u1 = undefined; subborrowxU64(&x85, &x86, x84, @as(u64, 0x0), @as(u64, 0x0)); var x87: u64 = undefined; cmovznzU64(&x87, x86, x77, x70); var x88: u64 = undefined; cmovznzU64(&x88, x86, x79, x72); var x89: u64 = undefined; cmovznzU64(&x89, x86, x81, x74); var x90: u64 = undefined; cmovznzU64(&x90, x86, x83, x76); out1[0] = x87; out1[1] = x88; out1[2] = x89; out1[3] = x90; } /// The function toMontgomery translates a field element into the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = eval arg1 mod m /// 0 ≤ eval out1 < m /// pub fn toMontgomery(out1: *MontgomeryDomainFieldElement, arg1: NonMontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[0]); var x5: u64 = undefined; var x6: u64 = undefined; mulxU64(&x5, &x6, x4, 0x4fffffffd); var x7: u64 = undefined; var x8: u64 = undefined; mulxU64(&x7, &x8, x4, 0xfffffffffffffffe); var x9: u64 = undefined; var x10: u64 = undefined; mulxU64(&x9, &x10, x4, 0xfffffffbffffffff); var x11: u64 = undefined; var x12: u64 = undefined; mulxU64(&x11, &x12, x4, 0x3); var x13: u64 = undefined; var x14: u1 = undefined; addcarryxU64(&x13, &x14, 0x0, x12, x9); var x15: u64 = undefined; var x16: u1 = undefined; addcarryxU64(&x15, &x16, x14, x10, x7); var x17: u64 = undefined; var x18: u1 = undefined; addcarryxU64(&x17, &x18, x16, x8, x5); var x19: u64 = undefined; var x20: u64 = undefined; mulxU64(&x19, &x20, x11, 0xffffffff00000001); var x21: u64 = undefined; var x22: u64 = undefined; mulxU64(&x21, &x22, x11, 0xffffffff); var x23: u64 = undefined; var x24: u64 = undefined; mulxU64(&x23, &x24, x11, 0xffffffffffffffff); var x25: u64 = undefined; var x26: u1 = undefined; addcarryxU64(&x25, &x26, 0x0, x24, x21); var x27: u64 = undefined; var x28: u1 = undefined; addcarryxU64(&x27, &x28, 0x0, x11, x23); var x29: u64 = undefined; var x30: u1 = undefined; addcarryxU64(&x29, &x30, x28, x13, x25); var x31: u64 = undefined; var x32: u1 = undefined; addcarryxU64(&x31, &x32, x30, x15, (@as(u64, x26) + x22)); var x33: u64 = undefined; var x34: u1 = undefined; addcarryxU64(&x33, &x34, x32, x17, x19); var x35: u64 = undefined; var x36: u1 = undefined; addcarryxU64(&x35, &x36, x34, (@as(u64, x18) + x6), x20); var x37: u64 = undefined; var x38: u64 = undefined; mulxU64(&x37, &x38, x1, 0x4fffffffd); var x39: u64 = undefined; var x40: u64 = undefined; mulxU64(&x39, &x40, x1, 0xfffffffffffffffe); var x41: u64 = undefined; var x42: u64 = undefined; mulxU64(&x41, &x42, x1, 0xfffffffbffffffff); var x43: u64 = undefined; var x44: u64 = undefined; mulxU64(&x43, &x44, x1, 0x3); var x45: u64 = undefined; var x46: u1 = undefined; addcarryxU64(&x45, &x46, 0x0, x44, x41); var x47: u64 = undefined; var x48: u1 = undefined; addcarryxU64(&x47, &x48, x46, x42, x39); var x49: u64 = undefined; var x50: u1 = undefined; addcarryxU64(&x49, &x50, x48, x40, x37); var x51: u64 = undefined; var x52: u1 = undefined; addcarryxU64(&x51, &x52, 0x0, x29, x43); var x53: u64 = undefined; var x54: u1 = undefined; addcarryxU64(&x53, &x54, x52, x31, x45); var x55: u64 = undefined; var x56: u1 = undefined; addcarryxU64(&x55, &x56, x54, x33, x47); var x57: u64 = undefined; var x58: u1 = undefined; addcarryxU64(&x57, &x58, x56, x35, x49); var x59: u64 = undefined; var x60: u64 = undefined; mulxU64(&x59, &x60, x51, 0xffffffff00000001); var x61: u64 = undefined; var x62: u64 = undefined; mulxU64(&x61, &x62, x51, 0xffffffff); var x63: u64 = undefined; var x64: u64 = undefined; mulxU64(&x63, &x64, x51, 0xffffffffffffffff); var x65: u64 = undefined; var x66: u1 = undefined; addcarryxU64(&x65, &x66, 0x0, x64, x61); var x67: u64 = undefined; var x68: u1 = undefined; addcarryxU64(&x67, &x68, 0x0, x51, x63); var x69: u64 = undefined; var x70: u1 = undefined; addcarryxU64(&x69, &x70, x68, x53, x65); var x71: u64 = undefined; var x72: u1 = undefined; addcarryxU64(&x71, &x72, x70, x55, (@as(u64, x66) + x62)); var x73: u64 = undefined; var x74: u1 = undefined; addcarryxU64(&x73, &x74, x72, x57, x59); var x75: u64 = undefined; var x76: u1 = undefined; addcarryxU64(&x75, &x76, x74, ((@as(u64, x58) + @as(u64, x36)) + (@as(u64, x50) + x38)), x60); var x77: u64 = undefined; var x78: u64 = undefined; mulxU64(&x77, &x78, x2, 0x4fffffffd); var x79: u64 = undefined; var x80: u64 = undefined; mulxU64(&x79, &x80, x2, 0xfffffffffffffffe); var x81: u64 = undefined; var x82: u64 = undefined; mulxU64(&x81, &x82, x2, 0xfffffffbffffffff); var x83: u64 = undefined; var x84: u64 = undefined; mulxU64(&x83, &x84, x2, 0x3); var x85: u64 = undefined; var x86: u1 = undefined; addcarryxU64(&x85, &x86, 0x0, x84, x81); var x87: u64 = undefined; var x88: u1 = undefined; addcarryxU64(&x87, &x88, x86, x82, x79); var x89: u64 = undefined; var x90: u1 = undefined; addcarryxU64(&x89, &x90, x88, x80, x77); var x91: u64 = undefined; var x92: u1 = undefined; addcarryxU64(&x91, &x92, 0x0, x69, x83); var x93: u64 = undefined; var x94: u1 = undefined; addcarryxU64(&x93, &x94, x92, x71, x85); var x95: u64 = undefined; var x96: u1 = undefined; addcarryxU64(&x95, &x96, x94, x73, x87); var x97: u64 = undefined; var x98: u1 = undefined; addcarryxU64(&x97, &x98, x96, x75, x89); var x99: u64 = undefined; var x100: u64 = undefined; mulxU64(&x99, &x100, x91, 0xffffffff00000001); var x101: u64 = undefined; var x102: u64 = undefined; mulxU64(&x101, &x102, x91, 0xffffffff); var x103: u64 = undefined; var x104: u64 = undefined; mulxU64(&x103, &x104, x91, 0xffffffffffffffff); var x105: u64 = undefined; var x106: u1 = undefined; addcarryxU64(&x105, &x106, 0x0, x104, x101); var x107: u64 = undefined; var x108: u1 = undefined; addcarryxU64(&x107, &x108, 0x0, x91, x103); var x109: u64 = undefined; var x110: u1 = undefined; addcarryxU64(&x109, &x110, x108, x93, x105); var x111: u64 = undefined; var x112: u1 = undefined; addcarryxU64(&x111, &x112, x110, x95, (@as(u64, x106) + x102)); var x113: u64 = undefined; var x114: u1 = undefined; addcarryxU64(&x113, &x114, x112, x97, x99); var x115: u64 = undefined; var x116: u1 = undefined; addcarryxU64(&x115, &x116, x114, ((@as(u64, x98) + @as(u64, x76)) + (@as(u64, x90) + x78)), x100); var x117: u64 = undefined; var x118: u64 = undefined; mulxU64(&x117, &x118, x3, 0x4fffffffd); var x119: u64 = undefined; var x120: u64 = undefined; mulxU64(&x119, &x120, x3, 0xfffffffffffffffe); var x121: u64 = undefined; var x122: u64 = undefined; mulxU64(&x121, &x122, x3, 0xfffffffbffffffff); var x123: u64 = undefined; var x124: u64 = undefined; mulxU64(&x123, &x124, x3, 0x3); var x125: u64 = undefined; var x126: u1 = undefined; addcarryxU64(&x125, &x126, 0x0, x124, x121); var x127: u64 = undefined; var x128: u1 = undefined; addcarryxU64(&x127, &x128, x126, x122, x119); var x129: u64 = undefined; var x130: u1 = undefined; addcarryxU64(&x129, &x130, x128, x120, x117); var x131: u64 = undefined; var x132: u1 = undefined; addcarryxU64(&x131, &x132, 0x0, x109, x123); var x133: u64 = undefined; var x134: u1 = undefined; addcarryxU64(&x133, &x134, x132, x111, x125); var x135: u64 = undefined; var x136: u1 = undefined; addcarryxU64(&x135, &x136, x134, x113, x127); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, x136, x115, x129); var x139: u64 = undefined; var x140: u64 = undefined; mulxU64(&x139, &x140, x131, 0xffffffff00000001); var x141: u64 = undefined; var x142: u64 = undefined; mulxU64(&x141, &x142, x131, 0xffffffff); var x143: u64 = undefined; var x144: u64 = undefined; mulxU64(&x143, &x144, x131, 0xffffffffffffffff); var x145: u64 = undefined; var x146: u1 = undefined; addcarryxU64(&x145, &x146, 0x0, x144, x141); var x147: u64 = undefined; var x148: u1 = undefined; addcarryxU64(&x147, &x148, 0x0, x131, x143); var x149: u64 = undefined; var x150: u1 = undefined; addcarryxU64(&x149, &x150, x148, x133, x145); var x151: u64 = undefined; var x152: u1 = undefined; addcarryxU64(&x151, &x152, x150, x135, (@as(u64, x146) + x142)); var x153: u64 = undefined; var x154: u1 = undefined; addcarryxU64(&x153, &x154, x152, x137, x139); var x155: u64 = undefined; var x156: u1 = undefined; addcarryxU64(&x155, &x156, x154, ((@as(u64, x138) + @as(u64, x116)) + (@as(u64, x130) + x118)), x140); var x157: u64 = undefined; var x158: u1 = undefined; subborrowxU64(&x157, &x158, 0x0, x149, 0xffffffffffffffff); var x159: u64 = undefined; var x160: u1 = undefined; subborrowxU64(&x159, &x160, x158, x151, 0xffffffff); var x161: u64 = undefined; var x162: u1 = undefined; subborrowxU64(&x161, &x162, x160, x153, @as(u64, 0x0)); var x163: u64 = undefined; var x164: u1 = undefined; subborrowxU64(&x163, &x164, x162, x155, 0xffffffff00000001); var x165: u64 = undefined; var x166: u1 = undefined; subborrowxU64(&x165, &x166, x164, @as(u64, x156), @as(u64, 0x0)); var x167: u64 = undefined; cmovznzU64(&x167, x166, x157, x149); var x168: u64 = undefined; cmovznzU64(&x168, x166, x159, x151); var x169: u64 = undefined; cmovznzU64(&x169, x166, x161, x153); var x170: u64 = undefined; cmovznzU64(&x170, x166, x163, x155); out1[0] = x167; out1[1] = x168; out1[2] = x169; out1[3] = x170; } /// The function nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] pub fn nonzero(out1: *u64, arg1: [4]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | (arg1[3])))); out1.* = x1; } /// The function selectznz is a multi-limb conditional select. /// /// Postconditions: /// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn selectznz(out1: *[4]u64, arg1: u1, arg2: [4]u64, arg3: [4]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; cmovznzU64(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u64 = undefined; cmovznzU64(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u64 = undefined; cmovznzU64(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u64 = undefined; cmovznzU64(&x4, arg1, (arg2[3]), (arg3[3])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; } /// The function toBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] pub fn toBytes(out1: *[32]u8, arg1: [4]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[3]); const x2 = (arg1[2]); const x3 = (arg1[1]); const x4 = (arg1[0]); const x5 = @as(u8, @truncate((x4 & @as(u64, 0xff)))); const x6 = (x4 >> 8); const x7 = @as(u8, @truncate((x6 & @as(u64, 0xff)))); const x8 = (x6 >> 8); const x9 = @as(u8, @truncate((x8 & @as(u64, 0xff)))); const x10 = (x8 >> 8); const x11 = @as(u8, @truncate((x10 & @as(u64, 0xff)))); const x12 = (x10 >> 8); const x13 = @as(u8, @truncate((x12 & @as(u64, 0xff)))); const x14 = (x12 >> 8); const x15 = @as(u8, @truncate((x14 & @as(u64, 0xff)))); const x16 = (x14 >> 8); const x17 = @as(u8, @truncate((x16 & @as(u64, 0xff)))); const x18 = @as(u8, @truncate((x16 >> 8))); const x19 = @as(u8, @truncate((x3 & @as(u64, 0xff)))); const x20 = (x3 >> 8); const x21 = @as(u8, @truncate((x20 & @as(u64, 0xff)))); const x22 = (x20 >> 8); const x23 = @as(u8, @truncate((x22 & @as(u64, 0xff)))); const x24 = (x22 >> 8); const x25 = @as(u8, @truncate((x24 & @as(u64, 0xff)))); const x26 = (x24 >> 8); const x27 = @as(u8, @truncate((x26 & @as(u64, 0xff)))); const x28 = (x26 >> 8); const x29 = @as(u8, @truncate((x28 & @as(u64, 0xff)))); const x30 = (x28 >> 8); const x31 = @as(u8, @truncate((x30 & @as(u64, 0xff)))); const x32 = @as(u8, @truncate((x30 >> 8))); const x33 = @as(u8, @truncate((x2 & @as(u64, 0xff)))); const x34 = (x2 >> 8); const x35 = @as(u8, @truncate((x34 & @as(u64, 0xff)))); const x36 = (x34 >> 8); const x37 = @as(u8, @truncate((x36 & @as(u64, 0xff)))); const x38 = (x36 >> 8); const x39 = @as(u8, @truncate((x38 & @as(u64, 0xff)))); const x40 = (x38 >> 8); const x41 = @as(u8, @truncate((x40 & @as(u64, 0xff)))); const x42 = (x40 >> 8); const x43 = @as(u8, @truncate((x42 & @as(u64, 0xff)))); const x44 = (x42 >> 8); const x45 = @as(u8, @truncate((x44 & @as(u64, 0xff)))); const x46 = @as(u8, @truncate((x44 >> 8))); const x47 = @as(u8, @truncate((x1 & @as(u64, 0xff)))); const x48 = (x1 >> 8); const x49 = @as(u8, @truncate((x48 & @as(u64, 0xff)))); const x50 = (x48 >> 8); const x51 = @as(u8, @truncate((x50 & @as(u64, 0xff)))); const x52 = (x50 >> 8); const x53 = @as(u8, @truncate((x52 & @as(u64, 0xff)))); const x54 = (x52 >> 8); const x55 = @as(u8, @truncate((x54 & @as(u64, 0xff)))); const x56 = (x54 >> 8); const x57 = @as(u8, @truncate((x56 & @as(u64, 0xff)))); const x58 = (x56 >> 8); const x59 = @as(u8, @truncate((x58 & @as(u64, 0xff)))); const x60 = @as(u8, @truncate((x58 >> 8))); out1[0] = x5; out1[1] = x7; out1[2] = x9; out1[3] = x11; out1[4] = x13; out1[5] = x15; out1[6] = x17; out1[7] = x18; out1[8] = x19; out1[9] = x21; out1[10] = x23; out1[11] = x25; out1[12] = x27; out1[13] = x29; out1[14] = x31; out1[15] = x32; out1[16] = x33; out1[17] = x35; out1[18] = x37; out1[19] = x39; out1[20] = x41; out1[21] = x43; out1[22] = x45; out1[23] = x46; out1[24] = x47; out1[25] = x49; out1[26] = x51; out1[27] = x53; out1[28] = x55; out1[29] = x57; out1[30] = x59; out1[31] = x60; } /// The function fromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. /// /// Preconditions: /// 0 ≤ bytes_eval arg1 < m /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn fromBytes(out1: *[4]u64, arg1: [32]u8) void { @setRuntimeSafety(mode == .Debug); const x1 = (@as(u64, (arg1[31])) << 56); const x2 = (@as(u64, (arg1[30])) << 48); const x3 = (@as(u64, (arg1[29])) << 40); const x4 = (@as(u64, (arg1[28])) << 32); const x5 = (@as(u64, (arg1[27])) << 24); const x6 = (@as(u64, (arg1[26])) << 16); const x7 = (@as(u64, (arg1[25])) << 8); const x8 = (arg1[24]); const x9 = (@as(u64, (arg1[23])) << 56); const x10 = (@as(u64, (arg1[22])) << 48); const x11 = (@as(u64, (arg1[21])) << 40); const x12 = (@as(u64, (arg1[20])) << 32); const x13 = (@as(u64, (arg1[19])) << 24); const x14 = (@as(u64, (arg1[18])) << 16); const x15 = (@as(u64, (arg1[17])) << 8); const x16 = (arg1[16]); const x17 = (@as(u64, (arg1[15])) << 56); const x18 = (@as(u64, (arg1[14])) << 48); const x19 = (@as(u64, (arg1[13])) << 40); const x20 = (@as(u64, (arg1[12])) << 32); const x21 = (@as(u64, (arg1[11])) << 24); const x22 = (@as(u64, (arg1[10])) << 16); const x23 = (@as(u64, (arg1[9])) << 8); const x24 = (arg1[8]); const x25 = (@as(u64, (arg1[7])) << 56); const x26 = (@as(u64, (arg1[6])) << 48); const x27 = (@as(u64, (arg1[5])) << 40); const x28 = (@as(u64, (arg1[4])) << 32); const x29 = (@as(u64, (arg1[3])) << 24); const x30 = (@as(u64, (arg1[2])) << 16); const x31 = (@as(u64, (arg1[1])) << 8); const x32 = (arg1[0]); const x33 = (x31 + @as(u64, x32)); const x34 = (x30 + x33); const x35 = (x29 + x34); const x36 = (x28 + x35); const x37 = (x27 + x36); const x38 = (x26 + x37); const x39 = (x25 + x38); const x40 = (x23 + @as(u64, x24)); const x41 = (x22 + x40); const x42 = (x21 + x41); const x43 = (x20 + x42); const x44 = (x19 + x43); const x45 = (x18 + x44); const x46 = (x17 + x45); const x47 = (x15 + @as(u64, x16)); const x48 = (x14 + x47); const x49 = (x13 + x48); const x50 = (x12 + x49); const x51 = (x11 + x50); const x52 = (x10 + x51); const x53 = (x9 + x52); const x54 = (x7 + @as(u64, x8)); const x55 = (x6 + x54); const x56 = (x5 + x55); const x57 = (x4 + x56); const x58 = (x3 + x57); const x59 = (x2 + x58); const x60 = (x1 + x59); out1[0] = x39; out1[1] = x46; out1[2] = x53; out1[3] = x60; } /// The function setOne returns the field element one in the Montgomery domain. /// /// Postconditions: /// eval (from_montgomery out1) mod m = 1 mod m /// 0 ≤ eval out1 < m /// pub fn setOne(out1: *MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); out1[0] = @as(u64, 0x1); out1[1] = 0xffffffff00000000; out1[2] = 0xffffffffffffffff; out1[3] = 0xfffffffe; } /// The function msat returns the saturated representation of the prime modulus. /// /// Postconditions: /// twos_complement_eval out1 = m /// 0 ≤ eval out1 < m /// /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn msat(out1: *[5]u64) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0xffffffffffffffff; out1[1] = 0xffffffff; out1[2] = @as(u64, 0x0); out1[3] = 0xffffffff00000001; out1[4] = @as(u64, 0x0); } /// The function divstep computes a divstep. /// /// Preconditions: /// 0 ≤ eval arg4 < m /// 0 ≤ eval arg5 < m /// Postconditions: /// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) /// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) /// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) /// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) /// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) /// 0 ≤ eval out5 < m /// 0 ≤ eval out5 < m /// 0 ≤ eval out2 < m /// 0 ≤ eval out3 < m /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn divstep(out1: *u64, out2: *[5]u64, out3: *[5]u64, out4: *[4]u64, out5: *[4]u64, arg1: u64, arg2: [5]u64, arg3: [5]u64, arg4: [4]u64, arg5: [4]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; addcarryxU64(&x1, &x2, 0x0, (~arg1), @as(u64, 0x1)); const x3 = (@as(u1, @truncate((x1 >> 63))) & @as(u1, @truncate(((arg3[0]) & @as(u64, 0x1))))); var x4: u64 = undefined; var x5: u1 = undefined; addcarryxU64(&x4, &x5, 0x0, (~arg1), @as(u64, 0x1)); var x6: u64 = undefined; cmovznzU64(&x6, x3, arg1, x4); var x7: u64 = undefined; cmovznzU64(&x7, x3, (arg2[0]), (arg3[0])); var x8: u64 = undefined; cmovznzU64(&x8, x3, (arg2[1]), (arg3[1])); var x9: u64 = undefined; cmovznzU64(&x9, x3, (arg2[2]), (arg3[2])); var x10: u64 = undefined; cmovznzU64(&x10, x3, (arg2[3]), (arg3[3])); var x11: u64 = undefined; cmovznzU64(&x11, x3, (arg2[4]), (arg3[4])); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU64(&x12, &x13, 0x0, @as(u64, 0x1), (~(arg2[0]))); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU64(&x14, &x15, x13, @as(u64, 0x0), (~(arg2[1]))); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, x15, @as(u64, 0x0), (~(arg2[2]))); var x18: u64 = undefined; var x19: u1 = undefined; addcarryxU64(&x18, &x19, x17, @as(u64, 0x0), (~(arg2[3]))); var x20: u64 = undefined; var x21: u1 = undefined; addcarryxU64(&x20, &x21, x19, @as(u64, 0x0), (~(arg2[4]))); var x22: u64 = undefined; cmovznzU64(&x22, x3, (arg3[0]), x12); var x23: u64 = undefined; cmovznzU64(&x23, x3, (arg3[1]), x14); var x24: u64 = undefined; cmovznzU64(&x24, x3, (arg3[2]), x16); var x25: u64 = undefined; cmovznzU64(&x25, x3, (arg3[3]), x18); var x26: u64 = undefined; cmovznzU64(&x26, x3, (arg3[4]), x20); var x27: u64 = undefined; cmovznzU64(&x27, x3, (arg4[0]), (arg5[0])); var x28: u64 = undefined; cmovznzU64(&x28, x3, (arg4[1]), (arg5[1])); var x29: u64 = undefined; cmovznzU64(&x29, x3, (arg4[2]), (arg5[2])); var x30: u64 = undefined; cmovznzU64(&x30, x3, (arg4[3]), (arg5[3])); var x31: u64 = undefined; var x32: u1 = undefined; addcarryxU64(&x31, &x32, 0x0, x27, x27); var x33: u64 = undefined; var x34: u1 = undefined; addcarryxU64(&x33, &x34, x32, x28, x28); var x35: u64 = undefined; var x36: u1 = undefined; addcarryxU64(&x35, &x36, x34, x29, x29); var x37: u64 = undefined; var x38: u1 = undefined; addcarryxU64(&x37, &x38, x36, x30, x30); var x39: u64 = undefined; var x40: u1 = undefined; subborrowxU64(&x39, &x40, 0x0, x31, 0xffffffffffffffff); var x41: u64 = undefined; var x42: u1 = undefined; subborrowxU64(&x41, &x42, x40, x33, 0xffffffff); var x43: u64 = undefined; var x44: u1 = undefined; subborrowxU64(&x43, &x44, x42, x35, @as(u64, 0x0)); var x45: u64 = undefined; var x46: u1 = undefined; subborrowxU64(&x45, &x46, x44, x37, 0xffffffff00000001); var x47: u64 = undefined; var x48: u1 = undefined; subborrowxU64(&x47, &x48, x46, @as(u64, x38), @as(u64, 0x0)); const x49 = (arg4[3]); const x50 = (arg4[2]); const x51 = (arg4[1]); const x52 = (arg4[0]); var x53: u64 = undefined; var x54: u1 = undefined; subborrowxU64(&x53, &x54, 0x0, @as(u64, 0x0), x52); var x55: u64 = undefined; var x56: u1 = undefined; subborrowxU64(&x55, &x56, x54, @as(u64, 0x0), x51); var x57: u64 = undefined; var x58: u1 = undefined; subborrowxU64(&x57, &x58, x56, @as(u64, 0x0), x50); var x59: u64 = undefined; var x60: u1 = undefined; subborrowxU64(&x59, &x60, x58, @as(u64, 0x0), x49); var x61: u64 = undefined; cmovznzU64(&x61, x60, @as(u64, 0x0), 0xffffffffffffffff); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, 0x0, x53, x61); var x64: u64 = undefined; var x65: u1 = undefined; addcarryxU64(&x64, &x65, x63, x55, (x61 & 0xffffffff)); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, x65, x57, @as(u64, 0x0)); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, x67, x59, (x61 & 0xffffffff00000001)); var x70: u64 = undefined; cmovznzU64(&x70, x3, (arg5[0]), x62); var x71: u64 = undefined; cmovznzU64(&x71, x3, (arg5[1]), x64); var x72: u64 = undefined; cmovznzU64(&x72, x3, (arg5[2]), x66); var x73: u64 = undefined; cmovznzU64(&x73, x3, (arg5[3]), x68); const x74 = @as(u1, @truncate((x22 & @as(u64, 0x1)))); var x75: u64 = undefined; cmovznzU64(&x75, x74, @as(u64, 0x0), x7); var x76: u64 = undefined; cmovznzU64(&x76, x74, @as(u64, 0x0), x8); var x77: u64 = undefined; cmovznzU64(&x77, x74, @as(u64, 0x0), x9); var x78: u64 = undefined; cmovznzU64(&x78, x74, @as(u64, 0x0), x10); var x79: u64 = undefined; cmovznzU64(&x79, x74, @as(u64, 0x0), x11); var x80: u64 = undefined; var x81: u1 = undefined; addcarryxU64(&x80, &x81, 0x0, x22, x75); var x82: u64 = undefined; var x83: u1 = undefined; addcarryxU64(&x82, &x83, x81, x23, x76); var x84: u64 = undefined; var x85: u1 = undefined; addcarryxU64(&x84, &x85, x83, x24, x77); var x86: u64 = undefined; var x87: u1 = undefined; addcarryxU64(&x86, &x87, x85, x25, x78); var x88: u64 = undefined; var x89: u1 = undefined; addcarryxU64(&x88, &x89, x87, x26, x79); var x90: u64 = undefined; cmovznzU64(&x90, x74, @as(u64, 0x0), x27); var x91: u64 = undefined; cmovznzU64(&x91, x74, @as(u64, 0x0), x28); var x92: u64 = undefined; cmovznzU64(&x92, x74, @as(u64, 0x0), x29); var x93: u64 = undefined; cmovznzU64(&x93, x74, @as(u64, 0x0), x30); var x94: u64 = undefined; var x95: u1 = undefined; addcarryxU64(&x94, &x95, 0x0, x70, x90); var x96: u64 = undefined; var x97: u1 = undefined; addcarryxU64(&x96, &x97, x95, x71, x91); var x98: u64 = undefined; var x99: u1 = undefined; addcarryxU64(&x98, &x99, x97, x72, x92); var x100: u64 = undefined; var x101: u1 = undefined; addcarryxU64(&x100, &x101, x99, x73, x93); var x102: u64 = undefined; var x103: u1 = undefined; subborrowxU64(&x102, &x103, 0x0, x94, 0xffffffffffffffff); var x104: u64 = undefined; var x105: u1 = undefined; subborrowxU64(&x104, &x105, x103, x96, 0xffffffff); var x106: u64 = undefined; var x107: u1 = undefined; subborrowxU64(&x106, &x107, x105, x98, @as(u64, 0x0)); var x108: u64 = undefined; var x109: u1 = undefined; subborrowxU64(&x108, &x109, x107, x100, 0xffffffff00000001); var x110: u64 = undefined; var x111: u1 = undefined; subborrowxU64(&x110, &x111, x109, @as(u64, x101), @as(u64, 0x0)); var x112: u64 = undefined; var x113: u1 = undefined; addcarryxU64(&x112, &x113, 0x0, x6, @as(u64, 0x1)); const x114 = ((x80 >> 1) | ((x82 << 63) & 0xffffffffffffffff)); const x115 = ((x82 >> 1) | ((x84 << 63) & 0xffffffffffffffff)); const x116 = ((x84 >> 1) | ((x86 << 63) & 0xffffffffffffffff)); const x117 = ((x86 >> 1) | ((x88 << 63) & 0xffffffffffffffff)); const x118 = ((x88 & 0x8000000000000000) | (x88 >> 1)); var x119: u64 = undefined; cmovznzU64(&x119, x48, x39, x31); var x120: u64 = undefined; cmovznzU64(&x120, x48, x41, x33); var x121: u64 = undefined; cmovznzU64(&x121, x48, x43, x35); var x122: u64 = undefined; cmovznzU64(&x122, x48, x45, x37); var x123: u64 = undefined; cmovznzU64(&x123, x111, x102, x94); var x124: u64 = undefined; cmovznzU64(&x124, x111, x104, x96); var x125: u64 = undefined; cmovznzU64(&x125, x111, x106, x98); var x126: u64 = undefined; cmovznzU64(&x126, x111, x108, x100); out1.* = x112; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out3[0] = x114; out3[1] = x115; out3[2] = x116; out3[3] = x117; out3[4] = x118; out4[0] = x119; out4[1] = x120; out4[2] = x121; out4[3] = x122; out5[0] = x123; out5[1] = x124; out5[2] = x125; out5[3] = x126; } /// The function divstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). /// /// Postconditions: /// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if ⌊log2 m⌋ + 1 < 46 then ⌊(49 * (⌊log2 m⌋ + 1) + 80) / 17⌋ else ⌊(49 * (⌊log2 m⌋ + 1) + 57) / 17⌋) /// 0 ≤ eval out1 < m /// /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn divstepPrecomp(out1: *[4]u64) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0x67ffffffb8000000; out1[1] = 0xc000000038000000; out1[2] = 0xd80000007fffffff; out1[3] = 0x2fffffffffffffff; }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/pcurves/p256/scalar.zig
const std = @import("std"); const common = @import("../common.zig"); const crypto = std.crypto; const debug = std.debug; const math = std.math; const mem = std.mem; const Field = common.Field; const NonCanonicalError = std.crypto.errors.NonCanonicalError; const NotSquareError = std.crypto.errors.NotSquareError; /// Number of bytes required to encode a scalar. pub const encoded_length = 32; /// A compressed scalar, in canonical form. pub const CompressedScalar = [encoded_length]u8; const Fe = Field(.{ .fiat = @import("p256_scalar_64.zig"), .field_order = 115792089210356248762697446949407573529996955224135760342422259061068512044369, .field_bits = 256, .saturated_bits = 255, .encoded_length = encoded_length, }); /// Reject a scalar whose encoding is not canonical. pub fn rejectNonCanonical(s: CompressedScalar, endian: std.builtin.Endian) NonCanonicalError!void { return Fe.rejectNonCanonical(s, endian); } /// Reduce a 48-bytes scalar to the field size. pub fn reduce48(s: [48]u8, endian: std.builtin.Endian) CompressedScalar { return Scalar.fromBytes48(s, endian).toBytes(endian); } /// Reduce a 64-bytes scalar to the field size. pub fn reduce64(s: [64]u8, endian: std.builtin.Endian) CompressedScalar { return ScalarDouble.fromBytes64(s, endian).toBytes(endian); } /// Return a*b (mod L) pub fn mul(a: CompressedScalar, b: CompressedScalar, endian: std.builtin.Endian) NonCanonicalError!CompressedScalar { return (try Scalar.fromBytes(a, endian)).mul(try Scalar.fromBytes(b, endian)).toBytes(endian); } /// Return a*b+c (mod L) pub fn mulAdd(a: CompressedScalar, b: CompressedScalar, c: CompressedScalar, endian: std.builtin.Endian) NonCanonicalError!CompressedScalar { return (try Scalar.fromBytes(a, endian)).mul(try Scalar.fromBytes(b, endian)).add(try Scalar.fromBytes(c, endian)).toBytes(endian); } /// Return a+b (mod L) pub fn add(a: CompressedScalar, b: CompressedScalar, endian: std.builtin.Endian) NonCanonicalError!CompressedScalar { return (try Scalar.fromBytes(a, endian)).add(try Scalar.fromBytes(b, endian)).toBytes(endian); } /// Return -s (mod L) pub fn neg(s: CompressedScalar, endian: std.builtin.Endian) NonCanonicalError!CompressedScalar { return (try Scalar.fromBytes(s, endian)).neg().toBytes(endian); } /// Return (a-b) (mod L) pub fn sub(a: CompressedScalar, b: CompressedScalar, endian: std.builtin.Endian) NonCanonicalError!CompressedScalar { return (try Scalar.fromBytes(a, endian)).sub(try Scalar.fromBytes(b.endian)).toBytes(endian); } /// Return a random scalar pub fn random(endian: std.builtin.Endian) CompressedScalar { return Scalar.random().toBytes(endian); } /// A scalar in unpacked representation. pub const Scalar = struct { fe: Fe, /// Zero. pub const zero = Scalar{ .fe = Fe.zero }; /// One. pub const one = Scalar{ .fe = Fe.one }; /// Unpack a serialized representation of a scalar. pub fn fromBytes(s: CompressedScalar, endian: std.builtin.Endian) NonCanonicalError!Scalar { return Scalar{ .fe = try Fe.fromBytes(s, endian) }; } /// Reduce a 384 bit input to the field size. pub fn fromBytes48(s: [48]u8, endian: std.builtin.Endian) Scalar { const t = ScalarDouble.fromBytes(384, s, endian); return t.reduce(384); } /// Reduce a 512 bit input to the field size. pub fn fromBytes64(s: [64]u8, endian: std.builtin.Endian) Scalar { const t = ScalarDouble.fromBytes(512, s, endian); return t.reduce(512); } /// Pack a scalar into bytes. pub fn toBytes(n: Scalar, endian: std.builtin.Endian) CompressedScalar { return n.fe.toBytes(endian); } /// Return true if the scalar is zero.. pub fn isZero(n: Scalar) bool { return n.fe.isZero(); } /// Return true if a and b are equivalent. pub fn equivalent(a: Scalar, b: Scalar) bool { return a.fe.equivalent(b.fe); } /// Compute x+y (mod L) pub fn add(x: Scalar, y: Scalar) Scalar { return Scalar{ .fe = x.fe.add(y.fe) }; } /// Compute x-y (mod L) pub fn sub(x: Scalar, y: Scalar) Scalar { return Scalar{ .fe = x.fe.sub(y.fe) }; } /// Compute 2n (mod L) pub fn dbl(n: Scalar) Scalar { return Scalar{ .fe = n.fe.dbl() }; } /// Compute x*y (mod L) pub fn mul(x: Scalar, y: Scalar) Scalar { return Scalar{ .fe = x.fe.mul(y.fe) }; } /// Compute x^2 (mod L) pub fn sq(n: Scalar) Scalar { return Scalar{ .fe = n.fe.sq() }; } /// Compute x^n (mod L) pub fn pow(a: Scalar, comptime T: type, comptime n: T) Scalar { return Scalar{ .fe = a.fe.pow(n) }; } /// Compute -x (mod L) pub fn neg(n: Scalar) Scalar { return Scalar{ .fe = n.fe.neg() }; } /// Compute x^-1 (mod L) pub fn invert(n: Scalar) Scalar { return Scalar{ .fe = n.fe.invert() }; } /// Return true if n is a quadratic residue mod L. pub fn isSquare(n: Scalar) Scalar { return n.fe.isSquare(); } /// Return the square root of L, or NotSquare if there isn't any solutions. pub fn sqrt(n: Scalar) NotSquareError!Scalar { return Scalar{ .fe = try n.fe.sqrt() }; } /// Return a random scalar < L. pub fn random() Scalar { var s: [48]u8 = undefined; while (true) { crypto.random.bytes(&s); const n = Scalar.fromBytes48(s, .Little); if (!n.isZero()) { return n; } } } }; const ScalarDouble = struct { x1: Fe, x2: Fe, x3: Fe, fn fromBytes(comptime bits: usize, s_: [bits / 8]u8, endian: std.builtin.Endian) ScalarDouble { debug.assert(bits > 0 and bits <= 512 and bits >= Fe.saturated_bits and bits <= Fe.saturated_bits * 3); var s = s_; if (endian == .Big) { for (s_, 0..) |x, i| s[s.len - 1 - i] = x; } var t = ScalarDouble{ .x1 = undefined, .x2 = Fe.zero, .x3 = Fe.zero }; { var b = [_]u8{0} ** encoded_length; const len = math.min(s.len, 24); mem.copy(u8, b[0..len], s[0..len]); t.x1 = Fe.fromBytes(b, .Little) catch unreachable; } if (s_.len >= 24) { var b = [_]u8{0} ** encoded_length; const len = math.min(s.len - 24, 24); mem.copy(u8, b[0..len], s[24..][0..len]); t.x2 = Fe.fromBytes(b, .Little) catch unreachable; } if (s_.len >= 48) { var b = [_]u8{0} ** encoded_length; const len = s.len - 48; mem.copy(u8, b[0..len], s[48..][0..len]); t.x3 = Fe.fromBytes(b, .Little) catch unreachable; } return t; } fn reduce(expanded: ScalarDouble, comptime bits: usize) Scalar { debug.assert(bits > 0 and bits <= Fe.saturated_bits * 3 and bits <= 512); var fe = expanded.x1; if (bits >= 192) { const st1 = Fe.fromInt(1 << 192) catch unreachable; fe = fe.add(expanded.x2.mul(st1)); if (bits >= 384) { const st2 = st1.sq(); fe = fe.add(expanded.x3.mul(st2)); } } return Scalar{ .fe = fe }; } };
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/25519/curve25519.zig
const std = @import("std"); const crypto = std.crypto; const IdentityElementError = crypto.errors.IdentityElementError; const NonCanonicalError = crypto.errors.NonCanonicalError; const WeakPublicKeyError = crypto.errors.WeakPublicKeyError; /// Group operations over Curve25519. pub const Curve25519 = struct { /// The underlying prime field. pub const Fe = @import("field.zig").Fe; /// Field arithmetic mod the order of the main subgroup. pub const scalar = @import("scalar.zig"); x: Fe, /// Decode a Curve25519 point from its compressed (X) coordinates. pub inline fn fromBytes(s: [32]u8) Curve25519 { return .{ .x = Fe.fromBytes(s) }; } /// Encode a Curve25519 point. pub inline fn toBytes(p: Curve25519) [32]u8 { return p.x.toBytes(); } /// The Curve25519 base point. pub const basePoint = Curve25519{ .x = Fe.curve25519BasePoint }; /// Check that the encoding of a Curve25519 point is canonical. pub fn rejectNonCanonical(s: [32]u8) NonCanonicalError!void { return Fe.rejectNonCanonical(s, false); } /// Reject the neutral element. pub fn rejectIdentity(p: Curve25519) IdentityElementError!void { if (p.x.isZero()) { return error.IdentityElement; } } /// Multiply a point by the cofactor pub const clearCofactor = @compileError("TODO what was this function supposed to do? it didn't compile successfully"); fn ladder(p: Curve25519, s: [32]u8, comptime bits: usize) IdentityElementError!Curve25519 { var x1 = p.x; var x2 = Fe.one; var z2 = Fe.zero; var x3 = x1; var z3 = Fe.one; var swap: u8 = 0; var pos: usize = bits - 1; while (true) : (pos -= 1) { const bit = (s[pos >> 3] >> @as(u3, @truncate(pos))) & 1; swap ^= bit; Fe.cSwap2(&x2, &x3, &z2, &z3, swap); swap = bit; const a = x2.add(z2); const b = x2.sub(z2); const aa = a.sq(); const bb = b.sq(); x2 = aa.mul(bb); const e = aa.sub(bb); const da = x3.sub(z3).mul(a); const cb = x3.add(z3).mul(b); x3 = da.add(cb).sq(); z3 = x1.mul(da.sub(cb).sq()); z2 = e.mul(bb.add(e.mul32(121666))); if (pos == 0) break; } Fe.cSwap2(&x2, &x3, &z2, &z3, swap); z2 = z2.invert(); x2 = x2.mul(z2); if (x2.isZero()) { return error.IdentityElement; } return Curve25519{ .x = x2 }; } /// Multiply a Curve25519 point by a scalar after "clamping" it. /// Clamping forces the scalar to be a multiple of the cofactor in /// order to prevent small subgroups attacks. This is the standard /// way to use Curve25519 for a DH operation. /// Return error.IdentityElement if the resulting point is /// the identity element. pub fn clampedMul(p: Curve25519, s: [32]u8) IdentityElementError!Curve25519 { var t: [32]u8 = s; scalar.clamp(&t); return try ladder(p, t, 255); } /// Multiply a Curve25519 point by a scalar without clamping it. /// Return error.IdentityElement if the resulting point is /// the identity element or error.WeakPublicKey if the public /// key is a low-order point. pub fn mul(p: Curve25519, s: [32]u8) (IdentityElementError || WeakPublicKeyError)!Curve25519 { const cofactor = [_]u8{8} ++ [_]u8{0} ** 31; _ = ladder(p, cofactor, 4) catch return error.WeakPublicKey; return try ladder(p, s, 256); } /// Compute the Curve25519 equivalent to an Edwards25519 point. pub fn fromEdwards25519(p: crypto.ecc.Edwards25519) IdentityElementError!Curve25519 { try p.clearCofactor().rejectIdentity(); const one = crypto.ecc.Edwards25519.Fe.one; const x = one.add(p.y).mul(one.sub(p.y).invert()); // xMont=(1+yEd)/(1-yEd) return Curve25519{ .x = x }; } }; test "curve25519" { var s = [32]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 }; 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"); const q = try p.clampedMul(s); try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&q.toBytes())}), "3614E119FFE55EC55B87D6B19971A9F4CBC78EFE80BEC55B96392BABCC712537"); try Curve25519.rejectNonCanonical(s); s[31] |= 0x80; try std.testing.expectError(error.NonCanonical, Curve25519.rejectNonCanonical(s)); } test "curve25519 small order check" { var s: [32]u8 = [_]u8{1} ++ [_]u8{0} ** 31; const small_order_ss: [7][32]u8 = .{ .{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0 (order 4) }, .{ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 1 (order 1) }, .{ 0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, 0x16, 0x56, 0xe3, 0xfa, 0xf1, 0x9f, 0xc4, 0x6a, 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32, 0xb1, 0xfd, 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00, // 325606250916557431795983626356110631294008115727848805560023387167927233504 (order 8) */ }, .{ 0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24, 0xb1, 0xd0, 0xb1, 0x55, 0x9c, 0x83, 0xef, 0x5b, 0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c, 0x8e, 0x86, 0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57, // 39382357235489614581723060781553021112529911719440698176882885853963445705823 (order 8) }, .{ 0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p-1 (order 2) }, .{ 0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p (=0, order 4) }, .{ 0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p+1 (=1, order 1) }, }; for (small_order_ss) |small_order_s| { try std.testing.expectError(error.WeakPublicKey, Curve25519.fromBytes(small_order_s).mul(s)); var extra = small_order_s; extra[31] ^= 0x80; try std.testing.expectError(error.WeakPublicKey, Curve25519.fromBytes(extra).mul(s)); var valid = small_order_s; valid[31] = 0x40; s[0] = 0; try std.testing.expectError(error.IdentityElement, Curve25519.fromBytes(valid).mul(s)); } }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/25519/ristretto255.zig
const std = @import("std"); const fmt = std.fmt; const EncodingError = std.crypto.errors.EncodingError; const IdentityElementError = std.crypto.errors.IdentityElementError; const NonCanonicalError = std.crypto.errors.NonCanonicalError; const WeakPublicKeyError = std.crypto.errors.WeakPublicKeyError; /// Group operations over Edwards25519. pub const Ristretto255 = struct { /// The underlying elliptic curve. pub const Curve = @import("edwards25519.zig").Edwards25519; /// The underlying prime field. pub const Fe = Curve.Fe; /// Field arithmetic mod the order of the main subgroup. pub const scalar = Curve.scalar; /// Length in byte of an encoded element. pub const encoded_length: usize = 32; p: Curve, fn sqrtRatioM1(u: Fe, v: Fe) struct { ratio_is_square: u32, root: Fe } { const v3 = v.sq().mul(v); // v^3 var x = v3.sq().mul(u).mul(v).pow2523().mul(v3).mul(u); // uv^3(uv^7)^((q-5)/8) const vxx = x.sq().mul(v); // vx^2 const m_root_check = vxx.sub(u); // vx^2-u const p_root_check = vxx.add(u); // vx^2+u const f_root_check = u.mul(Fe.sqrtm1).add(vxx); // vx^2+u*sqrt(-1) const has_m_root = m_root_check.isZero(); const has_p_root = p_root_check.isZero(); const has_f_root = f_root_check.isZero(); const x_sqrtm1 = x.mul(Fe.sqrtm1); // x*sqrt(-1) x.cMov(x_sqrtm1, @intFromBool(has_p_root) | @intFromBool(has_f_root)); return .{ .ratio_is_square = @intFromBool(has_m_root) | @intFromBool(has_p_root), .root = x.abs() }; } fn rejectNonCanonical(s: [encoded_length]u8) NonCanonicalError!void { if ((s[0] & 1) != 0) { return error.NonCanonical; } try Fe.rejectNonCanonical(s, false); } /// Reject the neutral element. pub inline fn rejectIdentity(p: Ristretto255) IdentityElementError!void { return p.p.rejectIdentity(); } /// The base point (Ristretto is a curve in desguise). pub const basePoint = Ristretto255{ .p = Curve.basePoint }; /// Decode a Ristretto255 representative. pub fn fromBytes(s: [encoded_length]u8) (NonCanonicalError || EncodingError)!Ristretto255 { try rejectNonCanonical(s); const s_ = Fe.fromBytes(s); const ss = s_.sq(); // s^2 const u1_ = Fe.one.sub(ss); // (1-s^2) const u1u1 = u1_.sq(); // (1-s^2)^2 const u2_ = Fe.one.add(ss); // (1+s^2) const u2u2 = u2_.sq(); // (1+s^2)^2 const v = Fe.edwards25519d.mul(u1u1).neg().sub(u2u2); // -(d*u1^2)-u2^2 const v_u2u2 = v.mul(u2u2); // v*u2^2 const inv_sqrt = sqrtRatioM1(Fe.one, v_u2u2); var x = inv_sqrt.root.mul(u2_); const y = inv_sqrt.root.mul(x).mul(v).mul(u1_); x = x.mul(s_); x = x.add(x).abs(); const t = x.mul(y); if ((1 - inv_sqrt.ratio_is_square) | @intFromBool(t.isNegative()) | @intFromBool(y.isZero()) != 0) { return error.InvalidEncoding; } const p: Curve = .{ .x = x, .y = y, .z = Fe.one, .t = t, }; return Ristretto255{ .p = p }; } /// Encode to a Ristretto255 representative. pub fn toBytes(e: Ristretto255) [encoded_length]u8 { const p = &e.p; var u1_ = p.z.add(p.y); // Z+Y const zmy = p.z.sub(p.y); // Z-Y u1_ = u1_.mul(zmy); // (Z+Y)*(Z-Y) const u2_ = p.x.mul(p.y); // X*Y const u1_u2u2 = u2_.sq().mul(u1_); // u1*u2^2 const inv_sqrt = sqrtRatioM1(Fe.one, u1_u2u2); const den1 = inv_sqrt.root.mul(u1_); const den2 = inv_sqrt.root.mul(u2_); const z_inv = den1.mul(den2).mul(p.t); // den1*den2*T const ix = p.x.mul(Fe.sqrtm1); // X*sqrt(-1) const iy = p.y.mul(Fe.sqrtm1); // Y*sqrt(-1) const eden = den1.mul(Fe.edwards25519sqrtamd); // den1/sqrt(a-d) const t_z_inv = p.t.mul(z_inv); // T*z_inv const rotate = @intFromBool(t_z_inv.isNegative()); var x = p.x; var y = p.y; var den_inv = den2; x.cMov(iy, rotate); y.cMov(ix, rotate); den_inv.cMov(eden, rotate); const x_z_inv = x.mul(z_inv); const yneg = y.neg(); y.cMov(yneg, @intFromBool(x_z_inv.isNegative())); return p.z.sub(y).mul(den_inv).abs().toBytes(); } fn elligator(t: Fe) Curve { const r = t.sq().mul(Fe.sqrtm1); // sqrt(-1)*t^2 const u = r.add(Fe.one).mul(Fe.edwards25519eonemsqd); // (r+1)*(1-d^2) var c = comptime Fe.one.neg(); // -1 const v = c.sub(r.mul(Fe.edwards25519d)).mul(r.add(Fe.edwards25519d)); // (c-r*d)*(r+d) const ratio_sqrt = sqrtRatioM1(u, v); const wasnt_square = 1 - ratio_sqrt.ratio_is_square; var s = ratio_sqrt.root; const s_prime = s.mul(t).abs().neg(); // -|s*t| s.cMov(s_prime, wasnt_square); c.cMov(r, wasnt_square); const n = r.sub(Fe.one).mul(c).mul(Fe.edwards25519sqdmone).sub(v); // c*(r-1)*(d-1)^2-v const w0 = s.add(s).mul(v); // 2s*v const w1 = n.mul(Fe.edwards25519sqrtadm1); // n*sqrt(ad-1) const ss = s.sq(); // s^2 const w2 = Fe.one.sub(ss); // 1-s^2 const w3 = Fe.one.add(ss); // 1+s^2 return .{ .x = w0.mul(w3), .y = w2.mul(w1), .z = w1.mul(w3), .t = w0.mul(w2) }; } /// Map a 64-bit string into a Ristretto255 group element pub fn fromUniform(h: [64]u8) Ristretto255 { const p0 = elligator(Fe.fromBytes(h[0..32].*)); const p1 = elligator(Fe.fromBytes(h[32..64].*)); return Ristretto255{ .p = p0.add(p1) }; } /// Double a Ristretto255 element. pub inline fn dbl(p: Ristretto255) Ristretto255 { return .{ .p = p.p.dbl() }; } /// Add two Ristretto255 elements. pub inline fn add(p: Ristretto255, q: Ristretto255) Ristretto255 { return .{ .p = p.p.add(q.p) }; } /// Multiply a Ristretto255 element with a scalar. /// Return error.WeakPublicKey if the resulting element is /// the identity element. pub inline fn mul(p: Ristretto255, s: [encoded_length]u8) (IdentityElementError || WeakPublicKeyError)!Ristretto255 { return Ristretto255{ .p = try p.p.mul(s) }; } /// Return true if two Ristretto255 elements are equivalent pub fn equivalent(p: Ristretto255, q: Ristretto255) bool { const p_ = &p.p; const q_ = &q.p; const a = p_.x.mul(q_.y).equivalent(p_.y.mul(q_.x)); const b = p_.y.mul(q_.y).equivalent(p_.x.mul(q_.x)); return (@intFromBool(a) | @intFromBool(b)) != 0; } }; 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"); 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"); 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.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"); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/25519/x25519.zig
const std = @import("std"); const crypto = std.crypto; const mem = std.mem; const fmt = std.fmt; const Sha512 = crypto.hash.sha2.Sha512; const EncodingError = crypto.errors.EncodingError; const IdentityElementError = crypto.errors.IdentityElementError; const WeakPublicKeyError = crypto.errors.WeakPublicKeyError; /// X25519 DH function. pub const X25519 = struct { /// The underlying elliptic curve. pub const Curve = @import("curve25519.zig").Curve25519; /// Length (in bytes) of a secret key. pub const secret_length = 32; /// Length (in bytes) of a public key. pub const public_length = 32; /// Length (in bytes) of the output of the DH function. pub const shared_length = 32; /// Seed (for key pair creation) length in bytes. pub const seed_length = 32; /// An X25519 key pair. pub const KeyPair = struct { /// Public part. public_key: [public_length]u8, /// Secret part. secret_key: [secret_length]u8, /// Create a new key pair using an optional seed. pub fn create(seed: ?[seed_length]u8) IdentityElementError!KeyPair { const sk = seed orelse sk: { var random_seed: [seed_length]u8 = undefined; crypto.random.bytes(&random_seed); break :sk random_seed; }; var kp: KeyPair = undefined; mem.copy(u8, &kp.secret_key, sk[0..]); kp.public_key = try X25519.recoverPublicKey(sk); return kp; } /// Create a key pair from an Ed25519 key pair pub fn fromEd25519(ed25519_key_pair: crypto.sign.Ed25519.KeyPair) (IdentityElementError || EncodingError)!KeyPair { const seed = ed25519_key_pair.secret_key[0..32]; var az: [Sha512.digest_length]u8 = undefined; Sha512.hash(seed, &az, .{}); var sk = az[0..32].*; Curve.scalar.clamp(&sk); const pk = try publicKeyFromEd25519(ed25519_key_pair.public_key); return KeyPair{ .public_key = pk, .secret_key = sk, }; } }; /// Compute the public key for a given private key. pub fn recoverPublicKey(secret_key: [secret_length]u8) IdentityElementError![public_length]u8 { const q = try Curve.basePoint.clampedMul(secret_key); return q.toBytes(); } /// Compute the X25519 equivalent to an Ed25519 public eky. pub fn publicKeyFromEd25519(ed25519_public_key: [crypto.sign.Ed25519.public_length]u8) (IdentityElementError || EncodingError)![public_length]u8 { const pk_ed = try crypto.ecc.Edwards25519.fromBytes(ed25519_public_key); const pk = try Curve.fromEdwards25519(pk_ed); return pk.toBytes(); } /// Compute the scalar product of a public key and a secret scalar. /// Note that the output should not be used as a shared secret without /// hashing it first. pub fn scalarmult(secret_key: [secret_length]u8, public_key: [public_length]u8) IdentityElementError![shared_length]u8 { const q = try Curve.fromBytes(public_key).clampedMul(secret_key); return q.toBytes(); } }; const htest = @import("../test.zig"); test "x25519 public key calculation from secret key" { var sk: [32]u8 = undefined; var pk_expected: [32]u8 = undefined; _ = try fmt.hexToBytes(sk[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); _ = try fmt.hexToBytes(pk_expected[0..], "f1814f0e8ff1043d8a44d25babff3cedcae6c22c3edaa48f857ae70de2baae50"); const pk_calculated = try X25519.recoverPublicKey(sk); try std.testing.expectEqual(pk_calculated, pk_expected); } test "x25519 rfc7748 vector1" { const secret_key = [32]u8{ 0xa5, 0x46, 0xe3, 0x6b, 0xf0, 0x52, 0x7c, 0x9d, 0x3b, 0x16, 0x15, 0x4b, 0x82, 0x46, 0x5e, 0xdd, 0x62, 0x14, 0x4c, 0x0a, 0xc1, 0xfc, 0x5a, 0x18, 0x50, 0x6a, 0x22, 0x44, 0xba, 0x44, 0x9a, 0xc4 }; const public_key = [32]u8{ 0xe6, 0xdb, 0x68, 0x67, 0x58, 0x30, 0x30, 0xdb, 0x35, 0x94, 0xc1, 0xa4, 0x24, 0xb1, 0x5f, 0x7c, 0x72, 0x66, 0x24, 0xec, 0x26, 0xb3, 0x35, 0x3b, 0x10, 0xa9, 0x03, 0xa6, 0xd0, 0xab, 0x1c, 0x4c }; const expected_output = [32]u8{ 0xc3, 0xda, 0x55, 0x37, 0x9d, 0xe9, 0xc6, 0x90, 0x8e, 0x94, 0xea, 0x4d, 0xf2, 0x8d, 0x08, 0x4f, 0x32, 0xec, 0xcf, 0x03, 0x49, 0x1c, 0x71, 0xf7, 0x54, 0xb4, 0x07, 0x55, 0x77, 0xa2, 0x85, 0x52 }; const output = try X25519.scalarmult(secret_key, public_key); try std.testing.expectEqual(output, expected_output); } test "x25519 rfc7748 vector2" { const secret_key = [32]u8{ 0x4b, 0x66, 0xe9, 0xd4, 0xd1, 0xb4, 0x67, 0x3c, 0x5a, 0xd2, 0x26, 0x91, 0x95, 0x7d, 0x6a, 0xf5, 0xc1, 0x1b, 0x64, 0x21, 0xe0, 0xea, 0x01, 0xd4, 0x2c, 0xa4, 0x16, 0x9e, 0x79, 0x18, 0xba, 0x0d }; const public_key = [32]u8{ 0xe5, 0x21, 0x0f, 0x12, 0x78, 0x68, 0x11, 0xd3, 0xf4, 0xb7, 0x95, 0x9d, 0x05, 0x38, 0xae, 0x2c, 0x31, 0xdb, 0xe7, 0x10, 0x6f, 0xc0, 0x3c, 0x3e, 0xfc, 0x4c, 0xd5, 0x49, 0xc7, 0x15, 0xa4, 0x93 }; const expected_output = [32]u8{ 0x95, 0xcb, 0xde, 0x94, 0x76, 0xe8, 0x90, 0x7d, 0x7a, 0xad, 0xe4, 0x5c, 0xb4, 0xb8, 0x73, 0xf8, 0x8b, 0x59, 0x5a, 0x68, 0x79, 0x9f, 0xa1, 0x52, 0xe6, 0xf8, 0xf7, 0x64, 0x7a, 0xac, 0x79, 0x57 }; const output = try X25519.scalarmult(secret_key, public_key); try std.testing.expectEqual(output, expected_output); } test "x25519 rfc7748 one iteration" { const initial_value = [32]u8{ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; const expected_output = [32]u8{ 0x42, 0x2c, 0x8e, 0x7a, 0x62, 0x27, 0xd7, 0xbc, 0xa1, 0x35, 0x0b, 0x3e, 0x2b, 0xb7, 0x27, 0x9f, 0x78, 0x97, 0xb8, 0x7b, 0xb6, 0x85, 0x4b, 0x78, 0x3c, 0x60, 0xe8, 0x03, 0x11, 0xae, 0x30, 0x79 }; var k: [32]u8 = initial_value; var u: [32]u8 = initial_value; var i: usize = 0; while (i < 1) : (i += 1) { const output = try X25519.scalarmult(k, u); mem.copy(u8, u[0..], k[0..]); mem.copy(u8, k[0..], output[0..]); } try std.testing.expectEqual(k, expected_output); } test "x25519 rfc7748 1,000 iterations" { // These iteration tests are slow so we always skip them. Results have been verified. if (true) { return error.SkipZigTest; } const initial_value = [32]u8{ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; const expected_output = [32]u8{ 0x68, 0x4c, 0xf5, 0x9b, 0xa8, 0x33, 0x09, 0x55, 0x28, 0x00, 0xef, 0x56, 0x6f, 0x2f, 0x4d, 0x3c, 0x1c, 0x38, 0x87, 0xc4, 0x93, 0x60, 0xe3, 0x87, 0x5f, 0x2e, 0xb9, 0x4d, 0x99, 0x53, 0x2c, 0x51 }; var k: [32]u8 = initial_value.*; var u: [32]u8 = initial_value.*; var i: usize = 0; while (i < 1000) : (i += 1) { const output = try X25519.scalarmult(&k, &u); mem.copy(u8, u[0..], k[0..]); mem.copy(u8, k[0..], output[0..]); } try std.testing.expectEqual(k, expected_output); } test "x25519 rfc7748 1,000,000 iterations" { if (true) { return error.SkipZigTest; } const initial_value = [32]u8{ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; const expected_output = [32]u8{ 0x7c, 0x39, 0x11, 0xe0, 0xab, 0x25, 0x86, 0xfd, 0x86, 0x44, 0x97, 0x29, 0x7e, 0x57, 0x5e, 0x6f, 0x3b, 0xc6, 0x01, 0xc0, 0x88, 0x3c, 0x30, 0xdf, 0x5f, 0x4d, 0xd2, 0xd2, 0x4f, 0x66, 0x54, 0x24 }; var k: [32]u8 = initial_value.*; var u: [32]u8 = initial_value.*; var i: usize = 0; while (i < 1000000) : (i += 1) { const output = try X25519.scalarmult(&k, &u); mem.copy(u8, u[0..], k[0..]); mem.copy(u8, k[0..], output[0..]); } try std.testing.expectEqual(k[0..], expected_output); } test "edwards25519 -> curve25519 map" { const ed_kp = try crypto.sign.Ed25519.KeyPair.create([_]u8{0x42} ** 32); const mont_kp = try X25519.KeyPair.fromEd25519(ed_kp); try htest.assertEqual("90e7595fc89e52fdfddce9c6a43d74dbf6047025ee0462d2d172e8b6a2841d6e", &mont_kp.secret_key); try htest.assertEqual("cc4f2cdb695dd766f34118eb67b98652fed1d8bc49c330b119bbfa8a64989378", &mont_kp.public_key); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/25519/edwards25519.zig
const std = @import("std"); const crypto = std.crypto; const debug = std.debug; const fmt = std.fmt; const mem = std.mem; const EncodingError = crypto.errors.EncodingError; const IdentityElementError = crypto.errors.IdentityElementError; const NonCanonicalError = crypto.errors.NonCanonicalError; const NotSquareError = crypto.errors.NotSquareError; const WeakPublicKeyError = crypto.errors.WeakPublicKeyError; /// Group operations over Edwards25519. pub const Edwards25519 = struct { /// The underlying prime field. pub const Fe = @import("field.zig").Fe; /// Field arithmetic mod the order of the main subgroup. pub const scalar = @import("scalar.zig"); /// Length in bytes of a compressed representation of a point. pub const encoded_length: usize = 32; x: Fe, y: Fe, z: Fe, t: Fe, is_base: bool = false, /// Decode an Edwards25519 point from its compressed (Y+sign) coordinates. pub fn fromBytes(s: [encoded_length]u8) EncodingError!Edwards25519 { const z = Fe.one; const y = Fe.fromBytes(s); var u = y.sq(); var v = u.mul(Fe.edwards25519d); u = u.sub(z); v = v.add(z); const v3 = v.sq().mul(v); var x = v3.sq().mul(v).mul(u).pow2523().mul(v3).mul(u); const vxx = x.sq().mul(v); const has_m_root = vxx.sub(u).isZero(); const has_p_root = vxx.add(u).isZero(); if ((@intFromBool(has_m_root) | @intFromBool(has_p_root)) == 0) { // best-effort to avoid two conditional branches return error.InvalidEncoding; } x.cMov(x.mul(Fe.sqrtm1), 1 - @intFromBool(has_m_root)); x.cMov(x.neg(), @intFromBool(x.isNegative()) ^ (s[31] >> 7)); const t = x.mul(y); return Edwards25519{ .x = x, .y = y, .z = z, .t = t }; } /// Encode an Edwards25519 point. pub fn toBytes(p: Edwards25519) [encoded_length]u8 { const zi = p.z.invert(); var s = p.y.mul(zi).toBytes(); s[31] ^= @as(u8, @intFromBool(p.x.mul(zi).isNegative())) << 7; return s; } /// Check that the encoding of a point is canonical. pub fn rejectNonCanonical(s: [32]u8) NonCanonicalError!void { return Fe.rejectNonCanonical(s, true); } /// The edwards25519 base point. pub const basePoint = Edwards25519{ .x = Fe{ .limbs = .{ 3990542415680775, 3398198340507945, 4322667446711068, 2814063955482877, 2839572215813860 } }, .y = Fe{ .limbs = .{ 1801439850948184, 1351079888211148, 450359962737049, 900719925474099, 1801439850948198 } }, .z = Fe.one, .t = Fe{ .limbs = .{ 1841354044333475, 16398895984059, 755974180946558, 900171276175154, 1821297809914039 } }, .is_base = true, }; pub const neutralElement = @compileError("deprecated: use identityElement instead"); pub const identityElement = Edwards25519{ .x = Fe.zero, .y = Fe.one, .z = Fe.one, .t = Fe.zero }; /// Reject the neutral element. pub fn rejectIdentity(p: Edwards25519) IdentityElementError!void { if (p.x.isZero()) { return error.IdentityElement; } } /// Multiply a point by the cofactor pub fn clearCofactor(p: Edwards25519) Edwards25519 { return p.dbl().dbl().dbl(); } /// Flip the sign of the X coordinate. pub inline fn neg(p: Edwards25519) Edwards25519 { return .{ .x = p.x.neg(), .y = p.y, .z = p.z, .t = p.t.neg() }; } /// Double an Edwards25519 point. pub fn dbl(p: Edwards25519) Edwards25519 { const t0 = p.x.add(p.y).sq(); var x = p.x.sq(); var z = p.y.sq(); const y = z.add(x); z = z.sub(x); x = t0.sub(y); const t = p.z.sq2().sub(z); return .{ .x = x.mul(t), .y = y.mul(z), .z = z.mul(t), .t = x.mul(y), }; } /// Add two Edwards25519 points. pub fn add(p: Edwards25519, q: Edwards25519) Edwards25519 { const a = p.y.sub(p.x).mul(q.y.sub(q.x)); const b = p.x.add(p.y).mul(q.x.add(q.y)); const c = p.t.mul(q.t).mul(Fe.edwards25519d2); var d = p.z.mul(q.z); d = d.add(d); const x = b.sub(a); const y = b.add(a); const z = d.add(c); const t = d.sub(c); return .{ .x = x.mul(t), .y = y.mul(z), .z = z.mul(t), .t = x.mul(y), }; } /// Substract two Edwards25519 points. pub fn sub(p: Edwards25519, q: Edwards25519) Edwards25519 { return p.add(q.neg()); } inline fn cMov(p: *Edwards25519, a: Edwards25519, c: u64) void { p.x.cMov(a.x, c); p.y.cMov(a.y, c); p.z.cMov(a.z, c); p.t.cMov(a.t, c); } inline fn pcSelect(comptime n: usize, pc: *const [n]Edwards25519, b: u8) Edwards25519 { var t = Edwards25519.identityElement; comptime var i: u8 = 1; inline while (i < pc.len) : (i += 1) { t.cMov(pc[i], ((@as(usize, b ^ i) -% 1) >> 8) & 1); } return t; } fn slide(s: [32]u8) [2 * 32]i8 { const reduced = if ((s[s.len - 1] & 0x80) != 0) s else scalar.reduce(s); var e: [2 * 32]i8 = undefined; for (reduced, 0..) |x, i| { e[i * 2 + 0] = @as(i8, @as(u4, @truncate(x))); e[i * 2 + 1] = @as(i8, @as(u4, @truncate(x >> 4))); } // Now, e[0..63] is between 0 and 15, e[63] is between 0 and 7 var carry: i8 = 0; for (e[0..63]) |*x| { x.* += carry; carry = (x.* + 8) >> 4; x.* -= carry * 16; } e[63] += carry; // Now, e[*] is between -8 and 8, including e[63] return e; } // Scalar multiplication with a 4-bit window and the first 8 multiples. // This requires the scalar to be converted to non-adjacent form. // Based on real-world benchmarks, we only use this for multi-scalar multiplication. // NAF could be useful to half the size of precomputation tables, but we intentionally // avoid these to keep the standard library lightweight. fn pcMul(pc: *const [9]Edwards25519, s: [32]u8, comptime vartime: bool) IdentityElementError!Edwards25519 { std.debug.assert(vartime); const e = slide(s); var q = Edwards25519.identityElement; var pos: usize = 2 * 32 - 1; while (true) : (pos -= 1) { const slot = e[pos]; if (slot > 0) { q = q.add(pc[@as(usize, @intCast(slot))]); } else if (slot < 0) { q = q.sub(pc[@as(usize, @intCast(-slot))]); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } // Scalar multiplication with a 4-bit window and the first 15 multiples. fn pcMul16(pc: *const [16]Edwards25519, s: [32]u8, comptime vartime: bool) IdentityElementError!Edwards25519 { var q = Edwards25519.identityElement; var pos: usize = 252; while (true) : (pos -= 4) { const slot = @as(u4, @truncate((s[pos >> 3] >> @as(u3, @truncate(pos))))); if (vartime) { if (slot != 0) { q = q.add(pc[slot]); } } else { q = q.add(pcSelect(16, pc, slot)); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } fn precompute(p: Edwards25519, comptime count: usize) [1 + count]Edwards25519 { var pc: [1 + count]Edwards25519 = undefined; pc[0] = Edwards25519.identityElement; pc[1] = p; var i: usize = 2; while (i <= count) : (i += 1) { pc[i] = if (i % 2 == 0) pc[i / 2].dbl() else pc[i - 1].add(p); } return pc; } const basePointPc = pc: { @setEvalBranchQuota(10000); break :pc precompute(Edwards25519.basePoint, 15); }; /// Multiply an Edwards25519 point by a scalar without clamping it. /// Return error.WeakPublicKey if the base generates a small-order group, /// and error.IdentityElement if the result is the identity element. pub fn mul(p: Edwards25519, s: [32]u8) (IdentityElementError || WeakPublicKeyError)!Edwards25519 { const pc = if (p.is_base) basePointPc else pc: { const xpc = precompute(p, 15); xpc[4].rejectIdentity() catch return error.WeakPublicKey; break :pc xpc; }; return pcMul16(&pc, s, false); } /// Multiply an Edwards25519 point by a *PUBLIC* scalar *IN VARIABLE TIME* /// This can be used for signature verification. pub fn mulPublic(p: Edwards25519, s: [32]u8) (IdentityElementError || WeakPublicKeyError)!Edwards25519 { if (p.is_base) { return pcMul16(&basePointPc, s, true); } else { const pc = precompute(p, 8); pc[4].rejectIdentity() catch return error.WeakPublicKey; return pcMul(&pc, s, true); } } /// Double-base multiplication of public parameters - Compute (p1*s1)+(p2*s2) *IN VARIABLE TIME* /// This can be used for signature verification. pub fn mulDoubleBasePublic(p1: Edwards25519, s1: [32]u8, p2: Edwards25519, s2: [32]u8) (IdentityElementError || WeakPublicKeyError)!Edwards25519 { var pc1_array: [9]Edwards25519 = undefined; const pc1 = if (p1.is_base) basePointPc[0..9] else pc: { pc1_array = precompute(p1, 8); pc1_array[4].rejectIdentity() catch return error.WeakPublicKey; break :pc &pc1_array; }; var pc2_array: [9]Edwards25519 = undefined; const pc2 = if (p2.is_base) basePointPc[0..9] else pc: { pc2_array = precompute(p2, 8); pc2_array[4].rejectIdentity() catch return error.WeakPublicKey; break :pc &pc2_array; }; const e1 = slide(s1); const e2 = slide(s2); var q = Edwards25519.identityElement; var pos: usize = 2 * 32 - 1; while (true) : (pos -= 1) { const slot1 = e1[pos]; if (slot1 > 0) { q = q.add(pc1[@as(usize, @intCast(slot1))]); } else if (slot1 < 0) { q = q.sub(pc1[@as(usize, @intCast(-slot1))]); } const slot2 = e2[pos]; if (slot2 > 0) { q = q.add(pc2[@as(usize, @intCast(slot2))]); } else if (slot2 < 0) { q = q.sub(pc2[@as(usize, @intCast(-slot2))]); } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } /// Multiscalar multiplication *IN VARIABLE TIME* for public data /// Computes ps0*ss0 + ps1*ss1 + ps2*ss2... faster than doing many of these operations individually pub fn mulMulti(comptime count: usize, ps: [count]Edwards25519, ss: [count][32]u8) (IdentityElementError || WeakPublicKeyError)!Edwards25519 { var pcs: [count][9]Edwards25519 = undefined; var bpc: [9]Edwards25519 = undefined; mem.copy(Edwards25519, bpc[0..], basePointPc[0..bpc.len]); for (ps, 0..) |p, i| { if (p.is_base) { pcs[i] = bpc; } else { pcs[i] = precompute(p, 8); pcs[i][4].rejectIdentity() catch return error.WeakPublicKey; } } var es: [count][2 * 32]i8 = undefined; for (ss, 0..) |s, i| { es[i] = slide(s); } var q = Edwards25519.identityElement; var pos: usize = 2 * 32 - 1; while (true) : (pos -= 1) { for (es, 0..) |e, i| { const slot = e[pos]; if (slot > 0) { q = q.add(pcs[i][@as(usize, @intCast(slot))]); } else if (slot < 0) { q = q.sub(pcs[i][@as(usize, @intCast(-slot))]); } } if (pos == 0) break; q = q.dbl().dbl().dbl().dbl(); } try q.rejectIdentity(); return q; } /// Multiply an Edwards25519 point by a scalar after "clamping" it. /// Clamping forces the scalar to be a multiple of the cofactor in /// order to prevent small subgroups attacks. /// This is strongly recommended for DH operations. /// Return error.WeakPublicKey if the resulting point is /// the identity element. pub fn clampedMul(p: Edwards25519, s: [32]u8) (IdentityElementError || WeakPublicKeyError)!Edwards25519 { var t: [32]u8 = s; scalar.clamp(&t); return mul(p, t); } // montgomery -- recover y = sqrt(x^3 + A*x^2 + x) fn xmontToYmont(x: Fe) NotSquareError!Fe { var x2 = x.sq(); const x3 = x.mul(x2); x2 = x2.mul32(Fe.edwards25519a_32); return x.add(x2).add(x3).sqrt(); } // montgomery affine coordinates to edwards extended coordinates fn montToEd(x: Fe, y: Fe) Edwards25519 { const x_plus_one = x.add(Fe.one); const x_minus_one = x.sub(Fe.one); const x_plus_one_y_inv = x_plus_one.mul(y).invert(); // 1/((x+1)*y) // xed = sqrt(-A-2)*x/y const xed = x.mul(Fe.edwards25519sqrtam2).mul(x_plus_one_y_inv).mul(x_plus_one); // yed = (x-1)/(x+1) or 1 if the denominator is 0 var yed = x_plus_one_y_inv.mul(y).mul(x_minus_one); yed.cMov(Fe.one, @intFromBool(x_plus_one_y_inv.isZero())); return Edwards25519{ .x = xed, .y = yed, .z = Fe.one, .t = xed.mul(yed), }; } /// Elligator2 map - Returns Montgomery affine coordinates pub fn elligator2(r: Fe) struct { x: Fe, y: Fe, not_square: bool } { const rr2 = r.sq2().add(Fe.one).invert(); var x = rr2.mul32(Fe.edwards25519a_32).neg(); // x=x1 var x2 = x.sq(); const x3 = x2.mul(x); x2 = x2.mul32(Fe.edwards25519a_32); // x2 = A*x1^2 const gx1 = x3.add(x).add(x2); // gx1 = x1^3 + A*x1^2 + x1 const not_square = !gx1.isSquare(); // gx1 not a square => x = -x1-A x.cMov(x.neg(), @intFromBool(not_square)); x2 = Fe.zero; x2.cMov(Fe.edwards25519a, @intFromBool(not_square)); x = x.sub(x2); // We have y = sqrt(gx1) or sqrt(gx2) with gx2 = gx1*(A+x1)/(-x1) // but it is about as fast to just recompute y from the curve equation. const y = xmontToYmont(x) catch unreachable; return .{ .x = x, .y = y, .not_square = not_square }; } /// Map a 64-bit hash into an Edwards25519 point pub fn fromHash(h: [64]u8) Edwards25519 { const fe_f = Fe.fromBytes64(h); var elr = elligator2(fe_f); const y_sign = elr.not_square; const y_neg = elr.y.neg(); elr.y.cMov(y_neg, @intFromBool(elr.y.isNegative()) ^ @intFromBool(y_sign)); return montToEd(elr.x, elr.y).clearCofactor(); } fn stringToPoints(comptime n: usize, ctx: []const u8, s: []const u8) [n]Edwards25519 { debug.assert(n <= 2); const H = crypto.hash.sha2.Sha512; const h_l: usize = 48; var xctx = ctx; var hctx: [H.digest_length]u8 = undefined; if (ctx.len > 0xff) { var st = H.init(.{}); st.update("H2C-OVERSIZE-DST-"); st.update(ctx); st.final(&hctx); xctx = hctx[0..]; } const empty_block = [_]u8{0} ** H.block_length; var t = [3]u8{ 0, n * h_l, 0 }; var xctx_len_u8 = [1]u8{@as(u8, @intCast(xctx.len))}; var st = H.init(.{}); st.update(empty_block[0..]); st.update(s); st.update(t[0..]); st.update(xctx); st.update(xctx_len_u8[0..]); var u_0: [H.digest_length]u8 = undefined; st.final(&u_0); var u: [n * H.digest_length]u8 = undefined; var i: usize = 0; while (i < n * H.digest_length) : (i += H.digest_length) { mem.copy(u8, u[i..][0..H.digest_length], u_0[0..]); var j: usize = 0; while (i > 0 and j < H.digest_length) : (j += 1) { u[i + j] ^= u[i + j - H.digest_length]; } t[2] += 1; st = H.init(.{}); st.update(u[i..][0..H.digest_length]); st.update(t[2..3]); st.update(xctx); st.update(xctx_len_u8[0..]); st.final(u[i..][0..H.digest_length]); } var px: [n]Edwards25519 = undefined; i = 0; while (i < n) : (i += 1) { mem.set(u8, u_0[0 .. H.digest_length - h_l], 0); mem.copy(u8, u_0[H.digest_length - h_l ..][0..h_l], u[i * h_l ..][0..h_l]); px[i] = fromHash(u_0); } return px; } /// Hash a context `ctx` and a string `s` into an Edwards25519 point /// /// This function implements the edwards25519_XMD:SHA-512_ELL2_RO_ and edwards25519_XMD:SHA-512_ELL2_NU_ /// methods from the "Hashing to Elliptic Curves" standard document. /// /// Although not strictly required by the standard, it is recommended to avoid NUL characters in /// the context in order to be compatible with other implementations. pub fn fromString(comptime random_oracle: bool, ctx: []const u8, s: []const u8) Edwards25519 { if (random_oracle) { const px = stringToPoints(2, ctx, s); return px[0].add(px[1]); } else { return stringToPoints(1, ctx, s)[0]; } } /// Map a 32 bit uniform bit string into an edwards25519 point pub fn fromUniform(r: [32]u8) Edwards25519 { var s = r; const x_sign = s[31] >> 7; s[31] &= 0x7f; const elr = elligator2(Fe.fromBytes(s)); var p = montToEd(elr.x, elr.y); const p_neg = p.neg(); p.cMov(p_neg, @intFromBool(p.x.isNegative()) ^ x_sign); return p.clearCofactor(); } }; const htest = @import("../test.zig"); test "edwards25519 packing/unpacking" { const s = [_]u8{170} ++ [_]u8{0} ** 31; 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"); const small_order_ss: [7][32]u8 = .{ .{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0 (order 4) }, .{ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 1 (order 1) }, .{ 0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0, 0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0, 0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39, 0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x05, // 270738550114484064931822528722565878893680426757531351946374360975030340202(order 8) }, .{ 0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f, 0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f, 0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6, 0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0x7a, // 55188659117513257062467267217118295137698188065244968500265048394206261417927 (order 8) }, .{ 0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p-1 (order 2) }, .{ 0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p (=0, order 4) }, .{ 0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, // p+1 (=1, order 1) }, }; for (small_order_ss) |small_order_s| { const small_p = try Edwards25519.fromBytes(small_order_s); try std.testing.expectError(error.WeakPublicKey, small_p.mul(s)); } } test "edwards25519 point addition/substraction" { var s1: [32]u8 = undefined; var s2: [32]u8 = undefined; crypto.random.bytes(&s1); crypto.random.bytes(&s2); const p = try Edwards25519.basePoint.clampedMul(s1); const q = try Edwards25519.basePoint.clampedMul(s2); const r = p.add(q).add(q).sub(q).sub(q); try r.rejectIdentity(); try std.testing.expectError(error.IdentityElement, r.sub(p).rejectIdentity()); try std.testing.expectError(error.IdentityElement, p.sub(p).rejectIdentity()); try std.testing.expectError(error.IdentityElement, p.sub(q).add(q).sub(p).rejectIdentity()); } test "edwards25519 uniform-to-point" { var r = [32]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; var p = Edwards25519.fromUniform(r); try htest.assertEqual("0691eee3cf70a0056df6bfa03120635636581b5c4ea571dfc680f78c7e0b4137", p.toBytes()[0..]); r[31] = 0xff; p = Edwards25519.fromUniform(r); try htest.assertEqual("f70718e68ef42d90ca1d936bb2d7e159be6c01d8095d39bd70487c82fe5c973a", p.toBytes()[0..]); } // Test vectors from draft-irtf-cfrg-hash-to-curve-10 test "edwards25519 hash-to-curve operation" { var p = Edwards25519.fromString(true, "QUUX-V01-CS02-with-edwards25519_XMD:SHA-512_ELL2_RO_", "abc"); try htest.assertEqual("31558a26887f23fb8218f143e69d5f0af2e7831130bd5b432ef23883b895831a", p.toBytes()[0..]); p = Edwards25519.fromString(false, "QUUX-V01-CS02-with-edwards25519_XMD:SHA-512_ELL2_NU_", "abc"); try htest.assertEqual("42fa27c8f5a1ae0aa38bb59d5938e5145622ba5dedd11d11736fa2f9502d73e7", p.toBytes()[0..]); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/25519/ed25519.zig
const std = @import("std"); const crypto = std.crypto; const debug = std.debug; const fmt = std.fmt; const mem = std.mem; const Sha512 = crypto.hash.sha2.Sha512; const EncodingError = crypto.errors.EncodingError; const IdentityElementError = crypto.errors.IdentityElementError; const NonCanonicalError = crypto.errors.NonCanonicalError; const SignatureVerificationError = crypto.errors.SignatureVerificationError; const KeyMismatchError = crypto.errors.KeyMismatchError; const WeakPublicKeyError = crypto.errors.WeakPublicKeyError; /// Ed25519 (EdDSA) signatures. pub const Ed25519 = struct { /// The underlying elliptic curve. pub const Curve = @import("edwards25519.zig").Edwards25519; /// Length (in bytes) of a seed required to create a key pair. pub const seed_length = 32; /// Length (in bytes) of a compressed secret key. pub const secret_length = 64; /// Length (in bytes) of a compressed public key. pub const public_length = 32; /// Length (in bytes) of a signature. pub const signature_length = 64; /// Length (in bytes) of optional random bytes, for non-deterministic signatures. pub const noise_length = 32; /// An Ed25519 key pair. pub const KeyPair = struct { /// Public part. public_key: [public_length]u8, /// Secret part. What we expose as a secret key is, under the hood, the concatenation of the seed and the public key. secret_key: [secret_length]u8, /// Derive a key pair from an optional secret seed. /// /// As in RFC 8032, an Ed25519 public key is generated by hashing /// the secret key using the SHA-512 function, and interpreting the /// bit-swapped, clamped lower-half of the output as the secret scalar. /// /// For this reason, an EdDSA secret key is commonly called a seed, /// from which the actual secret is derived. pub fn create(seed: ?[seed_length]u8) IdentityElementError!KeyPair { const ss = seed orelse ss: { var random_seed: [seed_length]u8 = undefined; crypto.random.bytes(&random_seed); break :ss random_seed; }; var az: [Sha512.digest_length]u8 = undefined; var h = Sha512.init(.{}); h.update(&ss); h.final(&az); const p = Curve.basePoint.clampedMul(az[0..32].*) catch return error.IdentityElement; var sk: [secret_length]u8 = undefined; mem.copy(u8, &sk, &ss); const pk = p.toBytes(); mem.copy(u8, sk[seed_length..], &pk); return KeyPair{ .public_key = pk, .secret_key = sk }; } /// Create a KeyPair from a secret key. pub fn fromSecretKey(secret_key: [secret_length]u8) KeyPair { return KeyPair{ .secret_key = secret_key, .public_key = secret_key[seed_length..].*, }; } }; /// Sign a message using a key pair, and optional random noise. /// Having noise creates non-standard, non-deterministic signatures, /// but has been proven to increase resilience against fault attacks. pub fn sign(msg: []const u8, key_pair: KeyPair, noise: ?[noise_length]u8) (IdentityElementError || WeakPublicKeyError || KeyMismatchError)![signature_length]u8 { const seed = key_pair.secret_key[0..seed_length]; const public_key = key_pair.secret_key[seed_length..]; if (!mem.eql(u8, public_key, &key_pair.public_key)) { return error.KeyMismatch; } var az: [Sha512.digest_length]u8 = undefined; var h = Sha512.init(.{}); h.update(seed); h.final(&az); h = Sha512.init(.{}); if (noise) |*z| { h.update(z); } h.update(az[32..]); h.update(msg); var nonce64: [64]u8 = undefined; h.final(&nonce64); const nonce = Curve.scalar.reduce64(nonce64); const r = try Curve.basePoint.mul(nonce); var sig: [signature_length]u8 = undefined; mem.copy(u8, sig[0..32], &r.toBytes()); mem.copy(u8, sig[32..], public_key); h = Sha512.init(.{}); h.update(&sig); h.update(msg); var hram64: [Sha512.digest_length]u8 = undefined; h.final(&hram64); const hram = Curve.scalar.reduce64(hram64); var x = az[0..32]; Curve.scalar.clamp(x); const s = Curve.scalar.mulAdd(hram, x.*, nonce); mem.copy(u8, sig[32..], s[0..]); return sig; } /// Verify an Ed25519 signature given a message and a public key. /// Returns error.SignatureVerificationFailed is the signature verification failed. pub fn verify(sig: [signature_length]u8, msg: []const u8, public_key: [public_length]u8) (SignatureVerificationError || WeakPublicKeyError || EncodingError || NonCanonicalError || IdentityElementError)!void { const r = sig[0..32]; const s = sig[32..64]; try Curve.scalar.rejectNonCanonical(s.*); try Curve.rejectNonCanonical(public_key); const a = try Curve.fromBytes(public_key); try a.rejectIdentity(); try Curve.rejectNonCanonical(r.*); const expected_r = try Curve.fromBytes(r.*); try expected_r.rejectIdentity(); var h = Sha512.init(.{}); h.update(r); h.update(&public_key); h.update(msg); var hram64: [Sha512.digest_length]u8 = undefined; h.final(&hram64); const hram = Curve.scalar.reduce64(hram64); const sb_ah = try Curve.basePoint.mulDoubleBasePublic(s.*, a.neg(), hram); if (expected_r.sub(sb_ah).clearCofactor().rejectIdentity()) |_| { return error.SignatureVerificationFailed; } else |_| {} } /// A (signature, message, public_key) tuple for batch verification pub const BatchElement = struct { sig: [signature_length]u8, msg: []const u8, public_key: [public_length]u8, }; /// Verify several signatures in a single operation, much faster than verifying signatures one-by-one pub fn verifyBatch(comptime count: usize, signature_batch: [count]BatchElement) (SignatureVerificationError || IdentityElementError || WeakPublicKeyError || EncodingError || NonCanonicalError)!void { var r_batch: [count][32]u8 = undefined; var s_batch: [count][32]u8 = undefined; var a_batch: [count]Curve = undefined; var expected_r_batch: [count]Curve = undefined; for (signature_batch, 0..) |signature, i| { const r = signature.sig[0..32]; const s = signature.sig[32..64]; try Curve.scalar.rejectNonCanonical(s.*); try Curve.rejectNonCanonical(signature.public_key); const a = try Curve.fromBytes(signature.public_key); try a.rejectIdentity(); try Curve.rejectNonCanonical(r.*); const expected_r = try Curve.fromBytes(r.*); try expected_r.rejectIdentity(); expected_r_batch[i] = expected_r; r_batch[i] = r.*; s_batch[i] = s.*; a_batch[i] = a; } var hram_batch: [count]Curve.scalar.CompressedScalar = undefined; for (signature_batch, 0..) |signature, i| { var h = Sha512.init(.{}); h.update(&r_batch[i]); h.update(&signature.public_key); h.update(signature.msg); var hram64: [Sha512.digest_length]u8 = undefined; h.final(&hram64); hram_batch[i] = Curve.scalar.reduce64(hram64); } var z_batch: [count]Curve.scalar.CompressedScalar = undefined; for (z_batch) |*z| { crypto.random.bytes(z[0..16]); mem.set(u8, z[16..], 0); } var zs_sum = Curve.scalar.zero; for (z_batch, 0..) |z, i| { const zs = Curve.scalar.mul(z, s_batch[i]); zs_sum = Curve.scalar.add(zs_sum, zs); } zs_sum = Curve.scalar.mul8(zs_sum); var zhs: [count]Curve.scalar.CompressedScalar = undefined; for (z_batch, 0..) |z, i| { zhs[i] = Curve.scalar.mul(z, hram_batch[i]); } const zr = (try Curve.mulMulti(count, expected_r_batch, z_batch)).clearCofactor(); const zah = (try Curve.mulMulti(count, a_batch, zhs)).clearCofactor(); const zsb = try Curve.basePoint.mulPublic(zs_sum); if (zr.add(zah).sub(zsb).rejectIdentity()) |_| { return error.SignatureVerificationFailed; } else |_| {} } }; test "ed25519 key pair creation" { var seed: [32]u8 = undefined; _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); const key_pair = try Ed25519.KeyPair.create(seed); var buf: [256]u8 = undefined; try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.secret_key)}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1662D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.public_key)}), "2D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); } test "ed25519 signature" { var seed: [32]u8 = undefined; _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); const key_pair = try Ed25519.KeyPair.create(seed); const sig = try Ed25519.sign("test", key_pair, null); var buf: [128]u8 = undefined; try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&sig)}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808"); try Ed25519.verify(sig, "test", key_pair.public_key); try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verify(sig, "TEST", key_pair.public_key)); } test "ed25519 batch verification" { var i: usize = 0; while (i < 100) : (i += 1) { const key_pair = try Ed25519.KeyPair.create(null); var msg1: [32]u8 = undefined; var msg2: [32]u8 = undefined; crypto.random.bytes(&msg1); crypto.random.bytes(&msg2); const sig1 = try Ed25519.sign(&msg1, key_pair, null); const sig2 = try Ed25519.sign(&msg2, key_pair, null); var signature_batch = [_]Ed25519.BatchElement{ Ed25519.BatchElement{ .sig = sig1, .msg = &msg1, .public_key = key_pair.public_key, }, Ed25519.BatchElement{ .sig = sig2, .msg = &msg2, .public_key = key_pair.public_key, }, }; try Ed25519.verifyBatch(2, signature_batch); signature_batch[1].sig = sig1; try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verifyBatch(signature_batch.len, signature_batch)); } } test "ed25519 test vectors" { const Vec = struct { msg_hex: *const [64:0]u8, public_key_hex: *const [64:0]u8, sig_hex: *const [128:0]u8, expected: ?anyerror, }; const entries = [_]Vec{ Vec{ .msg_hex = "8c93255d71dcab10e8f379c26200f3c7bd5f09d9bc3068d3ef4edeb4853022b6", .public_key_hex = "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa", .sig_hex = "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a0000000000000000000000000000000000000000000000000000000000000000", .expected = error.WeakPublicKey, // 0 }, Vec{ .msg_hex = "9bd9f44f4dcc75bd531b56b2cd280b0bb38fc1cd6d1230e14861d861de092e79", .public_key_hex = "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa", .sig_hex = "f7badec5b8abeaf699583992219b7b223f1df3fbbea919844e3f7c554a43dd43a5bb704786be79fc476f91d3f3f89b03984d8068dcf1bb7dfc6637b45450ac04", .expected = error.WeakPublicKey, // 1 }, Vec{ .msg_hex = "aebf3f2601a0c8c5d39cc7d8911642f740b78168218da8471772b35f9d35b9ab", .public_key_hex = "f7badec5b8abeaf699583992219b7b223f1df3fbbea919844e3f7c554a43dd43", .sig_hex = "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa8c4bd45aecaca5b24fb97bc10ac27ac8751a7dfe1baff8b953ec9f5833ca260e", .expected = null, // 2 - small order R is acceptable }, Vec{ .msg_hex = "9bd9f44f4dcc75bd531b56b2cd280b0bb38fc1cd6d1230e14861d861de092e79", .public_key_hex = "cdb267ce40c5cd45306fa5d2f29731459387dbf9eb933b7bd5aed9a765b88d4d", .sig_hex = "9046a64750444938de19f227bb80485e92b83fdb4b6506c160484c016cc1852f87909e14428a7a1d62e9f22f3d3ad7802db02eb2e688b6c52fcd6648a98bd009", .expected = null, // 3 - mixed orders }, Vec{ .msg_hex = "e47d62c63f830dc7a6851a0b1f33ae4bb2f507fb6cffec4011eaccd55b53f56c", .public_key_hex = "cdb267ce40c5cd45306fa5d2f29731459387dbf9eb933b7bd5aed9a765b88d4d", .sig_hex = "160a1cb0dc9c0258cd0a7d23e94d8fa878bcb1925f2c64246b2dee1796bed5125ec6bc982a269b723e0668e540911a9a6a58921d6925e434ab10aa7940551a09", .expected = null, // 4 - cofactored verification }, Vec{ .msg_hex = "e47d62c63f830dc7a6851a0b1f33ae4bb2f507fb6cffec4011eaccd55b53f56c", .public_key_hex = "cdb267ce40c5cd45306fa5d2f29731459387dbf9eb933b7bd5aed9a765b88d4d", .sig_hex = "21122a84e0b5fca4052f5b1235c80a537878b38f3142356b2c2384ebad4668b7e40bc836dac0f71076f9abe3a53f9c03c1ceeeddb658d0030494ace586687405", .expected = null, // 5 - cofactored verification }, Vec{ .msg_hex = "85e241a07d148b41e47d62c63f830dc7a6851a0b1f33ae4bb2f507fb6cffec40", .public_key_hex = "442aad9f089ad9e14647b1ef9099a1ff4798d78589e66f28eca69c11f582a623", .sig_hex = "e96f66be976d82e60150baecff9906684aebb1ef181f67a7189ac78ea23b6c0e547f7690a0e2ddcd04d87dbc3490dc19b3b3052f7ff0538cb68afb369ba3a514", .expected = error.NonCanonical, // 6 - S > L }, Vec{ .msg_hex = "85e241a07d148b41e47d62c63f830dc7a6851a0b1f33ae4bb2f507fb6cffec40", .public_key_hex = "442aad9f089ad9e14647b1ef9099a1ff4798d78589e66f28eca69c11f582a623", .sig_hex = "8ce5b96c8f26d0ab6c47958c9e68b937104cd36e13c33566acd2fe8d38aa19427e71f98a4734e74f2f13f06f97c20d58cc3f54b8bd0d272f42b695dd7e89a8c2", .expected = error.NonCanonical, // 7 - S >> L }, Vec{ .msg_hex = "9bedc267423725d473888631ebf45988bad3db83851ee85c85e241a07d148b41", .public_key_hex = "f7badec5b8abeaf699583992219b7b223f1df3fbbea919844e3f7c554a43dd43", .sig_hex = "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff03be9678ac102edcd92b0210bb34d7428d12ffc5df5f37e359941266a4e35f0f", .expected = error.IdentityElement, // 8 - non-canonical R }, Vec{ .msg_hex = "9bedc267423725d473888631ebf45988bad3db83851ee85c85e241a07d148b41", .public_key_hex = "f7badec5b8abeaf699583992219b7b223f1df3fbbea919844e3f7c554a43dd43", .sig_hex = "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffca8c5b64cd208982aa38d4936621a4775aa233aa0505711d8fdcfdaa943d4908", .expected = error.IdentityElement, // 9 - non-canonical R }, Vec{ .msg_hex = "e96b7021eb39c1a163b6da4e3093dcd3f21387da4cc4572be588fafae23c155b", .public_key_hex = "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", .sig_hex = "a9d55260f765261eb9b84e106f665e00b867287a761990d7135963ee0a7d59dca5bb704786be79fc476f91d3f3f89b03984d8068dcf1bb7dfc6637b45450ac04", .expected = error.IdentityElement, // 10 - small-order A }, Vec{ .msg_hex = "39a591f5321bbe07fd5a23dc2f39d025d74526615746727ceefd6e82ae65c06f", .public_key_hex = "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", .sig_hex = "a9d55260f765261eb9b84e106f665e00b867287a761990d7135963ee0a7d59dca5bb704786be79fc476f91d3f3f89b03984d8068dcf1bb7dfc6637b45450ac04", .expected = error.IdentityElement, // 11 - small-order A }, }; for (entries) |entry| { var msg: [entry.msg_hex.len / 2]u8 = undefined; _ = try fmt.hexToBytes(&msg, entry.msg_hex); var public_key: [32]u8 = undefined; _ = try fmt.hexToBytes(&public_key, entry.public_key_hex); var sig: [64]u8 = undefined; _ = try fmt.hexToBytes(&sig, entry.sig_hex); if (entry.expected) |error_type| { try std.testing.expectError(error_type, Ed25519.verify(sig, &msg, public_key)); } else { try Ed25519.verify(sig, &msg, public_key); } } }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/25519/field.zig
const std = @import("std"); const crypto = std.crypto; const readIntLittle = std.mem.readIntLittle; const writeIntLittle = std.mem.writeIntLittle; const NonCanonicalError = crypto.errors.NonCanonicalError; const NotSquareError = crypto.errors.NotSquareError; pub const Fe = struct { limbs: [5]u64, const MASK51: u64 = 0x7ffffffffffff; /// 0 pub const zero = Fe{ .limbs = .{ 0, 0, 0, 0, 0 } }; /// 1 pub const one = Fe{ .limbs = .{ 1, 0, 0, 0, 0 } }; /// sqrt(-1) pub const sqrtm1 = Fe{ .limbs = .{ 1718705420411056, 234908883556509, 2233514472574048, 2117202627021982, 765476049583133 } }; /// The Curve25519 base point pub const curve25519BasePoint = Fe{ .limbs = .{ 9, 0, 0, 0, 0 } }; /// Edwards25519 d = 37095705934669439343138083508754565189542113879843219016388785533085940283555 pub const edwards25519d = Fe{ .limbs = .{ 929955233495203, 466365720129213, 1662059464998953, 2033849074728123, 1442794654840575 } }; /// Edwards25519 2d pub const edwards25519d2 = Fe{ .limbs = .{ 1859910466990425, 932731440258426, 1072319116312658, 1815898335770999, 633789495995903 } }; /// Edwards25519 1/sqrt(a-d) pub const edwards25519sqrtamd = Fe{ .limbs = .{ 278908739862762, 821645201101625, 8113234426968, 1777959178193151, 2118520810568447 } }; /// Edwards25519 1-d^2 pub const edwards25519eonemsqd = Fe{ .limbs = .{ 1136626929484150, 1998550399581263, 496427632559748, 118527312129759, 45110755273534 } }; /// Edwards25519 (d-1)^2 pub const edwards25519sqdmone = Fe{ .limbs = .{ 1507062230895904, 1572317787530805, 683053064812840, 317374165784489, 1572899562415810 } }; /// Edwards25519 sqrt(ad-1) with a = -1 (mod p) pub const edwards25519sqrtadm1 = Fe{ .limbs = .{ 2241493124984347, 425987919032274, 2207028919301688, 1220490630685848, 974799131293748 } }; /// Edwards25519 A, as a single limb pub const edwards25519a_32: u32 = 486662; /// Edwards25519 A pub const edwards25519a = Fe{ .limbs = .{ @as(u64, edwards25519a_32), 0, 0, 0, 0 } }; /// Edwards25519 sqrt(A-2) pub const edwards25519sqrtam2 = Fe{ .limbs = .{ 1693982333959686, 608509411481997, 2235573344831311, 947681270984193, 266558006233600 } }; /// Return true if the field element is zero pub inline fn isZero(fe: Fe) bool { var reduced = fe; reduced.reduce(); const limbs = reduced.limbs; return (limbs[0] | limbs[1] | limbs[2] | limbs[3] | limbs[4]) == 0; } /// Return true if both field elements are equivalent pub inline fn equivalent(a: Fe, b: Fe) bool { return a.sub(b).isZero(); } /// Unpack a field element pub fn fromBytes(s: [32]u8) Fe { var fe: Fe = undefined; fe.limbs[0] = readIntLittle(u64, s[0..8]) & MASK51; fe.limbs[1] = (readIntLittle(u64, s[6..14]) >> 3) & MASK51; fe.limbs[2] = (readIntLittle(u64, s[12..20]) >> 6) & MASK51; fe.limbs[3] = (readIntLittle(u64, s[19..27]) >> 1) & MASK51; fe.limbs[4] = (readIntLittle(u64, s[24..32]) >> 12) & MASK51; return fe; } /// Pack a field element pub fn toBytes(fe: Fe) [32]u8 { var reduced = fe; reduced.reduce(); var s: [32]u8 = undefined; writeIntLittle(u64, s[0..8], reduced.limbs[0] | (reduced.limbs[1] << 51)); writeIntLittle(u64, s[8..16], (reduced.limbs[1] >> 13) | (reduced.limbs[2] << 38)); writeIntLittle(u64, s[16..24], (reduced.limbs[2] >> 26) | (reduced.limbs[3] << 25)); writeIntLittle(u64, s[24..32], (reduced.limbs[3] >> 39) | (reduced.limbs[4] << 12)); return s; } /// Map a 64 bytes big endian string into a field element pub fn fromBytes64(s: [64]u8) Fe { var fl: [32]u8 = undefined; var gl: [32]u8 = undefined; var i: usize = 0; while (i < 32) : (i += 1) { fl[i] = s[63 - i]; gl[i] = s[31 - i]; } fl[31] &= 0x7f; gl[31] &= 0x7f; var fe_f = fromBytes(fl); const fe_g = fromBytes(gl); fe_f.limbs[0] += (s[32] >> 7) * 19 + @as(u10, s[0] >> 7) * 722; i = 0; while (i < 5) : (i += 1) { fe_f.limbs[i] += 38 * fe_g.limbs[i]; } fe_f.reduce(); return fe_f; } /// Reject non-canonical encodings of an element, possibly ignoring the top bit pub fn rejectNonCanonical(s: [32]u8, comptime ignore_extra_bit: bool) NonCanonicalError!void { var c: u16 = (s[31] & 0x7f) ^ 0x7f; comptime var i = 30; inline while (i > 0) : (i -= 1) { c |= s[i] ^ 0xff; } c = (c -% 1) >> 8; const d = (@as(u16, 0xed - 1) -% @as(u16, s[0])) >> 8; const x = if (ignore_extra_bit) 0 else s[31] >> 7; if ((((c & d) | x) & 1) != 0) { return error.NonCanonical; } } /// Reduce a field element mod 2^255-19 fn reduce(fe: *Fe) void { comptime var i = 0; comptime var j = 0; const limbs = &fe.limbs; inline while (j < 2) : (j += 1) { i = 0; inline while (i < 4) : (i += 1) { limbs[i + 1] += limbs[i] >> 51; limbs[i] &= MASK51; } limbs[0] += 19 * (limbs[4] >> 51); limbs[4] &= MASK51; } limbs[0] += 19; i = 0; inline while (i < 4) : (i += 1) { limbs[i + 1] += limbs[i] >> 51; limbs[i] &= MASK51; } limbs[0] += 19 * (limbs[4] >> 51); limbs[4] &= MASK51; limbs[0] += 0x8000000000000 - 19; limbs[1] += 0x8000000000000 - 1; limbs[2] += 0x8000000000000 - 1; limbs[3] += 0x8000000000000 - 1; limbs[4] += 0x8000000000000 - 1; i = 0; inline while (i < 4) : (i += 1) { limbs[i + 1] += limbs[i] >> 51; limbs[i] &= MASK51; } limbs[4] &= MASK51; } /// Add a field element pub inline fn add(a: Fe, b: Fe) Fe { var fe: Fe = undefined; comptime var i = 0; inline while (i < 5) : (i += 1) { fe.limbs[i] = a.limbs[i] + b.limbs[i]; } return fe; } /// Substract a field elememnt pub inline fn sub(a: Fe, b: Fe) Fe { var fe = b; comptime var i = 0; inline while (i < 4) : (i += 1) { fe.limbs[i + 1] += fe.limbs[i] >> 51; fe.limbs[i] &= MASK51; } fe.limbs[0] += 19 * (fe.limbs[4] >> 51); fe.limbs[4] &= MASK51; fe.limbs[0] = (a.limbs[0] + 0xfffffffffffda) - fe.limbs[0]; fe.limbs[1] = (a.limbs[1] + 0xffffffffffffe) - fe.limbs[1]; fe.limbs[2] = (a.limbs[2] + 0xffffffffffffe) - fe.limbs[2]; fe.limbs[3] = (a.limbs[3] + 0xffffffffffffe) - fe.limbs[3]; fe.limbs[4] = (a.limbs[4] + 0xffffffffffffe) - fe.limbs[4]; return fe; } /// Negate a field element pub inline fn neg(a: Fe) Fe { return zero.sub(a); } /// Return true if a field element is negative pub inline fn isNegative(a: Fe) bool { return (a.toBytes()[0] & 1) != 0; } /// Conditonally replace a field element with `a` if `c` is positive pub inline fn cMov(fe: *Fe, a: Fe, c: u64) void { const mask: u64 = 0 -% c; var x = fe.*; comptime var i = 0; inline while (i < 5) : (i += 1) { x.limbs[i] ^= a.limbs[i]; } i = 0; inline while (i < 5) : (i += 1) { x.limbs[i] &= mask; } i = 0; inline while (i < 5) : (i += 1) { fe.limbs[i] ^= x.limbs[i]; } } /// Conditionally swap two pairs of field elements if `c` is positive pub fn cSwap2(a0: *Fe, b0: *Fe, a1: *Fe, b1: *Fe, c: u64) void { const mask: u64 = 0 -% c; var x0 = a0.*; var x1 = a1.*; comptime var i = 0; inline while (i < 5) : (i += 1) { x0.limbs[i] ^= b0.limbs[i]; x1.limbs[i] ^= b1.limbs[i]; } i = 0; inline while (i < 5) : (i += 1) { x0.limbs[i] &= mask; x1.limbs[i] &= mask; } i = 0; inline while (i < 5) : (i += 1) { a0.limbs[i] ^= x0.limbs[i]; b0.limbs[i] ^= x0.limbs[i]; a1.limbs[i] ^= x1.limbs[i]; b1.limbs[i] ^= x1.limbs[i]; } } inline fn _carry128(r: *[5]u128) Fe { var rs: [5]u64 = undefined; comptime var i = 0; inline while (i < 4) : (i += 1) { rs[i] = @as(u64, @truncate(r[i])) & MASK51; r[i + 1] += @as(u64, @intCast(r[i] >> 51)); } rs[4] = @as(u64, @truncate(r[4])) & MASK51; var carry = @as(u64, @intCast(r[4] >> 51)); rs[0] += 19 * carry; carry = rs[0] >> 51; rs[0] &= MASK51; rs[1] += carry; carry = rs[1] >> 51; rs[1] &= MASK51; rs[2] += carry; return .{ .limbs = rs }; } /// Multiply two field elements pub inline fn mul(a: Fe, b: Fe) Fe { var ax: [5]u128 = undefined; var bx: [5]u128 = undefined; var a19: [5]u128 = undefined; var r: [5]u128 = undefined; comptime var i = 0; inline while (i < 5) : (i += 1) { ax[i] = @as(u128, @intCast(a.limbs[i])); bx[i] = @as(u128, @intCast(b.limbs[i])); } i = 1; inline while (i < 5) : (i += 1) { a19[i] = 19 * ax[i]; } r[0] = ax[0] * bx[0] + a19[1] * bx[4] + a19[2] * bx[3] + a19[3] * bx[2] + a19[4] * bx[1]; r[1] = ax[0] * bx[1] + ax[1] * bx[0] + a19[2] * bx[4] + a19[3] * bx[3] + a19[4] * bx[2]; r[2] = ax[0] * bx[2] + ax[1] * bx[1] + ax[2] * bx[0] + a19[3] * bx[4] + a19[4] * bx[3]; r[3] = ax[0] * bx[3] + ax[1] * bx[2] + ax[2] * bx[1] + ax[3] * bx[0] + a19[4] * bx[4]; r[4] = ax[0] * bx[4] + ax[1] * bx[3] + ax[2] * bx[2] + ax[3] * bx[1] + ax[4] * bx[0]; return _carry128(&r); } inline fn _sq(a: Fe, comptime double: bool) Fe { var ax: [5]u128 = undefined; var r: [5]u128 = undefined; comptime var i = 0; inline while (i < 5) : (i += 1) { ax[i] = @as(u128, @intCast(a.limbs[i])); } const a0_2 = 2 * ax[0]; const a1_2 = 2 * ax[1]; const a1_38 = 38 * ax[1]; const a2_38 = 38 * ax[2]; const a3_38 = 38 * ax[3]; const a3_19 = 19 * ax[3]; const a4_19 = 19 * ax[4]; r[0] = ax[0] * ax[0] + a1_38 * ax[4] + a2_38 * ax[3]; r[1] = a0_2 * ax[1] + a2_38 * ax[4] + a3_19 * ax[3]; r[2] = a0_2 * ax[2] + ax[1] * ax[1] + a3_38 * ax[4]; r[3] = a0_2 * ax[3] + a1_2 * ax[2] + a4_19 * ax[4]; r[4] = a0_2 * ax[4] + a1_2 * ax[3] + ax[2] * ax[2]; if (double) { i = 0; inline while (i < 5) : (i += 1) { r[i] *= 2; } } return _carry128(&r); } /// Square a field element pub inline fn sq(a: Fe) Fe { return _sq(a, false); } /// Square and double a field element pub inline fn sq2(a: Fe) Fe { return _sq(a, true); } /// Multiply a field element with a small (32-bit) integer pub inline fn mul32(a: Fe, comptime n: u32) Fe { const sn = @as(u128, @intCast(n)); var fe: Fe = undefined; var x: u128 = 0; comptime var i = 0; inline while (i < 5) : (i += 1) { x = a.limbs[i] * sn + (x >> 51); fe.limbs[i] = @as(u64, @truncate(x)) & MASK51; } fe.limbs[0] += @as(u64, @intCast(x >> 51)) * 19; return fe; } /// Square a field element `n` times inline fn sqn(a: Fe, comptime n: comptime_int) Fe { var i: usize = 0; var fe = a; while (i < n) : (i += 1) { fe = fe.sq(); } return fe; } /// Return the inverse of a field element, or 0 if a=0. pub fn invert(a: Fe) Fe { var t0 = a.sq(); var t1 = t0.sqn(2).mul(a); t0 = t0.mul(t1); t1 = t1.mul(t0.sq()); t1 = t1.mul(t1.sqn(5)); var t2 = t1.sqn(10).mul(t1); t2 = t2.mul(t2.sqn(20)).sqn(10); t1 = t1.mul(t2); t2 = t1.sqn(50).mul(t1); return t1.mul(t2.mul(t2.sqn(100)).sqn(50)).sqn(5).mul(t0); } /// Return a^((p-5)/8) = a^(2^252-3) /// Used to compute square roots since we have p=5 (mod 8); see Cohen and Frey. pub fn pow2523(a: Fe) Fe { var t0 = a.mul(a.sq()); var t1 = t0.mul(t0.sqn(2)).sq().mul(a); t0 = t1.sqn(5).mul(t1); var t2 = t0.sqn(5).mul(t1); t1 = t2.sqn(15).mul(t2); t2 = t1.sqn(30).mul(t1); t1 = t2.sqn(60).mul(t2); return t1.sqn(120).mul(t1).sqn(10).mul(t0).sqn(2).mul(a); } /// Return the absolute value of a field element pub fn abs(a: Fe) Fe { var r = a; r.cMov(a.neg(), @intFromBool(a.isNegative())); return r; } /// Return true if the field element is a square pub fn isSquare(a: Fe) bool { // Compute the Jacobi symbol x^((p-1)/2) const _11 = a.mul(a.sq()); const _1111 = _11.mul(_11.sq().sq()); const _11111111 = _1111.mul(_1111.sq().sq().sq().sq()); var t = _11111111.sqn(2).mul(_11); const u = t; t = t.sqn(10).mul(u).sqn(10).mul(u); t = t.sqn(30).mul(t); t = t.sqn(60).mul(t); t = t.sqn(120).mul(t).sqn(10).mul(u).sqn(3).mul(_11).sq(); return @as(bool, @bitCast(@as(u1, @truncate(~(t.toBytes()[1] & 1))))); } fn uncheckedSqrt(x2: Fe) Fe { var e = x2.pow2523(); const p_root = e.mul(x2); // positive root const m_root = p_root.mul(Fe.sqrtm1); // negative root const m_root2 = m_root.sq(); e = x2.sub(m_root2); var x = p_root; x.cMov(m_root, @intFromBool(e.isZero())); return x; } /// Compute the square root of `x2`, returning `error.NotSquare` if `x2` was not a square pub fn sqrt(x2: Fe) NotSquareError!Fe { var x2_copy = x2; const x = x2.uncheckedSqrt(); const check = x.sq().sub(x2_copy); if (check.isZero()) { return x; } return error.NotSquare; } };
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto
repos/gotta-go-fast/src/self-hosted-parser/input_dir/crypto/25519/scalar.zig
const std = @import("std"); const mem = std.mem; const NonCanonicalError = std.crypto.errors.NonCanonicalError; /// 2^252 + 27742317777372353535851937790883648493 pub const field_size = [32]u8{ 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, // 2^252+27742317777372353535851937790883648493 }; /// A compressed scalar pub const CompressedScalar = [32]u8; /// Zero pub const zero = [_]u8{0} ** 32; /// Reject a scalar whose encoding is not canonical. pub fn rejectNonCanonical(s: [32]u8) NonCanonicalError!void { var c: u8 = 0; var n: u8 = 1; var i: usize = 31; while (true) : (i -= 1) { const xs = @as(u16, s[i]); const xfield_size = @as(u16, field_size[i]); c |= @as(u8, @intCast(((xs -% xfield_size) >> 8) & n)); n &= @as(u8, @intCast(((xs ^ xfield_size) -% 1) >> 8)); if (i == 0) break; } if (c == 0) { return error.NonCanonical; } } /// Reduce a scalar to the field size. pub fn reduce(s: [32]u8) [32]u8 { return Scalar.fromBytes(s).toBytes(); } /// Reduce a 64-bytes scalar to the field size. pub fn reduce64(s: [64]u8) [32]u8 { return ScalarDouble.fromBytes64(s).toBytes(); } /// Perform the X25519 "clamping" operation. /// The scalar is then guaranteed to be a multiple of the cofactor. pub inline fn clamp(s: *[32]u8) void { s[0] &= 248; s[31] = (s[31] & 127) | 64; } /// Return a*b (mod L) pub fn mul(a: [32]u8, b: [32]u8) [32]u8 { return Scalar.fromBytes(a).mul(Scalar.fromBytes(b)).toBytes(); } /// Return a*b+c (mod L) pub fn mulAdd(a: [32]u8, b: [32]u8, c: [32]u8) [32]u8 { return Scalar.fromBytes(a).mul(Scalar.fromBytes(b)).add(Scalar.fromBytes(c)).toBytes(); } /// Return a*8 (mod L) pub fn mul8(s: [32]u8) [32]u8 { var x = Scalar.fromBytes(s); x = x.add(x); x = x.add(x); x = x.add(x); return x.toBytes(); } /// Return a+b (mod L) pub fn add(a: [32]u8, b: [32]u8) [32]u8 { return Scalar.fromBytes(a).add(Scalar.fromBytes(b)).toBytes(); } /// Return -s (mod L) pub fn neg(s: [32]u8) [32]u8 { const fs: [64]u8 = field_size ++ [_]u8{0} ** 32; var sx: [64]u8 = undefined; mem.copy(u8, sx[0..32], s[0..]); mem.set(u8, sx[32..], 0); var carry: u32 = 0; var i: usize = 0; while (i < 64) : (i += 1) { carry = @as(u32, fs[i]) -% sx[i] -% @as(u32, carry); sx[i] = @as(u8, @truncate(carry)); carry = (carry >> 8) & 1; } return reduce64(sx); } /// Return (a-b) (mod L) pub fn sub(a: [32]u8, b: [32]u8) [32]u8 { return add(a, neg(b)); } /// A scalar in unpacked representation pub const Scalar = struct { const Limbs = [5]u64; limbs: Limbs = undefined, /// Unpack a 32-byte representation of a scalar pub fn fromBytes(bytes: [32]u8) Scalar { return ScalarDouble.fromBytes32(bytes).reduce(5); } /// Pack a scalar into bytes pub fn toBytes(expanded: *const Scalar) [32]u8 { var bytes: [32]u8 = undefined; var i: usize = 0; while (i < 4) : (i += 1) { mem.writeIntLittle(u64, bytes[i * 7 ..][0..8], expanded.limbs[i]); } mem.writeIntLittle(u32, bytes[i * 7 ..][0..4], @as(u32, @intCast(expanded.limbs[i]))); return bytes; } /// Return x+y (mod l) pub fn add(x: Scalar, y: Scalar) Scalar { const carry0 = (x.limbs[0] + y.limbs[0]) >> 56; const t0 = (x.limbs[0] + y.limbs[0]) & 0xffffffffffffff; const t00 = t0; const c0 = carry0; const carry1 = (x.limbs[1] + y.limbs[1] + c0) >> 56; const t1 = (x.limbs[1] + y.limbs[1] + c0) & 0xffffffffffffff; const t10 = t1; const c1 = carry1; const carry2 = (x.limbs[2] + y.limbs[2] + c1) >> 56; const t2 = (x.limbs[2] + y.limbs[2] + c1) & 0xffffffffffffff; const t20 = t2; const c2 = carry2; const carry = (x.limbs[3] + y.limbs[3] + c2) >> 56; const t3 = (x.limbs[3] + y.limbs[3] + c2) & 0xffffffffffffff; const t30 = t3; const c3 = carry; const t4 = x.limbs[4] + y.limbs[4] + c3; const y01: u64 = 5175514460705773; const y11: u64 = 70332060721272408; const y21: u64 = 5342; const y31: u64 = 0; const y41: u64 = 268435456; const b5 = (t00 -% y01) >> 63; const t5 = ((b5 << 56) + t00) -% y01; const b0 = b5; const t01 = t5; const b6 = (t10 -% (y11 + b0)) >> 63; const t6 = ((b6 << 56) + t10) -% (y11 + b0); const b1 = b6; const t11 = t6; const b7 = (t20 -% (y21 + b1)) >> 63; const t7 = ((b7 << 56) + t20) -% (y21 + b1); const b2 = b7; const t21 = t7; const b8 = (t30 -% (y31 + b2)) >> 63; const t8 = ((b8 << 56) + t30) -% (y31 + b2); const b3 = b8; const t31 = t8; const b = (t4 -% (y41 + b3)) >> 63; const t = ((b << 56) + t4) -% (y41 + b3); const b4 = b; const t41 = t; const mask = (b4 -% 1); const z00 = t00 ^ (mask & (t00 ^ t01)); const z10 = t10 ^ (mask & (t10 ^ t11)); const z20 = t20 ^ (mask & (t20 ^ t21)); const z30 = t30 ^ (mask & (t30 ^ t31)); const z40 = t4 ^ (mask & (t4 ^ t41)); return Scalar{ .limbs = .{ z00, z10, z20, z30, z40 } }; } /// Return x*r (mod l) pub fn mul(x: Scalar, y: Scalar) Scalar { const xy000 = @as(u128, x.limbs[0]) * @as(u128, y.limbs[0]); const xy010 = @as(u128, x.limbs[0]) * @as(u128, y.limbs[1]); const xy020 = @as(u128, x.limbs[0]) * @as(u128, y.limbs[2]); const xy030 = @as(u128, x.limbs[0]) * @as(u128, y.limbs[3]); const xy040 = @as(u128, x.limbs[0]) * @as(u128, y.limbs[4]); const xy100 = @as(u128, x.limbs[1]) * @as(u128, y.limbs[0]); const xy110 = @as(u128, x.limbs[1]) * @as(u128, y.limbs[1]); const xy120 = @as(u128, x.limbs[1]) * @as(u128, y.limbs[2]); const xy130 = @as(u128, x.limbs[1]) * @as(u128, y.limbs[3]); const xy140 = @as(u128, x.limbs[1]) * @as(u128, y.limbs[4]); const xy200 = @as(u128, x.limbs[2]) * @as(u128, y.limbs[0]); const xy210 = @as(u128, x.limbs[2]) * @as(u128, y.limbs[1]); const xy220 = @as(u128, x.limbs[2]) * @as(u128, y.limbs[2]); const xy230 = @as(u128, x.limbs[2]) * @as(u128, y.limbs[3]); const xy240 = @as(u128, x.limbs[2]) * @as(u128, y.limbs[4]); const xy300 = @as(u128, x.limbs[3]) * @as(u128, y.limbs[0]); const xy310 = @as(u128, x.limbs[3]) * @as(u128, y.limbs[1]); const xy320 = @as(u128, x.limbs[3]) * @as(u128, y.limbs[2]); const xy330 = @as(u128, x.limbs[3]) * @as(u128, y.limbs[3]); const xy340 = @as(u128, x.limbs[3]) * @as(u128, y.limbs[4]); const xy400 = @as(u128, x.limbs[4]) * @as(u128, y.limbs[0]); const xy410 = @as(u128, x.limbs[4]) * @as(u128, y.limbs[1]); const xy420 = @as(u128, x.limbs[4]) * @as(u128, y.limbs[2]); const xy430 = @as(u128, x.limbs[4]) * @as(u128, y.limbs[3]); const xy440 = @as(u128, x.limbs[4]) * @as(u128, y.limbs[4]); const z00 = xy000; const z10 = xy010 + xy100; const z20 = xy020 + xy110 + xy200; const z30 = xy030 + xy120 + xy210 + xy300; const z40 = xy040 + xy130 + xy220 + xy310 + xy400; const z50 = xy140 + xy230 + xy320 + xy410; const z60 = xy240 + xy330 + xy420; const z70 = xy340 + xy430; const z80 = xy440; const carry0 = z00 >> 56; const t10 = @as(u64, @truncate(z00)) & 0xffffffffffffff; const c00 = carry0; const t00 = t10; const carry1 = (z10 + c00) >> 56; const t11 = @as(u64, @truncate((z10 + c00))) & 0xffffffffffffff; const c10 = carry1; const t12 = t11; const carry2 = (z20 + c10) >> 56; const t13 = @as(u64, @truncate((z20 + c10))) & 0xffffffffffffff; const c20 = carry2; const t20 = t13; const carry3 = (z30 + c20) >> 56; const t14 = @as(u64, @truncate((z30 + c20))) & 0xffffffffffffff; const c30 = carry3; const t30 = t14; const carry4 = (z40 + c30) >> 56; const t15 = @as(u64, @truncate((z40 + c30))) & 0xffffffffffffff; const c40 = carry4; const t40 = t15; const carry5 = (z50 + c40) >> 56; const t16 = @as(u64, @truncate((z50 + c40))) & 0xffffffffffffff; const c50 = carry5; const t50 = t16; const carry6 = (z60 + c50) >> 56; const t17 = @as(u64, @truncate((z60 + c50))) & 0xffffffffffffff; const c60 = carry6; const t60 = t17; const carry7 = (z70 + c60) >> 56; const t18 = @as(u64, @truncate((z70 + c60))) & 0xffffffffffffff; const c70 = carry7; const t70 = t18; const carry8 = (z80 + c70) >> 56; const t19 = @as(u64, @truncate((z80 + c70))) & 0xffffffffffffff; const c80 = carry8; const t80 = t19; const t90 = (@as(u64, @truncate(c80))); const r0 = t00; const r1 = t12; const r2 = t20; const r3 = t30; const r4 = t40; const r5 = t50; const r6 = t60; const r7 = t70; const r8 = t80; const r9 = t90; const m0: u64 = 5175514460705773; const m1: u64 = 70332060721272408; const m2: u64 = 5342; const m3: u64 = 0; const m4: u64 = 268435456; const mu0: u64 = 44162584779952923; const mu1: u64 = 9390964836247533; const mu2: u64 = 72057594036560134; const mu3: u64 = 72057594037927935; const mu4: u64 = 68719476735; const y_ = (r5 & 0xffffff) << 32; const x_ = r4 >> 24; const z01 = (x_ | y_); const y_0 = (r6 & 0xffffff) << 32; const x_0 = r5 >> 24; const z11 = (x_0 | y_0); const y_1 = (r7 & 0xffffff) << 32; const x_1 = r6 >> 24; const z21 = (x_1 | y_1); const y_2 = (r8 & 0xffffff) << 32; const x_2 = r7 >> 24; const z31 = (x_2 | y_2); const y_3 = (r9 & 0xffffff) << 32; const x_3 = r8 >> 24; const z41 = (x_3 | y_3); const q0 = z01; const q1 = z11; const q2 = z21; const q3 = z31; const q4 = z41; const xy001 = @as(u128, q0) * @as(u128, mu0); const xy011 = @as(u128, q0) * @as(u128, mu1); const xy021 = @as(u128, q0) * @as(u128, mu2); const xy031 = @as(u128, q0) * @as(u128, mu3); const xy041 = @as(u128, q0) * @as(u128, mu4); const xy101 = @as(u128, q1) * @as(u128, mu0); const xy111 = @as(u128, q1) * @as(u128, mu1); const xy121 = @as(u128, q1) * @as(u128, mu2); const xy131 = @as(u128, q1) * @as(u128, mu3); const xy14 = @as(u128, q1) * @as(u128, mu4); const xy201 = @as(u128, q2) * @as(u128, mu0); const xy211 = @as(u128, q2) * @as(u128, mu1); const xy221 = @as(u128, q2) * @as(u128, mu2); const xy23 = @as(u128, q2) * @as(u128, mu3); const xy24 = @as(u128, q2) * @as(u128, mu4); const xy301 = @as(u128, q3) * @as(u128, mu0); const xy311 = @as(u128, q3) * @as(u128, mu1); const xy32 = @as(u128, q3) * @as(u128, mu2); const xy33 = @as(u128, q3) * @as(u128, mu3); const xy34 = @as(u128, q3) * @as(u128, mu4); const xy401 = @as(u128, q4) * @as(u128, mu0); const xy41 = @as(u128, q4) * @as(u128, mu1); const xy42 = @as(u128, q4) * @as(u128, mu2); const xy43 = @as(u128, q4) * @as(u128, mu3); const xy44 = @as(u128, q4) * @as(u128, mu4); const z02 = xy001; const z12 = xy011 + xy101; const z22 = xy021 + xy111 + xy201; const z32 = xy031 + xy121 + xy211 + xy301; const z42 = xy041 + xy131 + xy221 + xy311 + xy401; const z5 = xy14 + xy23 + xy32 + xy41; const z6 = xy24 + xy33 + xy42; const z7 = xy34 + xy43; const z8 = xy44; const carry9 = z02 >> 56; const c01 = carry9; const carry10 = (z12 + c01) >> 56; const c11 = carry10; const carry11 = (z22 + c11) >> 56; const c21 = carry11; const carry12 = (z32 + c21) >> 56; const c31 = carry12; const carry13 = (z42 + c31) >> 56; const t24 = @as(u64, @truncate(z42 + c31)) & 0xffffffffffffff; const c41 = carry13; const t41 = t24; const carry14 = (z5 + c41) >> 56; const t25 = @as(u64, @truncate(z5 + c41)) & 0xffffffffffffff; const c5 = carry14; const t5 = t25; const carry15 = (z6 + c5) >> 56; const t26 = @as(u64, @truncate(z6 + c5)) & 0xffffffffffffff; const c6 = carry15; const t6 = t26; const carry16 = (z7 + c6) >> 56; const t27 = @as(u64, @truncate(z7 + c6)) & 0xffffffffffffff; const c7 = carry16; const t7 = t27; const carry17 = (z8 + c7) >> 56; const t28 = @as(u64, @truncate(z8 + c7)) & 0xffffffffffffff; const c8 = carry17; const t8 = t28; const t9 = @as(u64, @truncate(c8)); const qmu4_ = t41; const qmu5_ = t5; const qmu6_ = t6; const qmu7_ = t7; const qmu8_ = t8; const qmu9_ = t9; const y_4 = (qmu5_ & 0xffffffffff) << 16; const x_4 = qmu4_ >> 40; const z03 = (x_4 | y_4); const y_5 = (qmu6_ & 0xffffffffff) << 16; const x_5 = qmu5_ >> 40; const z13 = (x_5 | y_5); const y_6 = (qmu7_ & 0xffffffffff) << 16; const x_6 = qmu6_ >> 40; const z23 = (x_6 | y_6); const y_7 = (qmu8_ & 0xffffffffff) << 16; const x_7 = qmu7_ >> 40; const z33 = (x_7 | y_7); const y_8 = (qmu9_ & 0xffffffffff) << 16; const x_8 = qmu8_ >> 40; const z43 = (x_8 | y_8); const qdiv0 = z03; const qdiv1 = z13; const qdiv2 = z23; const qdiv3 = z33; const qdiv4 = z43; const r01 = r0; const r11 = r1; const r21 = r2; const r31 = r3; const r41 = (r4 & 0xffffffffff); const xy00 = @as(u128, qdiv0) * @as(u128, m0); const xy01 = @as(u128, qdiv0) * @as(u128, m1); const xy02 = @as(u128, qdiv0) * @as(u128, m2); const xy03 = @as(u128, qdiv0) * @as(u128, m3); const xy04 = @as(u128, qdiv0) * @as(u128, m4); const xy10 = @as(u128, qdiv1) * @as(u128, m0); const xy11 = @as(u128, qdiv1) * @as(u128, m1); const xy12 = @as(u128, qdiv1) * @as(u128, m2); const xy13 = @as(u128, qdiv1) * @as(u128, m3); const xy20 = @as(u128, qdiv2) * @as(u128, m0); const xy21 = @as(u128, qdiv2) * @as(u128, m1); const xy22 = @as(u128, qdiv2) * @as(u128, m2); const xy30 = @as(u128, qdiv3) * @as(u128, m0); const xy31 = @as(u128, qdiv3) * @as(u128, m1); const xy40 = @as(u128, qdiv4) * @as(u128, m0); const carry18 = xy00 >> 56; const t29 = @as(u64, @truncate(xy00)) & 0xffffffffffffff; const c0 = carry18; const t01 = t29; const carry19 = (xy01 + xy10 + c0) >> 56; const t31 = @as(u64, @truncate(xy01 + xy10 + c0)) & 0xffffffffffffff; const c12 = carry19; const t110 = t31; const carry20 = (xy02 + xy11 + xy20 + c12) >> 56; const t32 = @as(u64, @truncate(xy02 + xy11 + xy20 + c12)) & 0xffffffffffffff; const c22 = carry20; const t210 = t32; const carry = (xy03 + xy12 + xy21 + xy30 + c22) >> 56; const t33 = @as(u64, @truncate(xy03 + xy12 + xy21 + xy30 + c22)) & 0xffffffffffffff; const c32 = carry; const t34 = t33; const t42 = @as(u64, @truncate(xy04 + xy13 + xy22 + xy31 + xy40 + c32)) & 0xffffffffff; const qmul0 = t01; const qmul1 = t110; const qmul2 = t210; const qmul3 = t34; const qmul4 = t42; const b5 = (r01 -% qmul0) >> 63; const t35 = ((b5 << 56) + r01) -% qmul0; const c1 = b5; const t02 = t35; const b6 = (r11 -% (qmul1 + c1)) >> 63; const t36 = ((b6 << 56) + r11) -% (qmul1 + c1); const c2 = b6; const t111 = t36; const b7 = (r21 -% (qmul2 + c2)) >> 63; const t37 = ((b7 << 56) + r21) -% (qmul2 + c2); const c3 = b7; const t211 = t37; const b8 = (r31 -% (qmul3 + c3)) >> 63; const t38 = ((b8 << 56) + r31) -% (qmul3 + c3); const c4 = b8; const t39 = t38; const b9 = (r41 -% (qmul4 + c4)) >> 63; const t43 = ((b9 << 40) + r41) -% (qmul4 + c4); const t44 = t43; const s0 = t02; const s1 = t111; const s2 = t211; const s3 = t39; const s4 = t44; const y01: u64 = 5175514460705773; const y11: u64 = 70332060721272408; const y21: u64 = 5342; const y31: u64 = 0; const y41: u64 = 268435456; const b10 = (s0 -% y01) >> 63; const t45 = ((b10 << 56) + s0) -% y01; const b0 = b10; const t0 = t45; const b11 = (s1 -% (y11 + b0)) >> 63; const t46 = ((b11 << 56) + s1) -% (y11 + b0); const b1 = b11; const t1 = t46; const b12 = (s2 -% (y21 + b1)) >> 63; const t47 = ((b12 << 56) + s2) -% (y21 + b1); const b2 = b12; const t2 = t47; const b13 = (s3 -% (y31 + b2)) >> 63; const t48 = ((b13 << 56) + s3) -% (y31 + b2); const b3 = b13; const t3 = t48; const b = (s4 -% (y41 + b3)) >> 63; const t = ((b << 56) + s4) -% (y41 + b3); const b4 = b; const t4 = t; const mask = (b4 -% @as(u64, @intCast(((1))))); const z04 = s0 ^ (mask & (s0 ^ t0)); const z14 = s1 ^ (mask & (s1 ^ t1)); const z24 = s2 ^ (mask & (s2 ^ t2)); const z34 = s3 ^ (mask & (s3 ^ t3)); const z44 = s4 ^ (mask & (s4 ^ t4)); return Scalar{ .limbs = .{ z04, z14, z24, z34, z44 } }; } }; const ScalarDouble = struct { const Limbs = [10]u64; limbs: Limbs = undefined, fn fromBytes64(bytes: [64]u8) ScalarDouble { var limbs: Limbs = undefined; var i: usize = 0; while (i < 9) : (i += 1) { limbs[i] = mem.readIntLittle(u64, bytes[i * 7 ..][0..8]) & 0xffffffffffffff; } limbs[i] = @as(u64, bytes[i * 7]); return ScalarDouble{ .limbs = limbs }; } fn fromBytes32(bytes: [32]u8) ScalarDouble { var limbs: Limbs = undefined; var i: usize = 0; while (i < 4) : (i += 1) { limbs[i] = mem.readIntLittle(u64, bytes[i * 7 ..][0..8]) & 0xffffffffffffff; } limbs[i] = @as(u64, mem.readIntLittle(u32, bytes[i * 7 ..][0..4])); mem.set(u64, limbs[5..], 0); return ScalarDouble{ .limbs = limbs }; } fn toBytes(expanded_double: *ScalarDouble) [32]u8 { return expanded_double.reduce(10).toBytes(); } /// Barrett reduction fn reduce(expanded: *ScalarDouble, comptime limbs_count: usize) Scalar { const t = expanded.limbs; const t0 = if (limbs_count <= 0) 0 else t[0]; const t1 = if (limbs_count <= 1) 0 else t[1]; const t2 = if (limbs_count <= 2) 0 else t[2]; const t3 = if (limbs_count <= 3) 0 else t[3]; const t4 = if (limbs_count <= 4) 0 else t[4]; const t5 = if (limbs_count <= 5) 0 else t[5]; const t6 = if (limbs_count <= 6) 0 else t[6]; const t7 = if (limbs_count <= 7) 0 else t[7]; const t8 = if (limbs_count <= 8) 0 else t[8]; const t9 = if (limbs_count <= 9) 0 else t[9]; const m0: u64 = 5175514460705773; const m1: u64 = 70332060721272408; const m2: u64 = 5342; const m3: u64 = 0; const m4: u64 = 268435456; const mu0: u64 = 44162584779952923; const mu1: u64 = 9390964836247533; const mu2: u64 = 72057594036560134; const mu3: u64 = 0xffffffffffffff; const mu4: u64 = 68719476735; const y_ = (t5 & 0xffffff) << 32; const x_ = t4 >> 24; const z00 = x_ | y_; const y_0 = (t6 & 0xffffff) << 32; const x_0 = t5 >> 24; const z10 = x_0 | y_0; const y_1 = (t7 & 0xffffff) << 32; const x_1 = t6 >> 24; const z20 = x_1 | y_1; const y_2 = (t8 & 0xffffff) << 32; const x_2 = t7 >> 24; const z30 = x_2 | y_2; const y_3 = (t9 & 0xffffff) << 32; const x_3 = t8 >> 24; const z40 = x_3 | y_3; const q0 = z00; const q1 = z10; const q2 = z20; const q3 = z30; const q4 = z40; const xy000 = @as(u128, q0) * @as(u128, mu0); const xy010 = @as(u128, q0) * @as(u128, mu1); const xy020 = @as(u128, q0) * @as(u128, mu2); const xy030 = @as(u128, q0) * @as(u128, mu3); const xy040 = @as(u128, q0) * @as(u128, mu4); const xy100 = @as(u128, q1) * @as(u128, mu0); const xy110 = @as(u128, q1) * @as(u128, mu1); const xy120 = @as(u128, q1) * @as(u128, mu2); const xy130 = @as(u128, q1) * @as(u128, mu3); const xy14 = @as(u128, q1) * @as(u128, mu4); const xy200 = @as(u128, q2) * @as(u128, mu0); const xy210 = @as(u128, q2) * @as(u128, mu1); const xy220 = @as(u128, q2) * @as(u128, mu2); const xy23 = @as(u128, q2) * @as(u128, mu3); const xy24 = @as(u128, q2) * @as(u128, mu4); const xy300 = @as(u128, q3) * @as(u128, mu0); const xy310 = @as(u128, q3) * @as(u128, mu1); const xy32 = @as(u128, q3) * @as(u128, mu2); const xy33 = @as(u128, q3) * @as(u128, mu3); const xy34 = @as(u128, q3) * @as(u128, mu4); const xy400 = @as(u128, q4) * @as(u128, mu0); const xy41 = @as(u128, q4) * @as(u128, mu1); const xy42 = @as(u128, q4) * @as(u128, mu2); const xy43 = @as(u128, q4) * @as(u128, mu3); const xy44 = @as(u128, q4) * @as(u128, mu4); const z01 = xy000; const z11 = xy010 + xy100; const z21 = xy020 + xy110 + xy200; const z31 = xy030 + xy120 + xy210 + xy300; const z41 = xy040 + xy130 + xy220 + xy310 + xy400; const z5 = xy14 + xy23 + xy32 + xy41; const z6 = xy24 + xy33 + xy42; const z7 = xy34 + xy43; const z8 = xy44; const carry0 = z01 >> 56; const c00 = carry0; const carry1 = (z11 + c00) >> 56; const c10 = carry1; const carry2 = (z21 + c10) >> 56; const c20 = carry2; const carry3 = (z31 + c20) >> 56; const c30 = carry3; const carry4 = (z41 + c30) >> 56; const t103 = @as(u64, @as(u64, @truncate(z41 + c30))) & 0xffffffffffffff; const c40 = carry4; const t410 = t103; const carry5 = (z5 + c40) >> 56; const t104 = @as(u64, @as(u64, @truncate(z5 + c40))) & 0xffffffffffffff; const c5 = carry5; const t51 = t104; const carry6 = (z6 + c5) >> 56; const t105 = @as(u64, @as(u64, @truncate(z6 + c5))) & 0xffffffffffffff; const c6 = carry6; const t61 = t105; const carry7 = (z7 + c6) >> 56; const t106 = @as(u64, @as(u64, @truncate(z7 + c6))) & 0xffffffffffffff; const c7 = carry7; const t71 = t106; const carry8 = (z8 + c7) >> 56; const t107 = @as(u64, @as(u64, @truncate(z8 + c7))) & 0xffffffffffffff; const c8 = carry8; const t81 = t107; const t91 = @as(u64, @as(u64, @truncate(c8))); const qmu4_ = t410; const qmu5_ = t51; const qmu6_ = t61; const qmu7_ = t71; const qmu8_ = t81; const qmu9_ = t91; const y_4 = (qmu5_ & 0xffffffffff) << 16; const x_4 = qmu4_ >> 40; const z02 = x_4 | y_4; const y_5 = (qmu6_ & 0xffffffffff) << 16; const x_5 = qmu5_ >> 40; const z12 = x_5 | y_5; const y_6 = (qmu7_ & 0xffffffffff) << 16; const x_6 = qmu6_ >> 40; const z22 = x_6 | y_6; const y_7 = (qmu8_ & 0xffffffffff) << 16; const x_7 = qmu7_ >> 40; const z32 = x_7 | y_7; const y_8 = (qmu9_ & 0xffffffffff) << 16; const x_8 = qmu8_ >> 40; const z42 = x_8 | y_8; const qdiv0 = z02; const qdiv1 = z12; const qdiv2 = z22; const qdiv3 = z32; const qdiv4 = z42; const r0 = t0; const r1 = t1; const r2 = t2; const r3 = t3; const r4 = t4 & 0xffffffffff; const xy00 = @as(u128, qdiv0) * @as(u128, m0); const xy01 = @as(u128, qdiv0) * @as(u128, m1); const xy02 = @as(u128, qdiv0) * @as(u128, m2); const xy03 = @as(u128, qdiv0) * @as(u128, m3); const xy04 = @as(u128, qdiv0) * @as(u128, m4); const xy10 = @as(u128, qdiv1) * @as(u128, m0); const xy11 = @as(u128, qdiv1) * @as(u128, m1); const xy12 = @as(u128, qdiv1) * @as(u128, m2); const xy13 = @as(u128, qdiv1) * @as(u128, m3); const xy20 = @as(u128, qdiv2) * @as(u128, m0); const xy21 = @as(u128, qdiv2) * @as(u128, m1); const xy22 = @as(u128, qdiv2) * @as(u128, m2); const xy30 = @as(u128, qdiv3) * @as(u128, m0); const xy31 = @as(u128, qdiv3) * @as(u128, m1); const xy40 = @as(u128, qdiv4) * @as(u128, m0); const carry9 = xy00 >> 56; const t108 = @as(u64, @truncate(xy00)) & 0xffffffffffffff; const c0 = carry9; const t010 = t108; const carry10 = (xy01 + xy10 + c0) >> 56; const t109 = @as(u64, @truncate(xy01 + xy10 + c0)) & 0xffffffffffffff; const c11 = carry10; const t110 = t109; const carry11 = (xy02 + xy11 + xy20 + c11) >> 56; const t1010 = @as(u64, @truncate(xy02 + xy11 + xy20 + c11)) & 0xffffffffffffff; const c21 = carry11; const t210 = t1010; const carry = (xy03 + xy12 + xy21 + xy30 + c21) >> 56; const t1011 = @as(u64, @truncate(xy03 + xy12 + xy21 + xy30 + c21)) & 0xffffffffffffff; const c31 = carry; const t310 = t1011; const t411 = @as(u64, @truncate(xy04 + xy13 + xy22 + xy31 + xy40 + c31)) & 0xffffffffff; const qmul0 = t010; const qmul1 = t110; const qmul2 = t210; const qmul3 = t310; const qmul4 = t411; const b5 = (r0 -% qmul0) >> 63; const t1012 = ((b5 << 56) + r0) -% qmul0; const c1 = b5; const t011 = t1012; const b6 = (r1 -% (qmul1 + c1)) >> 63; const t1013 = ((b6 << 56) + r1) -% (qmul1 + c1); const c2 = b6; const t111 = t1013; const b7 = (r2 -% (qmul2 + c2)) >> 63; const t1014 = ((b7 << 56) + r2) -% (qmul2 + c2); const c3 = b7; const t211 = t1014; const b8 = (r3 -% (qmul3 + c3)) >> 63; const t1015 = ((b8 << 56) + r3) -% (qmul3 + c3); const c4 = b8; const t311 = t1015; const b9 = (r4 -% (qmul4 + c4)) >> 63; const t1016 = ((b9 << 40) + r4) -% (qmul4 + c4); const t412 = t1016; const s0 = t011; const s1 = t111; const s2 = t211; const s3 = t311; const s4 = t412; const y0: u64 = 5175514460705773; const y1: u64 = 70332060721272408; const y2: u64 = 5342; const y3: u64 = 0; const y4: u64 = 268435456; const b10 = (s0 -% y0) >> 63; const t1017 = ((b10 << 56) + s0) -% y0; const b0 = b10; const t01 = t1017; const b11 = (s1 -% (y1 + b0)) >> 63; const t1018 = ((b11 << 56) + s1) -% (y1 + b0); const b1 = b11; const t11 = t1018; const b12 = (s2 -% (y2 + b1)) >> 63; const t1019 = ((b12 << 56) + s2) -% (y2 + b1); const b2 = b12; const t21 = t1019; const b13 = (s3 -% (y3 + b2)) >> 63; const t1020 = ((b13 << 56) + s3) -% (y3 + b2); const b3 = b13; const t31 = t1020; const b = (s4 -% (y4 + b3)) >> 63; const t10 = ((b << 56) + s4) -% (y4 + b3); const b4 = b; const t41 = t10; const mask = b4 -% @as(u64, @as(u64, 1)); const z03 = s0 ^ (mask & (s0 ^ t01)); const z13 = s1 ^ (mask & (s1 ^ t11)); const z23 = s2 ^ (mask & (s2 ^ t21)); const z33 = s3 ^ (mask & (s3 ^ t31)); const z43 = s4 ^ (mask & (s4 ^ t41)); return Scalar{ .limbs = .{ z03, z13, z23, z33, z43 } }; } }; test "scalar25519" { const bytes: [32]u8 = .{ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 255 }; var x = Scalar.fromBytes(bytes); 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"); const reduced = reduce(field_size); try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&reduced)}), "0000000000000000000000000000000000000000000000000000000000000000"); } test "non-canonical scalar25519" { const too_targe: [32]u8 = .{ 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 }; try std.testing.expectError(error.NonCanonical, rejectNonCanonical(too_targe)); } test "mulAdd overflow check" { const a: [32]u8 = [_]u8{0xff} ** 32; const b: [32]u8 = [_]u8{0xff} ** 32; 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"); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/fs/wasi.zig
const std = @import("std"); const builtin = @import("builtin"); const os = std.os; const mem = std.mem; const math = std.math; const Allocator = mem.Allocator; const wasi = std.os.wasi; const fd_t = wasi.fd_t; const prestat_t = wasi.prestat_t; /// Type-tag of WASI preopen. /// /// WASI currently offers only `Dir` as a valid preopen resource. pub const PreopenTypeTag = enum { Dir, }; /// Type of WASI preopen. /// /// WASI currently offers only `Dir` as a valid preopen resource. pub const PreopenType = union(PreopenTypeTag) { /// Preopened directory type. Dir: []const u8, const Self = @This(); pub fn eql(self: Self, other: PreopenType) bool { if (!mem.eql(u8, @tagName(self), @tagName(other))) return false; switch (self) { PreopenTypeTag.Dir => |this_path| return mem.eql(u8, this_path, other.Dir), } } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype) !void { _ = fmt; _ = options; try out_stream.print("PreopenType{{ ", .{}); switch (self) { PreopenType.Dir => |path| try out_stream.print(".Dir = '{}'", .{std.zig.fmtId(path)}), } return out_stream.print(" }}", .{}); } }; /// WASI preopen struct. This struct consists of a WASI file descriptor /// and type of WASI preopen. It can be obtained directly from the WASI /// runtime using `PreopenList.populate()` method. pub const Preopen = struct { /// WASI file descriptor. fd: fd_t, /// Type of the preopen. type: PreopenType, /// Construct new `Preopen` instance. pub fn new(fd: fd_t, preopen_type: PreopenType) Preopen { return Preopen{ .fd = fd, .type = preopen_type, }; } }; /// Dynamically-sized array list of WASI preopens. This struct is a /// convenience wrapper for issuing `std.os.wasi.fd_prestat_get` and /// `std.os.wasi.fd_prestat_dir_name` syscalls to the WASI runtime, and /// collecting the returned preopens. /// /// This struct is intended to be used in any WASI program which intends /// to use the capabilities as passed on by the user of the runtime. pub const PreopenList = struct { const InnerList = std.ArrayList(Preopen); /// Internal dynamically-sized buffer for storing the gathered preopens. buffer: InnerList, const Self = @This(); pub const Error = error{ OutOfMemory, Overflow } || os.UnexpectedError; /// Deinitialize with `deinit`. pub fn init(allocator: *Allocator) Self { return Self{ .buffer = InnerList.init(allocator) }; } /// Release all allocated memory. pub fn deinit(pm: Self) void { for (pm.buffer.items) |preopen| { switch (preopen.type) { PreopenType.Dir => |path| pm.buffer.allocator.free(path), } } pm.buffer.deinit(); } /// Populate the list with the preopens by issuing `std.os.wasi.fd_prestat_get` /// and `std.os.wasi.fd_prestat_dir_name` syscalls to the runtime. /// /// If called more than once, it will clear its contents every time before /// issuing the syscalls. /// /// In the unlinkely event of overflowing the number of available file descriptors, /// returns `error.Overflow`. In this case, even though an error condition was reached /// the preopen list still contains all valid preopened file descriptors that are valid /// for use. Therefore, it is fine to call `find`, `asSlice`, or `toOwnedSlice`. Finally, /// `deinit` still must be called! pub fn populate(self: *Self) Error!void { // Clear contents if we're being called again for (self.toOwnedSlice()) |preopen| { switch (preopen.type) { PreopenType.Dir => |path| self.buffer.allocator.free(path), } } errdefer self.deinit(); var fd: fd_t = 3; // start fd has to be beyond stdio fds while (true) { var buf: prestat_t = undefined; switch (wasi.fd_prestat_get(fd, &buf)) { .SUCCESS => {}, .OPNOTSUPP => { // not a preopen, so keep going fd = try math.add(fd_t, fd, 1); continue; }, .BADF => { // OK, no more fds available break; }, else => |err| return os.unexpectedErrno(err), } const preopen_len = buf.u.dir.pr_name_len; const path_buf = try self.buffer.allocator.alloc(u8, preopen_len); mem.set(u8, path_buf, 0); switch (wasi.fd_prestat_dir_name(fd, path_buf.ptr, preopen_len)) { .SUCCESS => {}, else => |err| return os.unexpectedErrno(err), } const preopen = Preopen.new(fd, PreopenType{ .Dir = path_buf }); try self.buffer.append(preopen); fd = try math.add(fd_t, fd, 1); } } /// Find preopen by type. If the preopen exists, return it. /// Otherwise, return `null`. pub fn find(self: Self, preopen_type: PreopenType) ?*const Preopen { for (self.buffer.items) |*preopen| { if (preopen.type.eql(preopen_type)) { return preopen; } } return null; } /// Return the inner buffer as read-only slice. pub fn asSlice(self: Self) []const Preopen { return self.buffer.items; } /// The caller owns the returned memory. ArrayList becomes empty. pub fn toOwnedSlice(self: *Self) []Preopen { return self.buffer.toOwnedSlice(); } }; test "extracting WASI preopens" { if (builtin.os.tag != .wasi or builtin.link_libc) return error.SkipZigTest; var preopens = PreopenList.init(std.testing.allocator); defer preopens.deinit(); try preopens.populate(); try std.testing.expectEqual(@as(usize, 1), preopens.asSlice().len); const preopen = preopens.find(PreopenType{ .Dir = "." }) orelse unreachable; try std.testing.expect(preopen.type.eql(PreopenType{ .Dir = "." })); try std.testing.expectEqual(@as(i32, 3), preopen.fd); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/fs/get_app_data_dir.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); const unicode = std.unicode; const mem = std.mem; const fs = std.fs; const os = std.os; pub const GetAppDataDirError = error{ OutOfMemory, AppDataDirUnavailable, }; /// Caller owns returned memory. /// TODO determine if we can remove the allocator requirement pub fn getAppDataDir(allocator: *mem.Allocator, appname: []const u8) GetAppDataDirError![]u8 { switch (builtin.os.tag) { .windows => { var dir_path_ptr: [*:0]u16 = undefined; switch (os.windows.shell32.SHGetKnownFolderPath( &os.windows.FOLDERID_LocalAppData, os.windows.KF_FLAG_CREATE, null, &dir_path_ptr, )) { os.windows.S_OK => { defer os.windows.ole32.CoTaskMemFree(@as(*anyopaque, @ptrCast(dir_path_ptr))); const global_dir = unicode.utf16leToUtf8Alloc(allocator, mem.spanZ(dir_path_ptr)) catch |err| switch (err) { error.UnexpectedSecondSurrogateHalf => return error.AppDataDirUnavailable, error.ExpectedSecondSurrogateHalf => return error.AppDataDirUnavailable, error.DanglingSurrogateHalf => return error.AppDataDirUnavailable, error.OutOfMemory => return error.OutOfMemory, }; defer allocator.free(global_dir); return fs.path.join(allocator, &[_][]const u8{ global_dir, appname }); }, os.windows.E_OUTOFMEMORY => return error.OutOfMemory, else => return error.AppDataDirUnavailable, } }, .macos => { const home_dir = os.getenv("HOME") orelse { // TODO look in /etc/passwd return error.AppDataDirUnavailable; }; return fs.path.join(allocator, &[_][]const u8{ home_dir, "Library", "Application Support", appname }); }, .linux, .freebsd, .netbsd, .dragonfly, .openbsd, .solaris => { const home_dir = os.getenv("HOME") orelse { // TODO look in /etc/passwd return error.AppDataDirUnavailable; }; return fs.path.join(allocator, &[_][]const u8{ home_dir, ".local", "share", appname }); }, .haiku => { var dir_path_ptr: [*:0]u8 = undefined; // TODO look into directory_which const be_user_settings = 0xbbe; const rc = os.system.find_directory(be_user_settings, -1, true, dir_path_ptr, 1); const settings_dir = try allocator.dupeZ(u8, mem.spanZ(dir_path_ptr)); defer allocator.free(settings_dir); switch (rc) { 0 => return fs.path.join(allocator, &[_][]const u8{ settings_dir, appname }), else => return error.AppDataDirUnavailable, } }, else => @compileError("Unsupported OS"), } } test "getAppDataDir" { if (builtin.os.tag == .wasi) return error.SkipZigTest; // We can't actually validate the result const dir = getAppDataDir(std.testing.allocator, "zig") catch return; defer std.testing.allocator.free(dir); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/fs/test.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); const testing = std.testing; const fs = std.fs; const mem = std.mem; const wasi = std.os.wasi; const ArenaAllocator = std.heap.ArenaAllocator; const Dir = std.fs.Dir; const File = std.fs.File; const tmpDir = testing.tmpDir; test "Dir.readLink" { var tmp = tmpDir(.{}); defer tmp.cleanup(); // Create some targets try tmp.dir.writeFile("file.txt", "nonsense"); try tmp.dir.makeDir("subdir"); { // Create symbolic link by path tmp.dir.symLink("file.txt", "symlink1", .{}) catch |err| switch (err) { // Symlink requires admin privileges on windows, so this test can legitimately fail. error.AccessDenied => return error.SkipZigTest, else => return err, }; try testReadLink(tmp.dir, "file.txt", "symlink1"); } { // Create symbolic link by path tmp.dir.symLink("subdir", "symlink2", .{ .is_directory = true }) catch |err| switch (err) { // Symlink requires admin privileges on windows, so this test can legitimately fail. error.AccessDenied => return error.SkipZigTest, else => return err, }; try testReadLink(tmp.dir, "subdir", "symlink2"); } } fn testReadLink(dir: Dir, target_path: []const u8, symlink_path: []const u8) !void { var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; const given = try dir.readLink(symlink_path, buffer[0..]); try testing.expect(mem.eql(u8, target_path, given)); } test "accessAbsolute" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; try fs.accessAbsolute(base_path, .{}); } test "openDirAbsolute" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makeDir("subdir"); var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..], "subdir" }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; { var dir = try fs.openDirAbsolute(base_path, .{}); defer dir.close(); } for ([_][]const u8{ ".", ".." }) |sub_path| { const dir_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, sub_path }); defer arena.allocator.free(dir_path); var dir = try fs.openDirAbsolute(dir_path, .{}); defer dir.close(); } } test "openDir cwd parent .." { if (builtin.os.tag == .wasi) return error.SkipZigTest; var dir = try fs.cwd().openDir("..", .{}); defer dir.close(); } test "readLinkAbsolute" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); // Create some targets try tmp.dir.writeFile("file.txt", "nonsense"); try tmp.dir.makeDir("subdir"); // Get base abs path var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; const allocator = &arena.allocator; { const target_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "file.txt" }); const symlink_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "symlink1" }); // Create symbolic link by path fs.symLinkAbsolute(target_path, symlink_path, .{}) catch |err| switch (err) { // Symlink requires admin privileges on windows, so this test can legitimately fail. error.AccessDenied => return error.SkipZigTest, else => return err, }; try testReadLinkAbsolute(target_path, symlink_path); } { const target_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "subdir" }); const symlink_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "symlink2" }); // Create symbolic link by path fs.symLinkAbsolute(target_path, symlink_path, .{ .is_directory = true }) catch |err| switch (err) { // Symlink requires admin privileges on windows, so this test can legitimately fail. error.AccessDenied => return error.SkipZigTest, else => return err, }; try testReadLinkAbsolute(target_path, symlink_path); } } fn testReadLinkAbsolute(target_path: []const u8, symlink_path: []const u8) !void { var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; const given = try fs.readLinkAbsolute(symlink_path, buffer[0..]); try testing.expect(mem.eql(u8, target_path, given)); } test "Dir.Iterator" { var tmp_dir = tmpDir(.{ .iterate = true }); defer tmp_dir.cleanup(); // First, create a couple of entries to iterate over. const file = try tmp_dir.dir.createFile("some_file", .{}); file.close(); try tmp_dir.dir.makeDir("some_dir"); var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); var entries = std.ArrayList(Dir.Entry).init(&arena.allocator); // Create iterator. var iter = tmp_dir.dir.iterate(); while (try iter.next()) |entry| { // We cannot just store `entry` as on Windows, we're re-using the name buffer // which means we'll actually share the `name` pointer between entries! const name = try arena.allocator.dupe(u8, entry.name); try entries.append(Dir.Entry{ .name = name, .kind = entry.kind }); } try testing.expect(entries.items.len == 2); // note that the Iterator skips '.' and '..' try testing.expect(contains(&entries, Dir.Entry{ .name = "some_file", .kind = Dir.Entry.Kind.File })); try testing.expect(contains(&entries, Dir.Entry{ .name = "some_dir", .kind = Dir.Entry.Kind.Directory })); } fn entryEql(lhs: Dir.Entry, rhs: Dir.Entry) bool { return mem.eql(u8, lhs.name, rhs.name) and lhs.kind == rhs.kind; } fn contains(entries: *const std.ArrayList(Dir.Entry), el: Dir.Entry) bool { for (entries.items) |entry| { if (entryEql(entry, el)) return true; } return false; } test "Dir.realpath smoke test" { switch (builtin.os.tag) { .linux, .windows, .macos, .ios, .watchos, .tvos, .solaris => {}, else => return error.SkipZigTest, } var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); var file = try tmp_dir.dir.createFile("test_file", .{ .lock = File.Lock.Shared }); // We need to close the file immediately as otherwise on Windows we'll end up // with a sharing violation. file.close(); var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..] }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; // First, test non-alloc version { var buf1: [fs.MAX_PATH_BYTES]u8 = undefined; const file_path = try tmp_dir.dir.realpath("test_file", buf1[0..]); const expected_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "test_file" }); try testing.expect(mem.eql(u8, file_path, expected_path)); } // Next, test alloc version { const file_path = try tmp_dir.dir.realpathAlloc(&arena.allocator, "test_file"); const expected_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "test_file" }); try testing.expect(mem.eql(u8, file_path, expected_path)); } } test "readAllAlloc" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); var file = try tmp_dir.dir.createFile("test_file", .{ .read = true }); defer file.close(); const buf1 = try file.readToEndAlloc(testing.allocator, 1024); defer testing.allocator.free(buf1); try testing.expect(buf1.len == 0); const write_buf: []const u8 = "this is a test.\nthis is a test.\nthis is a test.\nthis is a test.\n"; try file.writeAll(write_buf); try file.seekTo(0); // max_bytes > file_size const buf2 = try file.readToEndAlloc(testing.allocator, 1024); defer testing.allocator.free(buf2); try testing.expectEqual(write_buf.len, buf2.len); try testing.expect(std.mem.eql(u8, write_buf, buf2)); try file.seekTo(0); // max_bytes == file_size const buf3 = try file.readToEndAlloc(testing.allocator, write_buf.len); defer testing.allocator.free(buf3); try testing.expectEqual(write_buf.len, buf3.len); try testing.expect(std.mem.eql(u8, write_buf, buf3)); try file.seekTo(0); // max_bytes < file_size try testing.expectError(error.FileTooBig, file.readToEndAlloc(testing.allocator, write_buf.len - 1)); } test "directory operations on files" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); const test_file_name = "test_file"; var file = try tmp_dir.dir.createFile(test_file_name, .{ .read = true }); file.close(); try testing.expectError(error.PathAlreadyExists, tmp_dir.dir.makeDir(test_file_name)); try testing.expectError(error.NotDir, tmp_dir.dir.openDir(test_file_name, .{})); try testing.expectError(error.NotDir, tmp_dir.dir.deleteDir(test_file_name)); switch (builtin.os.tag) { .wasi, .freebsd, .netbsd, .openbsd, .dragonfly => {}, else => { const absolute_path = try tmp_dir.dir.realpathAlloc(testing.allocator, test_file_name); defer testing.allocator.free(absolute_path); try testing.expectError(error.PathAlreadyExists, fs.makeDirAbsolute(absolute_path)); try testing.expectError(error.NotDir, fs.deleteDirAbsolute(absolute_path)); }, } // ensure the file still exists and is a file as a sanity check file = try tmp_dir.dir.openFile(test_file_name, .{}); const stat = try file.stat(); try testing.expect(stat.kind == .File); file.close(); } test "file operations on directories" { // TODO: fix this test on FreeBSD. https://github.com/ziglang/zig/issues/1759 if (builtin.os.tag == .freebsd) return error.SkipZigTest; var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); const test_dir_name = "test_dir"; try tmp_dir.dir.makeDir(test_dir_name); try testing.expectError(error.IsDir, tmp_dir.dir.createFile(test_dir_name, .{})); try testing.expectError(error.IsDir, tmp_dir.dir.deleteFile(test_dir_name)); switch (builtin.os.tag) { // NetBSD does not error when reading a directory. .netbsd => {}, // Currently, WASI will return error.Unexpected (via ENOTCAPABLE) when attempting fd_read on a directory handle. // TODO: Re-enable on WASI once https://github.com/bytecodealliance/wasmtime/issues/1935 is resolved. .wasi => {}, else => { try testing.expectError(error.IsDir, tmp_dir.dir.readFileAlloc(testing.allocator, test_dir_name, std.math.maxInt(usize))); }, } // Note: The `.write = true` is necessary to ensure the error occurs on all platforms. // TODO: Add a read-only test as well, see https://github.com/ziglang/zig/issues/5732 try testing.expectError(error.IsDir, tmp_dir.dir.openFile(test_dir_name, .{ .write = true })); switch (builtin.os.tag) { .wasi, .freebsd, .netbsd, .openbsd, .dragonfly => {}, else => { const absolute_path = try tmp_dir.dir.realpathAlloc(testing.allocator, test_dir_name); defer testing.allocator.free(absolute_path); try testing.expectError(error.IsDir, fs.createFileAbsolute(absolute_path, .{})); try testing.expectError(error.IsDir, fs.deleteFileAbsolute(absolute_path)); }, } // ensure the directory still exists as a sanity check var dir = try tmp_dir.dir.openDir(test_dir_name, .{}); dir.close(); } test "deleteDir" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); // deleting a non-existent directory try testing.expectError(error.FileNotFound, tmp_dir.dir.deleteDir("test_dir")); var dir = try tmp_dir.dir.makeOpenPath("test_dir", .{}); var file = try dir.createFile("test_file", .{}); file.close(); dir.close(); // deleting a non-empty directory // TODO: Re-enable this check on Windows, see https://github.com/ziglang/zig/issues/5537 if (builtin.os.tag != .windows) { try testing.expectError(error.DirNotEmpty, tmp_dir.dir.deleteDir("test_dir")); } dir = try tmp_dir.dir.openDir("test_dir", .{}); try dir.deleteFile("test_file"); dir.close(); // deleting an empty directory try tmp_dir.dir.deleteDir("test_dir"); } test "Dir.rename files" { var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); try testing.expectError(error.FileNotFound, tmp_dir.dir.rename("missing_file_name", "something_else")); // Renaming files const test_file_name = "test_file"; const renamed_test_file_name = "test_file_renamed"; var file = try tmp_dir.dir.createFile(test_file_name, .{ .read = true }); file.close(); try tmp_dir.dir.rename(test_file_name, renamed_test_file_name); // Ensure the file was renamed try testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(test_file_name, .{})); file = try tmp_dir.dir.openFile(renamed_test_file_name, .{}); file.close(); // Rename to self succeeds try tmp_dir.dir.rename(renamed_test_file_name, renamed_test_file_name); // Rename to existing file succeeds var existing_file = try tmp_dir.dir.createFile("existing_file", .{ .read = true }); existing_file.close(); try tmp_dir.dir.rename(renamed_test_file_name, "existing_file"); try testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(renamed_test_file_name, .{})); file = try tmp_dir.dir.openFile("existing_file", .{}); file.close(); } test "Dir.rename directories" { // TODO: Fix on Windows, see https://github.com/ziglang/zig/issues/6364 if (builtin.os.tag == .windows) return error.SkipZigTest; var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); // Renaming directories try tmp_dir.dir.makeDir("test_dir"); try tmp_dir.dir.rename("test_dir", "test_dir_renamed"); // Ensure the directory was renamed try testing.expectError(error.FileNotFound, tmp_dir.dir.openDir("test_dir", .{})); var dir = try tmp_dir.dir.openDir("test_dir_renamed", .{}); // Put a file in the directory var file = try dir.createFile("test_file", .{ .read = true }); file.close(); dir.close(); try tmp_dir.dir.rename("test_dir_renamed", "test_dir_renamed_again"); // Ensure the directory was renamed and the file still exists in it try testing.expectError(error.FileNotFound, tmp_dir.dir.openDir("test_dir_renamed", .{})); dir = try tmp_dir.dir.openDir("test_dir_renamed_again", .{}); file = try dir.openFile("test_file", .{}); file.close(); dir.close(); // Try to rename to a non-empty directory now var target_dir = try tmp_dir.dir.makeOpenPath("non_empty_target_dir", .{}); file = try target_dir.createFile("filler", .{ .read = true }); file.close(); try testing.expectError(error.PathAlreadyExists, tmp_dir.dir.rename("test_dir_renamed_again", "non_empty_target_dir")); // Ensure the directory was not renamed dir = try tmp_dir.dir.openDir("test_dir_renamed_again", .{}); file = try dir.openFile("test_file", .{}); file.close(); dir.close(); } test "Dir.rename file <-> dir" { // TODO: Fix on Windows, see https://github.com/ziglang/zig/issues/6364 if (builtin.os.tag == .windows) return error.SkipZigTest; var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); var file = try tmp_dir.dir.createFile("test_file", .{ .read = true }); file.close(); try tmp_dir.dir.makeDir("test_dir"); try testing.expectError(error.IsDir, tmp_dir.dir.rename("test_file", "test_dir")); try testing.expectError(error.NotDir, tmp_dir.dir.rename("test_dir", "test_file")); } test "rename" { var tmp_dir1 = tmpDir(.{}); defer tmp_dir1.cleanup(); var tmp_dir2 = tmpDir(.{}); defer tmp_dir2.cleanup(); // Renaming files const test_file_name = "test_file"; const renamed_test_file_name = "test_file_renamed"; var file = try tmp_dir1.dir.createFile(test_file_name, .{ .read = true }); file.close(); try fs.rename(tmp_dir1.dir, test_file_name, tmp_dir2.dir, renamed_test_file_name); // ensure the file was renamed try testing.expectError(error.FileNotFound, tmp_dir1.dir.openFile(test_file_name, .{})); file = try tmp_dir2.dir.openFile(renamed_test_file_name, .{}); file.close(); } test "renameAbsolute" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp_dir = tmpDir(.{}); defer tmp_dir.cleanup(); // Get base abs path var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const allocator = &arena.allocator; const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..] }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; try testing.expectError(error.FileNotFound, fs.renameAbsolute( try fs.path.join(allocator, &[_][]const u8{ base_path, "missing_file_name" }), try fs.path.join(allocator, &[_][]const u8{ base_path, "something_else" }), )); // Renaming files const test_file_name = "test_file"; const renamed_test_file_name = "test_file_renamed"; var file = try tmp_dir.dir.createFile(test_file_name, .{ .read = true }); file.close(); try fs.renameAbsolute( try fs.path.join(allocator, &[_][]const u8{ base_path, test_file_name }), try fs.path.join(allocator, &[_][]const u8{ base_path, renamed_test_file_name }), ); // ensure the file was renamed try testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(test_file_name, .{})); file = try tmp_dir.dir.openFile(renamed_test_file_name, .{}); const stat = try file.stat(); try testing.expect(stat.kind == .File); file.close(); // Renaming directories const test_dir_name = "test_dir"; const renamed_test_dir_name = "test_dir_renamed"; try tmp_dir.dir.makeDir(test_dir_name); try fs.renameAbsolute( try fs.path.join(allocator, &[_][]const u8{ base_path, test_dir_name }), try fs.path.join(allocator, &[_][]const u8{ base_path, renamed_test_dir_name }), ); // ensure the directory was renamed try testing.expectError(error.FileNotFound, tmp_dir.dir.openDir(test_dir_name, .{})); var dir = try tmp_dir.dir.openDir(renamed_test_dir_name, .{}); dir.close(); } test "openSelfExe" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const self_exe_file = try std.fs.openSelfExe(.{}); self_exe_file.close(); } test "makePath, put some files in it, deleteTree" { var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c"); try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c" ++ fs.path.sep_str ++ "file.txt", "nonsense"); try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "file2.txt", "blah"); try tmp.dir.deleteTree("os_test_tmp"); if (tmp.dir.openDir("os_test_tmp", .{})) |dir| { _ = dir; @panic("expected error"); } else |err| { try testing.expect(err == error.FileNotFound); } } test "writev, readv" { var tmp = tmpDir(.{}); defer tmp.cleanup(); const line1 = "line1\n"; const line2 = "line2\n"; var buf1: [line1.len]u8 = undefined; var buf2: [line2.len]u8 = undefined; var write_vecs = [_]std.os.iovec_const{ .{ .iov_base = line1, .iov_len = line1.len, }, .{ .iov_base = line2, .iov_len = line2.len, }, }; var read_vecs = [_]std.os.iovec{ .{ .iov_base = &buf2, .iov_len = buf2.len, }, .{ .iov_base = &buf1, .iov_len = buf1.len, }, }; var src_file = try tmp.dir.createFile("test.txt", .{ .read = true }); defer src_file.close(); try src_file.writevAll(&write_vecs); try testing.expectEqual(@as(u64, line1.len + line2.len), try src_file.getEndPos()); try src_file.seekTo(0); const read = try src_file.readvAll(&read_vecs); try testing.expectEqual(@as(usize, line1.len + line2.len), read); try testing.expectEqualStrings(&buf1, "line2\n"); try testing.expectEqualStrings(&buf2, "line1\n"); } test "pwritev, preadv" { var tmp = tmpDir(.{}); defer tmp.cleanup(); const line1 = "line1\n"; const line2 = "line2\n"; var buf1: [line1.len]u8 = undefined; var buf2: [line2.len]u8 = undefined; var write_vecs = [_]std.os.iovec_const{ .{ .iov_base = line1, .iov_len = line1.len, }, .{ .iov_base = line2, .iov_len = line2.len, }, }; var read_vecs = [_]std.os.iovec{ .{ .iov_base = &buf2, .iov_len = buf2.len, }, .{ .iov_base = &buf1, .iov_len = buf1.len, }, }; var src_file = try tmp.dir.createFile("test.txt", .{ .read = true }); defer src_file.close(); try src_file.pwritevAll(&write_vecs, 16); try testing.expectEqual(@as(u64, 16 + line1.len + line2.len), try src_file.getEndPos()); const read = try src_file.preadvAll(&read_vecs, 16); try testing.expectEqual(@as(usize, line1.len + line2.len), read); try testing.expectEqualStrings(&buf1, "line2\n"); try testing.expectEqualStrings(&buf2, "line1\n"); } test "access file" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp"); if (tmp.dir.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", .{})) |ok| { _ = ok; @panic("expected error"); } else |err| { try testing.expect(err == error.FileNotFound); } try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", ""); try tmp.dir.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", .{}); try tmp.dir.deleteTree("os_test_tmp"); } test "sendfile" { var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp"); defer tmp.dir.deleteTree("os_test_tmp") catch {}; var dir = try tmp.dir.openDir("os_test_tmp", .{}); defer dir.close(); const line1 = "line1\n"; const line2 = "second line\n"; var vecs = [_]std.os.iovec_const{ .{ .iov_base = line1, .iov_len = line1.len, }, .{ .iov_base = line2, .iov_len = line2.len, }, }; var src_file = try dir.createFile("sendfile1.txt", .{ .read = true }); defer src_file.close(); try src_file.writevAll(&vecs); var dest_file = try dir.createFile("sendfile2.txt", .{ .read = true }); defer dest_file.close(); const header1 = "header1\n"; const header2 = "second header\n"; const trailer1 = "trailer1\n"; const trailer2 = "second trailer\n"; var hdtr = [_]std.os.iovec_const{ .{ .iov_base = header1, .iov_len = header1.len, }, .{ .iov_base = header2, .iov_len = header2.len, }, .{ .iov_base = trailer1, .iov_len = trailer1.len, }, .{ .iov_base = trailer2, .iov_len = trailer2.len, }, }; var written_buf: [100]u8 = undefined; try dest_file.writeFileAll(src_file, .{ .in_offset = 1, .in_len = 10, .headers_and_trailers = &hdtr, .header_count = 2, }); const amt = try dest_file.preadAll(&written_buf, 0); try testing.expect(mem.eql(u8, written_buf[0..amt], "header1\nsecond header\nine1\nsecontrailer1\nsecond trailer\n")); } test "copyRangeAll" { var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makePath("os_test_tmp"); defer tmp.dir.deleteTree("os_test_tmp") catch {}; var dir = try tmp.dir.openDir("os_test_tmp", .{}); defer dir.close(); var src_file = try dir.createFile("file1.txt", .{ .read = true }); defer src_file.close(); const data = "u6wj+JmdF3qHsFPE BUlH2g4gJCmEz0PP"; try src_file.writeAll(data); var dest_file = try dir.createFile("file2.txt", .{ .read = true }); defer dest_file.close(); var written_buf: [100]u8 = undefined; _ = try src_file.copyRangeAll(0, dest_file, 0, data.len); const amt = try dest_file.preadAll(&written_buf, 0); try testing.expect(mem.eql(u8, written_buf[0..amt], data)); } test "fs.copyFile" { const data = "u6wj+JmdF3qHsFPE BUlH2g4gJCmEz0PP"; const src_file = "tmp_test_copy_file.txt"; const dest_file = "tmp_test_copy_file2.txt"; const dest_file2 = "tmp_test_copy_file3.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(src_file, data); defer tmp.dir.deleteFile(src_file) catch {}; try tmp.dir.copyFile(src_file, tmp.dir, dest_file, .{}); defer tmp.dir.deleteFile(dest_file) catch {}; try tmp.dir.copyFile(src_file, tmp.dir, dest_file2, .{ .override_mode = File.default_mode }); defer tmp.dir.deleteFile(dest_file2) catch {}; try expectFileContents(tmp.dir, dest_file, data); try expectFileContents(tmp.dir, dest_file2, data); } fn expectFileContents(dir: Dir, file_path: []const u8, data: []const u8) !void { const contents = try dir.readFileAlloc(testing.allocator, file_path, 1000); defer testing.allocator.free(contents); try testing.expectEqualSlices(u8, data, contents); } test "AtomicFile" { const test_out_file = "tmp_atomic_file_test_dest.txt"; const test_content = \\ hello! \\ this is a test file ; var tmp = tmpDir(.{}); defer tmp.cleanup(); { var af = try tmp.dir.atomicFile(test_out_file, .{}); defer af.deinit(); try af.file.writeAll(test_content); try af.finish(); } const content = try tmp.dir.readFileAlloc(testing.allocator, test_out_file, 9999); defer testing.allocator.free(content); try testing.expect(mem.eql(u8, content, test_content)); try tmp.dir.deleteFile(test_out_file); } test "realpath" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; try testing.expectError(error.FileNotFound, fs.realpath("definitely_bogus_does_not_exist1234", &buf)); } test "open file with exclusive nonblocking lock twice" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const filename = "file_nonblocking_lock_test.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); const file1 = try tmp.dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); defer file1.close(); const file2 = tmp.dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); try testing.expectError(error.WouldBlock, file2); } test "open file with shared and exclusive nonblocking lock" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const filename = "file_nonblocking_lock_test.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); const file1 = try tmp.dir.createFile(filename, .{ .lock = .Shared, .lock_nonblocking = true }); defer file1.close(); const file2 = tmp.dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); try testing.expectError(error.WouldBlock, file2); } test "open file with exclusive and shared nonblocking lock" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const filename = "file_nonblocking_lock_test.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); const file1 = try tmp.dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); defer file1.close(); const file2 = tmp.dir.createFile(filename, .{ .lock = .Shared, .lock_nonblocking = true }); try testing.expectError(error.WouldBlock, file2); } test "open file with exclusive lock twice, make sure it waits" { if (builtin.single_threaded) return error.SkipZigTest; if (std.io.is_async) { // This test starts its own threads and is not compatible with async I/O. return error.SkipZigTest; } const filename = "file_lock_test.txt"; var tmp = tmpDir(.{}); defer tmp.cleanup(); const file = try tmp.dir.createFile(filename, .{ .lock = .Exclusive }); errdefer file.close(); const S = struct { fn checkFn(dir: *fs.Dir, evt: *std.Thread.ResetEvent) !void { const file1 = try dir.createFile(filename, .{ .lock = .Exclusive }); defer file1.close(); evt.set(); } }; var evt: std.Thread.ResetEvent = undefined; try evt.init(); defer evt.deinit(); const t = try std.Thread.spawn(.{}, S.checkFn, .{ &tmp.dir, &evt }); defer t.join(); const SLEEP_TIMEOUT_NS = 10 * std.time.ns_per_ms; // Make sure we've slept enough. var timer = try std.time.Timer.start(); while (true) { std.time.sleep(SLEEP_TIMEOUT_NS); if (timer.read() >= SLEEP_TIMEOUT_NS) break; } file.close(); // No timeout to avoid failures on heavily loaded systems. evt.wait(); } test "open file with exclusive nonblocking lock twice (absolute paths)" { if (builtin.os.tag == .wasi) return error.SkipZigTest; const allocator = testing.allocator; const file_paths: [1][]const u8 = .{"zig-test-absolute-paths.txt"}; const filename = try fs.path.resolve(allocator, &file_paths); defer allocator.free(filename); const file1 = try fs.createFileAbsolute(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); const file2 = fs.createFileAbsolute(filename, .{ .lock = .Exclusive, .lock_nonblocking = true }); file1.close(); try testing.expectError(error.WouldBlock, file2); try fs.deleteFileAbsolute(filename); } test "walker" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{ .iterate = true }); defer tmp.cleanup(); // iteration order of walker is undefined, so need lookup maps to check against const expected_paths = std.ComptimeStringMap(void, .{ .{"dir1"}, .{"dir2"}, .{"dir3"}, .{"dir4"}, .{"dir3" ++ std.fs.path.sep_str ++ "sub1"}, .{"dir3" ++ std.fs.path.sep_str ++ "sub2"}, .{"dir3" ++ std.fs.path.sep_str ++ "sub2" ++ std.fs.path.sep_str ++ "subsub1"}, }); const expected_basenames = std.ComptimeStringMap(void, .{ .{"dir1"}, .{"dir2"}, .{"dir3"}, .{"dir4"}, .{"sub1"}, .{"sub2"}, .{"subsub1"}, }); for (expected_paths.kvs) |kv| { try tmp.dir.makePath(kv.key); } var walker = try tmp.dir.walk(testing.allocator); defer walker.deinit(); var num_walked: usize = 0; while (try walker.next()) |entry| { testing.expect(expected_basenames.has(entry.basename)) catch |err| { std.debug.print("found unexpected basename: {s}\n", .{std.fmt.fmtSliceEscapeLower(entry.basename)}); return err; }; testing.expect(expected_paths.has(entry.path)) catch |err| { std.debug.print("found unexpected path: {s}\n", .{std.fmt.fmtSliceEscapeLower(entry.path)}); return err; }; num_walked += 1; } try testing.expectEqual(expected_paths.kvs.len, num_walked); } test ". and .. in fs.Dir functions" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.makeDir("./subdir"); try tmp.dir.access("./subdir", .{}); var created_subdir = try tmp.dir.openDir("./subdir", .{}); created_subdir.close(); const created_file = try tmp.dir.createFile("./subdir/../file", .{}); created_file.close(); try tmp.dir.access("./subdir/../file", .{}); try tmp.dir.copyFile("./subdir/../file", tmp.dir, "./subdir/../copy", .{}); try tmp.dir.rename("./subdir/../copy", "./subdir/../rename"); const renamed_file = try tmp.dir.openFile("./subdir/../rename", .{}); renamed_file.close(); try tmp.dir.deleteFile("./subdir/../rename"); try tmp.dir.writeFile("./subdir/../update", "something"); const prev_status = try tmp.dir.updateFile("./subdir/../file", tmp.dir, "./subdir/../update", .{}); try testing.expectEqual(fs.PrevStatus.stale, prev_status); try tmp.dir.deleteDir("./subdir"); } test ". and .. in absolute functions" { if (builtin.os.tag == .wasi) return error.SkipZigTest; var tmp = tmpDir(.{}); defer tmp.cleanup(); var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const allocator = &arena.allocator; const base_path = blk: { const relative_path = try fs.path.join(&arena.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] }); break :blk try fs.realpathAlloc(&arena.allocator, relative_path); }; const subdir_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "./subdir" }); try fs.makeDirAbsolute(subdir_path); try fs.accessAbsolute(subdir_path, .{}); var created_subdir = try fs.openDirAbsolute(subdir_path, .{}); created_subdir.close(); const created_file_path = try fs.path.join(allocator, &[_][]const u8{ subdir_path, "../file" }); const created_file = try fs.createFileAbsolute(created_file_path, .{}); created_file.close(); try fs.accessAbsolute(created_file_path, .{}); const copied_file_path = try fs.path.join(allocator, &[_][]const u8{ subdir_path, "../copy" }); try fs.copyFileAbsolute(created_file_path, copied_file_path, .{}); const renamed_file_path = try fs.path.join(allocator, &[_][]const u8{ subdir_path, "../rename" }); try fs.renameAbsolute(copied_file_path, renamed_file_path); const renamed_file = try fs.openFileAbsolute(renamed_file_path, .{}); renamed_file.close(); try fs.deleteFileAbsolute(renamed_file_path); const update_file_path = try fs.path.join(allocator, &[_][]const u8{ subdir_path, "../update" }); const update_file = try fs.createFileAbsolute(update_file_path, .{}); try update_file.writeAll("something"); update_file.close(); const prev_status = try fs.updateFileAbsolute(created_file_path, update_file_path, .{}); try testing.expectEqual(fs.PrevStatus.stale, prev_status); try fs.deleteDirAbsolute(subdir_path); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/fs/file.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); const os = std.os; const io = std.io; const mem = std.mem; const math = std.math; const assert = std.debug.assert; const windows = os.windows; const Os = std.builtin.Os; const maxInt = std.math.maxInt; const is_windows = builtin.os.tag == .windows; pub const File = struct { /// The OS-specific file descriptor or file handle. handle: Handle, /// On some systems, such as Linux, file system file descriptors are incapable /// of non-blocking I/O. This forces us to perform asynchronous I/O on a dedicated thread, /// to achieve non-blocking file-system I/O. To do this, `File` must be aware of whether /// it is a file system file descriptor, or, more specifically, whether the I/O is always /// blocking. capable_io_mode: io.ModeOverride = io.default_mode, /// Furthermore, even when `std.io.mode` is async, it is still sometimes desirable /// to perform blocking I/O, although not by default. For example, when printing a /// stack trace to stderr. This field tracks both by acting as an overriding I/O mode. /// When not building in async I/O mode, the type only has the `.blocking` tag, making /// it a zero-bit type. intended_io_mode: io.ModeOverride = io.default_mode, pub const Handle = os.fd_t; pub const Mode = os.mode_t; pub const INode = os.ino_t; pub const Kind = enum { BlockDevice, CharacterDevice, Directory, NamedPipe, SymLink, File, UnixDomainSocket, Whiteout, Door, EventPort, Unknown, }; pub const default_mode = switch (builtin.os.tag) { .windows => 0, .wasi => 0, else => 0o666, }; pub const OpenError = error{ SharingViolation, PathAlreadyExists, FileNotFound, AccessDenied, PipeBusy, NameTooLong, /// On Windows, file paths must be valid Unicode. InvalidUtf8, /// On Windows, file paths cannot contain these characters: /// '/', '*', '?', '"', '<', '>', '|' BadPathName, Unexpected, } || os.OpenError || os.FlockError; pub const Lock = enum { None, Shared, Exclusive }; /// TODO https://github.com/ziglang/zig/issues/3802 pub const OpenFlags = struct { read: bool = true, write: bool = false, /// Open the file with an advisory lock to coordinate with other processes /// accessing it at the same time. An exclusive lock will prevent other /// processes from acquiring a lock. A shared lock will prevent other /// processes from acquiring a exclusive lock, but does not prevent /// other process from getting their own shared locks. /// /// The lock is advisory, except on Linux in very specific cirsumstances[1]. /// This means that a process that does not respect the locking API can still get access /// to the file, despite the lock. /// /// On these operating systems, the lock is acquired atomically with /// opening the file: /// * Darwin /// * DragonFlyBSD /// * FreeBSD /// * Haiku /// * NetBSD /// * OpenBSD /// On these operating systems, the lock is acquired via a separate syscall /// after opening the file: /// * Linux /// * Windows /// /// [1]: https://www.kernel.org/doc/Documentation/filesystems/mandatory-locking.txt lock: Lock = .None, /// Sets whether or not to wait until the file is locked to return. If set to true, /// `error.WouldBlock` will be returned. Otherwise, the file will wait until the file /// is available to proceed. /// In async I/O mode, non-blocking at the OS level is /// determined by `intended_io_mode`, and `true` means `error.WouldBlock` is returned, /// and `false` means `error.WouldBlock` is handled by the event loop. lock_nonblocking: bool = false, /// Setting this to `.blocking` prevents `O.NONBLOCK` from being passed even /// if `std.io.is_async`. It allows the use of `nosuspend` when calling functions /// related to opening the file, reading, writing, and locking. intended_io_mode: io.ModeOverride = io.default_mode, /// Set this to allow the opened file to automatically become the /// controlling TTY for the current process. allow_ctty: bool = false, }; /// TODO https://github.com/ziglang/zig/issues/3802 pub const CreateFlags = struct { /// Whether the file will be created with read access. read: bool = false, /// If the file already exists, and is a regular file, and the access /// mode allows writing, it will be truncated to length 0. truncate: bool = true, /// Ensures that this open call creates the file, otherwise causes /// `error.PathAlreadyExists` to be returned. exclusive: bool = false, /// Open the file with an advisory lock to coordinate with other processes /// accessing it at the same time. An exclusive lock will prevent other /// processes from acquiring a lock. A shared lock will prevent other /// processes from acquiring a exclusive lock, but does not prevent /// other process from getting their own shared locks. /// /// The lock is advisory, except on Linux in very specific cirsumstances[1]. /// This means that a process that does not respect the locking API can still get access /// to the file, despite the lock. /// /// On these operating systems, the lock is acquired atomically with /// opening the file: /// * Darwin /// * DragonFlyBSD /// * FreeBSD /// * Haiku /// * NetBSD /// * OpenBSD /// On these operating systems, the lock is acquired via a separate syscall /// after opening the file: /// * Linux /// * Windows /// /// [1]: https://www.kernel.org/doc/Documentation/filesystems/mandatory-locking.txt lock: Lock = .None, /// Sets whether or not to wait until the file is locked to return. If set to true, /// `error.WouldBlock` will be returned. Otherwise, the file will wait until the file /// is available to proceed. /// In async I/O mode, non-blocking at the OS level is /// determined by `intended_io_mode`, and `true` means `error.WouldBlock` is returned, /// and `false` means `error.WouldBlock` is handled by the event loop. lock_nonblocking: bool = false, /// For POSIX systems this is the file system mode the file will /// be created with. mode: Mode = default_mode, /// Setting this to `.blocking` prevents `O.NONBLOCK` from being passed even /// if `std.io.is_async`. It allows the use of `nosuspend` when calling functions /// related to opening the file, reading, writing, and locking. intended_io_mode: io.ModeOverride = io.default_mode, }; /// Upon success, the stream is in an uninitialized state. To continue using it, /// you must use the open() function. pub fn close(self: File) void { if (is_windows) { windows.CloseHandle(self.handle); } else if (self.capable_io_mode != self.intended_io_mode) { std.event.Loop.instance.?.close(self.handle); } else { os.close(self.handle); } } /// Test whether the file refers to a terminal. /// See also `supportsAnsiEscapeCodes`. pub fn isTty(self: File) bool { return os.isatty(self.handle); } /// Test whether ANSI escape codes will be treated as such. pub fn supportsAnsiEscapeCodes(self: File) bool { if (builtin.os.tag == .windows) { return os.isCygwinPty(self.handle); } if (builtin.os.tag == .wasi) { // WASI sanitizes stdout when fd is a tty so ANSI escape codes // will not be interpreted as actual cursor commands, and // stderr is always sanitized. return false; } if (self.isTty()) { if (self.handle == os.STDOUT_FILENO or self.handle == os.STDERR_FILENO) { // Use getenvC to workaround https://github.com/ziglang/zig/issues/3511 if (os.getenvZ("TERM")) |term| { if (std.mem.eql(u8, term, "dumb")) return false; } } return true; } return false; } pub const SetEndPosError = os.TruncateError; /// Shrinks or expands the file. /// The file offset after this call is left unchanged. pub fn setEndPos(self: File, length: u64) SetEndPosError!void { try os.ftruncate(self.handle, length); } pub const SeekError = os.SeekError; /// Repositions read/write file offset relative to the current offset. /// TODO: integrate with async I/O pub fn seekBy(self: File, offset: i64) SeekError!void { return os.lseek_CUR(self.handle, offset); } /// Repositions read/write file offset relative to the end. /// TODO: integrate with async I/O pub fn seekFromEnd(self: File, offset: i64) SeekError!void { return os.lseek_END(self.handle, offset); } /// Repositions read/write file offset relative to the beginning. /// TODO: integrate with async I/O pub fn seekTo(self: File, offset: u64) SeekError!void { return os.lseek_SET(self.handle, offset); } pub const GetSeekPosError = os.SeekError || os.FStatError; /// TODO: integrate with async I/O pub fn getPos(self: File) GetSeekPosError!u64 { return os.lseek_CUR_get(self.handle); } /// TODO: integrate with async I/O pub fn getEndPos(self: File) GetSeekPosError!u64 { if (builtin.os.tag == .windows) { return windows.GetFileSizeEx(self.handle); } return (try self.stat()).size; } pub const ModeError = os.FStatError; /// TODO: integrate with async I/O pub fn mode(self: File) ModeError!Mode { if (builtin.os.tag == .windows) { return 0; } return (try self.stat()).mode; } pub const Stat = struct { /// A number that the system uses to point to the file metadata. This number is not guaranteed to be /// unique across time, as some file systems may reuse an inode after its file has been deleted. /// Some systems may change the inode of a file over time. /// /// On Linux, the inode is a structure that stores the metadata, and the inode _number_ is what /// you see here: the index number of the inode. /// /// The FileIndex on Windows is similar. It is a number for a file that is unique to each filesystem. inode: INode, size: u64, mode: Mode, kind: Kind, /// Access time in nanoseconds, relative to UTC 1970-01-01. atime: i128, /// Last modification time in nanoseconds, relative to UTC 1970-01-01. mtime: i128, /// Creation time in nanoseconds, relative to UTC 1970-01-01. ctime: i128, }; pub const StatError = os.FStatError; /// TODO: integrate with async I/O pub fn stat(self: File) StatError!Stat { if (builtin.os.tag == .windows) { var io_status_block: windows.IO_STATUS_BLOCK = undefined; var info: windows.FILE_ALL_INFORMATION = undefined; const rc = windows.ntdll.NtQueryInformationFile(self.handle, &io_status_block, &info, @sizeOf(windows.FILE_ALL_INFORMATION), .FileAllInformation); switch (rc) { .SUCCESS => {}, .BUFFER_OVERFLOW => {}, .INVALID_PARAMETER => unreachable, .ACCESS_DENIED => return error.AccessDenied, else => return windows.unexpectedStatus(rc), } return Stat{ .inode = info.InternalInformation.IndexNumber, .size = @as(u64, @bitCast(info.StandardInformation.EndOfFile)), .mode = 0, .kind = if (info.StandardInformation.Directory == 0) .File else .Directory, .atime = windows.fromSysTime(info.BasicInformation.LastAccessTime), .mtime = windows.fromSysTime(info.BasicInformation.LastWriteTime), .ctime = windows.fromSysTime(info.BasicInformation.CreationTime), }; } const st = try os.fstat(self.handle); const atime = st.atime(); const mtime = st.mtime(); const ctime = st.ctime(); const kind: Kind = if (builtin.os.tag == .wasi and !builtin.link_libc) switch (st.filetype) { .BLOCK_DEVICE => Kind.BlockDevice, .CHARACTER_DEVICE => Kind.CharacterDevice, .DIRECTORY => Kind.Directory, .SYMBOLIC_LINK => Kind.SymLink, .REGULAR_FILE => Kind.File, .SOCKET_STREAM, .SOCKET_DGRAM => Kind.UnixDomainSocket, else => Kind.Unknown, } else blk: { const m = st.mode & os.S.IFMT; switch (m) { os.S.IFBLK => break :blk Kind.BlockDevice, os.S.IFCHR => break :blk Kind.CharacterDevice, os.S.IFDIR => break :blk Kind.Directory, os.S.IFIFO => break :blk Kind.NamedPipe, os.S.IFLNK => break :blk Kind.SymLink, os.S.IFREG => break :blk Kind.File, os.S.IFSOCK => break :blk Kind.UnixDomainSocket, else => {}, } if (builtin.os.tag == .solaris) switch (m) { os.S.IFDOOR => break :blk Kind.Door, os.S.IFPORT => break :blk Kind.EventPort, else => {}, }; break :blk .Unknown; }; return Stat{ .inode = st.ino, .size = @as(u64, @bitCast(st.size)), .mode = st.mode, .kind = kind, .atime = @as(i128, atime.tv_sec) * std.time.ns_per_s + atime.tv_nsec, .mtime = @as(i128, mtime.tv_sec) * std.time.ns_per_s + mtime.tv_nsec, .ctime = @as(i128, ctime.tv_sec) * std.time.ns_per_s + ctime.tv_nsec, }; } pub const UpdateTimesError = os.FutimensError || windows.SetFileTimeError; /// The underlying file system may have a different granularity than nanoseconds, /// and therefore this function cannot guarantee any precision will be stored. /// Further, the maximum value is limited by the system ABI. When a value is provided /// that exceeds this range, the value is clamped to the maximum. /// TODO: integrate with async I/O pub fn updateTimes( self: File, /// access timestamp in nanoseconds atime: i128, /// last modification timestamp in nanoseconds mtime: i128, ) UpdateTimesError!void { if (builtin.os.tag == .windows) { const atime_ft = windows.nanoSecondsToFileTime(atime); const mtime_ft = windows.nanoSecondsToFileTime(mtime); return windows.SetFileTime(self.handle, null, &atime_ft, &mtime_ft); } const times = [2]os.timespec{ os.timespec{ .tv_sec = math.cast(isize, @divFloor(atime, std.time.ns_per_s)) catch maxInt(isize), .tv_nsec = math.cast(isize, @mod(atime, std.time.ns_per_s)) catch maxInt(isize), }, os.timespec{ .tv_sec = math.cast(isize, @divFloor(mtime, std.time.ns_per_s)) catch maxInt(isize), .tv_nsec = math.cast(isize, @mod(mtime, std.time.ns_per_s)) catch maxInt(isize), }, }; try os.futimens(self.handle, &times); } /// Reads all the bytes from the current position to the end of the file. /// On success, caller owns returned buffer. /// If the file is larger than `max_bytes`, returns `error.FileTooBig`. pub fn readToEndAlloc(self: File, allocator: *mem.Allocator, max_bytes: usize) ![]u8 { return self.readToEndAllocOptions(allocator, max_bytes, null, @alignOf(u8), null); } /// Reads all the bytes from the current position to the end of the file. /// On success, caller owns returned buffer. /// If the file is larger than `max_bytes`, returns `error.FileTooBig`. /// If `size_hint` is specified the initial buffer size is calculated using /// that value, otherwise an arbitrary value is used instead. /// Allows specifying alignment and a sentinel value. pub fn readToEndAllocOptions( self: File, allocator: *mem.Allocator, max_bytes: usize, size_hint: ?usize, comptime alignment: u29, comptime optional_sentinel: ?u8, ) !(if (optional_sentinel) |s| [:s]align(alignment) u8 else []align(alignment) u8) { // If no size hint is provided fall back to the size=0 code path const size = size_hint orelse 0; // The file size returned by stat is used as hint to set the buffer // size. If the reported size is zero, as it happens on Linux for files // in /proc, a small buffer is allocated instead. const initial_cap = (if (size > 0) size else 1024) + @intFromBool(optional_sentinel != null); var array_list = try std.ArrayListAligned(u8, alignment).initCapacity(allocator, initial_cap); defer array_list.deinit(); self.reader().readAllArrayListAligned(alignment, &array_list, max_bytes) catch |err| switch (err) { error.StreamTooLong => return error.FileTooBig, else => |e| return e, }; if (optional_sentinel) |sentinel| { try array_list.append(sentinel); const buf = array_list.toOwnedSlice(); return buf[0 .. buf.len - 1 :sentinel]; } else { return array_list.toOwnedSlice(); } } pub const ReadError = os.ReadError; pub const PReadError = os.PReadError; pub fn read(self: File, buffer: []u8) ReadError!usize { if (is_windows) { return windows.ReadFile(self.handle, buffer, null, self.intended_io_mode); } if (self.intended_io_mode == .blocking) { return os.read(self.handle, buffer); } else { return std.event.Loop.instance.?.read(self.handle, buffer, self.capable_io_mode != self.intended_io_mode); } } /// Returns the number of bytes read. If the number read is smaller than `buffer.len`, it /// means the file reached the end. Reaching the end of a file is not an error condition. pub fn readAll(self: File, buffer: []u8) ReadError!usize { var index: usize = 0; while (index != buffer.len) { const amt = try self.read(buffer[index..]); if (amt == 0) break; index += amt; } return index; } pub fn pread(self: File, buffer: []u8, offset: u64) PReadError!usize { if (is_windows) { return windows.ReadFile(self.handle, buffer, offset, self.intended_io_mode); } if (self.intended_io_mode == .blocking) { return os.pread(self.handle, buffer, offset); } else { return std.event.Loop.instance.?.pread(self.handle, buffer, offset, self.capable_io_mode != self.intended_io_mode); } } /// Returns the number of bytes read. If the number read is smaller than `buffer.len`, it /// means the file reached the end. Reaching the end of a file is not an error condition. pub fn preadAll(self: File, buffer: []u8, offset: u64) PReadError!usize { var index: usize = 0; while (index != buffer.len) { const amt = try self.pread(buffer[index..], offset + index); if (amt == 0) break; index += amt; } return index; } /// See https://github.com/ziglang/zig/issues/7699 pub fn readv(self: File, iovecs: []const os.iovec) ReadError!usize { if (is_windows) { // TODO improve this to use ReadFileScatter if (iovecs.len == 0) return @as(usize, 0); const first = iovecs[0]; return windows.ReadFile(self.handle, first.iov_base[0..first.iov_len], null, self.intended_io_mode); } if (self.intended_io_mode == .blocking) { return os.readv(self.handle, iovecs); } else { return std.event.Loop.instance.?.readv(self.handle, iovecs, self.capable_io_mode != self.intended_io_mode); } } /// Returns the number of bytes read. If the number read is smaller than the total bytes /// from all the buffers, it means the file reached the end. Reaching the end of a file /// is not an error condition. /// The `iovecs` parameter is mutable because this function needs to mutate the fields in /// order to handle partial reads from the underlying OS layer. /// See https://github.com/ziglang/zig/issues/7699 pub fn readvAll(self: File, iovecs: []os.iovec) ReadError!usize { if (iovecs.len == 0) return 0; var i: usize = 0; var off: usize = 0; while (true) { var amt = try self.readv(iovecs[i..]); var eof = amt == 0; off += amt; while (amt >= iovecs[i].iov_len) { amt -= iovecs[i].iov_len; i += 1; if (i >= iovecs.len) return off; eof = false; } if (eof) return off; iovecs[i].iov_base += amt; iovecs[i].iov_len -= amt; } } /// See https://github.com/ziglang/zig/issues/7699 pub fn preadv(self: File, iovecs: []const os.iovec, offset: u64) PReadError!usize { if (is_windows) { // TODO improve this to use ReadFileScatter if (iovecs.len == 0) return @as(usize, 0); const first = iovecs[0]; return windows.ReadFile(self.handle, first.iov_base[0..first.iov_len], offset, self.intended_io_mode); } if (self.intended_io_mode == .blocking) { return os.preadv(self.handle, iovecs, offset); } else { return std.event.Loop.instance.?.preadv(self.handle, iovecs, offset, self.capable_io_mode != self.intended_io_mode); } } /// Returns the number of bytes read. If the number read is smaller than the total bytes /// from all the buffers, it means the file reached the end. Reaching the end of a file /// is not an error condition. /// The `iovecs` parameter is mutable because this function needs to mutate the fields in /// order to handle partial reads from the underlying OS layer. /// See https://github.com/ziglang/zig/issues/7699 pub fn preadvAll(self: File, iovecs: []os.iovec, offset: u64) PReadError!usize { if (iovecs.len == 0) return 0; var i: usize = 0; var off: usize = 0; while (true) { var amt = try self.preadv(iovecs[i..], offset + off); var eof = amt == 0; off += amt; while (amt >= iovecs[i].iov_len) { amt -= iovecs[i].iov_len; i += 1; if (i >= iovecs.len) return off; eof = false; } if (eof) return off; iovecs[i].iov_base += amt; iovecs[i].iov_len -= amt; } } pub const WriteError = os.WriteError; pub const PWriteError = os.PWriteError; pub fn write(self: File, bytes: []const u8) WriteError!usize { if (is_windows) { return windows.WriteFile(self.handle, bytes, null, self.intended_io_mode); } if (self.intended_io_mode == .blocking) { return os.write(self.handle, bytes); } else { return std.event.Loop.instance.?.write(self.handle, bytes, self.capable_io_mode != self.intended_io_mode); } } pub fn writeAll(self: File, bytes: []const u8) WriteError!void { var index: usize = 0; while (index < bytes.len) { index += try self.write(bytes[index..]); } } pub fn pwrite(self: File, bytes: []const u8, offset: u64) PWriteError!usize { if (is_windows) { return windows.WriteFile(self.handle, bytes, offset, self.intended_io_mode); } if (self.intended_io_mode == .blocking) { return os.pwrite(self.handle, bytes, offset); } else { return std.event.Loop.instance.?.pwrite(self.handle, bytes, offset, self.capable_io_mode != self.intended_io_mode); } } pub fn pwriteAll(self: File, bytes: []const u8, offset: u64) PWriteError!void { var index: usize = 0; while (index < bytes.len) { index += try self.pwrite(bytes[index..], offset + index); } } /// See https://github.com/ziglang/zig/issues/7699 /// See equivalent function: `std.net.Stream.writev`. pub fn writev(self: File, iovecs: []const os.iovec_const) WriteError!usize { if (is_windows) { // TODO improve this to use WriteFileScatter if (iovecs.len == 0) return @as(usize, 0); const first = iovecs[0]; return windows.WriteFile(self.handle, first.iov_base[0..first.iov_len], null, self.intended_io_mode); } if (self.intended_io_mode == .blocking) { return os.writev(self.handle, iovecs); } else { return std.event.Loop.instance.?.writev(self.handle, iovecs, self.capable_io_mode != self.intended_io_mode); } } /// The `iovecs` parameter is mutable because this function needs to mutate the fields in /// order to handle partial writes from the underlying OS layer. /// See https://github.com/ziglang/zig/issues/7699 /// See equivalent function: `std.net.Stream.writevAll`. pub fn writevAll(self: File, iovecs: []os.iovec_const) WriteError!void { if (iovecs.len == 0) return; var i: usize = 0; while (true) { var amt = try self.writev(iovecs[i..]); while (amt >= iovecs[i].iov_len) { amt -= iovecs[i].iov_len; i += 1; if (i >= iovecs.len) return; } iovecs[i].iov_base += amt; iovecs[i].iov_len -= amt; } } /// See https://github.com/ziglang/zig/issues/7699 pub fn pwritev(self: File, iovecs: []os.iovec_const, offset: u64) PWriteError!usize { if (is_windows) { // TODO improve this to use WriteFileScatter if (iovecs.len == 0) return @as(usize, 0); const first = iovecs[0]; return windows.WriteFile(self.handle, first.iov_base[0..first.iov_len], offset, self.intended_io_mode); } if (self.intended_io_mode == .blocking) { return os.pwritev(self.handle, iovecs, offset); } else { return std.event.Loop.instance.?.pwritev(self.handle, iovecs, offset, self.capable_io_mode != self.intended_io_mode); } } /// The `iovecs` parameter is mutable because this function needs to mutate the fields in /// order to handle partial writes from the underlying OS layer. /// See https://github.com/ziglang/zig/issues/7699 pub fn pwritevAll(self: File, iovecs: []os.iovec_const, offset: u64) PWriteError!void { if (iovecs.len == 0) return; var i: usize = 0; var off: u64 = 0; while (true) { var amt = try self.pwritev(iovecs[i..], offset + off); off += amt; while (amt >= iovecs[i].iov_len) { amt -= iovecs[i].iov_len; i += 1; if (i >= iovecs.len) return; } iovecs[i].iov_base += amt; iovecs[i].iov_len -= amt; } } pub const CopyRangeError = os.CopyFileRangeError; pub fn copyRange(in: File, in_offset: u64, out: File, out_offset: u64, len: u64) CopyRangeError!u64 { const adjusted_len = math.cast(usize, len) catch math.maxInt(usize); const result = try os.copy_file_range(in.handle, in_offset, out.handle, out_offset, adjusted_len, 0); return result; } /// Returns the number of bytes copied. If the number read is smaller than `buffer.len`, it /// means the in file reached the end. Reaching the end of a file is not an error condition. pub fn copyRangeAll(in: File, in_offset: u64, out: File, out_offset: u64, len: u64) CopyRangeError!u64 { var total_bytes_copied: u64 = 0; var in_off = in_offset; var out_off = out_offset; while (total_bytes_copied < len) { const amt_copied = try copyRange(in, in_off, out, out_off, len - total_bytes_copied); if (amt_copied == 0) return total_bytes_copied; total_bytes_copied += amt_copied; in_off += amt_copied; out_off += amt_copied; } return total_bytes_copied; } pub const WriteFileOptions = struct { in_offset: u64 = 0, /// `null` means the entire file. `0` means no bytes from the file. /// When this is `null`, trailers must be sent in a separate writev() call /// due to a flaw in the BSD sendfile API. Other operating systems, such as /// Linux, already do this anyway due to API limitations. /// If the size of the source file is known, passing the size here will save one syscall. in_len: ?u64 = null, headers_and_trailers: []os.iovec_const = &[0]os.iovec_const{}, /// The trailer count is inferred from `headers_and_trailers.len - header_count` header_count: usize = 0, }; pub const WriteFileError = ReadError || error{EndOfStream} || WriteError; pub fn writeFileAll(self: File, in_file: File, args: WriteFileOptions) WriteFileError!void { return self.writeFileAllSendfile(in_file, args) catch |err| switch (err) { error.Unseekable, error.FastOpenAlreadyInProgress, error.MessageTooBig, error.FileDescriptorNotASocket, error.NetworkUnreachable, error.NetworkSubsystemFailed, => return self.writeFileAllUnseekable(in_file, args), else => |e| return e, }; } /// Does not try seeking in either of the File parameters. /// See `writeFileAll` as an alternative to calling this. pub fn writeFileAllUnseekable(self: File, in_file: File, args: WriteFileOptions) WriteFileError!void { const headers = args.headers_and_trailers[0..args.header_count]; const trailers = args.headers_and_trailers[args.header_count..]; try self.writevAll(headers); try in_file.reader().skipBytes(args.in_offset, .{ .buf_size = 4096 }); var fifo = std.fifo.LinearFifo(u8, .{ .Static = 4096 }).init(); if (args.in_len) |len| { var stream = std.io.limitedReader(in_file.reader(), len); try fifo.pump(stream.reader(), self.writer()); } else { try fifo.pump(in_file.reader(), self.writer()); } try self.writevAll(trailers); } /// Low level function which can fail for OS-specific reasons. /// See `writeFileAll` as an alternative to calling this. /// TODO integrate with async I/O fn writeFileAllSendfile(self: File, in_file: File, args: WriteFileOptions) os.SendFileError!void { const count = blk: { if (args.in_len) |l| { if (l == 0) { return self.writevAll(args.headers_and_trailers); } else { break :blk l; } } else { break :blk 0; } }; const headers = args.headers_and_trailers[0..args.header_count]; const trailers = args.headers_and_trailers[args.header_count..]; const zero_iovec = &[0]os.iovec_const{}; // When reading the whole file, we cannot put the trailers in the sendfile() syscall, // because we have no way to determine whether a partial write is past the end of the file or not. const trls = if (count == 0) zero_iovec else trailers; const offset = args.in_offset; const out_fd = self.handle; const in_fd = in_file.handle; const flags = 0; var amt: usize = 0; hdrs: { var i: usize = 0; while (i < headers.len) { amt = try os.sendfile(out_fd, in_fd, offset, count, headers[i..], trls, flags); while (amt >= headers[i].iov_len) { amt -= headers[i].iov_len; i += 1; if (i >= headers.len) break :hdrs; } headers[i].iov_base += amt; headers[i].iov_len -= amt; } } if (count == 0) { var off: u64 = amt; while (true) { amt = try os.sendfile(out_fd, in_fd, offset + off, 0, zero_iovec, zero_iovec, flags); if (amt == 0) break; off += amt; } } else { var off: u64 = amt; while (off < count) { amt = try os.sendfile(out_fd, in_fd, offset + off, count - off, zero_iovec, trailers, flags); off += amt; } amt = @as(usize, @intCast(off - count)); } var i: usize = 0; while (i < trailers.len) { while (amt >= trailers[i].iov_len) { amt -= trailers[i].iov_len; i += 1; if (i >= trailers.len) return; } trailers[i].iov_base += amt; trailers[i].iov_len -= amt; amt = try os.writev(self.handle, trailers[i..]); } } pub const Reader = io.Reader(File, ReadError, read); pub fn reader(file: File) Reader { return .{ .context = file }; } pub const Writer = io.Writer(File, WriteError, write); pub fn writer(file: File) Writer { return .{ .context = file }; } pub const SeekableStream = io.SeekableStream( File, SeekError, GetSeekPosError, seekTo, seekBy, getPos, getEndPos, ); pub fn seekableStream(file: File) SeekableStream { return .{ .context = file }; } const range_off: windows.LARGE_INTEGER = 0; const range_len: windows.LARGE_INTEGER = 1; pub const LockError = error{ SystemResources, FileLocksNotSupported, } || os.UnexpectedError; /// Blocks when an incompatible lock is held by another process. /// A process may hold only one type of lock (shared or exclusive) on /// a file. When a process terminates in any way, the lock is released. /// /// Assumes the file is unlocked. /// /// TODO: integrate with async I/O pub fn lock(file: File, l: Lock) LockError!void { if (is_windows) { var io_status_block: windows.IO_STATUS_BLOCK = undefined; const exclusive = switch (l) { .None => return, .Shared => false, .Exclusive => true, }; return windows.LockFile( file.handle, null, null, null, &io_status_block, &range_off, &range_len, null, windows.FALSE, // non-blocking=false @intFromBool(exclusive), ) catch |err| switch (err) { error.WouldBlock => unreachable, // non-blocking=false else => |e| return e, }; } else { return os.flock(file.handle, switch (l) { .None => os.LOCK.UN, .Shared => os.LOCK.SH, .Exclusive => os.LOCK.EX, }) catch |err| switch (err) { error.WouldBlock => unreachable, // non-blocking=false else => |e| return e, }; } } /// Assumes the file is locked. pub fn unlock(file: File) void { if (is_windows) { var io_status_block: windows.IO_STATUS_BLOCK = undefined; return windows.UnlockFile( file.handle, &io_status_block, &range_off, &range_len, null, ) catch |err| switch (err) { error.RangeNotLocked => unreachable, // Function assumes unlocked. error.Unexpected => unreachable, // Resource deallocation must succeed. }; } else { return os.flock(file.handle, os.LOCK.UN) catch |err| switch (err) { error.WouldBlock => unreachable, // unlocking can't block error.SystemResources => unreachable, // We are deallocating resources. error.FileLocksNotSupported => unreachable, // We already got the lock. error.Unexpected => unreachable, // Resource deallocation must succeed. }; } } /// Attempts to obtain a lock, returning `true` if the lock is /// obtained, and `false` if there was an existing incompatible lock held. /// A process may hold only one type of lock (shared or exclusive) on /// a file. When a process terminates in any way, the lock is released. /// /// Assumes the file is unlocked. /// /// TODO: integrate with async I/O pub fn tryLock(file: File, l: Lock) LockError!bool { if (is_windows) { var io_status_block: windows.IO_STATUS_BLOCK = undefined; const exclusive = switch (l) { .None => return, .Shared => false, .Exclusive => true, }; windows.LockFile( file.handle, null, null, null, &io_status_block, &range_off, &range_len, null, windows.TRUE, // non-blocking=true @intFromBool(exclusive), ) catch |err| switch (err) { error.WouldBlock => return false, else => |e| return e, }; } else { os.flock(file.handle, switch (l) { .None => os.LOCK.UN, .Shared => os.LOCK.SH | os.LOCK.NB, .Exclusive => os.LOCK.EX | os.LOCK.NB, }) catch |err| switch (err) { error.WouldBlock => return false, else => |e| return e, }; } return true; } /// Assumes the file is already locked in exclusive mode. /// Atomically modifies the lock to be in shared mode, without releasing it. /// /// TODO: integrate with async I/O pub fn downgradeLock(file: File) LockError!void { if (is_windows) { // On Windows it works like a semaphore + exclusivity flag. To implement this // function, we first obtain another lock in shared mode. This changes the // exclusivity flag, but increments the semaphore to 2. So we follow up with // an NtUnlockFile which decrements the semaphore but does not modify the // exclusivity flag. var io_status_block: windows.IO_STATUS_BLOCK = undefined; windows.LockFile( file.handle, null, null, null, &io_status_block, &range_off, &range_len, null, windows.TRUE, // non-blocking=true windows.FALSE, // exclusive=false ) catch |err| switch (err) { error.WouldBlock => unreachable, // File was not locked in exclusive mode. else => |e| return e, }; return windows.UnlockFile( file.handle, &io_status_block, &range_off, &range_len, null, ) catch |err| switch (err) { error.RangeNotLocked => unreachable, // File was not locked. error.Unexpected => unreachable, // Resource deallocation must succeed. }; } else { return os.flock(file.handle, os.LOCK.SH | os.LOCK.NB) catch |err| switch (err) { error.WouldBlock => unreachable, // File was not locked in exclusive mode. else => |e| return e, }; } } };
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/fs/path.zig
const builtin = @import("builtin"); const std = @import("../std.zig"); const debug = std.debug; const assert = debug.assert; const testing = std.testing; const mem = std.mem; const fmt = std.fmt; const Allocator = mem.Allocator; const math = std.math; const windows = std.os.windows; const fs = std.fs; const process = std.process; const native_os = builtin.target.os.tag; pub const sep_windows = '\\'; pub const sep_posix = '/'; pub const sep = if (native_os == .windows) sep_windows else sep_posix; pub const sep_str_windows = "\\"; pub const sep_str_posix = "/"; pub const sep_str = if (native_os == .windows) sep_str_windows else sep_str_posix; pub const delimiter_windows = ';'; pub const delimiter_posix = ':'; pub const delimiter = if (native_os == .windows) delimiter_windows else delimiter_posix; /// Returns if the given byte is a valid path separator pub fn isSep(byte: u8) bool { if (native_os == .windows) { return byte == '/' or byte == '\\'; } else { return byte == '/'; } } /// This is different from mem.join in that the separator will not be repeated if /// it is found at the end or beginning of a pair of consecutive paths. fn joinSepMaybeZ(allocator: *Allocator, separator: u8, sepPredicate: fn (u8) bool, paths: []const []const u8, zero: bool) ![]u8 { if (paths.len == 0) return if (zero) try allocator.dupe(u8, &[1]u8{0}) else &[0]u8{}; // Find first non-empty path index. const first_path_index = blk: { for (paths, 0..) |path, index| { if (path.len == 0) continue else break :blk index; } // All paths provided were empty, so return early. return if (zero) try allocator.dupe(u8, &[1]u8{0}) else &[0]u8{}; }; // Calculate length needed for resulting joined path buffer. const total_len = blk: { var sum: usize = paths[first_path_index].len; var prev_path = paths[first_path_index]; assert(prev_path.len > 0); var i: usize = first_path_index + 1; while (i < paths.len) : (i += 1) { const this_path = paths[i]; if (this_path.len == 0) continue; const prev_sep = sepPredicate(prev_path[prev_path.len - 1]); const this_sep = sepPredicate(this_path[0]); sum += @intFromBool(!prev_sep and !this_sep); sum += if (prev_sep and this_sep) this_path.len - 1 else this_path.len; prev_path = this_path; } if (zero) sum += 1; break :blk sum; }; const buf = try allocator.alloc(u8, total_len); errdefer allocator.free(buf); mem.copy(u8, buf, paths[first_path_index]); var buf_index: usize = paths[first_path_index].len; var prev_path = paths[first_path_index]; assert(prev_path.len > 0); var i: usize = first_path_index + 1; while (i < paths.len) : (i += 1) { const this_path = paths[i]; if (this_path.len == 0) continue; const prev_sep = sepPredicate(prev_path[prev_path.len - 1]); const this_sep = sepPredicate(this_path[0]); if (!prev_sep and !this_sep) { buf[buf_index] = separator; buf_index += 1; } const adjusted_path = if (prev_sep and this_sep) this_path[1..] else this_path; mem.copy(u8, buf[buf_index..], adjusted_path); buf_index += adjusted_path.len; prev_path = this_path; } if (zero) buf[buf.len - 1] = 0; // No need for shrink since buf is exactly the correct size. return buf; } /// Naively combines a series of paths with the native path seperator. /// Allocates memory for the result, which must be freed by the caller. pub fn join(allocator: *Allocator, paths: []const []const u8) ![]u8 { return joinSepMaybeZ(allocator, sep, isSep, paths, false); } /// Naively combines a series of paths with the native path seperator and null terminator. /// Allocates memory for the result, which must be freed by the caller. pub fn joinZ(allocator: *Allocator, paths: []const []const u8) ![:0]u8 { const out = try joinSepMaybeZ(allocator, sep, isSep, paths, true); return out[0 .. out.len - 1 :0]; } fn testJoinMaybeZWindows(paths: []const []const u8, expected: []const u8, zero: bool) !void { const windowsIsSep = struct { fn isSep(byte: u8) bool { return byte == '/' or byte == '\\'; } }.isSep; const actual = try joinSepMaybeZ(testing.allocator, sep_windows, windowsIsSep, paths, zero); defer testing.allocator.free(actual); try testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual); } fn testJoinMaybeZPosix(paths: []const []const u8, expected: []const u8, zero: bool) !void { const posixIsSep = struct { fn isSep(byte: u8) bool { return byte == '/'; } }.isSep; const actual = try joinSepMaybeZ(testing.allocator, sep_posix, posixIsSep, paths, zero); defer testing.allocator.free(actual); try testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual); } test "join" { { const actual: []u8 = try join(testing.allocator, &[_][]const u8{}); defer testing.allocator.free(actual); try testing.expectEqualSlices(u8, "", actual); } { const actual: [:0]u8 = try joinZ(testing.allocator, &[_][]const u8{}); defer testing.allocator.free(actual); try testing.expectEqualSlices(u8, "", actual); } for (&[_]bool{ false, true }) |zero| { try testJoinMaybeZWindows(&[_][]const u8{}, "", zero); try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero); try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero); try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b\\", "c" }, "c:\\a\\b\\c", zero); try testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b\\", "c" }, "c:\\a\\b\\c", zero); try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\", "b\\", "c" }, "c:\\a\\b\\c", zero); try testJoinMaybeZWindows( &[_][]const u8{ "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std", "io.zig" }, "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std\\io.zig", zero, ); try testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b/", "c" }, "c:\\a\\b/c", zero); try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a/", "b\\", "/c" }, "c:\\a/b\\c", zero); try testJoinMaybeZWindows(&[_][]const u8{ "", "c:\\", "", "", "a", "b\\", "c", "" }, "c:\\a\\b\\c", zero); try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a/", "", "b\\", "", "/c" }, "c:\\a/b\\c", zero); try testJoinMaybeZWindows(&[_][]const u8{ "", "" }, "", zero); try testJoinMaybeZPosix(&[_][]const u8{}, "", zero); try testJoinMaybeZPosix(&[_][]const u8{ "/a/b", "c" }, "/a/b/c", zero); try testJoinMaybeZPosix(&[_][]const u8{ "/a/b/", "c" }, "/a/b/c", zero); try testJoinMaybeZPosix(&[_][]const u8{ "/", "a", "b/", "c" }, "/a/b/c", zero); try testJoinMaybeZPosix(&[_][]const u8{ "/a/", "b/", "c" }, "/a/b/c", zero); try testJoinMaybeZPosix( &[_][]const u8{ "/home/andy/dev/zig/build/lib/zig/std", "io.zig" }, "/home/andy/dev/zig/build/lib/zig/std/io.zig", zero, ); try testJoinMaybeZPosix(&[_][]const u8{ "a", "/c" }, "a/c", zero); try testJoinMaybeZPosix(&[_][]const u8{ "a/", "/c" }, "a/c", zero); try testJoinMaybeZPosix(&[_][]const u8{ "", "/", "a", "", "b/", "c", "" }, "/a/b/c", zero); try testJoinMaybeZPosix(&[_][]const u8{ "/a/", "", "", "b/", "c" }, "/a/b/c", zero); try testJoinMaybeZPosix(&[_][]const u8{ "", "" }, "", zero); } } pub const isAbsoluteC = @compileError("deprecated: renamed to isAbsoluteZ"); pub fn isAbsoluteZ(path_c: [*:0]const u8) bool { if (native_os == .windows) { return isAbsoluteWindowsZ(path_c); } else { return isAbsolutePosixZ(path_c); } } pub fn isAbsolute(path: []const u8) bool { if (native_os == .windows) { return isAbsoluteWindows(path); } else { return isAbsolutePosix(path); } } fn isAbsoluteWindowsImpl(comptime T: type, path: []const T) bool { if (path.len < 1) return false; if (path[0] == '/') return true; if (path[0] == '\\') return true; if (path.len < 3) return false; if (path[1] == ':') { if (path[2] == '/') return true; if (path[2] == '\\') return true; } return false; } pub fn isAbsoluteWindows(path: []const u8) bool { return isAbsoluteWindowsImpl(u8, path); } pub fn isAbsoluteWindowsW(path_w: [*:0]const u16) bool { return isAbsoluteWindowsImpl(u16, mem.spanZ(path_w)); } pub fn isAbsoluteWindowsWTF16(path: []const u16) bool { return isAbsoluteWindowsImpl(u16, path); } pub const isAbsoluteWindowsC = @compileError("deprecated: renamed to isAbsoluteWindowsZ"); pub fn isAbsoluteWindowsZ(path_c: [*:0]const u8) bool { return isAbsoluteWindowsImpl(u8, mem.spanZ(path_c)); } pub fn isAbsolutePosix(path: []const u8) bool { return path.len > 0 and path[0] == sep_posix; } pub const isAbsolutePosixC = @compileError("deprecated: renamed to isAbsolutePosixZ"); pub fn isAbsolutePosixZ(path_c: [*:0]const u8) bool { return isAbsolutePosix(mem.spanZ(path_c)); } test "isAbsoluteWindows" { try testIsAbsoluteWindows("", false); try testIsAbsoluteWindows("/", true); try testIsAbsoluteWindows("//", true); try testIsAbsoluteWindows("//server", true); try testIsAbsoluteWindows("//server/file", true); try testIsAbsoluteWindows("\\\\server\\file", true); try testIsAbsoluteWindows("\\\\server", true); try testIsAbsoluteWindows("\\\\", true); try testIsAbsoluteWindows("c", false); try testIsAbsoluteWindows("c:", false); try testIsAbsoluteWindows("c:\\", true); try testIsAbsoluteWindows("c:/", true); try testIsAbsoluteWindows("c://", true); try testIsAbsoluteWindows("C:/Users/", true); try testIsAbsoluteWindows("C:\\Users\\", true); try testIsAbsoluteWindows("C:cwd/another", false); try testIsAbsoluteWindows("C:cwd\\another", false); try testIsAbsoluteWindows("directory/directory", false); try testIsAbsoluteWindows("directory\\directory", false); try testIsAbsoluteWindows("/usr/local", true); } test "isAbsolutePosix" { try testIsAbsolutePosix("", false); try testIsAbsolutePosix("/home/foo", true); try testIsAbsolutePosix("/home/foo/..", true); try testIsAbsolutePosix("bar/", false); try testIsAbsolutePosix("./baz", false); } fn testIsAbsoluteWindows(path: []const u8, expected_result: bool) !void { try testing.expectEqual(expected_result, isAbsoluteWindows(path)); } fn testIsAbsolutePosix(path: []const u8, expected_result: bool) !void { try testing.expectEqual(expected_result, isAbsolutePosix(path)); } pub const WindowsPath = struct { is_abs: bool, kind: Kind, disk_designator: []const u8, pub const Kind = enum { None, Drive, NetworkShare, }; }; pub fn windowsParsePath(path: []const u8) WindowsPath { if (path.len >= 2 and path[1] == ':') { return WindowsPath{ .is_abs = isAbsoluteWindows(path), .kind = WindowsPath.Kind.Drive, .disk_designator = path[0..2], }; } if (path.len >= 1 and (path[0] == '/' or path[0] == '\\') and (path.len == 1 or (path[1] != '/' and path[1] != '\\'))) { return WindowsPath{ .is_abs = true, .kind = WindowsPath.Kind.None, .disk_designator = path[0..0], }; } const relative_path = WindowsPath{ .kind = WindowsPath.Kind.None, .disk_designator = &[_]u8{}, .is_abs = false, }; if (path.len < "//a/b".len) { return relative_path; } inline for ("/\\") |this_sep| { const two_sep = [_]u8{ this_sep, this_sep }; if (mem.startsWith(u8, path, &two_sep)) { if (path[2] == this_sep) { return relative_path; } var it = mem.tokenize(u8, path, &[_]u8{this_sep}); _ = (it.next() orelse return relative_path); _ = (it.next() orelse return relative_path); return WindowsPath{ .is_abs = isAbsoluteWindows(path), .kind = WindowsPath.Kind.NetworkShare, .disk_designator = path[0..it.index], }; } } return relative_path; } test "windowsParsePath" { { const parsed = windowsParsePath("//a/b"); try testing.expect(parsed.is_abs); try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare); try testing.expect(mem.eql(u8, parsed.disk_designator, "//a/b")); } { const parsed = windowsParsePath("\\\\a\\b"); try testing.expect(parsed.is_abs); try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare); try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\b")); } { const parsed = windowsParsePath("\\\\a\\"); try testing.expect(!parsed.is_abs); try testing.expect(parsed.kind == WindowsPath.Kind.None); try testing.expect(mem.eql(u8, parsed.disk_designator, "")); } { const parsed = windowsParsePath("/usr/local"); try testing.expect(parsed.is_abs); try testing.expect(parsed.kind == WindowsPath.Kind.None); try testing.expect(mem.eql(u8, parsed.disk_designator, "")); } { const parsed = windowsParsePath("c:../"); try testing.expect(!parsed.is_abs); try testing.expect(parsed.kind == WindowsPath.Kind.Drive); try testing.expect(mem.eql(u8, parsed.disk_designator, "c:")); } } pub fn diskDesignator(path: []const u8) []const u8 { if (native_os == .windows) { return diskDesignatorWindows(path); } else { return ""; } } pub fn diskDesignatorWindows(path: []const u8) []const u8 { return windowsParsePath(path).disk_designator; } fn networkShareServersEql(ns1: []const u8, ns2: []const u8) bool { const sep1 = ns1[0]; const sep2 = ns2[0]; var it1 = mem.tokenize(u8, ns1, &[_]u8{sep1}); var it2 = mem.tokenize(u8, ns2, &[_]u8{sep2}); // TODO ASCII is wrong, we actually need full unicode support to compare paths. return asciiEqlIgnoreCase(it1.next().?, it2.next().?); } fn compareDiskDesignators(kind: WindowsPath.Kind, p1: []const u8, p2: []const u8) bool { switch (kind) { WindowsPath.Kind.None => { assert(p1.len == 0); assert(p2.len == 0); return true; }, WindowsPath.Kind.Drive => { return asciiUpper(p1[0]) == asciiUpper(p2[0]); }, WindowsPath.Kind.NetworkShare => { const sep1 = p1[0]; const sep2 = p2[0]; var it1 = mem.tokenize(u8, p1, &[_]u8{sep1}); var it2 = mem.tokenize(u8, p2, &[_]u8{sep2}); // TODO ASCII is wrong, we actually need full unicode support to compare paths. return asciiEqlIgnoreCase(it1.next().?, it2.next().?) and asciiEqlIgnoreCase(it1.next().?, it2.next().?); }, } } fn asciiUpper(byte: u8) u8 { return switch (byte) { 'a'...'z' => 'A' + (byte - 'a'), else => byte, }; } fn asciiEqlIgnoreCase(s1: []const u8, s2: []const u8) bool { if (s1.len != s2.len) return false; var i: usize = 0; while (i < s1.len) : (i += 1) { if (asciiUpper(s1[i]) != asciiUpper(s2[i])) return false; } return true; } /// On Windows, this calls `resolveWindows` and on POSIX it calls `resolvePosix`. pub fn resolve(allocator: *Allocator, paths: []const []const u8) ![]u8 { if (native_os == .windows) { return resolveWindows(allocator, paths); } else { return resolvePosix(allocator, paths); } } /// This function is like a series of `cd` statements executed one after another. /// It resolves "." and "..". /// The result does not have a trailing path separator. /// If all paths are relative it uses the current working directory as a starting point. /// Each drive has its own current working directory. /// Path separators are canonicalized to '\\' and drives are canonicalized to capital letters. /// Note: all usage of this function should be audited due to the existence of symlinks. /// Without performing actual syscalls, resolving `..` could be incorrect. pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 { if (paths.len == 0) { assert(native_os == .windows); // resolveWindows called on non windows can't use getCwd return process.getCwdAlloc(allocator); } // determine which disk designator we will result with, if any var result_drive_buf = "_:".*; var result_disk_designator: []const u8 = ""; var have_drive_kind = WindowsPath.Kind.None; var have_abs_path = false; var first_index: usize = 0; var max_size: usize = 0; for (paths, 0..) |p, i| { const parsed = windowsParsePath(p); if (parsed.is_abs) { have_abs_path = true; first_index = i; max_size = result_disk_designator.len; } switch (parsed.kind) { WindowsPath.Kind.Drive => { result_drive_buf[0] = asciiUpper(parsed.disk_designator[0]); result_disk_designator = result_drive_buf[0..]; have_drive_kind = WindowsPath.Kind.Drive; }, WindowsPath.Kind.NetworkShare => { result_disk_designator = parsed.disk_designator; have_drive_kind = WindowsPath.Kind.NetworkShare; }, WindowsPath.Kind.None => {}, } max_size += p.len + 1; } // if we will result with a disk designator, loop again to determine // which is the last time the disk designator is absolutely specified, if any // and count up the max bytes for paths related to this disk designator if (have_drive_kind != WindowsPath.Kind.None) { have_abs_path = false; first_index = 0; max_size = result_disk_designator.len; var correct_disk_designator = false; for (paths, 0..) |p, i| { const parsed = windowsParsePath(p); if (parsed.kind != WindowsPath.Kind.None) { if (parsed.kind == have_drive_kind) { correct_disk_designator = compareDiskDesignators(have_drive_kind, result_disk_designator, parsed.disk_designator); } else { continue; } } if (!correct_disk_designator) { continue; } if (parsed.is_abs) { first_index = i; max_size = result_disk_designator.len; have_abs_path = true; } max_size += p.len + 1; } } // Allocate result and fill in the disk designator, calling getCwd if we have to. var result: []u8 = undefined; var result_index: usize = 0; if (have_abs_path) { switch (have_drive_kind) { WindowsPath.Kind.Drive => { result = try allocator.alloc(u8, max_size); mem.copy(u8, result, result_disk_designator); result_index += result_disk_designator.len; }, WindowsPath.Kind.NetworkShare => { result = try allocator.alloc(u8, max_size); var it = mem.tokenize(u8, paths[first_index], "/\\"); const server_name = it.next().?; const other_name = it.next().?; result[result_index] = '\\'; result_index += 1; result[result_index] = '\\'; result_index += 1; mem.copy(u8, result[result_index..], server_name); result_index += server_name.len; result[result_index] = '\\'; result_index += 1; mem.copy(u8, result[result_index..], other_name); result_index += other_name.len; result_disk_designator = result[0..result_index]; }, WindowsPath.Kind.None => { assert(native_os == .windows); // resolveWindows called on non windows can't use getCwd const cwd = try process.getCwdAlloc(allocator); defer allocator.free(cwd); const parsed_cwd = windowsParsePath(cwd); result = try allocator.alloc(u8, max_size + parsed_cwd.disk_designator.len + 1); mem.copy(u8, result, parsed_cwd.disk_designator); result_index += parsed_cwd.disk_designator.len; result_disk_designator = result[0..parsed_cwd.disk_designator.len]; if (parsed_cwd.kind == WindowsPath.Kind.Drive) { result[0] = asciiUpper(result[0]); } have_drive_kind = parsed_cwd.kind; }, } } else { assert(native_os == .windows); // resolveWindows called on non windows can't use getCwd // TODO call get cwd for the result_disk_designator instead of the global one const cwd = try process.getCwdAlloc(allocator); defer allocator.free(cwd); result = try allocator.alloc(u8, max_size + cwd.len + 1); mem.copy(u8, result, cwd); result_index += cwd.len; const parsed_cwd = windowsParsePath(result[0..result_index]); result_disk_designator = parsed_cwd.disk_designator; if (parsed_cwd.kind == WindowsPath.Kind.Drive) { result[0] = asciiUpper(result[0]); } have_drive_kind = parsed_cwd.kind; } errdefer allocator.free(result); // Now we know the disk designator to use, if any, and what kind it is. And our result // is big enough to append all the paths to. var correct_disk_designator = true; for (paths[first_index..]) |p| { const parsed = windowsParsePath(p); if (parsed.kind != WindowsPath.Kind.None) { if (parsed.kind == have_drive_kind) { correct_disk_designator = compareDiskDesignators(have_drive_kind, result_disk_designator, parsed.disk_designator); } else { continue; } } if (!correct_disk_designator) { continue; } var it = mem.tokenize(u8, p[parsed.disk_designator.len..], "/\\"); while (it.next()) |component| { if (mem.eql(u8, component, ".")) { continue; } else if (mem.eql(u8, component, "..")) { while (true) { if (result_index == 0 or result_index == result_disk_designator.len) break; result_index -= 1; if (result[result_index] == '\\' or result[result_index] == '/') break; } } else { result[result_index] = sep_windows; result_index += 1; mem.copy(u8, result[result_index..], component); result_index += component.len; } } } if (result_index == result_disk_designator.len) { result[result_index] = '\\'; result_index += 1; } return allocator.shrink(result, result_index); } /// This function is like a series of `cd` statements executed one after another. /// It resolves "." and "..". /// The result does not have a trailing path separator. /// If all paths are relative it uses the current working directory as a starting point. /// Note: all usage of this function should be audited due to the existence of symlinks. /// Without performing actual syscalls, resolving `..` could be incorrect. pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 { if (paths.len == 0) { assert(native_os != .windows); // resolvePosix called on windows can't use getCwd return process.getCwdAlloc(allocator); } var first_index: usize = 0; var have_abs = false; var max_size: usize = 0; for (paths, 0..) |p, i| { if (isAbsolutePosix(p)) { first_index = i; have_abs = true; max_size = 0; } max_size += p.len + 1; } var result: []u8 = undefined; var result_index: usize = 0; if (have_abs) { result = try allocator.alloc(u8, max_size); } else { assert(native_os != .windows); // resolvePosix called on windows can't use getCwd const cwd = try process.getCwdAlloc(allocator); defer allocator.free(cwd); result = try allocator.alloc(u8, max_size + cwd.len + 1); mem.copy(u8, result, cwd); result_index += cwd.len; } errdefer allocator.free(result); for (paths[first_index..]) |p| { var it = mem.tokenize(u8, p, "/"); while (it.next()) |component| { if (mem.eql(u8, component, ".")) { continue; } else if (mem.eql(u8, component, "..")) { while (true) { if (result_index == 0) break; result_index -= 1; if (result[result_index] == '/') break; } } else { result[result_index] = '/'; result_index += 1; mem.copy(u8, result[result_index..], component); result_index += component.len; } } } if (result_index == 0) { result[0] = '/'; result_index += 1; } return allocator.shrink(result, result_index); } test "resolve" { if (native_os == .wasi) return error.SkipZigTest; const cwd = try process.getCwdAlloc(testing.allocator); defer testing.allocator.free(cwd); if (native_os == .windows) { if (windowsParsePath(cwd).kind == WindowsPath.Kind.Drive) { cwd[0] = asciiUpper(cwd[0]); } try testResolveWindows(&[_][]const u8{"."}, cwd); } else { try testResolvePosix(&[_][]const u8{ "a/b/c/", "../../.." }, cwd); try testResolvePosix(&[_][]const u8{"."}, cwd); } } test "resolveWindows" { if (builtin.target.cpu.arch == .aarch64) { // TODO https://github.com/ziglang/zig/issues/3288 return error.SkipZigTest; } if (native_os == .wasi) return error.SkipZigTest; if (native_os == .windows) { const cwd = try process.getCwdAlloc(testing.allocator); defer testing.allocator.free(cwd); const parsed_cwd = windowsParsePath(cwd); { const expected = try join(testing.allocator, &[_][]const u8{ parsed_cwd.disk_designator, "usr\\local\\lib\\zig\\std\\array_list.zig", }); defer testing.allocator.free(expected); if (parsed_cwd.kind == WindowsPath.Kind.Drive) { expected[0] = asciiUpper(parsed_cwd.disk_designator[0]); } try testResolveWindows(&[_][]const u8{ "/usr/local", "lib\\zig\\std\\array_list.zig" }, expected); } { const expected = try join(testing.allocator, &[_][]const u8{ cwd, "usr\\local\\lib\\zig", }); defer testing.allocator.free(expected); if (parsed_cwd.kind == WindowsPath.Kind.Drive) { expected[0] = asciiUpper(parsed_cwd.disk_designator[0]); } try testResolveWindows(&[_][]const u8{ "usr/local", "lib\\zig" }, expected); } } try testResolveWindows(&[_][]const u8{ "c:\\a\\b\\c", "/hi", "ok" }, "C:\\hi\\ok"); try testResolveWindows(&[_][]const u8{ "c:/blah\\blah", "d:/games", "c:../a" }, "C:\\blah\\a"); try testResolveWindows(&[_][]const u8{ "c:/blah\\blah", "d:/games", "C:../a" }, "C:\\blah\\a"); try testResolveWindows(&[_][]const u8{ "c:/ignore", "d:\\a/b\\c/d", "\\e.exe" }, "D:\\e.exe"); try testResolveWindows(&[_][]const u8{ "c:/ignore", "c:/some/file" }, "C:\\some\\file"); try testResolveWindows(&[_][]const u8{ "d:/ignore", "d:some/dir//" }, "D:\\ignore\\some\\dir"); try testResolveWindows(&[_][]const u8{ "//server/share", "..", "relative\\" }, "\\\\server\\share\\relative"); try testResolveWindows(&[_][]const u8{ "c:/", "//" }, "C:\\"); try testResolveWindows(&[_][]const u8{ "c:/", "//dir" }, "C:\\dir"); try testResolveWindows(&[_][]const u8{ "c:/", "//server/share" }, "\\\\server\\share\\"); try testResolveWindows(&[_][]const u8{ "c:/", "//server//share" }, "\\\\server\\share\\"); try testResolveWindows(&[_][]const u8{ "c:/", "///some//dir" }, "C:\\some\\dir"); try testResolveWindows(&[_][]const u8{ "C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js" }, "C:\\foo\\tmp.3\\cycles\\root.js"); } test "resolvePosix" { if (native_os == .wasi) return error.SkipZigTest; try testResolvePosix(&[_][]const u8{ "/a/b", "c" }, "/a/b/c"); try testResolvePosix(&[_][]const u8{ "/a/b", "c", "//d", "e///" }, "/d/e"); try testResolvePosix(&[_][]const u8{ "/a/b/c", "..", "../" }, "/a"); try testResolvePosix(&[_][]const u8{ "/", "..", ".." }, "/"); try testResolvePosix(&[_][]const u8{"/a/b/c/"}, "/a/b/c"); try testResolvePosix(&[_][]const u8{ "/var/lib", "../", "file/" }, "/var/file"); try testResolvePosix(&[_][]const u8{ "/var/lib", "/../", "file/" }, "/file"); try testResolvePosix(&[_][]const u8{ "/some/dir", ".", "/absolute/" }, "/absolute"); try testResolvePosix(&[_][]const u8{ "/foo/tmp.3/", "../tmp.3/cycles/root.js" }, "/foo/tmp.3/cycles/root.js"); } fn testResolveWindows(paths: []const []const u8, expected: []const u8) !void { const actual = try resolveWindows(testing.allocator, paths); defer testing.allocator.free(actual); try testing.expect(mem.eql(u8, actual, expected)); } fn testResolvePosix(paths: []const []const u8, expected: []const u8) !void { const actual = try resolvePosix(testing.allocator, paths); defer testing.allocator.free(actual); try testing.expect(mem.eql(u8, actual, expected)); } /// Strip the last component from a file path. /// /// If the path is a file in the current directory (no directory component) /// then returns null. /// /// If the path is the root directory, returns null. pub fn dirname(path: []const u8) ?[]const u8 { if (native_os == .windows) { return dirnameWindows(path); } else { return dirnamePosix(path); } } pub fn dirnameWindows(path: []const u8) ?[]const u8 { if (path.len == 0) return null; const root_slice = diskDesignatorWindows(path); if (path.len == root_slice.len) return null; const have_root_slash = path.len > root_slice.len and (path[root_slice.len] == '/' or path[root_slice.len] == '\\'); var end_index: usize = path.len - 1; while (path[end_index] == '/' or path[end_index] == '\\') { if (end_index == 0) return null; end_index -= 1; } while (path[end_index] != '/' and path[end_index] != '\\') { if (end_index == 0) return null; end_index -= 1; } if (have_root_slash and end_index == root_slice.len) { end_index += 1; } if (end_index == 0) return null; return path[0..end_index]; } pub fn dirnamePosix(path: []const u8) ?[]const u8 { if (path.len == 0) return null; var end_index: usize = path.len - 1; while (path[end_index] == '/') { if (end_index == 0) return null; end_index -= 1; } while (path[end_index] != '/') { if (end_index == 0) return null; end_index -= 1; } if (end_index == 0 and path[0] == '/') return path[0..1]; if (end_index == 0) return null; return path[0..end_index]; } test "dirnamePosix" { try testDirnamePosix("/a/b/c", "/a/b"); try testDirnamePosix("/a/b/c///", "/a/b"); try testDirnamePosix("/a", "/"); try testDirnamePosix("/", null); try testDirnamePosix("//", null); try testDirnamePosix("///", null); try testDirnamePosix("////", null); try testDirnamePosix("", null); try testDirnamePosix("a", null); try testDirnamePosix("a/", null); try testDirnamePosix("a//", null); } test "dirnameWindows" { try testDirnameWindows("c:\\", null); try testDirnameWindows("c:\\foo", "c:\\"); try testDirnameWindows("c:\\foo\\", "c:\\"); try testDirnameWindows("c:\\foo\\bar", "c:\\foo"); try testDirnameWindows("c:\\foo\\bar\\", "c:\\foo"); try testDirnameWindows("c:\\foo\\bar\\baz", "c:\\foo\\bar"); try testDirnameWindows("\\", null); try testDirnameWindows("\\foo", "\\"); try testDirnameWindows("\\foo\\", "\\"); try testDirnameWindows("\\foo\\bar", "\\foo"); try testDirnameWindows("\\foo\\bar\\", "\\foo"); try testDirnameWindows("\\foo\\bar\\baz", "\\foo\\bar"); try testDirnameWindows("c:", null); try testDirnameWindows("c:foo", null); try testDirnameWindows("c:foo\\", null); try testDirnameWindows("c:foo\\bar", "c:foo"); try testDirnameWindows("c:foo\\bar\\", "c:foo"); try testDirnameWindows("c:foo\\bar\\baz", "c:foo\\bar"); try testDirnameWindows("file:stream", null); try testDirnameWindows("dir\\file:stream", "dir"); try testDirnameWindows("\\\\unc\\share", null); try testDirnameWindows("\\\\unc\\share\\foo", "\\\\unc\\share\\"); try testDirnameWindows("\\\\unc\\share\\foo\\", "\\\\unc\\share\\"); try testDirnameWindows("\\\\unc\\share\\foo\\bar", "\\\\unc\\share\\foo"); try testDirnameWindows("\\\\unc\\share\\foo\\bar\\", "\\\\unc\\share\\foo"); try testDirnameWindows("\\\\unc\\share\\foo\\bar\\baz", "\\\\unc\\share\\foo\\bar"); try testDirnameWindows("/a/b/", "/a"); try testDirnameWindows("/a/b", "/a"); try testDirnameWindows("/a", "/"); try testDirnameWindows("", null); try testDirnameWindows("/", null); try testDirnameWindows("////", null); try testDirnameWindows("foo", null); } fn testDirnamePosix(input: []const u8, expected_output: ?[]const u8) !void { if (dirnamePosix(input)) |output| { try testing.expect(mem.eql(u8, output, expected_output.?)); } else { try testing.expect(expected_output == null); } } fn testDirnameWindows(input: []const u8, expected_output: ?[]const u8) !void { if (dirnameWindows(input)) |output| { try testing.expect(mem.eql(u8, output, expected_output.?)); } else { try testing.expect(expected_output == null); } } pub fn basename(path: []const u8) []const u8 { if (native_os == .windows) { return basenameWindows(path); } else { return basenamePosix(path); } } pub fn basenamePosix(path: []const u8) []const u8 { if (path.len == 0) return &[_]u8{}; var end_index: usize = path.len - 1; while (path[end_index] == '/') { if (end_index == 0) return &[_]u8{}; end_index -= 1; } var start_index: usize = end_index; end_index += 1; while (path[start_index] != '/') { if (start_index == 0) return path[0..end_index]; start_index -= 1; } return path[start_index + 1 .. end_index]; } pub fn basenameWindows(path: []const u8) []const u8 { if (path.len == 0) return &[_]u8{}; var end_index: usize = path.len - 1; while (true) { const byte = path[end_index]; if (byte == '/' or byte == '\\') { if (end_index == 0) return &[_]u8{}; end_index -= 1; continue; } if (byte == ':' and end_index == 1) { return &[_]u8{}; } break; } var start_index: usize = end_index; end_index += 1; while (path[start_index] != '/' and path[start_index] != '\\' and !(path[start_index] == ':' and start_index == 1)) { if (start_index == 0) return path[0..end_index]; start_index -= 1; } return path[start_index + 1 .. end_index]; } test "basename" { try testBasename("", ""); try testBasename("/", ""); try testBasename("/dir/basename.ext", "basename.ext"); try testBasename("/basename.ext", "basename.ext"); try testBasename("basename.ext", "basename.ext"); try testBasename("basename.ext/", "basename.ext"); try testBasename("basename.ext//", "basename.ext"); try testBasename("/aaa/bbb", "bbb"); try testBasename("/aaa/", "aaa"); try testBasename("/aaa/b", "b"); try testBasename("/a/b", "b"); try testBasename("//a", "a"); try testBasenamePosix("\\dir\\basename.ext", "\\dir\\basename.ext"); try testBasenamePosix("\\basename.ext", "\\basename.ext"); try testBasenamePosix("basename.ext", "basename.ext"); try testBasenamePosix("basename.ext\\", "basename.ext\\"); try testBasenamePosix("basename.ext\\\\", "basename.ext\\\\"); try testBasenamePosix("foo", "foo"); try testBasenameWindows("\\dir\\basename.ext", "basename.ext"); try testBasenameWindows("\\basename.ext", "basename.ext"); try testBasenameWindows("basename.ext", "basename.ext"); try testBasenameWindows("basename.ext\\", "basename.ext"); try testBasenameWindows("basename.ext\\\\", "basename.ext"); try testBasenameWindows("foo", "foo"); try testBasenameWindows("C:", ""); try testBasenameWindows("C:.", "."); try testBasenameWindows("C:\\", ""); try testBasenameWindows("C:\\dir\\base.ext", "base.ext"); try testBasenameWindows("C:\\basename.ext", "basename.ext"); try testBasenameWindows("C:basename.ext", "basename.ext"); try testBasenameWindows("C:basename.ext\\", "basename.ext"); try testBasenameWindows("C:basename.ext\\\\", "basename.ext"); try testBasenameWindows("C:foo", "foo"); try testBasenameWindows("file:stream", "file:stream"); } fn testBasename(input: []const u8, expected_output: []const u8) !void { try testing.expectEqualSlices(u8, expected_output, basename(input)); } fn testBasenamePosix(input: []const u8, expected_output: []const u8) !void { try testing.expectEqualSlices(u8, expected_output, basenamePosix(input)); } fn testBasenameWindows(input: []const u8, expected_output: []const u8) !void { try testing.expectEqualSlices(u8, expected_output, basenameWindows(input)); } /// Returns the relative path from `from` to `to`. If `from` and `to` each /// resolve to the same path (after calling `resolve` on each), a zero-length /// string is returned. /// On Windows this canonicalizes the drive to a capital letter and paths to `\\`. pub fn relative(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 { if (native_os == .windows) { return relativeWindows(allocator, from, to); } else { return relativePosix(allocator, from, to); } } pub fn relativeWindows(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 { const resolved_from = try resolveWindows(allocator, &[_][]const u8{from}); defer allocator.free(resolved_from); var clean_up_resolved_to = true; const resolved_to = try resolveWindows(allocator, &[_][]const u8{to}); defer if (clean_up_resolved_to) allocator.free(resolved_to); const parsed_from = windowsParsePath(resolved_from); const parsed_to = windowsParsePath(resolved_to); const result_is_to = x: { if (parsed_from.kind != parsed_to.kind) { break :x true; } else switch (parsed_from.kind) { WindowsPath.Kind.NetworkShare => { break :x !networkShareServersEql(parsed_to.disk_designator, parsed_from.disk_designator); }, WindowsPath.Kind.Drive => { break :x asciiUpper(parsed_from.disk_designator[0]) != asciiUpper(parsed_to.disk_designator[0]); }, else => unreachable, } }; if (result_is_to) { clean_up_resolved_to = false; return resolved_to; } var from_it = mem.tokenize(u8, resolved_from, "/\\"); var to_it = mem.tokenize(u8, resolved_to, "/\\"); while (true) { const from_component = from_it.next() orelse return allocator.dupe(u8, to_it.rest()); const to_rest = to_it.rest(); if (to_it.next()) |to_component| { // TODO ASCII is wrong, we actually need full unicode support to compare paths. if (asciiEqlIgnoreCase(from_component, to_component)) continue; } var up_count: usize = 1; while (from_it.next()) |_| { up_count += 1; } const up_index_end = up_count * "..\\".len; const result = try allocator.alloc(u8, up_index_end + to_rest.len); errdefer allocator.free(result); var result_index: usize = 0; while (result_index < up_index_end) { result[result_index] = '.'; result_index += 1; result[result_index] = '.'; result_index += 1; result[result_index] = '\\'; result_index += 1; } // shave off the trailing slash result_index -= 1; var rest_it = mem.tokenize(u8, to_rest, "/\\"); while (rest_it.next()) |to_component| { result[result_index] = '\\'; result_index += 1; mem.copy(u8, result[result_index..], to_component); result_index += to_component.len; } return result[0..result_index]; } return [_]u8{}; } pub fn relativePosix(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 { const resolved_from = try resolvePosix(allocator, &[_][]const u8{from}); defer allocator.free(resolved_from); const resolved_to = try resolvePosix(allocator, &[_][]const u8{to}); defer allocator.free(resolved_to); var from_it = mem.tokenize(u8, resolved_from, "/"); var to_it = mem.tokenize(u8, resolved_to, "/"); while (true) { const from_component = from_it.next() orelse return allocator.dupe(u8, to_it.rest()); const to_rest = to_it.rest(); if (to_it.next()) |to_component| { if (mem.eql(u8, from_component, to_component)) continue; } var up_count: usize = 1; while (from_it.next()) |_| { up_count += 1; } const up_index_end = up_count * "../".len; const result = try allocator.alloc(u8, up_index_end + to_rest.len); errdefer allocator.free(result); var result_index: usize = 0; while (result_index < up_index_end) { result[result_index] = '.'; result_index += 1; result[result_index] = '.'; result_index += 1; result[result_index] = '/'; result_index += 1; } if (to_rest.len == 0) { // shave off the trailing slash return allocator.shrink(result, result_index - 1); } mem.copy(u8, result[result_index..], to_rest); return result; } return [_]u8{}; } test "relative" { if (builtin.target.cpu.arch == .aarch64) { // TODO https://github.com/ziglang/zig/issues/3288 return error.SkipZigTest; } if (native_os == .wasi) return error.SkipZigTest; try testRelativeWindows("c:/blah\\blah", "d:/games", "D:\\games"); try testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa", ".."); try testRelativeWindows("c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc"); try testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa/bbbb", ""); try testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa/cccc", "..\\cccc"); try testRelativeWindows("c:/aaaa/", "c:/aaaa/cccc", "cccc"); try testRelativeWindows("c:/", "c:\\aaaa\\bbbb", "aaaa\\bbbb"); try testRelativeWindows("c:/aaaa/bbbb", "d:\\", "D:\\"); try testRelativeWindows("c:/AaAa/bbbb", "c:/aaaa/bbbb", ""); try testRelativeWindows("c:/aaaaa/", "c:/aaaa/cccc", "..\\aaaa\\cccc"); try testRelativeWindows("C:\\foo\\bar\\baz\\quux", "C:\\", "..\\..\\..\\.."); try testRelativeWindows("C:\\foo\\test", "C:\\foo\\test\\bar\\package.json", "bar\\package.json"); try testRelativeWindows("C:\\foo\\bar\\baz-quux", "C:\\foo\\bar\\baz", "..\\baz"); try testRelativeWindows("C:\\foo\\bar\\baz", "C:\\foo\\bar\\baz-quux", "..\\baz-quux"); try testRelativeWindows("\\\\foo\\bar", "\\\\foo\\bar\\baz", "baz"); try testRelativeWindows("\\\\foo\\bar\\baz", "\\\\foo\\bar", ".."); try testRelativeWindows("\\\\foo\\bar\\baz-quux", "\\\\foo\\bar\\baz", "..\\baz"); try testRelativeWindows("\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz-quux", "..\\baz-quux"); try testRelativeWindows("C:\\baz-quux", "C:\\baz", "..\\baz"); try testRelativeWindows("C:\\baz", "C:\\baz-quux", "..\\baz-quux"); try testRelativeWindows("\\\\foo\\baz-quux", "\\\\foo\\baz", "..\\baz"); try testRelativeWindows("\\\\foo\\baz", "\\\\foo\\baz-quux", "..\\baz-quux"); try testRelativeWindows("C:\\baz", "\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz"); try testRelativeWindows("\\\\foo\\bar\\baz", "C:\\baz", "C:\\baz"); try testRelativePosix("/var/lib", "/var", ".."); try testRelativePosix("/var/lib", "/bin", "../../bin"); try testRelativePosix("/var/lib", "/var/lib", ""); try testRelativePosix("/var/lib", "/var/apache", "../apache"); try testRelativePosix("/var/", "/var/lib", "lib"); try testRelativePosix("/", "/var/lib", "var/lib"); try testRelativePosix("/foo/test", "/foo/test/bar/package.json", "bar/package.json"); try testRelativePosix("/Users/a/web/b/test/mails", "/Users/a/web/b", "../.."); try testRelativePosix("/foo/bar/baz-quux", "/foo/bar/baz", "../baz"); try testRelativePosix("/foo/bar/baz", "/foo/bar/baz-quux", "../baz-quux"); try testRelativePosix("/baz-quux", "/baz", "../baz"); try testRelativePosix("/baz", "/baz-quux", "../baz-quux"); } fn testRelativePosix(from: []const u8, to: []const u8, expected_output: []const u8) !void { const result = try relativePosix(testing.allocator, from, to); defer testing.allocator.free(result); try testing.expectEqualSlices(u8, expected_output, result); } fn testRelativeWindows(from: []const u8, to: []const u8, expected_output: []const u8) !void { const result = try relativeWindows(testing.allocator, from, to); defer testing.allocator.free(result); try testing.expectEqualSlices(u8, expected_output, result); } /// Returns the extension of the file name (if any). /// This function will search for the file extension (separated by a `.`) and will return the text after the `.`. /// Files that end with `.` are considered to have no extension, files that start with `.` /// Examples: /// - `"main.zig"` ⇒ `".zig"` /// - `"src/main.zig"` ⇒ `".zig"` /// - `".gitignore"` ⇒ `""` /// - `"keep."` ⇒ `"."` /// - `"src.keep.me"` ⇒ `".me"` /// - `"/src/keep.me"` ⇒ `".me"` /// - `"/src/keep.me/"` ⇒ `".me"` /// The returned slice is guaranteed to have its pointer within the start and end /// pointer address range of `path`, even if it is length zero. pub fn extension(path: []const u8) []const u8 { const filename = basename(path); const index = mem.lastIndexOfScalar(u8, filename, '.') orelse return path[path.len..]; if (index == 0) return path[path.len..]; return filename[index..]; } fn testExtension(path: []const u8, expected: []const u8) !void { try std.testing.expectEqualStrings(expected, extension(path)); } test "extension" { try testExtension("", ""); try testExtension(".", ""); try testExtension("a.", "."); try testExtension("abc.", "."); try testExtension(".a", ""); try testExtension(".file", ""); try testExtension(".gitignore", ""); try testExtension("file.ext", ".ext"); try testExtension("file.ext.", "."); try testExtension("very-long-file.bruh", ".bruh"); try testExtension("a.b.c", ".c"); try testExtension("a.b.c/", ".c"); try testExtension("/", ""); try testExtension("/.", ""); try testExtension("/a.", "."); try testExtension("/abc.", "."); try testExtension("/.a", ""); try testExtension("/.file", ""); try testExtension("/.gitignore", ""); try testExtension("/file.ext", ".ext"); try testExtension("/file.ext.", "."); try testExtension("/very-long-file.bruh", ".bruh"); try testExtension("/a.b.c", ".c"); try testExtension("/a.b.c/", ".c"); try testExtension("/foo/bar/bam/", ""); try testExtension("/foo/bar/bam/.", ""); try testExtension("/foo/bar/bam/a.", "."); try testExtension("/foo/bar/bam/abc.", "."); try testExtension("/foo/bar/bam/.a", ""); try testExtension("/foo/bar/bam/.file", ""); try testExtension("/foo/bar/bam/.gitignore", ""); try testExtension("/foo/bar/bam/file.ext", ".ext"); try testExtension("/foo/bar/bam/file.ext.", "."); try testExtension("/foo/bar/bam/very-long-file.bruh", ".bruh"); try testExtension("/foo/bar/bam/a.b.c", ".c"); try testExtension("/foo/bar/bam/a.b.c/", ".c"); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/fs/watch.zig
const std = @import("std"); const builtin = @import("builtin"); const event = std.event; const assert = std.debug.assert; const testing = std.testing; const os = std.os; const mem = std.mem; const windows = os.windows; const Loop = event.Loop; const fd_t = os.fd_t; const File = std.fs.File; const Allocator = mem.Allocator; const global_event_loop = Loop.instance orelse @compileError("std.fs.Watch currently only works with event-based I/O"); const WatchEventId = enum { CloseWrite, Delete, }; const WatchEventError = error{ UserResourceLimitReached, SystemResources, AccessDenied, Unexpected, // TODO remove this possibility }; pub fn Watch(comptime V: type) type { return struct { channel: event.Channel(Event.Error!Event), os_data: OsData, allocator: *Allocator, const OsData = switch (builtin.os.tag) { // TODO https://github.com/ziglang/zig/issues/3778 .macos, .freebsd, .netbsd, .dragonfly, .openbsd => KqOsData, .linux => LinuxOsData, .windows => WindowsOsData, else => @compileError("Unsupported OS"), }; const KqOsData = struct { table_lock: event.Lock, file_table: FileTable, const FileTable = std.StringHashMapUnmanaged(*Put); const Put = struct { putter_frame: @Frame(kqPutEvents), cancelled: bool = false, value: V, }; }; const WindowsOsData = struct { table_lock: event.Lock, dir_table: DirTable, cancelled: bool = false, const DirTable = std.StringHashMapUnmanaged(*Dir); const FileTable = std.StringHashMapUnmanaged(V); const Dir = struct { putter_frame: @Frame(windowsDirReader), file_table: FileTable, dir_handle: os.windows.HANDLE, }; }; const LinuxOsData = struct { putter_frame: @Frame(linuxEventPutter), inotify_fd: i32, wd_table: WdTable, table_lock: event.Lock, cancelled: bool = false, const WdTable = std.AutoHashMapUnmanaged(i32, Dir); const FileTable = std.StringHashMapUnmanaged(V); const Dir = struct { dirname: []const u8, file_table: FileTable, }; }; const Self = @This(); pub const Event = struct { id: Id, data: V, dirname: []const u8, basename: []const u8, pub const Id = WatchEventId; pub const Error = WatchEventError; }; pub fn init(allocator: *Allocator, event_buf_count: usize) !*Self { const self = try allocator.create(Self); errdefer allocator.destroy(self); switch (builtin.os.tag) { .linux => { const inotify_fd = try os.inotify_init1(os.linux.IN_NONBLOCK | os.linux.IN_CLOEXEC); errdefer os.close(inotify_fd); self.* = Self{ .allocator = allocator, .channel = undefined, .os_data = OsData{ .putter_frame = undefined, .inotify_fd = inotify_fd, .wd_table = OsData.WdTable.init(allocator), .table_lock = event.Lock{}, }, }; var buf = try allocator.alloc(Event.Error!Event, event_buf_count); self.channel.init(buf); self.os_data.putter_frame = async self.linuxEventPutter(); return self; }, .windows => { self.* = Self{ .allocator = allocator, .channel = undefined, .os_data = OsData{ .table_lock = event.Lock{}, .dir_table = OsData.DirTable.init(allocator), }, }; var buf = try allocator.alloc(Event.Error!Event, event_buf_count); self.channel.init(buf); return self; }, .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { self.* = Self{ .allocator = allocator, .channel = undefined, .os_data = OsData{ .table_lock = event.Lock{}, .file_table = OsData.FileTable.init(allocator), }, }; var buf = try allocator.alloc(Event.Error!Event, event_buf_count); self.channel.init(buf); return self; }, else => @compileError("Unsupported OS"), } } pub fn deinit(self: *Self) void { switch (builtin.os.tag) { .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { var it = self.os_data.file_table.iterator(); while (it.next()) |entry| { const key = entry.key_ptr.*; const value = entry.value_ptr.*; value.cancelled = true; // @TODO Close the fd here? await value.putter_frame; self.allocator.free(key); self.allocator.destroy(value); } }, .linux => { self.os_data.cancelled = true; { // Remove all directory watches linuxEventPutter will take care of // cleaning up the memory and closing the inotify fd. var dir_it = self.os_data.wd_table.keyIterator(); while (dir_it.next()) |wd_key| { const rc = os.linux.inotify_rm_watch(self.os_data.inotify_fd, wd_key.*); // Errno can only be EBADF, EINVAL if either the inotify fs or the wd are invalid std.debug.assert(rc == 0); } } await self.os_data.putter_frame; }, .windows => { self.os_data.cancelled = true; var dir_it = self.os_data.dir_table.iterator(); while (dir_it.next()) |dir_entry| { if (windows.kernel32.CancelIoEx(dir_entry.value.dir_handle, null) != 0) { // We canceled the pending ReadDirectoryChangesW operation, but our // frame is still suspending, now waiting indefinitely. // Thus, it is safe to resume it ourslves resume dir_entry.value.putter_frame; } else { std.debug.assert(windows.kernel32.GetLastError() == .NOT_FOUND); // We are at another suspend point, we can await safely for the // function to exit the loop await dir_entry.value.putter_frame; } self.allocator.free(dir_entry.key_ptr.*); var file_it = dir_entry.value.file_table.keyIterator(); while (file_it.next()) |file_entry| { self.allocator.free(file_entry.*); } dir_entry.value.file_table.deinit(self.allocator); self.allocator.destroy(dir_entry.value_ptr.*); } self.os_data.dir_table.deinit(self.allocator); }, else => @compileError("Unsupported OS"), } self.allocator.free(self.channel.buffer_nodes); self.channel.deinit(); self.allocator.destroy(self); } pub fn addFile(self: *Self, file_path: []const u8, value: V) !?V { switch (builtin.os.tag) { .macos, .freebsd, .netbsd, .dragonfly, .openbsd => return addFileKEvent(self, file_path, value), .linux => return addFileLinux(self, file_path, value), .windows => return addFileWindows(self, file_path, value), else => @compileError("Unsupported OS"), } } fn addFileKEvent(self: *Self, file_path: []const u8, value: V) !?V { var realpath_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; const realpath = try os.realpath(file_path, &realpath_buf); const held = self.os_data.table_lock.acquire(); defer held.release(); const gop = try self.os_data.file_table.getOrPut(self.allocator, realpath); errdefer assert(self.os_data.file_table.remove(realpath)); if (gop.found_existing) { const prev_value = gop.value_ptr.value; gop.value_ptr.value = value; return prev_value; } gop.key_ptr.* = try self.allocator.dupe(u8, realpath); errdefer self.allocator.free(gop.key_ptr.*); gop.value_ptr.* = try self.allocator.create(OsData.Put); errdefer self.allocator.destroy(gop.value_ptr.*); gop.value_ptr.* = .{ .putter_frame = undefined, .value = value, }; // @TODO Can I close this fd and get an error from bsdWaitKev? const flags = if (comptime builtin.target.isDarwin()) os.O.SYMLINK | os.O.EVTONLY else 0; const fd = try os.open(realpath, flags, 0); gop.value_ptr.putter_frame = async self.kqPutEvents(fd, gop.key_ptr.*, gop.value_ptr.*); return null; } fn kqPutEvents(self: *Self, fd: os.fd_t, file_path: []const u8, put: *OsData.Put) void { global_event_loop.beginOneEvent(); defer { global_event_loop.finishOneEvent(); // @TODO: Remove this if we force close otherwise os.close(fd); } // We need to manually do a bsdWaitKev to access the fflags. var resume_node = event.Loop.ResumeNode.Basic{ .base = .{ .id = .Basic, .handle = @frame(), .overlapped = event.Loop.ResumeNode.overlapped_init, }, .kev = undefined, }; var kevs = [1]os.Kevent{undefined}; const kev = &kevs[0]; while (!put.cancelled) { kev.* = os.Kevent{ .ident = @as(usize, @intCast(fd)), .filter = os.EVFILT_VNODE, .flags = os.EV_ADD | os.EV_ENABLE | os.EV_CLEAR | os.EV_ONESHOT | os.NOTE_WRITE | os.NOTE_DELETE | os.NOTE_REVOKE, .fflags = 0, .data = 0, .udata = @intFromPtr(&resume_node.base), }; suspend { global_event_loop.beginOneEvent(); errdefer global_event_loop.finishOneEvent(); const empty_kevs = &[0]os.Kevent{}; _ = os.kevent(global_event_loop.os_data.kqfd, &kevs, empty_kevs, null) catch |err| switch (err) { error.EventNotFound, error.ProcessNotFound, error.Overflow, => unreachable, error.AccessDenied, error.SystemResources => |e| { self.channel.put(e); continue; }, }; } if (kev.flags & os.EV_ERROR != 0) { self.channel.put(os.unexpectedErrno(os.errno(kev.data))); continue; } if (kev.fflags & os.NOTE_DELETE != 0 or kev.fflags & os.NOTE_REVOKE != 0) { self.channel.put(Self.Event{ .id = .Delete, .data = put.value, .dirname = std.fs.path.dirname(file_path) orelse "/", .basename = std.fs.path.basename(file_path), }); } else if (kev.fflags & os.NOTE_WRITE != 0) { self.channel.put(Self.Event{ .id = .CloseWrite, .data = put.value, .dirname = std.fs.path.dirname(file_path) orelse "/", .basename = std.fs.path.basename(file_path), }); } } } fn addFileLinux(self: *Self, file_path: []const u8, value: V) !?V { const dirname = std.fs.path.dirname(file_path) orelse if (file_path[0] == '/') "/" else "."; const basename = std.fs.path.basename(file_path); const wd = try os.inotify_add_watch( self.os_data.inotify_fd, dirname, os.linux.IN_CLOSE_WRITE | os.linux.IN_ONLYDIR | os.linux.IN_DELETE | os.linux.IN_EXCL_UNLINK, ); // wd is either a newly created watch or an existing one. const held = self.os_data.table_lock.acquire(); defer held.release(); const gop = try self.os_data.wd_table.getOrPut(self.allocator, wd); errdefer assert(self.os_data.wd_table.remove(wd)); if (!gop.found_existing) { gop.value_ptr.* = OsData.Dir{ .dirname = try self.allocator.dupe(u8, dirname), .file_table = OsData.FileTable.init(self.allocator), }; } const dir = gop.value_ptr; const file_table_gop = try dir.file_table.getOrPut(self.allocator, basename); errdefer assert(dir.file_table.remove(basename)); if (file_table_gop.found_existing) { const prev_value = file_table_gop.value_ptr.*; file_table_gop.value_ptr.* = value; return prev_value; } else { file_table_gop.key_ptr.* = try self.allocator.dupe(u8, basename); file_table_gop.value_ptr.* = value; return null; } } fn addFileWindows(self: *Self, file_path: []const u8, value: V) !?V { // TODO we might need to convert dirname and basename to canonical file paths ("short"?) const dirname = std.fs.path.dirname(file_path) orelse if (file_path[0] == '/') "/" else "."; var dirname_path_space: windows.PathSpace = undefined; dirname_path_space.len = try std.unicode.utf8ToUtf16Le(&dirname_path_space.data, dirname); dirname_path_space.data[dirname_path_space.len] = 0; const basename = std.fs.path.basename(file_path); var basename_path_space: windows.PathSpace = undefined; basename_path_space.len = try std.unicode.utf8ToUtf16Le(&basename_path_space.data, basename); basename_path_space.data[basename_path_space.len] = 0; const held = self.os_data.table_lock.acquire(); defer held.release(); const gop = try self.os_data.dir_table.getOrPut(self.allocator, dirname); errdefer assert(self.os_data.dir_table.remove(dirname)); if (gop.found_existing) { const dir = gop.value_ptr.*; const file_gop = try dir.file_table.getOrPut(self.allocator, basename); errdefer assert(dir.file_table.remove(basename)); if (file_gop.found_existing) { const prev_value = file_gop.value_ptr.*; file_gop.value_ptr.* = value; return prev_value; } else { file_gop.value_ptr.* = value; file_gop.key_ptr.* = try self.allocator.dupe(u8, basename); return null; } } else { const dir_handle = try windows.OpenFile(dirname_path_space.span(), .{ .dir = std.fs.cwd().fd, .access_mask = windows.FILE_LIST_DIRECTORY, .creation = windows.FILE_OPEN, .io_mode = .evented, .open_dir = true, }); errdefer windows.CloseHandle(dir_handle); const dir = try self.allocator.create(OsData.Dir); errdefer self.allocator.destroy(dir); gop.key_ptr.* = try self.allocator.dupe(u8, dirname); errdefer self.allocator.free(gop.key_ptr.*); dir.* = OsData.Dir{ .file_table = OsData.FileTable.init(self.allocator), .putter_frame = undefined, .dir_handle = dir_handle, }; gop.value_ptr.* = dir; try dir.file_table.put(self.allocator, try self.allocator.dupe(u8, basename), value); dir.putter_frame = async self.windowsDirReader(dir, gop.key_ptr.*); return null; } } fn windowsDirReader(self: *Self, dir: *OsData.Dir, dirname: []const u8) void { defer os.close(dir.dir_handle); var resume_node = Loop.ResumeNode.Basic{ .base = Loop.ResumeNode{ .id = .Basic, .handle = @frame(), .overlapped = windows.OVERLAPPED{ .Internal = 0, .InternalHigh = 0, .DUMMYUNIONNAME = .{ .DUMMYSTRUCTNAME = .{ .Offset = 0, .OffsetHigh = 0, }, }, .hEvent = null, }, }, }; var event_buf: [4096]u8 align(@alignOf(windows.FILE_NOTIFY_INFORMATION)) = undefined; global_event_loop.beginOneEvent(); defer global_event_loop.finishOneEvent(); while (!self.os_data.cancelled) main_loop: { suspend { _ = windows.kernel32.ReadDirectoryChangesW( dir.dir_handle, &event_buf, event_buf.len, windows.FALSE, // watch subtree windows.FILE_NOTIFY_CHANGE_FILE_NAME | windows.FILE_NOTIFY_CHANGE_DIR_NAME | windows.FILE_NOTIFY_CHANGE_ATTRIBUTES | windows.FILE_NOTIFY_CHANGE_SIZE | windows.FILE_NOTIFY_CHANGE_LAST_WRITE | windows.FILE_NOTIFY_CHANGE_LAST_ACCESS | windows.FILE_NOTIFY_CHANGE_CREATION | windows.FILE_NOTIFY_CHANGE_SECURITY, null, // number of bytes transferred (unused for async) &resume_node.base.overlapped, null, // completion routine - unused because we use IOCP ); } var bytes_transferred: windows.DWORD = undefined; if (windows.kernel32.GetOverlappedResult( dir.dir_handle, &resume_node.base.overlapped, &bytes_transferred, windows.FALSE, ) == 0) { const potential_error = windows.kernel32.GetLastError(); const err = switch (potential_error) { .OPERATION_ABORTED, .IO_INCOMPLETE => err_blk: { if (self.os_data.cancelled) break :main_loop else break :err_blk windows.unexpectedError(potential_error); }, else => |err| windows.unexpectedError(err), }; self.channel.put(err); } else { var ptr: [*]u8 = &event_buf; const end_ptr = ptr + bytes_transferred; while (@intFromPtr(ptr) < @intFromPtr(end_ptr)) { const ev = @as(*const windows.FILE_NOTIFY_INFORMATION, @ptrCast(ptr)); const emit = switch (ev.Action) { windows.FILE_ACTION_REMOVED => WatchEventId.Delete, windows.FILE_ACTION_MODIFIED => .CloseWrite, else => null, }; if (emit) |id| { const basename_ptr = @as([*]u16, @ptrCast(ptr + @sizeOf(windows.FILE_NOTIFY_INFORMATION))); const basename_utf16le = basename_ptr[0 .. ev.FileNameLength / 2]; var basename_data: [std.fs.MAX_PATH_BYTES]u8 = undefined; const basename = basename_data[0 .. std.unicode.utf16leToUtf8(&basename_data, basename_utf16le) catch unreachable]; if (dir.file_table.getEntry(basename)) |entry| { self.channel.put(Event{ .id = id, .data = entry.value_ptr.*, .dirname = dirname, .basename = entry.key_ptr.*, }); } } if (ev.NextEntryOffset == 0) break; ptr = @alignCast(ptr + ev.NextEntryOffset); } } } } pub fn removeFile(self: *Self, file_path: []const u8) !?V { switch (builtin.os.tag) { .linux => { const dirname = std.fs.path.dirname(file_path) orelse if (file_path[0] == '/') "/" else "."; const basename = std.fs.path.basename(file_path); const held = self.os_data.table_lock.acquire(); defer held.release(); const dir = self.os_data.wd_table.get(dirname) orelse return null; if (dir.file_table.fetchRemove(basename)) |file_entry| { self.allocator.free(file_entry.key); return file_entry.value; } return null; }, .windows => { const dirname = std.fs.path.dirname(file_path) orelse if (file_path[0] == '/') "/" else "."; const basename = std.fs.path.basename(file_path); const held = self.os_data.table_lock.acquire(); defer held.release(); const dir = self.os_data.dir_table.get(dirname) orelse return null; if (dir.file_table.fetchRemove(basename)) |file_entry| { self.allocator.free(file_entry.key); return file_entry.value; } return null; }, .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { var realpath_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; const realpath = try os.realpath(file_path, &realpath_buf); const held = self.os_data.table_lock.acquire(); defer held.release(); const entry = self.os_data.file_table.getEntry(realpath) orelse return null; entry.value_ptr.cancelled = true; // @TODO Close the fd here? await entry.value_ptr.putter_frame; self.allocator.free(entry.key_ptr.*); self.allocator.destroy(entry.value_ptr.*); assert(self.os_data.file_table.remove(realpath)); }, else => @compileError("Unsupported OS"), } } fn linuxEventPutter(self: *Self) void { global_event_loop.beginOneEvent(); defer { std.debug.assert(self.os_data.wd_table.count() == 0); self.os_data.wd_table.deinit(self.allocator); os.close(self.os_data.inotify_fd); self.allocator.free(self.channel.buffer_nodes); self.channel.deinit(); global_event_loop.finishOneEvent(); } var event_buf: [4096]u8 align(@alignOf(os.linux.inotify_event)) = undefined; while (!self.os_data.cancelled) { const bytes_read = global_event_loop.read(self.os_data.inotify_fd, &event_buf, false) catch unreachable; var ptr: [*]u8 = &event_buf; const end_ptr = ptr + bytes_read; while (@intFromPtr(ptr) < @intFromPtr(end_ptr)) { const ev = @as(*const os.linux.inotify_event, @ptrCast(ptr)); if (ev.mask & os.linux.IN_CLOSE_WRITE == os.linux.IN_CLOSE_WRITE) { const basename_ptr = ptr + @sizeOf(os.linux.inotify_event); const basename = std.mem.span(@as([*:0]u8, @ptrCast(basename_ptr))); const dir = &self.os_data.wd_table.get(ev.wd).?; if (dir.file_table.getEntry(basename)) |file_value| { self.channel.put(Event{ .id = .CloseWrite, .data = file_value.value_ptr.*, .dirname = dir.dirname, .basename = file_value.key_ptr.*, }); } } else if (ev.mask & os.linux.IN_IGNORED == os.linux.IN_IGNORED) { // Directory watch was removed const held = self.os_data.table_lock.acquire(); defer held.release(); if (self.os_data.wd_table.fetchRemove(ev.wd)) |wd_entry| { var file_it = wd_entry.value.file_table.keyIterator(); while (file_it.next()) |file_entry| { self.allocator.free(file_entry.*); } self.allocator.free(wd_entry.value.dirname); wd_entry.value.file_table.deinit(self.allocator); } } else if (ev.mask & os.linux.IN_DELETE == os.linux.IN_DELETE) { // File or directory was removed or deleted const basename_ptr = ptr + @sizeOf(os.linux.inotify_event); const basename = std.mem.span(@as([*:0]u8, @ptrCast(basename_ptr))); const dir = &self.os_data.wd_table.get(ev.wd).?; if (dir.file_table.getEntry(basename)) |file_value| { self.channel.put(Event{ .id = .Delete, .data = file_value.value_ptr.*, .dirname = dir.dirname, .basename = file_value.key_ptr.*, }); } } ptr = @alignCast(ptr + @sizeOf(os.linux.inotify_event) + ev.len); } } } }; } const test_tmp_dir = "std_event_fs_test"; test "write a file, watch it, write it again, delete it" { if (!std.io.is_async) return error.SkipZigTest; // TODO https://github.com/ziglang/zig/issues/1908 if (builtin.single_threaded) return error.SkipZigTest; try std.fs.cwd().makePath(test_tmp_dir); defer std.fs.cwd().deleteTree(test_tmp_dir) catch {}; return testWriteWatchWriteDelete(std.testing.allocator); } fn testWriteWatchWriteDelete(allocator: *Allocator) !void { const file_path = try std.fs.path.join(allocator, &[_][]const u8{ test_tmp_dir, "file.txt" }); defer allocator.free(file_path); const contents = \\line 1 \\line 2 ; const line2_offset = 7; // first just write then read the file try std.fs.cwd().writeFile(file_path, contents); const read_contents = try std.fs.cwd().readFileAlloc(allocator, file_path, 1024 * 1024); defer allocator.free(read_contents); try testing.expectEqualSlices(u8, contents, read_contents); // now watch the file var watch = try Watch(void).init(allocator, 0); defer watch.deinit(); try testing.expect((try watch.addFile(file_path, {})) == null); var ev = async watch.channel.get(); var ev_consumed = false; defer if (!ev_consumed) { _ = await ev; }; // overwrite line 2 const file = try std.fs.cwd().openFile(file_path, .{ .read = true, .write = true }); { defer file.close(); const write_contents = "lorem ipsum"; var iovec = [_]os.iovec_const{.{ .iov_base = write_contents, .iov_len = write_contents.len, }}; _ = try file.pwritevAll(&iovec, line2_offset); } switch ((try await ev).id) { .CloseWrite => { ev_consumed = true; }, .Delete => @panic("wrong event"), } const contents_updated = try std.fs.cwd().readFileAlloc(allocator, file_path, 1024 * 1024); defer allocator.free(contents_updated); try testing.expectEqualSlices(u8, \\line 1 \\lorem ipsum , contents_updated); ev = async watch.channel.get(); ev_consumed = false; try std.fs.cwd().deleteFile(file_path); switch ((try await ev).id) { .Delete => { ev_consumed = true; }, .CloseWrite => @panic("wrong event"), } } // TODO Test: Add another file watch, remove the old file watch, get an event in the new
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/valgrind/callgrind.zig
const std = @import("../std.zig"); const valgrind = std.valgrind; pub const CallgrindClientRequest = enum(usize) { DumpStats = valgrind.ToolBase("CT"), ZeroStats, ToggleCollect, DumpStatsAt, StartInstrumentation, StopInstrumentation, }; fn doCallgrindClientRequestExpr(default: usize, request: CallgrindClientRequest, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) usize { return valgrind.doClientRequest(default, @as(usize, @intCast(@intFromEnum(request))), a1, a2, a3, a4, a5); } fn doCallgrindClientRequestStmt(request: CallgrindClientRequest, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) void { _ = doCallgrindClientRequestExpr(0, request, a1, a2, a3, a4, a5); } /// Dump current state of cost centers, and zero them afterwards pub fn dumpStats() void { doCallgrindClientRequestStmt(.DumpStats, 0, 0, 0, 0, 0); } /// Dump current state of cost centers, and zero them afterwards. /// The argument is appended to a string stating the reason which triggered /// the dump. This string is written as a description field into the /// profile data dump. pub fn dumpStatsAt(pos_str: [*]u8) void { doCallgrindClientRequestStmt(.DumpStatsAt, @intFromPtr(pos_str), 0, 0, 0, 0); } /// Zero cost centers pub fn zeroStats() void { doCallgrindClientRequestStmt(.ZeroStats, 0, 0, 0, 0, 0); } /// Toggles collection state. /// The collection state specifies whether the happening of events /// should be noted or if they are to be ignored. Events are noted /// by increment of counters in a cost center pub fn toggleCollect() void { doCallgrindClientRequestStmt(.ToggleCollect, 0, 0, 0, 0, 0); } /// Start full callgrind instrumentation if not already switched on. /// When cache simulation is done, it will flush the simulated cache; /// this will lead to an artificial cache warmup phase afterwards with /// cache misses which would not have happened in reality. pub fn startInstrumentation() void { doCallgrindClientRequestStmt(.StartInstrumentation, 0, 0, 0, 0, 0); } /// Stop full callgrind instrumentation if not already switched off. /// This flushes Valgrinds translation cache, and does no additional /// instrumentation afterwards, which effectivly will run at the same /// speed as the "none" tool (ie. at minimal slowdown). /// Use this to bypass Callgrind aggregation for uninteresting code parts. /// To start Callgrind in this mode to ignore the setup phase, use /// the option "--instr-atstart=no". pub fn stopInstrumentation() void { doCallgrindClientRequestStmt(.StopInstrumentation, 0, 0, 0, 0, 0); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/valgrind/memcheck.zig
const std = @import("../std.zig"); const testing = std.testing; const valgrind = std.valgrind; pub const MemCheckClientRequest = enum(usize) { MakeMemNoAccess = valgrind.ToolBase("MC".*), MakeMemUndefined, MakeMemDefined, Discard, CheckMemIsAddressable, CheckMemIsDefined, DoLeakCheck, CountLeaks, GetVbits, SetVbits, CreateBlock, MakeMemDefinedIfAddressable, CountLeakBlocks, EnableAddrErrorReportingInRange, DisableAddrErrorReportingInRange, }; fn doMemCheckClientRequestExpr(default: usize, request: MemCheckClientRequest, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) usize { return valgrind.doClientRequest(default, @as(usize, @intCast(@intFromEnum(request))), a1, a2, a3, a4, a5); } fn doMemCheckClientRequestStmt(request: MemCheckClientRequest, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) void { _ = doMemCheckClientRequestExpr(0, request, a1, a2, a3, a4, a5); } /// Mark memory at qzz.ptr as unaddressable for qzz.len bytes. /// This returns -1 when run on Valgrind and 0 otherwise. pub fn makeMemNoAccess(qzz: []u8) i1 { return @as(i1, @intCast(doMemCheckClientRequestExpr(0, // default return .MakeMemNoAccess, @intFromPtr(qzz.ptr), qzz.len, 0, 0, 0))); } /// Similarly, mark memory at qzz.ptr as addressable but undefined /// for qzz.len bytes. /// This returns -1 when run on Valgrind and 0 otherwise. pub fn makeMemUndefined(qzz: []u8) i1 { return @as(i1, @intCast(doMemCheckClientRequestExpr(0, // default return .MakeMemUndefined, @intFromPtr(qzz.ptr), qzz.len, 0, 0, 0))); } /// Similarly, mark memory at qzz.ptr as addressable and defined /// for qzz.len bytes. pub fn makeMemDefined(qzz: []u8) i1 { // This returns -1 when run on Valgrind and 0 otherwise. return @as(i1, @intCast(doMemCheckClientRequestExpr(0, // default return .MakeMemDefined, @intFromPtr(qzz.ptr), qzz.len, 0, 0, 0))); } /// Similar to makeMemDefined except that addressability is /// not altered: bytes which are addressable are marked as defined, /// but those which are not addressable are left unchanged. /// This returns -1 when run on Valgrind and 0 otherwise. pub fn makeMemDefinedIfAddressable(qzz: []u8) i1 { return @as(i1, @intCast(doMemCheckClientRequestExpr(0, // default return .MakeMemDefinedIfAddressable, @intFromPtr(qzz.ptr), qzz.len, 0, 0, 0))); } /// Create a block-description handle. The description is an ascii /// string which is included in any messages pertaining to addresses /// within the specified memory range. Has no other effect on the /// properties of the memory range. pub fn createBlock(qzz: []u8, desc: [*]u8) usize { return doMemCheckClientRequestExpr(0, // default return .CreateBlock, @intFromPtr(qzz.ptr), qzz.len, @intFromPtr(desc), 0, 0); } /// Discard a block-description-handle. Returns 1 for an /// invalid handle, 0 for a valid handle. pub fn discard(blkindex: usize) bool { return doMemCheckClientRequestExpr(0, // default return .Discard, 0, blkindex, 0, 0, 0) != 0; } /// Check that memory at qzz.ptr is addressable for qzz.len bytes. /// If suitable addressibility is not established, Valgrind prints an /// error message and returns the address of the first offending byte. /// Otherwise it returns zero. pub fn checkMemIsAddressable(qzz: []u8) usize { return doMemCheckClientRequestExpr(0, .CheckMemIsAddressable, @intFromPtr(qzz.ptr), qzz.len, 0, 0, 0); } /// Check that memory at qzz.ptr is addressable and defined for /// qzz.len bytes. If suitable addressibility and definedness are not /// established, Valgrind prints an error message and returns the /// address of the first offending byte. Otherwise it returns zero. pub fn checkMemIsDefined(qzz: []u8) usize { return doMemCheckClientRequestExpr(0, .CheckMemIsDefined, @intFromPtr(qzz.ptr), qzz.len, 0, 0, 0); } /// Do a full memory leak check (like --leak-check=full) mid-execution. pub fn doLeakCheck() void { doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 0, 0, 0, 0, 0); } /// Same as doLeakCheck() but only showing the entries for /// which there was an increase in leaked bytes or leaked nr of blocks /// since the previous leak search. pub fn doAddedLeakCheck() void { doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 0, 1, 0, 0, 0); } /// Same as doAddedLeakCheck() but showing entries with /// increased or decreased leaked bytes/blocks since previous leak /// search. pub fn doChangedLeakCheck() void { doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 0, 2, 0, 0, 0); } /// Do a summary memory leak check (like --leak-check=summary) mid-execution. pub fn doQuickLeakCheck() void { doMemCheckClientRequestStmt(.DO_LEAK_CHECK, 1, 0, 0, 0, 0); } /// Return number of leaked, dubious, reachable and suppressed bytes found by /// all previous leak checks. const CountResult = struct { leaked: usize, dubious: usize, reachable: usize, suppressed: usize, }; pub fn countLeaks() CountResult { var res: CountResult = .{ .leaked = 0, .dubious = 0, .reachable = 0, .suppressed = 0, }; doMemCheckClientRequestStmt( .CountLeaks, @intFromPtr(&res.leaked), @intFromPtr(&res.dubious), @intFromPtr(&res.reachable), @intFromPtr(&res.suppressed), 0, ); return res; } test "countLeaks" { try testing.expectEqual( @as(CountResult, .{ .leaked = 0, .dubious = 0, .reachable = 0, .suppressed = 0, }), countLeaks(), ); } pub fn countLeakBlocks() CountResult { var res: CountResult = .{ .leaked = 0, .dubious = 0, .reachable = 0, .suppressed = 0, }; doMemCheckClientRequestStmt( .CountLeakBlocks, @intFromPtr(&res.leaked), @intFromPtr(&res.dubious), @intFromPtr(&res.reachable), @intFromPtr(&res.suppressed), 0, ); return res; } test "countLeakBlocks" { try testing.expectEqual( @as(CountResult, .{ .leaked = 0, .dubious = 0, .reachable = 0, .suppressed = 0, }), countLeakBlocks(), ); } /// Get the validity data for addresses zza and copy it /// into the provided zzvbits array. Return values: /// 0 if not running on valgrind /// 1 success /// 2 [previously indicated unaligned arrays; these are now allowed] /// 3 if any parts of zzsrc/zzvbits are not addressable. /// The metadata is not copied in cases 0, 2 or 3 so it should be /// impossible to segfault your system by using this call. pub fn getVbits(zza: []u8, zzvbits: []u8) u2 { std.debug.assert(zzvbits.len >= zza.len / 8); return @as(u2, @intCast(doMemCheckClientRequestExpr(0, .GetVbits, @intFromPtr(zza.ptr), @intFromPtr(zzvbits), zza.len, 0, 0))); } /// Set the validity data for addresses zza, copying it /// from the provided zzvbits array. Return values: /// 0 if not running on valgrind /// 1 success /// 2 [previously indicated unaligned arrays; these are now allowed] /// 3 if any parts of zza/zzvbits are not addressable. /// The metadata is not copied in cases 0, 2 or 3 so it should be /// impossible to segfault your system by using this call. pub fn setVbits(zzvbits: []u8, zza: []u8) u2 { std.debug.assert(zzvbits.len >= zza.len / 8); return @as(u2, @intCast(doMemCheckClientRequestExpr(0, .SetVbits, @intFromPtr(zza.ptr), @intFromPtr(zzvbits), zza.len, 0, 0))); } /// Disable and re-enable reporting of addressing errors in the /// specified address range. pub fn disableAddrErrorReportingInRange(qzz: []u8) usize { return doMemCheckClientRequestExpr(0, // default return .DisableAddrErrorReportingInRange, @intFromPtr(qzz.ptr), qzz.len, 0, 0, 0); } pub fn enableAddrErrorReportingInRange(qzz: []u8) usize { return doMemCheckClientRequestExpr(0, // default return .EnableAddrErrorReportingInRange, @intFromPtr(qzz.ptr), qzz.len, 0, 0, 0); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/asin.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/asinf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/asin.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the arc-sin of x. /// /// Special Cases: /// - asin(+-0) = +-0 /// - asin(x) = nan if x < -1 or x > 1 pub fn asin(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => asin32(x), f64 => asin64(x), else => @compileError("asin not implemented for " ++ @typeName(T)), }; } fn r32(z: f32) f32 { const pS0 = 1.6666586697e-01; const pS1 = -4.2743422091e-02; const pS2 = -8.6563630030e-03; const qS1 = -7.0662963390e-01; const p = z * (pS0 + z * (pS1 + z * pS2)); const q = 1.0 + z * qS1; return p / q; } fn asin32(x: f32) f32 { const pio2 = 1.570796326794896558e+00; const hx: u32 = @as(u32, @bitCast(x)); const ix: u32 = hx & 0x7FFFFFFF; // |x| >= 1 if (ix >= 0x3F800000) { // |x| >= 1 if (ix == 0x3F800000) { return x * pio2 + 0x1.0p-120; // asin(+-1) = +-pi/2 with inexact } else { return math.nan(f32); // asin(|x| > 1) is nan } } // |x| < 0.5 if (ix < 0x3F000000) { // 0x1p-126 <= |x| < 0x1p-12 if (ix < 0x39800000 and ix >= 0x00800000) { return x; } else { return x + x * r32(x * x); } } // 1 > |x| >= 0.5 const z = (1 - math.fabs(x)) * 0.5; const s = math.sqrt(z); const fx = pio2 - 2 * (s + s * r32(z)); if (hx >> 31 != 0) { return -fx; } else { return fx; } } fn r64(z: f64) f64 { const pS0: f64 = 1.66666666666666657415e-01; const pS1: f64 = -3.25565818622400915405e-01; const pS2: f64 = 2.01212532134862925881e-01; const pS3: f64 = -4.00555345006794114027e-02; const pS4: f64 = 7.91534994289814532176e-04; const pS5: f64 = 3.47933107596021167570e-05; const qS1: f64 = -2.40339491173441421878e+00; const qS2: f64 = 2.02094576023350569471e+00; const qS3: f64 = -6.88283971605453293030e-01; const qS4: f64 = 7.70381505559019352791e-02; const p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5))))); const q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4))); return p / q; } fn asin64(x: f64) f64 { const pio2_hi: f64 = 1.57079632679489655800e+00; const pio2_lo: f64 = 6.12323399573676603587e-17; const ux = @as(u64, @bitCast(x)); const hx = @as(u32, @intCast(ux >> 32)); const ix = hx & 0x7FFFFFFF; // |x| >= 1 or nan if (ix >= 0x3FF00000) { const lx = @as(u32, @intCast(ux & 0xFFFFFFFF)); // asin(1) = +-pi/2 with inexact if ((ix - 0x3FF00000) | lx == 0) { return x * pio2_hi + 0x1.0p-120; } else { return math.nan(f64); } } // |x| < 0.5 if (ix < 0x3FE00000) { // if 0x1p-1022 <= |x| < 0x1p-26 avoid raising overflow if (ix < 0x3E500000 and ix >= 0x00100000) { return x; } else { return x + x * r64(x * x); } } // 1 > |x| >= 0.5 const z = (1 - math.fabs(x)) * 0.5; const s = math.sqrt(z); const r = r64(z); var fx: f64 = undefined; // |x| > 0.975 if (ix >= 0x3FEF3333) { fx = pio2_hi - 2 * (s + s * r); } else { const jx = @as(u64, @bitCast(s)); const df = @as(f64, @bitCast(jx & 0xFFFFFFFF00000000)); const c = (z - df * df) / (s + df); fx = 0.5 * pio2_hi - (2 * s * r - (pio2_lo - 2 * c) - (0.5 * pio2_hi - 2 * df)); } if (hx >> 31 != 0) { return -fx; } else { return fx; } } test "math.asin" { try expect(asin(@as(f32, 0.0)) == asin32(0.0)); try expect(asin(@as(f64, 0.0)) == asin64(0.0)); } test "math.asin32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, asin32(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, asin32(0.2), 0.201358, epsilon)); try expect(math.approxEqAbs(f32, asin32(-0.2), -0.201358, epsilon)); try expect(math.approxEqAbs(f32, asin32(0.3434), 0.350535, epsilon)); try expect(math.approxEqAbs(f32, asin32(0.5), 0.523599, epsilon)); try expect(math.approxEqAbs(f32, asin32(0.8923), 1.102415, epsilon)); } test "math.asin64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, asin64(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, asin64(0.2), 0.201358, epsilon)); try expect(math.approxEqAbs(f64, asin64(-0.2), -0.201358, epsilon)); try expect(math.approxEqAbs(f64, asin64(0.3434), 0.350535, epsilon)); try expect(math.approxEqAbs(f64, asin64(0.5), 0.523599, epsilon)); try expect(math.approxEqAbs(f64, asin64(0.8923), 1.102415, epsilon)); } test "math.asin32.special" { try expect(asin32(0.0) == 0.0); try expect(asin32(-0.0) == -0.0); try expect(math.isNan(asin32(-2))); try expect(math.isNan(asin32(1.5))); } test "math.asin64.special" { try expect(asin64(0.0) == 0.0); try expect(asin64(-0.0) == -0.0); try expect(math.isNan(asin64(-2))); try expect(math.isNan(asin64(1.5))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/big.zig
const std = @import("../std.zig"); const assert = std.debug.assert; pub const Rational = @import("big/rational.zig").Rational; pub const int = @import("big/int.zig"); pub const Limb = usize; const limb_info = @typeInfo(Limb).Int; pub const SignedLimb = std.meta.Int(.signed, limb_info.bits); pub const DoubleLimb = std.meta.Int(.unsigned, 2 * limb_info.bits); pub const SignedDoubleLimb = std.meta.Int(.signed, 2 * limb_info.bits); pub const Log2Limb = std.math.Log2Int(Limb); comptime { assert(std.math.floorPowerOfTwo(usize, limb_info.bits) == limb_info.bits); assert(limb_info.bits <= 64); // u128 set is unsupported assert(limb_info.signedness == .unsigned); } test { _ = int; _ = Rational; _ = Limb; _ = SignedLimb; _ = DoubleLimb; _ = SignedDoubleLimb; _ = Log2Limb; }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/floor.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/floorf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/floor.c const expect = std.testing.expect; const std = @import("../std.zig"); const math = std.math; /// Returns the greatest integer value less than or equal to x. /// /// Special Cases: /// - floor(+-0) = +-0 /// - floor(+-inf) = +-inf /// - floor(nan) = nan pub fn floor(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f16 => floor16(x), f32 => floor32(x), f64 => floor64(x), f128 => floor128(x), // TODO this is not correct for some targets c_longdouble => @as(c_longdouble, @floatCast(floor128(x))), else => @compileError("floor not implemented for " ++ @typeName(T)), }; } fn floor16(x: f16) f16 { var u = @as(u16, @bitCast(x)); const e = @as(i16, @intCast((u >> 10) & 31)) - 15; var m: u16 = undefined; // TODO: Shouldn't need this explicit check. if (x == 0.0) { return x; } if (e >= 10) { return x; } if (e >= 0) { m = @as(u16, 1023) >> @as(u4, @intCast(e)); if (u & m == 0) { return x; } math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 15 != 0) { u += m; } return @as(f16, @bitCast(u & ~m)); } else { math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 15 == 0) { return 0.0; } else { return -1.0; } } } fn floor32(x: f32) f32 { var u = @as(u32, @bitCast(x)); const e = @as(i32, @intCast((u >> 23) & 0xFF)) - 0x7F; var m: u32 = undefined; // TODO: Shouldn't need this explicit check. if (x == 0.0) { return x; } if (e >= 23) { return x; } if (e >= 0) { m = @as(u32, 0x007FFFFF) >> @as(u5, @intCast(e)); if (u & m == 0) { return x; } math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 31 != 0) { u += m; } return @as(f32, @bitCast(u & ~m)); } else { math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 31 == 0) { return 0.0; } else { return -1.0; } } } fn floor64(x: f64) f64 { const u = @as(u64, @bitCast(x)); const e = (u >> 52) & 0x7FF; var y: f64 = undefined; if (e >= 0x3FF + 52 or x == 0) { return x; } if (u >> 63 != 0) { y = x - math.f64_toint + math.f64_toint - x; } else { y = x + math.f64_toint - math.f64_toint - x; } if (e <= 0x3FF - 1) { math.doNotOptimizeAway(y); if (u >> 63 != 0) { return -1.0; } else { return 0.0; } } else if (y > 0) { return x + y - 1; } else { return x + y; } } fn floor128(x: f128) f128 { const u = @as(u128, @bitCast(x)); const e = (u >> 112) & 0x7FFF; var y: f128 = undefined; if (e >= 0x3FFF + 112 or x == 0) return x; if (u >> 127 != 0) { y = x - math.f128_toint + math.f128_toint - x; } else { y = x + math.f128_toint - math.f128_toint - x; } if (e <= 0x3FFF - 1) { math.doNotOptimizeAway(y); if (u >> 127 != 0) { return -1.0; } else { return 0.0; } } else if (y > 0) { return x + y - 1; } else { return x + y; } } test "math.floor" { try expect(floor(@as(f16, 1.3)) == floor16(1.3)); try expect(floor(@as(f32, 1.3)) == floor32(1.3)); try expect(floor(@as(f64, 1.3)) == floor64(1.3)); try expect(floor(@as(f128, 1.3)) == floor128(1.3)); } test "math.floor16" { try expect(floor16(1.3) == 1.0); try expect(floor16(-1.3) == -2.0); try expect(floor16(0.2) == 0.0); } test "math.floor32" { try expect(floor32(1.3) == 1.0); try expect(floor32(-1.3) == -2.0); try expect(floor32(0.2) == 0.0); } test "math.floor64" { try expect(floor64(1.3) == 1.0); try expect(floor64(-1.3) == -2.0); try expect(floor64(0.2) == 0.0); } test "math.floor128" { try expect(floor128(1.3) == 1.0); try expect(floor128(-1.3) == -2.0); try expect(floor128(0.2) == 0.0); } test "math.floor16.special" { try expect(floor16(0.0) == 0.0); try expect(floor16(-0.0) == -0.0); try expect(math.isPositiveInf(floor16(math.inf(f16)))); try expect(math.isNegativeInf(floor16(-math.inf(f16)))); try expect(math.isNan(floor16(math.nan(f16)))); } test "math.floor32.special" { try expect(floor32(0.0) == 0.0); try expect(floor32(-0.0) == -0.0); try expect(math.isPositiveInf(floor32(math.inf(f32)))); try expect(math.isNegativeInf(floor32(-math.inf(f32)))); try expect(math.isNan(floor32(math.nan(f32)))); } test "math.floor64.special" { try expect(floor64(0.0) == 0.0); try expect(floor64(-0.0) == -0.0); try expect(math.isPositiveInf(floor64(math.inf(f64)))); try expect(math.isNegativeInf(floor64(-math.inf(f64)))); try expect(math.isNan(floor64(math.nan(f64)))); } test "math.floor128.special" { try expect(floor128(0.0) == 0.0); try expect(floor128(-0.0) == -0.0); try expect(math.isPositiveInf(floor128(math.inf(f128)))); try expect(math.isNegativeInf(floor128(-math.inf(f128)))); try expect(math.isNan(floor128(math.nan(f128)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/isinf.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns whether x is an infinity, ignoring sign. pub fn isInf(x: anytype) bool { const T = @TypeOf(x); switch (T) { f16 => { const bits = @as(u16, @bitCast(x)); return bits & 0x7FFF == 0x7C00; }, f32 => { const bits = @as(u32, @bitCast(x)); return bits & 0x7FFFFFFF == 0x7F800000; }, f64 => { const bits = @as(u64, @bitCast(x)); return bits & (maxInt(u64) >> 1) == (0x7FF << 52); }, f128 => { const bits = @as(u128, @bitCast(x)); return bits & (maxInt(u128) >> 1) == (0x7FFF << 112); }, else => { @compileError("isInf not implemented for " ++ @typeName(T)); }, } } /// Returns whether x is an infinity with a positive sign. pub fn isPositiveInf(x: anytype) bool { const T = @TypeOf(x); switch (T) { f16 => { return @as(u16, @bitCast(x)) == 0x7C00; }, f32 => { return @as(u32, @bitCast(x)) == 0x7F800000; }, f64 => { return @as(u64, @bitCast(x)) == 0x7FF << 52; }, f128 => { return @as(u128, @bitCast(x)) == 0x7FFF << 112; }, else => { @compileError("isPositiveInf not implemented for " ++ @typeName(T)); }, } } /// Returns whether x is an infinity with a negative sign. pub fn isNegativeInf(x: anytype) bool { const T = @TypeOf(x); switch (T) { f16 => { return @as(u16, @bitCast(x)) == 0xFC00; }, f32 => { return @as(u32, @bitCast(x)) == 0xFF800000; }, f64 => { return @as(u64, @bitCast(x)) == 0xFFF << 52; }, f128 => { return @as(u128, @bitCast(x)) == 0xFFFF << 112; }, else => { @compileError("isNegativeInf not implemented for " ++ @typeName(T)); }, } } test "math.isInf" { try expect(!isInf(@as(f16, 0.0))); try expect(!isInf(@as(f16, -0.0))); try expect(!isInf(@as(f32, 0.0))); try expect(!isInf(@as(f32, -0.0))); try expect(!isInf(@as(f64, 0.0))); try expect(!isInf(@as(f64, -0.0))); try expect(!isInf(@as(f128, 0.0))); try expect(!isInf(@as(f128, -0.0))); try expect(isInf(math.inf(f16))); try expect(isInf(-math.inf(f16))); try expect(isInf(math.inf(f32))); try expect(isInf(-math.inf(f32))); try expect(isInf(math.inf(f64))); try expect(isInf(-math.inf(f64))); try expect(isInf(math.inf(f128))); try expect(isInf(-math.inf(f128))); } test "math.isPositiveInf" { try expect(!isPositiveInf(@as(f16, 0.0))); try expect(!isPositiveInf(@as(f16, -0.0))); try expect(!isPositiveInf(@as(f32, 0.0))); try expect(!isPositiveInf(@as(f32, -0.0))); try expect(!isPositiveInf(@as(f64, 0.0))); try expect(!isPositiveInf(@as(f64, -0.0))); try expect(!isPositiveInf(@as(f128, 0.0))); try expect(!isPositiveInf(@as(f128, -0.0))); try expect(isPositiveInf(math.inf(f16))); try expect(!isPositiveInf(-math.inf(f16))); try expect(isPositiveInf(math.inf(f32))); try expect(!isPositiveInf(-math.inf(f32))); try expect(isPositiveInf(math.inf(f64))); try expect(!isPositiveInf(-math.inf(f64))); try expect(isPositiveInf(math.inf(f128))); try expect(!isPositiveInf(-math.inf(f128))); } test "math.isNegativeInf" { try expect(!isNegativeInf(@as(f16, 0.0))); try expect(!isNegativeInf(@as(f16, -0.0))); try expect(!isNegativeInf(@as(f32, 0.0))); try expect(!isNegativeInf(@as(f32, -0.0))); try expect(!isNegativeInf(@as(f64, 0.0))); try expect(!isNegativeInf(@as(f64, -0.0))); try expect(!isNegativeInf(@as(f128, 0.0))); try expect(!isNegativeInf(@as(f128, -0.0))); try expect(!isNegativeInf(math.inf(f16))); try expect(isNegativeInf(-math.inf(f16))); try expect(!isNegativeInf(math.inf(f32))); try expect(isNegativeInf(-math.inf(f32))); try expect(!isNegativeInf(math.inf(f64))); try expect(isNegativeInf(-math.inf(f64))); try expect(!isNegativeInf(math.inf(f128))); try expect(isNegativeInf(-math.inf(f128))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/hypot.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/hypotf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/hypot.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns sqrt(x * x + y * y), avoiding unnecessary overflow and underflow. /// /// Special Cases: /// - hypot(+-inf, y) = +inf /// - hypot(x, +-inf) = +inf /// - hypot(nan, y) = nan /// - hypot(x, nan) = nan pub fn hypot(comptime T: type, x: T, y: T) T { return switch (T) { f32 => hypot32(x, y), f64 => hypot64(x, y), else => @compileError("hypot not implemented for " ++ @typeName(T)), }; } fn hypot32(x: f32, y: f32) f32 { var ux = @as(u32, @bitCast(x)); var uy = @as(u32, @bitCast(y)); ux &= maxInt(u32) >> 1; uy &= maxInt(u32) >> 1; if (ux < uy) { const tmp = ux; ux = uy; uy = tmp; } var xx = @as(f32, @bitCast(ux)); var yy = @as(f32, @bitCast(uy)); if (uy == 0xFF << 23) { return yy; } if (ux >= 0xFF << 23 or uy == 0 or ux - uy >= (25 << 23)) { return xx + yy; } var z: f32 = 1.0; if (ux >= (0x7F + 60) << 23) { z = 0x1.0p90; xx *= 0x1.0p-90; yy *= 0x1.0p-90; } else if (uy < (0x7F - 60) << 23) { z = 0x1.0p-90; xx *= 0x1.0p-90; yy *= 0x1.0p-90; } return z * math.sqrt(@as(f32, @floatCast(@as(f64, x) * x + @as(f64, y) * y))); } fn sq(hi: *f64, lo: *f64, x: f64) void { const split: f64 = 0x1.0p27 + 1.0; const xc = x * split; const xh = x - xc + xc; const xl = x - xh; hi.* = x * x; lo.* = xh * xh - hi.* + 2 * xh * xl + xl * xl; } fn hypot64(x: f64, y: f64) f64 { var ux = @as(u64, @bitCast(x)); var uy = @as(u64, @bitCast(y)); ux &= maxInt(u64) >> 1; uy &= maxInt(u64) >> 1; if (ux < uy) { const tmp = ux; ux = uy; uy = tmp; } const ex = ux >> 52; const ey = uy >> 52; var xx = @as(f64, @bitCast(ux)); var yy = @as(f64, @bitCast(uy)); // hypot(inf, nan) == inf if (ey == 0x7FF) { return yy; } if (ex == 0x7FF or uy == 0) { return xx; } // hypot(x, y) ~= x + y * y / x / 2 with inexact for small y/x if (ex - ey > 64) { return xx + yy; } var z: f64 = 1; if (ex > 0x3FF + 510) { z = 0x1.0p700; xx *= 0x1.0p-700; yy *= 0x1.0p-700; } else if (ey < 0x3FF - 450) { z = 0x1.0p-700; xx *= 0x1.0p700; yy *= 0x1.0p700; } var hx: f64 = undefined; var lx: f64 = undefined; var hy: f64 = undefined; var ly: f64 = undefined; sq(&hx, &lx, x); sq(&hy, &ly, y); return z * math.sqrt(ly + lx + hy + hx); } test "math.hypot" { try expect(hypot(f32, 0.0, -1.2) == hypot32(0.0, -1.2)); try expect(hypot(f64, 0.0, -1.2) == hypot64(0.0, -1.2)); } test "math.hypot32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, hypot32(0.0, -1.2), 1.2, epsilon)); try expect(math.approxEqAbs(f32, hypot32(0.2, -0.34), 0.394462, epsilon)); try expect(math.approxEqAbs(f32, hypot32(0.8923, 2.636890), 2.783772, epsilon)); try expect(math.approxEqAbs(f32, hypot32(1.5, 5.25), 5.460083, epsilon)); try expect(math.approxEqAbs(f32, hypot32(37.45, 159.835), 164.163742, epsilon)); try expect(math.approxEqAbs(f32, hypot32(89.123, 382.028905), 392.286865, epsilon)); try expect(math.approxEqAbs(f32, hypot32(123123.234375, 529428.707813), 543556.875, epsilon)); } test "math.hypot64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, hypot64(0.0, -1.2), 1.2, epsilon)); try expect(math.approxEqAbs(f64, hypot64(0.2, -0.34), 0.394462, epsilon)); try expect(math.approxEqAbs(f64, hypot64(0.8923, 2.636890), 2.783772, epsilon)); try expect(math.approxEqAbs(f64, hypot64(1.5, 5.25), 5.460082, epsilon)); try expect(math.approxEqAbs(f64, hypot64(37.45, 159.835), 164.163728, epsilon)); try expect(math.approxEqAbs(f64, hypot64(89.123, 382.028905), 392.286876, epsilon)); try expect(math.approxEqAbs(f64, hypot64(123123.234375, 529428.707813), 543556.885247, epsilon)); } test "math.hypot32.special" { try expect(math.isPositiveInf(hypot32(math.inf(f32), 0.0))); try expect(math.isPositiveInf(hypot32(-math.inf(f32), 0.0))); try expect(math.isPositiveInf(hypot32(0.0, math.inf(f32)))); try expect(math.isPositiveInf(hypot32(0.0, -math.inf(f32)))); try expect(math.isNan(hypot32(math.nan(f32), 0.0))); try expect(math.isNan(hypot32(0.0, math.nan(f32)))); } test "math.hypot64.special" { try expect(math.isPositiveInf(hypot64(math.inf(f64), 0.0))); try expect(math.isPositiveInf(hypot64(-math.inf(f64), 0.0))); try expect(math.isPositiveInf(hypot64(0.0, math.inf(f64)))); try expect(math.isPositiveInf(hypot64(0.0, -math.inf(f64)))); try expect(math.isNan(hypot64(math.nan(f64), 0.0))); try expect(math.isNan(hypot64(0.0, math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/exp2.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/exp2f.c // https://git.musl-libc.org/cgit/musl/tree/src/math/exp2.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns 2 raised to the power of x (2^x). /// /// Special Cases: /// - exp2(+inf) = +inf /// - exp2(nan) = nan pub fn exp2(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => exp2_32(x), f64 => exp2_64(x), else => @compileError("exp2 not implemented for " ++ @typeName(T)), }; } const exp2ft = [_]f64{ 0x1.6a09e667f3bcdp-1, 0x1.7a11473eb0187p-1, 0x1.8ace5422aa0dbp-1, 0x1.9c49182a3f090p-1, 0x1.ae89f995ad3adp-1, 0x1.c199bdd85529cp-1, 0x1.d5818dcfba487p-1, 0x1.ea4afa2a490dap-1, 0x1.0000000000000p+0, 0x1.0b5586cf9890fp+0, 0x1.172b83c7d517bp+0, 0x1.2387a6e756238p+0, 0x1.306fe0a31b715p+0, 0x1.3dea64c123422p+0, 0x1.4bfdad5362a27p+0, 0x1.5ab07dd485429p+0, }; fn exp2_32(x: f32) f32 { const tblsiz = @as(u32, @intCast(exp2ft.len)); const redux: f32 = 0x1.8p23 / @as(f32, @floatFromInt(tblsiz)); const P1: f32 = 0x1.62e430p-1; const P2: f32 = 0x1.ebfbe0p-3; const P3: f32 = 0x1.c6b348p-5; const P4: f32 = 0x1.3b2c9cp-7; var u = @as(u32, @bitCast(x)); const ix = u & 0x7FFFFFFF; // |x| > 126 if (ix > 0x42FC0000) { // nan if (ix > 0x7F800000) { return x; } // x >= 128 if (u >= 0x43000000 and u < 0x80000000) { return x * 0x1.0p127; } // x < -126 if (u >= 0x80000000) { if (u >= 0xC3160000 or u & 0x000FFFF != 0) { math.doNotOptimizeAway(-0x1.0p-149 / x); } // x <= -150 if (u >= 0x3160000) { return 0; } } } // |x| <= 0x1p-25 else if (ix <= 0x33000000) { return 1.0 + x; } // NOTE: musl relies on unsafe behaviours which are replicated below // (addition/bit-shift overflow). Appears that this produces the // intended result but should confirm how GCC/Clang handle this to ensure. var uf = x + redux; var i_0 = @as(u32, @bitCast(uf)); i_0 +%= tblsiz / 2; const k = i_0 / tblsiz; const uk = @as(f64, @bitCast(@as(u64, 0x3FF + k) << 52)); i_0 &= tblsiz - 1; uf -= redux; const z: f64 = x - uf; var r: f64 = exp2ft[@as(usize, @intCast(i_0))]; const t: f64 = r * z; r = r + t * (P1 + z * P2) + t * (z * z) * (P3 + z * P4); return @as(f32, @floatCast(r * uk)); } const exp2dt = [_]f64{ // exp2(z + eps) eps 0x1.6a09e667f3d5dp-1, 0x1.9880p-44, 0x1.6b052fa751744p-1, 0x1.8000p-50, 0x1.6c012750bd9fep-1, -0x1.8780p-45, 0x1.6cfdcddd476bfp-1, 0x1.ec00p-46, 0x1.6dfb23c651a29p-1, -0x1.8000p-50, 0x1.6ef9298593ae3p-1, -0x1.c000p-52, 0x1.6ff7df9519386p-1, -0x1.fd80p-45, 0x1.70f7466f42da3p-1, -0x1.c880p-45, 0x1.71f75e8ec5fc3p-1, 0x1.3c00p-46, 0x1.72f8286eacf05p-1, -0x1.8300p-44, 0x1.73f9a48a58152p-1, -0x1.0c00p-47, 0x1.74fbd35d7ccfcp-1, 0x1.f880p-45, 0x1.75feb564267f1p-1, 0x1.3e00p-47, 0x1.77024b1ab6d48p-1, -0x1.7d00p-45, 0x1.780694fde5d38p-1, -0x1.d000p-50, 0x1.790b938ac1d00p-1, 0x1.3000p-49, 0x1.7a11473eb0178p-1, -0x1.d000p-49, 0x1.7b17b0976d060p-1, 0x1.0400p-45, 0x1.7c1ed0130c133p-1, 0x1.0000p-53, 0x1.7d26a62ff8636p-1, -0x1.6900p-45, 0x1.7e2f336cf4e3bp-1, -0x1.2e00p-47, 0x1.7f3878491c3e8p-1, -0x1.4580p-45, 0x1.80427543e1b4ep-1, 0x1.3000p-44, 0x1.814d2add1071ap-1, 0x1.f000p-47, 0x1.82589994ccd7ep-1, -0x1.1c00p-45, 0x1.8364c1eb942d0p-1, 0x1.9d00p-45, 0x1.8471a4623cab5p-1, 0x1.7100p-43, 0x1.857f4179f5bbcp-1, 0x1.2600p-45, 0x1.868d99b4491afp-1, -0x1.2c40p-44, 0x1.879cad931a395p-1, -0x1.3000p-45, 0x1.88ac7d98a65b8p-1, -0x1.a800p-45, 0x1.89bd0a4785800p-1, -0x1.d000p-49, 0x1.8ace5422aa223p-1, 0x1.3280p-44, 0x1.8be05bad619fap-1, 0x1.2b40p-43, 0x1.8cf3216b54383p-1, -0x1.ed00p-45, 0x1.8e06a5e08664cp-1, -0x1.0500p-45, 0x1.8f1ae99157807p-1, 0x1.8280p-45, 0x1.902fed0282c0ep-1, -0x1.cb00p-46, 0x1.9145b0b91ff96p-1, -0x1.5e00p-47, 0x1.925c353aa2ff9p-1, 0x1.5400p-48, 0x1.93737b0cdc64ap-1, 0x1.7200p-46, 0x1.948b82b5f98aep-1, -0x1.9000p-47, 0x1.95a44cbc852cbp-1, 0x1.5680p-45, 0x1.96bdd9a766f21p-1, -0x1.6d00p-44, 0x1.97d829fde4e2ap-1, -0x1.1000p-47, 0x1.98f33e47a23a3p-1, 0x1.d000p-45, 0x1.9a0f170ca0604p-1, -0x1.8a40p-44, 0x1.9b2bb4d53ff89p-1, 0x1.55c0p-44, 0x1.9c49182a3f15bp-1, 0x1.6b80p-45, 0x1.9d674194bb8c5p-1, -0x1.c000p-49, 0x1.9e86319e3238ep-1, 0x1.7d00p-46, 0x1.9fa5e8d07f302p-1, 0x1.6400p-46, 0x1.a0c667b5de54dp-1, -0x1.5000p-48, 0x1.a1e7aed8eb8f6p-1, 0x1.9e00p-47, 0x1.a309bec4a2e27p-1, 0x1.ad80p-45, 0x1.a42c980460a5dp-1, -0x1.af00p-46, 0x1.a5503b23e259bp-1, 0x1.b600p-47, 0x1.a674a8af46213p-1, 0x1.8880p-44, 0x1.a799e1330b3a7p-1, 0x1.1200p-46, 0x1.a8bfe53c12e8dp-1, 0x1.6c00p-47, 0x1.a9e6b5579fcd2p-1, -0x1.9b80p-45, 0x1.ab0e521356fb8p-1, 0x1.b700p-45, 0x1.ac36bbfd3f381p-1, 0x1.9000p-50, 0x1.ad5ff3a3c2780p-1, 0x1.4000p-49, 0x1.ae89f995ad2a3p-1, -0x1.c900p-45, 0x1.afb4ce622f367p-1, 0x1.6500p-46, 0x1.b0e07298db790p-1, 0x1.fd40p-45, 0x1.b20ce6c9a89a9p-1, 0x1.2700p-46, 0x1.b33a2b84f1a4bp-1, 0x1.d470p-43, 0x1.b468415b747e7p-1, -0x1.8380p-44, 0x1.b59728de5593ap-1, 0x1.8000p-54, 0x1.b6c6e29f1c56ap-1, 0x1.ad00p-47, 0x1.b7f76f2fb5e50p-1, 0x1.e800p-50, 0x1.b928cf22749b2p-1, -0x1.4c00p-47, 0x1.ba5b030a10603p-1, -0x1.d700p-47, 0x1.bb8e0b79a6f66p-1, 0x1.d900p-47, 0x1.bcc1e904bc1ffp-1, 0x1.2a00p-47, 0x1.bdf69c3f3a16fp-1, -0x1.f780p-46, 0x1.bf2c25bd71db8p-1, -0x1.0a00p-46, 0x1.c06286141b2e9p-1, -0x1.1400p-46, 0x1.c199bdd8552e0p-1, 0x1.be00p-47, 0x1.c2d1cd9fa64eep-1, -0x1.9400p-47, 0x1.c40ab5fffd02fp-1, -0x1.ed00p-47, 0x1.c544778fafd15p-1, 0x1.9660p-44, 0x1.c67f12e57d0cbp-1, -0x1.a100p-46, 0x1.c7ba88988c1b6p-1, -0x1.8458p-42, 0x1.c8f6d9406e733p-1, -0x1.a480p-46, 0x1.ca3405751c4dfp-1, 0x1.b000p-51, 0x1.cb720dcef9094p-1, 0x1.1400p-47, 0x1.ccb0f2e6d1689p-1, 0x1.0200p-48, 0x1.cdf0b555dc412p-1, 0x1.3600p-48, 0x1.cf3155b5bab3bp-1, -0x1.6900p-47, 0x1.d072d4a0789bcp-1, 0x1.9a00p-47, 0x1.d1b532b08c8fap-1, -0x1.5e00p-46, 0x1.d2f87080d8a85p-1, 0x1.d280p-46, 0x1.d43c8eacaa203p-1, 0x1.1a00p-47, 0x1.d5818dcfba491p-1, 0x1.f000p-50, 0x1.d6c76e862e6a1p-1, -0x1.3a00p-47, 0x1.d80e316c9834ep-1, -0x1.cd80p-47, 0x1.d955d71ff6090p-1, 0x1.4c00p-48, 0x1.da9e603db32aep-1, 0x1.f900p-48, 0x1.dbe7cd63a8325p-1, 0x1.9800p-49, 0x1.dd321f301b445p-1, -0x1.5200p-48, 0x1.de7d5641c05bfp-1, -0x1.d700p-46, 0x1.dfc97337b9aecp-1, -0x1.6140p-46, 0x1.e11676b197d5ep-1, 0x1.b480p-47, 0x1.e264614f5a3e7p-1, 0x1.0ce0p-43, 0x1.e3b333b16ee5cp-1, 0x1.c680p-47, 0x1.e502ee78b3fb4p-1, -0x1.9300p-47, 0x1.e653924676d68p-1, -0x1.5000p-49, 0x1.e7a51fbc74c44p-1, -0x1.7f80p-47, 0x1.e8f7977cdb726p-1, -0x1.3700p-48, 0x1.ea4afa2a490e8p-1, 0x1.5d00p-49, 0x1.eb9f4867ccae4p-1, 0x1.61a0p-46, 0x1.ecf482d8e680dp-1, 0x1.5500p-48, 0x1.ee4aaa2188514p-1, 0x1.6400p-51, 0x1.efa1bee615a13p-1, -0x1.e800p-49, 0x1.f0f9c1cb64106p-1, -0x1.a880p-48, 0x1.f252b376bb963p-1, -0x1.c900p-45, 0x1.f3ac948dd7275p-1, 0x1.a000p-53, 0x1.f50765b6e4524p-1, -0x1.4f00p-48, 0x1.f6632798844fdp-1, 0x1.a800p-51, 0x1.f7bfdad9cbe38p-1, 0x1.abc0p-48, 0x1.f91d802243c82p-1, -0x1.4600p-50, 0x1.fa7c1819e908ep-1, -0x1.b0c0p-47, 0x1.fbdba3692d511p-1, -0x1.0e00p-51, 0x1.fd3c22b8f7194p-1, -0x1.0de8p-46, 0x1.fe9d96b2a23eep-1, 0x1.e430p-49, 0x1.0000000000000p+0, 0x0.0000p+0, 0x1.00b1afa5abcbep+0, -0x1.3400p-52, 0x1.0163da9fb3303p+0, -0x1.2170p-46, 0x1.02168143b0282p+0, 0x1.a400p-52, 0x1.02c9a3e77806cp+0, 0x1.f980p-49, 0x1.037d42e11bbcap+0, -0x1.7400p-51, 0x1.04315e86e7f89p+0, 0x1.8300p-50, 0x1.04e5f72f65467p+0, -0x1.a3f0p-46, 0x1.059b0d315855ap+0, -0x1.2840p-47, 0x1.0650a0e3c1f95p+0, 0x1.1600p-48, 0x1.0706b29ddf71ap+0, 0x1.5240p-46, 0x1.07bd42b72a82dp+0, -0x1.9a00p-49, 0x1.0874518759bd0p+0, 0x1.6400p-49, 0x1.092bdf66607c8p+0, -0x1.0780p-47, 0x1.09e3ecac6f383p+0, -0x1.8000p-54, 0x1.0a9c79b1f3930p+0, 0x1.fa00p-48, 0x1.0b5586cf988fcp+0, -0x1.ac80p-48, 0x1.0c0f145e46c8ap+0, 0x1.9c00p-50, 0x1.0cc922b724816p+0, 0x1.5200p-47, 0x1.0d83b23395dd8p+0, -0x1.ad00p-48, 0x1.0e3ec32d3d1f3p+0, 0x1.bac0p-46, 0x1.0efa55fdfa9a6p+0, -0x1.4e80p-47, 0x1.0fb66affed2f0p+0, -0x1.d300p-47, 0x1.1073028d7234bp+0, 0x1.1500p-48, 0x1.11301d0125b5bp+0, 0x1.c000p-49, 0x1.11edbab5e2af9p+0, 0x1.6bc0p-46, 0x1.12abdc06c31d5p+0, 0x1.8400p-49, 0x1.136a814f2047dp+0, -0x1.ed00p-47, 0x1.1429aaea92de9p+0, 0x1.8e00p-49, 0x1.14e95934f3138p+0, 0x1.b400p-49, 0x1.15a98c8a58e71p+0, 0x1.5300p-47, 0x1.166a45471c3dfp+0, 0x1.3380p-47, 0x1.172b83c7d5211p+0, 0x1.8d40p-45, 0x1.17ed48695bb9fp+0, -0x1.5d00p-47, 0x1.18af9388c8d93p+0, -0x1.c880p-46, 0x1.1972658375d66p+0, 0x1.1f00p-46, 0x1.1a35beb6fcba7p+0, 0x1.0480p-46, 0x1.1af99f81387e3p+0, -0x1.7390p-43, 0x1.1bbe084045d54p+0, 0x1.4e40p-45, 0x1.1c82f95281c43p+0, -0x1.a200p-47, 0x1.1d4873168b9b2p+0, 0x1.3800p-49, 0x1.1e0e75eb44031p+0, 0x1.ac00p-49, 0x1.1ed5022fcd938p+0, 0x1.1900p-47, 0x1.1f9c18438cdf7p+0, -0x1.b780p-46, 0x1.2063b88628d8fp+0, 0x1.d940p-45, 0x1.212be3578a81ep+0, 0x1.8000p-50, 0x1.21f49917ddd41p+0, 0x1.b340p-45, 0x1.22bdda2791323p+0, 0x1.9f80p-46, 0x1.2387a6e7561e7p+0, -0x1.9c80p-46, 0x1.2451ffb821427p+0, 0x1.2300p-47, 0x1.251ce4fb2a602p+0, -0x1.3480p-46, 0x1.25e85711eceb0p+0, 0x1.2700p-46, 0x1.26b4565e27d16p+0, 0x1.1d00p-46, 0x1.2780e341de00fp+0, 0x1.1ee0p-44, 0x1.284dfe1f5633ep+0, -0x1.4c00p-46, 0x1.291ba7591bb30p+0, -0x1.3d80p-46, 0x1.29e9df51fdf09p+0, 0x1.8b00p-47, 0x1.2ab8a66d10e9bp+0, -0x1.27c0p-45, 0x1.2b87fd0dada3ap+0, 0x1.a340p-45, 0x1.2c57e39771af9p+0, -0x1.0800p-46, 0x1.2d285a6e402d9p+0, -0x1.ed00p-47, 0x1.2df961f641579p+0, -0x1.4200p-48, 0x1.2ecafa93e2ecfp+0, -0x1.4980p-45, 0x1.2f9d24abd8822p+0, -0x1.6300p-46, 0x1.306fe0a31b625p+0, -0x1.2360p-44, 0x1.31432edeea50bp+0, -0x1.0df8p-40, 0x1.32170fc4cd7b8p+0, -0x1.2480p-45, 0x1.32eb83ba8e9a2p+0, -0x1.5980p-45, 0x1.33c08b2641766p+0, 0x1.ed00p-46, 0x1.3496266e3fa27p+0, -0x1.c000p-50, 0x1.356c55f929f0fp+0, -0x1.0d80p-44, 0x1.36431a2de88b9p+0, 0x1.2c80p-45, 0x1.371a7373aaa39p+0, 0x1.0600p-45, 0x1.37f26231e74fep+0, -0x1.6600p-46, 0x1.38cae6d05d838p+0, -0x1.ae00p-47, 0x1.39a401b713ec3p+0, -0x1.4720p-43, 0x1.3a7db34e5a020p+0, 0x1.8200p-47, 0x1.3b57fbfec6e95p+0, 0x1.e800p-44, 0x1.3c32dc313a8f2p+0, 0x1.f800p-49, 0x1.3d0e544ede122p+0, -0x1.7a00p-46, 0x1.3dea64c1234bbp+0, 0x1.6300p-45, 0x1.3ec70df1c4eccp+0, -0x1.8a60p-43, 0x1.3fa4504ac7e8cp+0, -0x1.cdc0p-44, 0x1.40822c367a0bbp+0, 0x1.5b80p-45, 0x1.4160a21f72e95p+0, 0x1.ec00p-46, 0x1.423fb27094646p+0, -0x1.3600p-46, 0x1.431f5d950a920p+0, 0x1.3980p-45, 0x1.43ffa3f84b9ebp+0, 0x1.a000p-48, 0x1.44e0860618919p+0, -0x1.6c00p-48, 0x1.45c2042a7d201p+0, -0x1.bc00p-47, 0x1.46a41ed1d0016p+0, -0x1.2800p-46, 0x1.4786d668b3326p+0, 0x1.0e00p-44, 0x1.486a2b5c13c00p+0, -0x1.d400p-45, 0x1.494e1e192af04p+0, 0x1.c200p-47, 0x1.4a32af0d7d372p+0, -0x1.e500p-46, 0x1.4b17dea6db801p+0, 0x1.7800p-47, 0x1.4bfdad53629e1p+0, -0x1.3800p-46, 0x1.4ce41b817c132p+0, 0x1.0800p-47, 0x1.4dcb299fddddbp+0, 0x1.c700p-45, 0x1.4eb2d81d8ab96p+0, -0x1.ce00p-46, 0x1.4f9b2769d2d02p+0, 0x1.9200p-46, 0x1.508417f4531c1p+0, -0x1.8c00p-47, 0x1.516daa2cf662ap+0, -0x1.a000p-48, 0x1.5257de83f51eap+0, 0x1.a080p-43, 0x1.5342b569d4edap+0, -0x1.6d80p-45, 0x1.542e2f4f6ac1ap+0, -0x1.2440p-44, 0x1.551a4ca5d94dbp+0, 0x1.83c0p-43, 0x1.56070dde9116bp+0, 0x1.4b00p-45, 0x1.56f4736b529dep+0, 0x1.15a0p-43, 0x1.57e27dbe2c40ep+0, -0x1.9e00p-45, 0x1.58d12d497c76fp+0, -0x1.3080p-45, 0x1.59c0827ff0b4cp+0, 0x1.dec0p-43, 0x1.5ab07dd485427p+0, -0x1.4000p-51, 0x1.5ba11fba87af4p+0, 0x1.0080p-44, 0x1.5c9268a59460bp+0, -0x1.6c80p-45, 0x1.5d84590998e3fp+0, 0x1.69a0p-43, 0x1.5e76f15ad20e1p+0, -0x1.b400p-46, 0x1.5f6a320dcebcap+0, 0x1.7700p-46, 0x1.605e1b976dcb8p+0, 0x1.6f80p-45, 0x1.6152ae6cdf715p+0, 0x1.1000p-47, 0x1.6247eb03a5531p+0, -0x1.5d00p-46, 0x1.633dd1d1929b5p+0, -0x1.2d00p-46, 0x1.6434634ccc313p+0, -0x1.a800p-49, 0x1.652b9febc8efap+0, -0x1.8600p-45, 0x1.6623882553397p+0, 0x1.1fe0p-40, 0x1.671c1c708328ep+0, -0x1.7200p-44, 0x1.68155d44ca97ep+0, 0x1.6800p-49, 0x1.690f4b19e9471p+0, -0x1.9780p-45, }; fn exp2_64(x: f64) f64 { const tblsiz: u32 = @as(u32, @intCast(exp2dt.len / 2)); const redux: f64 = 0x1.8p52 / @as(f64, @floatFromInt(tblsiz)); const P1: f64 = 0x1.62e42fefa39efp-1; const P2: f64 = 0x1.ebfbdff82c575p-3; const P3: f64 = 0x1.c6b08d704a0a6p-5; const P4: f64 = 0x1.3b2ab88f70400p-7; const P5: f64 = 0x1.5d88003875c74p-10; const ux = @as(u64, @bitCast(x)); const ix = @as(u32, @intCast(ux >> 32)) & 0x7FFFFFFF; // TODO: This should be handled beneath. if (math.isNan(x)) { return math.nan(f64); } // |x| >= 1022 or nan if (ix >= 0x408FF000) { // x >= 1024 or nan if (ix >= 0x40900000 and ux >> 63 == 0) { math.raiseOverflow(); return math.inf(f64); } // -inf or -nan if (ix >= 0x7FF00000) { return -1 / x; } // x <= -1022 if (ux >> 63 != 0) { // underflow if (x <= -1075 or x - 0x1.0p52 + 0x1.0p52 != x) { math.doNotOptimizeAway(@as(f32, @floatCast(-0x1.0p-149 / x))); } if (x <= -1075) { return 0; } } } // |x| < 0x1p-54 else if (ix < 0x3C900000) { return 1.0 + x; } // NOTE: musl relies on unsafe behaviours which are replicated below // (addition overflow, division truncation, casting). Appears that this // produces the intended result but should confirm how GCC/Clang handle this // to ensure. // reduce x var uf: f64 = x + redux; // NOTE: musl performs an implicit 64-bit to 32-bit u32 truncation here var i_0: u32 = @as(u32, @truncate(@as(u64, @bitCast(uf)))); i_0 +%= tblsiz / 2; const k: u32 = i_0 / tblsiz * tblsiz; const ik: i32 = @divTrunc(@as(i32, @bitCast(k)), tblsiz); i_0 %= tblsiz; uf -= redux; // r = exp2(y) = exp2t[i_0] * p(z - eps[i]) var z: f64 = x - uf; const t: f64 = exp2dt[@as(usize, @intCast(2 * i_0))]; z -= exp2dt[@as(usize, @intCast(2 * i_0 + 1))]; const r: f64 = t + t * z * (P1 + z * (P2 + z * (P3 + z * (P4 + z * P5)))); return math.scalbn(r, ik); } test "math.exp2" { try expect(exp2(@as(f32, 0.8923)) == exp2_32(0.8923)); try expect(exp2(@as(f64, 0.8923)) == exp2_64(0.8923)); } test "math.exp2_32" { const epsilon = 0.000001; try expect(exp2_32(0.0) == 1.0); try expect(math.approxEqAbs(f32, exp2_32(0.2), 1.148698, epsilon)); try expect(math.approxEqAbs(f32, exp2_32(0.8923), 1.856133, epsilon)); try expect(math.approxEqAbs(f32, exp2_32(1.5), 2.828427, epsilon)); try expect(math.approxEqAbs(f32, exp2_32(37.45), 187747237888, epsilon)); try expect(math.approxEqAbs(f32, exp2_32(-1), 0.5, epsilon)); } test "math.exp2_64" { const epsilon = 0.000001; try expect(exp2_64(0.0) == 1.0); try expect(math.approxEqAbs(f64, exp2_64(0.2), 1.148698, epsilon)); try expect(math.approxEqAbs(f64, exp2_64(0.8923), 1.856133, epsilon)); try expect(math.approxEqAbs(f64, exp2_64(1.5), 2.828427, epsilon)); try expect(math.approxEqAbs(f64, exp2_64(-1), 0.5, epsilon)); try expect(math.approxEqAbs(f64, exp2_64(-0x1.a05cc754481d1p-2), 0x1.824056efc687cp-1, epsilon)); } test "math.exp2_32.special" { try expect(math.isPositiveInf(exp2_32(math.inf(f32)))); try expect(math.isNan(exp2_32(math.nan(f32)))); } test "math.exp2_64.special" { try expect(math.isPositiveInf(exp2_64(math.inf(f64)))); try expect(math.isNan(exp2_64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/modf.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/modff.c // https://git.musl-libc.org/cgit/musl/tree/src/math/modf.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const maxInt = std.math.maxInt; fn modf_result(comptime T: type) type { return struct { fpart: T, ipart: T, }; } pub const modf32_result = modf_result(f32); pub const modf64_result = modf_result(f64); /// Returns the integer and fractional floating-point numbers that sum to x. The sign of each /// result is the same as the sign of x. /// /// Special Cases: /// - modf(+-inf) = +-inf, nan /// - modf(nan) = nan, nan pub fn modf(x: anytype) modf_result(@TypeOf(x)) { const T = @TypeOf(x); return switch (T) { f32 => modf32(x), f64 => modf64(x), else => @compileError("modf not implemented for " ++ @typeName(T)), }; } fn modf32(x: f32) modf32_result { var result: modf32_result = undefined; const u = @as(u32, @bitCast(x)); const e = @as(i32, @intCast((u >> 23) & 0xFF)) - 0x7F; const us = u & 0x80000000; // TODO: Shouldn't need this. if (math.isInf(x)) { result.ipart = x; result.fpart = math.nan(f32); return result; } // no fractional part if (e >= 23) { result.ipart = x; if (e == 0x80 and u << 9 != 0) { // nan result.fpart = x; } else { result.fpart = @as(f32, @bitCast(us)); } return result; } // no integral part if (e < 0) { result.ipart = @as(f32, @bitCast(us)); result.fpart = x; return result; } const mask = @as(u32, 0x007FFFFF) >> @as(u5, @intCast(e)); if (u & mask == 0) { result.ipart = x; result.fpart = @as(f32, @bitCast(us)); return result; } const uf = @as(f32, @bitCast(u & ~mask)); result.ipart = uf; result.fpart = x - uf; return result; } fn modf64(x: f64) modf64_result { var result: modf64_result = undefined; const u = @as(u64, @bitCast(x)); const e = @as(i32, @intCast((u >> 52) & 0x7FF)) - 0x3FF; const us = u & (1 << 63); if (math.isInf(x)) { result.ipart = x; result.fpart = math.nan(f64); return result; } // no fractional part if (e >= 52) { result.ipart = x; if (e == 0x400 and u << 12 != 0) { // nan result.fpart = x; } else { result.fpart = @as(f64, @bitCast(us)); } return result; } // no integral part if (e < 0) { result.ipart = @as(f64, @bitCast(us)); result.fpart = x; return result; } const mask = @as(u64, maxInt(u64) >> 12) >> @as(u6, @intCast(e)); if (u & mask == 0) { result.ipart = x; result.fpart = @as(f64, @bitCast(us)); return result; } const uf = @as(f64, @bitCast(u & ~mask)); result.ipart = uf; result.fpart = x - uf; return result; } test "math.modf" { const a = modf(@as(f32, 1.0)); const b = modf32(1.0); // NOTE: No struct comparison on generic return type function? non-named, makes sense, but still. try expectEqual(a, b); } test "math.modf32" { const epsilon = 0.000001; var r: modf32_result = undefined; r = modf32(1.0); try expect(math.approxEqAbs(f32, r.ipart, 1.0, epsilon)); try expect(math.approxEqAbs(f32, r.fpart, 0.0, epsilon)); r = modf32(2.545); try expect(math.approxEqAbs(f32, r.ipart, 2.0, epsilon)); try expect(math.approxEqAbs(f32, r.fpart, 0.545, epsilon)); r = modf32(3.978123); try expect(math.approxEqAbs(f32, r.ipart, 3.0, epsilon)); try expect(math.approxEqAbs(f32, r.fpart, 0.978123, epsilon)); r = modf32(43874.3); try expect(math.approxEqAbs(f32, r.ipart, 43874, epsilon)); try expect(math.approxEqAbs(f32, r.fpart, 0.300781, epsilon)); r = modf32(1234.340780); try expect(math.approxEqAbs(f32, r.ipart, 1234, epsilon)); try expect(math.approxEqAbs(f32, r.fpart, 0.340820, epsilon)); } test "math.modf64" { const epsilon = 0.000001; var r: modf64_result = undefined; r = modf64(1.0); try expect(math.approxEqAbs(f64, r.ipart, 1.0, epsilon)); try expect(math.approxEqAbs(f64, r.fpart, 0.0, epsilon)); r = modf64(2.545); try expect(math.approxEqAbs(f64, r.ipart, 2.0, epsilon)); try expect(math.approxEqAbs(f64, r.fpart, 0.545, epsilon)); r = modf64(3.978123); try expect(math.approxEqAbs(f64, r.ipart, 3.0, epsilon)); try expect(math.approxEqAbs(f64, r.fpart, 0.978123, epsilon)); r = modf64(43874.3); try expect(math.approxEqAbs(f64, r.ipart, 43874, epsilon)); try expect(math.approxEqAbs(f64, r.fpart, 0.3, epsilon)); r = modf64(1234.340780); try expect(math.approxEqAbs(f64, r.ipart, 1234, epsilon)); try expect(math.approxEqAbs(f64, r.fpart, 0.340780, epsilon)); } test "math.modf32.special" { var r: modf32_result = undefined; r = modf32(math.inf(f32)); try expect(math.isPositiveInf(r.ipart) and math.isNan(r.fpart)); r = modf32(-math.inf(f32)); try expect(math.isNegativeInf(r.ipart) and math.isNan(r.fpart)); r = modf32(math.nan(f32)); try expect(math.isNan(r.ipart) and math.isNan(r.fpart)); } test "math.modf64.special" { var r: modf64_result = undefined; r = modf64(math.inf(f64)); try expect(math.isPositiveInf(r.ipart) and math.isNan(r.fpart)); r = modf64(-math.inf(f64)); try expect(math.isNegativeInf(r.ipart) and math.isNan(r.fpart)); r = modf64(math.nan(f64)); try expect(math.isNan(r.ipart) and math.isNan(r.fpart)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/inf.zig
const std = @import("../std.zig"); const math = std.math; /// Returns value inf for the type T. pub fn inf(comptime T: type) T { return switch (T) { f16 => math.inf_f16, f32 => math.inf_f32, f64 => math.inf_f64, f128 => math.inf_f128, else => @compileError("inf not implemented for " ++ @typeName(T)), }; }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/signbit.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns whether x is negative or negative 0. pub fn signbit(x: anytype) bool { const T = @TypeOf(x); return switch (T) { f16 => signbit16(x), f32 => signbit32(x), f64 => signbit64(x), f128 => signbit128(x), else => @compileError("signbit not implemented for " ++ @typeName(T)), }; } fn signbit16(x: f16) bool { const bits = @as(u16, @bitCast(x)); return bits >> 15 != 0; } fn signbit32(x: f32) bool { const bits = @as(u32, @bitCast(x)); return bits >> 31 != 0; } fn signbit64(x: f64) bool { const bits = @as(u64, @bitCast(x)); return bits >> 63 != 0; } fn signbit128(x: f128) bool { const bits = @as(u128, @bitCast(x)); return bits >> 127 != 0; } test "math.signbit" { try expect(signbit(@as(f16, 4.0)) == signbit16(4.0)); try expect(signbit(@as(f32, 4.0)) == signbit32(4.0)); try expect(signbit(@as(f64, 4.0)) == signbit64(4.0)); try expect(signbit(@as(f128, 4.0)) == signbit128(4.0)); } test "math.signbit16" { try expect(!signbit16(4.0)); try expect(signbit16(-3.0)); } test "math.signbit32" { try expect(!signbit32(4.0)); try expect(signbit32(-3.0)); } test "math.signbit64" { try expect(!signbit64(4.0)); try expect(signbit64(-3.0)); } test "math.signbit128" { try expect(!signbit128(4.0)); try expect(signbit128(-3.0)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/scalbn.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/scalbnf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/scalbn.c const std = @import("std"); const math = std.math; const assert = std.debug.assert; const expect = std.testing.expect; /// Returns x * 2^n. pub fn scalbn(x: anytype, n: i32) @TypeOf(x) { var base = x; var shift = n; const T = @TypeOf(base); const IntT = std.meta.Int(.unsigned, @bitSizeOf(T)); if (@typeInfo(T) != .Float) { @compileError("scalbn not implemented for " ++ @typeName(T)); } const mantissa_bits = math.floatMantissaBits(T); const exponent_bits = math.floatExponentBits(T); const exponent_bias = (1 << (exponent_bits - 1)) - 1; const exponent_min = 1 - exponent_bias; const exponent_max = exponent_bias; // fix double rounding errors in subnormal ranges // https://git.musl-libc.org/cgit/musl/commit/src/math/scalbn.c?id=8c44a060243f04283ca68dad199aab90336141db const scale_min_expo = exponent_min + mantissa_bits + 1; const scale_min = @as(T, @bitCast(@as(IntT, scale_min_expo + exponent_bias) << mantissa_bits)); const scale_max = @as(T, @bitCast(@as(IntT, @intCast(exponent_max + exponent_bias)) << mantissa_bits)); // scale `shift` within floating point limits, if possible // second pass is possible due to subnormal range // third pass always results in +/-0.0 or +/-inf if (shift > exponent_max) { base *= scale_max; shift -= exponent_max; if (shift > exponent_max) { base *= scale_max; shift -= exponent_max; if (shift > exponent_max) shift = exponent_max; } } else if (shift < exponent_min) { base *= scale_min; shift -= scale_min_expo; if (shift < exponent_min) { base *= scale_min; shift -= scale_min_expo; if (shift < exponent_min) shift = exponent_min; } } return base * @as(T, @bitCast(@as(IntT, @intCast(shift + exponent_bias)) << mantissa_bits)); } test "math.scalbn" { // basic usage try expect(scalbn(@as(f16, 1.5), 4) == 24.0); try expect(scalbn(@as(f32, 1.5), 4) == 24.0); try expect(scalbn(@as(f64, 1.5), 4) == 24.0); try expect(scalbn(@as(f128, 1.5), 4) == 24.0); // subnormals try expect(math.isNormal(scalbn(@as(f16, 1.0), -14))); try expect(!math.isNormal(scalbn(@as(f16, 1.0), -15))); try expect(math.isNormal(scalbn(@as(f32, 1.0), -126))); try expect(!math.isNormal(scalbn(@as(f32, 1.0), -127))); try expect(math.isNormal(scalbn(@as(f64, 1.0), -1022))); try expect(!math.isNormal(scalbn(@as(f64, 1.0), -1023))); try expect(math.isNormal(scalbn(@as(f128, 1.0), -16382))); try expect(!math.isNormal(scalbn(@as(f128, 1.0), -16383))); // unreliable due to lack of native f16 support, see talk on PR #8733 // try expect(scalbn(@as(f16, 0x1.1FFp-1), -14 - 9) == math.f16_true_min); try expect(scalbn(@as(f32, 0x1.3FFFFFp-1), -126 - 22) == math.f32_true_min); try expect(scalbn(@as(f64, 0x1.7FFFFFFFFFFFFp-1), -1022 - 51) == math.f64_true_min); try expect(scalbn(@as(f128, 0x1.7FFFFFFFFFFFFFFFFFFFFFFFFFFFp-1), -16382 - 111) == math.f128_true_min); // float limits try expect(scalbn(@as(f32, math.f32_max), -128 - 149) > 0.0); try expect(scalbn(@as(f32, math.f32_max), -128 - 149 - 1) == 0.0); try expect(!math.isPositiveInf(scalbn(@as(f16, math.f16_true_min), 15 + 24))); try expect(math.isPositiveInf(scalbn(@as(f16, math.f16_true_min), 15 + 24 + 1))); try expect(!math.isPositiveInf(scalbn(@as(f32, math.f32_true_min), 127 + 149))); try expect(math.isPositiveInf(scalbn(@as(f32, math.f32_true_min), 127 + 149 + 1))); try expect(!math.isPositiveInf(scalbn(@as(f64, math.f64_true_min), 1023 + 1074))); try expect(math.isPositiveInf(scalbn(@as(f64, math.f64_true_min), 1023 + 1074 + 1))); try expect(!math.isPositiveInf(scalbn(@as(f128, math.f128_true_min), 16383 + 16494))); try expect(math.isPositiveInf(scalbn(@as(f128, math.f128_true_min), 16383 + 16494 + 1))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/copysign.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/copysignf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/copysign.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns a value with the magnitude of x and the sign of y. pub fn copysign(comptime T: type, x: T, y: T) T { return switch (T) { f16 => copysign16(x, y), f32 => copysign32(x, y), f64 => copysign64(x, y), f128 => copysign128(x, y), else => @compileError("copysign not implemented for " ++ @typeName(T)), }; } fn copysign16(x: f16, y: f16) f16 { const ux = @as(u16, @bitCast(x)); const uy = @as(u16, @bitCast(y)); const h1 = ux & (maxInt(u16) / 2); const h2 = uy & (@as(u16, 1) << 15); return @as(f16, @bitCast(h1 | h2)); } fn copysign32(x: f32, y: f32) f32 { const ux = @as(u32, @bitCast(x)); const uy = @as(u32, @bitCast(y)); const h1 = ux & (maxInt(u32) / 2); const h2 = uy & (@as(u32, 1) << 31); return @as(f32, @bitCast(h1 | h2)); } fn copysign64(x: f64, y: f64) f64 { const ux = @as(u64, @bitCast(x)); const uy = @as(u64, @bitCast(y)); const h1 = ux & (maxInt(u64) / 2); const h2 = uy & (@as(u64, 1) << 63); return @as(f64, @bitCast(h1 | h2)); } fn copysign128(x: f128, y: f128) f128 { const ux = @as(u128, @bitCast(x)); const uy = @as(u128, @bitCast(y)); const h1 = ux & (maxInt(u128) / 2); const h2 = uy & (@as(u128, 1) << 127); return @as(f128, @bitCast(h1 | h2)); } test "math.copysign" { try expect(copysign(f16, 1.0, 1.0) == copysign16(1.0, 1.0)); try expect(copysign(f32, 1.0, 1.0) == copysign32(1.0, 1.0)); try expect(copysign(f64, 1.0, 1.0) == copysign64(1.0, 1.0)); try expect(copysign(f128, 1.0, 1.0) == copysign128(1.0, 1.0)); } test "math.copysign16" { try expect(copysign16(5.0, 1.0) == 5.0); try expect(copysign16(5.0, -1.0) == -5.0); try expect(copysign16(-5.0, -1.0) == -5.0); try expect(copysign16(-5.0, 1.0) == 5.0); } test "math.copysign32" { try expect(copysign32(5.0, 1.0) == 5.0); try expect(copysign32(5.0, -1.0) == -5.0); try expect(copysign32(-5.0, -1.0) == -5.0); try expect(copysign32(-5.0, 1.0) == 5.0); } test "math.copysign64" { try expect(copysign64(5.0, 1.0) == 5.0); try expect(copysign64(5.0, -1.0) == -5.0); try expect(copysign64(-5.0, -1.0) == -5.0); try expect(copysign64(-5.0, 1.0) == 5.0); } test "math.copysign128" { try expect(copysign128(5.0, 1.0) == 5.0); try expect(copysign128(5.0, -1.0) == -5.0); try expect(copysign128(-5.0, -1.0) == -5.0); try expect(copysign128(-5.0, 1.0) == 5.0); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/atan2.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/atan2f.c // https://git.musl-libc.org/cgit/musl/tree/src/math/atan2.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the arc-tangent of y/x. /// /// Special Cases: /// - atan2(y, nan) = nan /// - atan2(nan, x) = nan /// - atan2(+0, x>=0) = +0 /// - atan2(-0, x>=0) = -0 /// - atan2(+0, x<=-0) = +pi /// - atan2(-0, x<=-0) = -pi /// - atan2(y>0, 0) = +pi/2 /// - atan2(y<0, 0) = -pi/2 /// - atan2(+inf, +inf) = +pi/4 /// - atan2(-inf, +inf) = -pi/4 /// - atan2(+inf, -inf) = 3pi/4 /// - atan2(-inf, -inf) = -3pi/4 /// - atan2(y, +inf) = 0 /// - atan2(y>0, -inf) = +pi /// - atan2(y<0, -inf) = -pi /// - atan2(+inf, x) = +pi/2 /// - atan2(-inf, x) = -pi/2 pub fn atan2(comptime T: type, y: T, x: T) T { return switch (T) { f32 => atan2_32(y, x), f64 => atan2_64(y, x), else => @compileError("atan2 not implemented for " ++ @typeName(T)), }; } fn atan2_32(y: f32, x: f32) f32 { const pi: f32 = 3.1415927410e+00; const pi_lo: f32 = -8.7422776573e-08; if (math.isNan(x) or math.isNan(y)) { return x + y; } var ix = @as(u32, @bitCast(x)); var iy = @as(u32, @bitCast(y)); // x = 1.0 if (ix == 0x3F800000) { return math.atan(y); } // 2 * sign(x) + sign(y) const m = ((iy >> 31) & 1) | ((ix >> 30) & 2); ix &= 0x7FFFFFFF; iy &= 0x7FFFFFFF; if (iy == 0) { switch (m) { 0, 1 => return y, // atan(+-0, +...) 2 => return pi, // atan(+0, -...) 3 => return -pi, // atan(-0, -...) else => unreachable, } } if (ix == 0) { if (m & 1 != 0) { return -pi / 2; } else { return pi / 2; } } if (ix == 0x7F800000) { if (iy == 0x7F800000) { switch (m) { 0 => return pi / 4, // atan(+inf, +inf) 1 => return -pi / 4, // atan(-inf, +inf) 2 => return 3 * pi / 4, // atan(+inf, -inf) 3 => return -3 * pi / 4, // atan(-inf, -inf) else => unreachable, } } else { switch (m) { 0 => return 0.0, // atan(+..., +inf) 1 => return -0.0, // atan(-..., +inf) 2 => return pi, // atan(+..., -inf) 3 => return -pi, // atan(-...f, -inf) else => unreachable, } } } // |y / x| > 0x1p26 if (ix + (26 << 23) < iy or iy == 0x7F800000) { if (m & 1 != 0) { return -pi / 2; } else { return pi / 2; } } // z = atan(|y / x|) with correct underflow var z = z: { if ((m & 2) != 0 and iy + (26 << 23) < ix) { break :z 0.0; } else { break :z math.atan(math.fabs(y / x)); } }; switch (m) { 0 => return z, // atan(+, +) 1 => return -z, // atan(-, +) 2 => return pi - (z - pi_lo), // atan(+, -) 3 => return (z - pi_lo) - pi, // atan(-, -) else => unreachable, } } fn atan2_64(y: f64, x: f64) f64 { const pi: f64 = 3.1415926535897931160E+00; const pi_lo: f64 = 1.2246467991473531772E-16; if (math.isNan(x) or math.isNan(y)) { return x + y; } var ux = @as(u64, @bitCast(x)); var ix = @as(u32, @intCast(ux >> 32)); var lx = @as(u32, @intCast(ux & 0xFFFFFFFF)); var uy = @as(u64, @bitCast(y)); var iy = @as(u32, @intCast(uy >> 32)); var ly = @as(u32, @intCast(uy & 0xFFFFFFFF)); // x = 1.0 if ((ix -% 0x3FF00000) | lx == 0) { return math.atan(y); } // 2 * sign(x) + sign(y) const m = ((iy >> 31) & 1) | ((ix >> 30) & 2); ix &= 0x7FFFFFFF; iy &= 0x7FFFFFFF; if (iy | ly == 0) { switch (m) { 0, 1 => return y, // atan(+-0, +...) 2 => return pi, // atan(+0, -...) 3 => return -pi, // atan(-0, -...) else => unreachable, } } if (ix | lx == 0) { if (m & 1 != 0) { return -pi / 2; } else { return pi / 2; } } if (ix == 0x7FF00000) { if (iy == 0x7FF00000) { switch (m) { 0 => return pi / 4, // atan(+inf, +inf) 1 => return -pi / 4, // atan(-inf, +inf) 2 => return 3 * pi / 4, // atan(+inf, -inf) 3 => return -3 * pi / 4, // atan(-inf, -inf) else => unreachable, } } else { switch (m) { 0 => return 0.0, // atan(+..., +inf) 1 => return -0.0, // atan(-..., +inf) 2 => return pi, // atan(+..., -inf) 3 => return -pi, // atan(-...f, -inf) else => unreachable, } } } // |y / x| > 0x1p64 if (ix +% (64 << 20) < iy or iy == 0x7FF00000) { if (m & 1 != 0) { return -pi / 2; } else { return pi / 2; } } // z = atan(|y / x|) with correct underflow var z = z: { if ((m & 2) != 0 and iy +% (64 << 20) < ix) { break :z 0.0; } else { break :z math.atan(math.fabs(y / x)); } }; switch (m) { 0 => return z, // atan(+, +) 1 => return -z, // atan(-, +) 2 => return pi - (z - pi_lo), // atan(+, -) 3 => return (z - pi_lo) - pi, // atan(-, -) else => unreachable, } } test "math.atan2" { try expect(atan2(f32, 0.2, 0.21) == atan2_32(0.2, 0.21)); try expect(atan2(f64, 0.2, 0.21) == atan2_64(0.2, 0.21)); } test "math.atan2_32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, atan2_32(0.0, 0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(0.2, 0.2), 0.785398, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(-0.2, 0.2), -0.785398, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(0.2, -0.2), 2.356194, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(-0.2, -0.2), -2.356194, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(0.34, -0.4), 2.437099, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(0.34, 1.243), 0.267001, epsilon)); } test "math.atan2_64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, atan2_64(0.0, 0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(0.2, 0.2), 0.785398, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(-0.2, 0.2), -0.785398, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(0.2, -0.2), 2.356194, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(-0.2, -0.2), -2.356194, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(0.34, -0.4), 2.437099, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(0.34, 1.243), 0.267001, epsilon)); } test "math.atan2_32.special" { const epsilon = 0.000001; try expect(math.isNan(atan2_32(1.0, math.nan(f32)))); try expect(math.isNan(atan2_32(math.nan(f32), 1.0))); try expect(atan2_32(0.0, 5.0) == 0.0); try expect(atan2_32(-0.0, 5.0) == -0.0); try expect(math.approxEqAbs(f32, atan2_32(0.0, -5.0), math.pi, epsilon)); //expect(math.approxEqAbs(f32, atan2_32(-0.0, -5.0), -math.pi, .{.rel=0,.abs=epsilon})); TODO support negative zero? try expect(math.approxEqAbs(f32, atan2_32(1.0, 0.0), math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(1.0, -0.0), math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(-1.0, 0.0), -math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(-1.0, -0.0), -math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(math.inf(f32), math.inf(f32)), math.pi / 4.0, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(-math.inf(f32), math.inf(f32)), -math.pi / 4.0, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(math.inf(f32), -math.inf(f32)), 3.0 * math.pi / 4.0, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(-math.inf(f32), -math.inf(f32)), -3.0 * math.pi / 4.0, epsilon)); try expect(atan2_32(1.0, math.inf(f32)) == 0.0); try expect(math.approxEqAbs(f32, atan2_32(1.0, -math.inf(f32)), math.pi, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(-1.0, -math.inf(f32)), -math.pi, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(math.inf(f32), 1.0), math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f32, atan2_32(-math.inf(f32), 1.0), -math.pi / 2.0, epsilon)); } test "math.atan2_64.special" { const epsilon = 0.000001; try expect(math.isNan(atan2_64(1.0, math.nan(f64)))); try expect(math.isNan(atan2_64(math.nan(f64), 1.0))); try expect(atan2_64(0.0, 5.0) == 0.0); try expect(atan2_64(-0.0, 5.0) == -0.0); try expect(math.approxEqAbs(f64, atan2_64(0.0, -5.0), math.pi, epsilon)); //expect(math.approxEqAbs(f64, atan2_64(-0.0, -5.0), -math.pi, .{.rel=0,.abs=epsilon})); TODO support negative zero? try expect(math.approxEqAbs(f64, atan2_64(1.0, 0.0), math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(1.0, -0.0), math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(-1.0, 0.0), -math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(-1.0, -0.0), -math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(math.inf(f64), math.inf(f64)), math.pi / 4.0, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(-math.inf(f64), math.inf(f64)), -math.pi / 4.0, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(math.inf(f64), -math.inf(f64)), 3.0 * math.pi / 4.0, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(-math.inf(f64), -math.inf(f64)), -3.0 * math.pi / 4.0, epsilon)); try expect(atan2_64(1.0, math.inf(f64)) == 0.0); try expect(math.approxEqAbs(f64, atan2_64(1.0, -math.inf(f64)), math.pi, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(-1.0, -math.inf(f64)), -math.pi, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(math.inf(f64), 1.0), math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f64, atan2_64(-math.inf(f64), 1.0), -math.pi / 2.0, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/epsilon.zig
const math = @import("../math.zig"); /// Returns the machine epsilon for type T. /// This is the smallest value of type T that satisfies the inequality 1.0 + /// epsilon != 1.0. pub fn epsilon(comptime T: type) T { return switch (T) { f16 => math.f16_epsilon, f32 => math.f32_epsilon, f64 => math.f64_epsilon, f128 => math.f128_epsilon, else => @compileError("epsilon not implemented for " ++ @typeName(T)), }; }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/isnan.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns whether x is a nan. pub fn isNan(x: anytype) bool { return x != x; } /// Returns whether x is a signalling nan. pub fn isSignalNan(x: anytype) bool { // Note: A signalling nan is identical to a standard nan right now but may have a different bit // representation in the future when required. return isNan(x); } test "math.isNan" { try expect(isNan(math.nan(f16))); try expect(isNan(math.nan(f32))); try expect(isNan(math.nan(f64))); try expect(isNan(math.nan(f128))); try expect(!isNan(@as(f16, 1.0))); try expect(!isNan(@as(f32, 1.0))); try expect(!isNan(@as(f64, 1.0))); try expect(!isNan(@as(f128, 1.0))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/ilogb.zig
// Ported from musl, which is MIT licensed. // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/ilogbl.c // https://git.musl-libc.org/cgit/musl/tree/src/math/ilogbf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/ilogb.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; const minInt = std.math.minInt; /// Returns the binary exponent of x as an integer. /// /// Special Cases: /// - ilogb(+-inf) = maxInt(i32) /// - ilogb(0) = maxInt(i32) /// - ilogb(nan) = maxInt(i32) pub fn ilogb(x: anytype) i32 { const T = @TypeOf(x); return switch (T) { f32 => ilogb32(x), f64 => ilogb64(x), f128 => ilogb128(x), else => @compileError("ilogb not implemented for " ++ @typeName(T)), }; } // TODO: unify these implementations with generics // NOTE: Should these be exposed publicly? const fp_ilogbnan = -1 - @as(i32, maxInt(u32) >> 1); const fp_ilogb0 = fp_ilogbnan; fn ilogb32(x: f32) i32 { var u = @as(u32, @bitCast(x)); var e = @as(i32, @intCast((u >> 23) & 0xFF)); // TODO: We should be able to merge this with the lower check. if (math.isNan(x)) { return maxInt(i32); } if (e == 0) { u <<= 9; if (u == 0) { math.raiseInvalid(); return fp_ilogb0; } // subnormal e = -0x7F; while (u >> 31 == 0) : (u <<= 1) { e -= 1; } return e; } if (e == 0xFF) { math.raiseInvalid(); if (u << 9 != 0) { return fp_ilogbnan; } else { return maxInt(i32); } } return e - 0x7F; } fn ilogb64(x: f64) i32 { var u = @as(u64, @bitCast(x)); var e = @as(i32, @intCast((u >> 52) & 0x7FF)); if (math.isNan(x)) { return maxInt(i32); } if (e == 0) { u <<= 12; if (u == 0) { math.raiseInvalid(); return fp_ilogb0; } // subnormal e = -0x3FF; while (u >> 63 == 0) : (u <<= 1) { e -= 1; } return e; } if (e == 0x7FF) { math.raiseInvalid(); if (u << 12 != 0) { return fp_ilogbnan; } else { return maxInt(i32); } } return e - 0x3FF; } fn ilogb128(x: f128) i32 { var u = @as(u128, @bitCast(x)); var e = @as(i32, @intCast((u >> 112) & 0x7FFF)); if (math.isNan(x)) { return maxInt(i32); } if (e == 0) { u <<= 16; if (u == 0) { math.raiseInvalid(); return fp_ilogb0; } // subnormal x return ilogb128(x * 0x1p120) - 120; } if (e == 0x7FFF) { math.raiseInvalid(); if (u << 16 != 0) { return fp_ilogbnan; } else { return maxInt(i32); } } return e - 0x3FFF; } test "type dispatch" { try expect(ilogb(@as(f32, 0.2)) == ilogb32(0.2)); try expect(ilogb(@as(f64, 0.2)) == ilogb64(0.2)); } test "32" { try expect(ilogb32(0.0) == fp_ilogb0); try expect(ilogb32(0.5) == -1); try expect(ilogb32(0.8923) == -1); try expect(ilogb32(10.0) == 3); try expect(ilogb32(-123984) == 16); try expect(ilogb32(2398.23) == 11); } test "64" { try expect(ilogb64(0.0) == fp_ilogb0); try expect(ilogb64(0.5) == -1); try expect(ilogb64(0.8923) == -1); try expect(ilogb64(10.0) == 3); try expect(ilogb64(-123984) == 16); try expect(ilogb64(2398.23) == 11); } test "128" { try expect(ilogb128(0.0) == fp_ilogb0); try expect(ilogb128(0.5) == -1); try expect(ilogb128(0.8923) == -1); try expect(ilogb128(10.0) == 3); try expect(ilogb128(-123984) == 16); try expect(ilogb128(2398.23) == 11); } test "32 special" { try expect(ilogb32(math.inf(f32)) == maxInt(i32)); try expect(ilogb32(-math.inf(f32)) == maxInt(i32)); try expect(ilogb32(0.0) == minInt(i32)); try expect(ilogb32(math.nan(f32)) == maxInt(i32)); } test "64 special" { try expect(ilogb64(math.inf(f64)) == maxInt(i32)); try expect(ilogb64(-math.inf(f64)) == maxInt(i32)); try expect(ilogb64(0.0) == minInt(i32)); try expect(ilogb64(math.nan(f64)) == maxInt(i32)); } test "128 special" { try expect(ilogb128(math.inf(f128)) == maxInt(i32)); try expect(ilogb128(-math.inf(f128)) == maxInt(i32)); try expect(ilogb128(0.0) == minInt(i32)); try expect(ilogb128(math.nan(f128)) == maxInt(i32)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/log10.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/log10f.c // https://git.musl-libc.org/cgit/musl/tree/src/math/log10.c const std = @import("../std.zig"); const math = std.math; const testing = std.testing; const maxInt = std.math.maxInt; /// Returns the base-10 logarithm of x. /// /// Special Cases: /// - log10(+inf) = +inf /// - log10(0) = -inf /// - log10(x) = nan if x < 0 /// - log10(nan) = nan pub fn log10(x: anytype) @TypeOf(x) { const T = @TypeOf(x); switch (@typeInfo(T)) { .ComptimeFloat => { return @as(comptime_float, log10_64(x)); }, .Float => { return switch (T) { f32 => log10_32(x), f64 => log10_64(x), else => @compileError("log10 not implemented for " ++ @typeName(T)), }; }, .ComptimeInt => { return @as(comptime_int, math.floor(log10_64(@as(f64, x)))); }, .Int => |IntType| switch (IntType.signedness) { .signed => @compileError("log10 not implemented for signed integers"), .unsigned => return @as(T, @intFromFloat(math.floor(log10_64(@as(f64, @floatFromInt(x)))))), }, else => @compileError("log10 not implemented for " ++ @typeName(T)), } } pub fn log10_32(x_: f32) f32 { const ivln10hi: f32 = 4.3432617188e-01; const ivln10lo: f32 = -3.1689971365e-05; const log10_2hi: f32 = 3.0102920532e-01; const log10_2lo: f32 = 7.9034151668e-07; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; const Lg3: f32 = 0x91e9ee.0p-25; const Lg4: f32 = 0xf89e26.0p-26; var x = x_; var u = @as(u32, @bitCast(x)); var ix = u; var k: i32 = 0; // x < 2^(-126) if (ix < 0x00800000 or ix >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -math.inf(f32); } // log(-#) = nan if (ix >> 31 != 0) { return math.nan(f32); } k -= 25; x *= 0x1.0p25; ix = @as(u32, @bitCast(x)); } else if (ix >= 0x7F800000) { return x; } else if (ix == 0x3F800000) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; k += @as(i32, @intCast(ix >> 23)) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @as(f32, @bitCast(ix)); const f = x - 1.0; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * Lg4); const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; var hi = f - hfsq; u = @as(u32, @bitCast(hi)); u &= 0xFFFFF000; hi = @as(f32, @bitCast(u)); const lo = f - hi - hfsq + s * (hfsq + R); const dk = @as(f32, @floatFromInt(k)); return dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi + hi * ivln10hi + dk * log10_2hi; } pub fn log10_64(x_: f64) f64 { const ivln10hi: f64 = 4.34294481878168880939e-01; const ivln10lo: f64 = 2.50829467116452752298e-11; const log10_2hi: f64 = 3.01029995663611771306e-01; const log10_2lo: f64 = 3.69423907715893078616e-13; const Lg1: f64 = 6.666666666666735130e-01; const Lg2: f64 = 3.999999999940941908e-01; const Lg3: f64 = 2.857142874366239149e-01; const Lg4: f64 = 2.222219843214978396e-01; const Lg5: f64 = 1.818357216161805012e-01; const Lg6: f64 = 1.531383769920937332e-01; const Lg7: f64 = 1.479819860511658591e-01; var x = x_; var ix = @as(u64, @bitCast(x)); var hx = @as(u32, @intCast(ix >> 32)); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -math.inf(f32); } // log(-#) = nan if (hx >> 31 != 0) { return math.nan(f32); } // subnormal, scale x k -= 54; x *= 0x1.0p54; hx = @as(u32, @intCast(@as(u64, @bitCast(x)) >> 32)); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; k += @as(i32, @intCast(hx >> 20)) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (@as(u64, hx) << 32) | (ix & 0xFFFFFFFF); x = @as(f64, @bitCast(ix)); const f = x - 1.0; const hfsq = 0.5 * f * f; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; // hi + lo = f - hfsq + s * (hfsq + R) ~ log(1 + f) var hi = f - hfsq; var hii = @as(u64, @bitCast(hi)); hii &= @as(u64, maxInt(u64)) << 32; hi = @as(f64, @bitCast(hii)); const lo = f - hi - hfsq + s * (hfsq + R); // val_hi + val_lo ~ log10(1 + f) + k * log10(2) var val_hi = hi * ivln10hi; const dk = @as(f64, @floatFromInt(k)); const y = dk * log10_2hi; var val_lo = dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi; // Extra precision multiplication const ww = y + val_hi; val_lo += (y - ww) + val_hi; val_hi = ww; return val_lo + val_hi; } test "math.log10" { try testing.expect(log10(@as(f32, 0.2)) == log10_32(0.2)); try testing.expect(log10(@as(f64, 0.2)) == log10_64(0.2)); } test "math.log10_32" { const epsilon = 0.000001; try testing.expect(math.approxEqAbs(f32, log10_32(0.2), -0.698970, epsilon)); try testing.expect(math.approxEqAbs(f32, log10_32(0.8923), -0.049489, epsilon)); try testing.expect(math.approxEqAbs(f32, log10_32(1.5), 0.176091, epsilon)); try testing.expect(math.approxEqAbs(f32, log10_32(37.45), 1.573452, epsilon)); try testing.expect(math.approxEqAbs(f32, log10_32(89.123), 1.94999, epsilon)); try testing.expect(math.approxEqAbs(f32, log10_32(123123.234375), 5.09034, epsilon)); } test "math.log10_64" { const epsilon = 0.000001; try testing.expect(math.approxEqAbs(f64, log10_64(0.2), -0.698970, epsilon)); try testing.expect(math.approxEqAbs(f64, log10_64(0.8923), -0.049489, epsilon)); try testing.expect(math.approxEqAbs(f64, log10_64(1.5), 0.176091, epsilon)); try testing.expect(math.approxEqAbs(f64, log10_64(37.45), 1.573452, epsilon)); try testing.expect(math.approxEqAbs(f64, log10_64(89.123), 1.94999, epsilon)); try testing.expect(math.approxEqAbs(f64, log10_64(123123.234375), 5.09034, epsilon)); } test "math.log10_32.special" { try testing.expect(math.isPositiveInf(log10_32(math.inf(f32)))); try testing.expect(math.isNegativeInf(log10_32(0.0))); try testing.expect(math.isNan(log10_32(-1.0))); try testing.expect(math.isNan(log10_32(math.nan(f32)))); } test "math.log10_64.special" { try testing.expect(math.isPositiveInf(log10_64(math.inf(f64)))); try testing.expect(math.isNegativeInf(log10_64(0.0))); try testing.expect(math.isNan(log10_64(-1.0))); try testing.expect(math.isNan(log10_64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/sinh.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/sinhf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/sinh.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const expo2 = @import("expo2.zig").expo2; const maxInt = std.math.maxInt; /// Returns the hyperbolic sine of x. /// /// Special Cases: /// - sinh(+-0) = +-0 /// - sinh(+-inf) = +-inf /// - sinh(nan) = nan pub fn sinh(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => sinh32(x), f64 => sinh64(x), else => @compileError("sinh not implemented for " ++ @typeName(T)), }; } // sinh(x) = (exp(x) - 1 / exp(x)) / 2 // = (exp(x) - 1 + (exp(x) - 1) / exp(x)) / 2 // = x + x^3 / 6 + o(x^5) fn sinh32(x: f32) f32 { const u = @as(u32, @bitCast(x)); const ux = u & 0x7FFFFFFF; const ax = @as(f32, @bitCast(ux)); if (x == 0.0 or math.isNan(x)) { return x; } var h: f32 = 0.5; if (u >> 31 != 0) { h = -h; } // |x| < log(FLT_MAX) if (ux < 0x42B17217) { const t = math.expm1(ax); if (ux < 0x3F800000) { if (ux < 0x3F800000 - (12 << 23)) { return x; } else { return h * (2 * t - t * t / (t + 1)); } } return h * (t + t / (t + 1)); } // |x| > log(FLT_MAX) or nan return 2 * h * expo2(ax); } fn sinh64(x: f64) f64 { const u = @as(u64, @bitCast(x)); const w = @as(u32, @intCast(u >> 32)) & (maxInt(u32) >> 1); const ax = @as(f64, @bitCast(u & (maxInt(u64) >> 1))); if (x == 0.0 or math.isNan(x)) { return x; } var h: f32 = 0.5; if (u >> 63 != 0) { h = -h; } // |x| < log(FLT_MAX) if (w < 0x40862E42) { const t = math.expm1(ax); if (w < 0x3FF00000) { if (w < 0x3FF00000 - (26 << 20)) { return x; } else { return h * (2 * t - t * t / (t + 1)); } } // NOTE: |x| > log(0x1p26) + eps could be h * exp(x) return h * (t + t / (t + 1)); } // |x| > log(DBL_MAX) or nan return 2 * h * expo2(ax); } test "math.sinh" { try expect(sinh(@as(f32, 1.5)) == sinh32(1.5)); try expect(sinh(@as(f64, 1.5)) == sinh64(1.5)); } test "math.sinh32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, sinh32(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, sinh32(0.2), 0.201336, epsilon)); try expect(math.approxEqAbs(f32, sinh32(0.8923), 1.015512, epsilon)); try expect(math.approxEqAbs(f32, sinh32(1.5), 2.129279, epsilon)); try expect(math.approxEqAbs(f32, sinh32(-0.0), -0.0, epsilon)); try expect(math.approxEqAbs(f32, sinh32(-0.2), -0.201336, epsilon)); try expect(math.approxEqAbs(f32, sinh32(-0.8923), -1.015512, epsilon)); try expect(math.approxEqAbs(f32, sinh32(-1.5), -2.129279, epsilon)); } test "math.sinh64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, sinh64(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, sinh64(0.2), 0.201336, epsilon)); try expect(math.approxEqAbs(f64, sinh64(0.8923), 1.015512, epsilon)); try expect(math.approxEqAbs(f64, sinh64(1.5), 2.129279, epsilon)); try expect(math.approxEqAbs(f64, sinh64(-0.0), -0.0, epsilon)); try expect(math.approxEqAbs(f64, sinh64(-0.2), -0.201336, epsilon)); try expect(math.approxEqAbs(f64, sinh64(-0.8923), -1.015512, epsilon)); try expect(math.approxEqAbs(f64, sinh64(-1.5), -2.129279, epsilon)); } test "math.sinh32.special" { try expect(sinh32(0.0) == 0.0); try expect(sinh32(-0.0) == -0.0); try expect(math.isPositiveInf(sinh32(math.inf(f32)))); try expect(math.isNegativeInf(sinh32(-math.inf(f32)))); try expect(math.isNan(sinh32(math.nan(f32)))); } test "math.sinh64.special" { try expect(sinh64(0.0) == 0.0); try expect(sinh64(-0.0) == -0.0); try expect(math.isPositiveInf(sinh64(math.inf(f64)))); try expect(math.isNegativeInf(sinh64(-math.inf(f64)))); try expect(math.isNan(sinh64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/sqrt.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const TypeId = std.builtin.TypeId; const maxInt = std.math.maxInt; /// Returns the square root of x. /// /// Special Cases: /// - sqrt(+inf) = +inf /// - sqrt(+-0) = +-0 /// - sqrt(x) = nan if x < 0 /// - sqrt(nan) = nan /// TODO Decide if all this logic should be implemented directly in the @sqrt bultin function. pub fn sqrt(x: anytype) Sqrt(@TypeOf(x)) { const T = @TypeOf(x); switch (@typeInfo(T)) { .Float, .ComptimeFloat => return @sqrt(x), .ComptimeInt => comptime { if (x > maxInt(u128)) { @compileError("sqrt not implemented for comptime_int greater than 128 bits"); } if (x < 0) { @compileError("sqrt on negative number"); } return @as(T, sqrt_int(u128, x)); }, .Int => |IntType| switch (IntType.signedness) { .signed => @compileError("sqrt not implemented for signed integers"), .unsigned => return sqrt_int(T, x), }, else => @compileError("sqrt not implemented for " ++ @typeName(T)), } } fn sqrt_int(comptime T: type, value: T) Sqrt(T) { if (@typeInfo(T).Int.bits <= 2) { return if (value == 0) 0 else 1; // shortcut for small number of bits to simplify general case } else { var op = value; var res: T = 0; var one: T = 1 << ((@typeInfo(T).Int.bits - 1) & -2); // highest power of four that fits into T // "one" starts at the highest power of four <= than the argument. while (one > op) { one >>= 2; } while (one != 0) { var c = op >= res + one; if (c) op -= res + one; res >>= 1; if (c) res += one; one >>= 2; } return @as(Sqrt(T), @intCast(res)); } } test "math.sqrt_int" { try expect(sqrt_int(u32, 3) == 1); try expect(sqrt_int(u32, 4) == 2); try expect(sqrt_int(u32, 5) == 2); try expect(sqrt_int(u32, 8) == 2); try expect(sqrt_int(u32, 9) == 3); try expect(sqrt_int(u32, 10) == 3); try expect(sqrt_int(u0, 0) == 0); try expect(sqrt_int(u1, 1) == 1); try expect(sqrt_int(u2, 3) == 1); try expect(sqrt_int(u3, 4) == 2); try expect(sqrt_int(u4, 8) == 2); try expect(sqrt_int(u4, 9) == 3); } /// Returns the return type `sqrt` will return given an operand of type `T`. pub fn Sqrt(comptime T: type) type { return switch (@typeInfo(T)) { .Int => |int| std.meta.Int(.unsigned, (int.bits + 1) / 2), else => T, }; }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/ceil.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/ceil.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the least integer value greater than of equal to x. /// /// Special Cases: /// - ceil(+-0) = +-0 /// - ceil(+-inf) = +-inf /// - ceil(nan) = nan pub fn ceil(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => ceil32(x), f64 => ceil64(x), f128 => ceil128(x), // TODO this is not correct for some targets c_longdouble => @as(c_longdouble, @floatCast(ceil128(x))), else => @compileError("ceil not implemented for " ++ @typeName(T)), }; } fn ceil32(x: f32) f32 { var u = @as(u32, @bitCast(x)); var e = @as(i32, @intCast((u >> 23) & 0xFF)) - 0x7F; var m: u32 = undefined; // TODO: Shouldn't need this explicit check. if (x == 0.0) { return x; } if (e >= 23) { return x; } else if (e >= 0) { m = @as(u32, 0x007FFFFF) >> @as(u5, @intCast(e)); if (u & m == 0) { return x; } math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 31 == 0) { u += m; } u &= ~m; return @as(f32, @bitCast(u)); } else { math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 31 != 0) { return -0.0; } else { return 1.0; } } } fn ceil64(x: f64) f64 { const u = @as(u64, @bitCast(x)); const e = (u >> 52) & 0x7FF; var y: f64 = undefined; if (e >= 0x3FF + 52 or x == 0) { return x; } if (u >> 63 != 0) { y = x - math.f64_toint + math.f64_toint - x; } else { y = x + math.f64_toint - math.f64_toint - x; } if (e <= 0x3FF - 1) { math.doNotOptimizeAway(y); if (u >> 63 != 0) { return -0.0; } else { return 1.0; } } else if (y < 0) { return x + y + 1; } else { return x + y; } } fn ceil128(x: f128) f128 { const u = @as(u128, @bitCast(x)); const e = (u >> 112) & 0x7FFF; var y: f128 = undefined; if (e >= 0x3FFF + 112 or x == 0) return x; if (u >> 127 != 0) { y = x - math.f128_toint + math.f128_toint - x; } else { y = x + math.f128_toint - math.f128_toint - x; } if (e <= 0x3FFF - 1) { math.doNotOptimizeAway(y); if (u >> 127 != 0) { return -0.0; } else { return 1.0; } } else if (y < 0) { return x + y + 1; } else { return x + y; } } test "math.ceil" { try expect(ceil(@as(f32, 0.0)) == ceil32(0.0)); try expect(ceil(@as(f64, 0.0)) == ceil64(0.0)); try expect(ceil(@as(f128, 0.0)) == ceil128(0.0)); } test "math.ceil32" { try expect(ceil32(1.3) == 2.0); try expect(ceil32(-1.3) == -1.0); try expect(ceil32(0.2) == 1.0); } test "math.ceil64" { try expect(ceil64(1.3) == 2.0); try expect(ceil64(-1.3) == -1.0); try expect(ceil64(0.2) == 1.0); } test "math.ceil128" { try expect(ceil128(1.3) == 2.0); try expect(ceil128(-1.3) == -1.0); try expect(ceil128(0.2) == 1.0); } test "math.ceil32.special" { try expect(ceil32(0.0) == 0.0); try expect(ceil32(-0.0) == -0.0); try expect(math.isPositiveInf(ceil32(math.inf(f32)))); try expect(math.isNegativeInf(ceil32(-math.inf(f32)))); try expect(math.isNan(ceil32(math.nan(f32)))); } test "math.ceil64.special" { try expect(ceil64(0.0) == 0.0); try expect(ceil64(-0.0) == -0.0); try expect(math.isPositiveInf(ceil64(math.inf(f64)))); try expect(math.isNegativeInf(ceil64(-math.inf(f64)))); try expect(math.isNan(ceil64(math.nan(f64)))); } test "math.ceil128.special" { try expect(ceil128(0.0) == 0.0); try expect(ceil128(-0.0) == -0.0); try expect(math.isPositiveInf(ceil128(math.inf(f128)))); try expect(math.isNegativeInf(ceil128(-math.inf(f128)))); try expect(math.isNan(ceil128(math.nan(f128)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/expo2.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/__expo2f.c // https://git.musl-libc.org/cgit/musl/tree/src/math/__expo2.c const math = @import("../math.zig"); /// Returns exp(x) / 2 for x >= log(maxFloat(T)). pub fn expo2(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => expo2f(x), f64 => expo2d(x), else => @compileError("expo2 not implemented for " ++ @typeName(T)), }; } fn expo2f(x: f32) f32 { const k: u32 = 235; const kln2 = 0x1.45C778p+7; const u = (0x7F + k / 2) << 23; const scale = @as(f32, @bitCast(u)); return math.exp(x - kln2) * scale * scale; } fn expo2d(x: f64) f64 { const k: u32 = 2043; const kln2 = 0x1.62066151ADD8BP+10; const u = (0x3FF + k / 2) << 20; const scale = @as(f64, @bitCast(@as(u64, u) << 32)); return math.exp(x - kln2) * scale * scale; }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/tanh.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/tanhf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/tanh.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const expo2 = @import("expo2.zig").expo2; const maxInt = std.math.maxInt; /// Returns the hyperbolic tangent of x. /// /// Special Cases: /// - sinh(+-0) = +-0 /// - sinh(+-inf) = +-1 /// - sinh(nan) = nan pub fn tanh(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => tanh32(x), f64 => tanh64(x), else => @compileError("tanh not implemented for " ++ @typeName(T)), }; } // tanh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x)) // = (exp(2x) - 1) / (exp(2x) - 1 + 2) // = (1 - exp(-2x)) / (exp(-2x) - 1 + 2) fn tanh32(x: f32) f32 { const u = @as(u32, @bitCast(x)); const ux = u & 0x7FFFFFFF; const ax = @as(f32, @bitCast(ux)); const sign = (u >> 31) != 0; var t: f32 = undefined; // |x| < log(3) / 2 ~= 0.5493 or nan if (ux > 0x3F0C9F54) { // |x| > 10 if (ux > 0x41200000) { t = 1.0 + 0 / x; } else { t = math.expm1(2 * ax); t = 1 - 2 / (t + 2); } } // |x| > log(5 / 3) / 2 ~= 0.2554 else if (ux > 0x3E82C578) { t = math.expm1(2 * ax); t = t / (t + 2); } // |x| >= 0x1.0p-126 else if (ux >= 0x00800000) { t = math.expm1(-2 * ax); t = -t / (t + 2); } // |x| is subnormal else { math.doNotOptimizeAway(ax * ax); t = ax; } return if (sign) -t else t; } fn tanh64(x: f64) f64 { const u = @as(u64, @bitCast(x)); const ux = u & 0x7FFFFFFFFFFFFFFF; const w = @as(u32, @intCast(ux >> 32)); const ax = @as(f64, @bitCast(ux)); const sign = (u >> 63) != 0; var t: f64 = undefined; // |x| < log(3) / 2 ~= 0.5493 or nan if (w > 0x3FE193EA) { // |x| > 20 or nan if (w > 0x40340000) { t = 1.0 - 0 / ax; } else { t = math.expm1(2 * ax); t = 1 - 2 / (t + 2); } } // |x| > log(5 / 3) / 2 ~= 0.2554 else if (w > 0x3FD058AE) { t = math.expm1(2 * ax); t = t / (t + 2); } // |x| >= 0x1.0p-1022 else if (w >= 0x00100000) { t = math.expm1(-2 * ax); t = -t / (t + 2); } // |x| is subnormal else { math.doNotOptimizeAway(@as(f32, @floatCast(ax))); t = ax; } return if (sign) -t else t; } test "math.tanh" { try expect(tanh(@as(f32, 1.5)) == tanh32(1.5)); try expect(tanh(@as(f64, 1.5)) == tanh64(1.5)); } test "math.tanh32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, tanh32(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, tanh32(0.2), 0.197375, epsilon)); try expect(math.approxEqAbs(f32, tanh32(0.8923), 0.712528, epsilon)); try expect(math.approxEqAbs(f32, tanh32(1.5), 0.905148, epsilon)); try expect(math.approxEqAbs(f32, tanh32(37.45), 1.0, epsilon)); try expect(math.approxEqAbs(f32, tanh32(-0.8923), -0.712528, epsilon)); try expect(math.approxEqAbs(f32, tanh32(-1.5), -0.905148, epsilon)); try expect(math.approxEqAbs(f32, tanh32(-37.45), -1.0, epsilon)); } test "math.tanh64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, tanh64(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, tanh64(0.2), 0.197375, epsilon)); try expect(math.approxEqAbs(f64, tanh64(0.8923), 0.712528, epsilon)); try expect(math.approxEqAbs(f64, tanh64(1.5), 0.905148, epsilon)); try expect(math.approxEqAbs(f64, tanh64(37.45), 1.0, epsilon)); try expect(math.approxEqAbs(f64, tanh64(-0.8923), -0.712528, epsilon)); try expect(math.approxEqAbs(f64, tanh64(-1.5), -0.905148, epsilon)); try expect(math.approxEqAbs(f64, tanh64(-37.45), -1.0, epsilon)); } test "math.tanh32.special" { try expect(tanh32(0.0) == 0.0); try expect(tanh32(-0.0) == -0.0); try expect(tanh32(math.inf(f32)) == 1.0); try expect(tanh32(-math.inf(f32)) == -1.0); try expect(math.isNan(tanh32(math.nan(f32)))); } test "math.tanh64.special" { try expect(tanh64(0.0) == 0.0); try expect(tanh64(-0.0) == -0.0); try expect(tanh64(math.inf(f64)) == 1.0); try expect(tanh64(-math.inf(f64)) == -1.0); try expect(math.isNan(tanh64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/atanh.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/atanhf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/atanh.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns the hyperbolic arc-tangent of x. /// /// Special Cases: /// - atanh(+-1) = +-inf with signal /// - atanh(x) = nan if |x| > 1 with signal /// - atanh(nan) = nan pub fn atanh(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => atanh_32(x), f64 => atanh_64(x), else => @compileError("atanh not implemented for " ++ @typeName(T)), }; } // atanh(x) = log((1 + x) / (1 - x)) / 2 = log1p(2x / (1 - x)) / 2 ~= x + x^3 / 3 + o(x^5) fn atanh_32(x: f32) f32 { const u = @as(u32, @bitCast(x)); const i = u & 0x7FFFFFFF; const s = u >> 31; var y = @as(f32, @bitCast(i)); // |x| if (y == 1.0) { return math.copysign(f32, math.inf(f32), x); } if (u < 0x3F800000 - (1 << 23)) { if (u < 0x3F800000 - (32 << 23)) { // underflow if (u < (1 << 23)) { math.doNotOptimizeAway(y * y); } } // |x| < 0.5 else { y = 0.5 * math.log1p(2 * y + 2 * y * y / (1 - y)); } } else { y = 0.5 * math.log1p(2 * (y / (1 - y))); } return if (s != 0) -y else y; } fn atanh_64(x: f64) f64 { const u = @as(u64, @bitCast(x)); const e = (u >> 52) & 0x7FF; const s = u >> 63; var y = @as(f64, @bitCast(u & (maxInt(u64) >> 1))); // |x| if (y == 1.0) { return math.copysign(f64, math.inf(f64), x); } if (e < 0x3FF - 1) { if (e < 0x3FF - 32) { // underflow if (e == 0) { math.doNotOptimizeAway(@as(f32, @floatCast(y))); } } // |x| < 0.5 else { y = 0.5 * math.log1p(2 * y + 2 * y * y / (1 - y)); } } else { y = 0.5 * math.log1p(2 * (y / (1 - y))); } return if (s != 0) -y else y; } test "math.atanh" { try expect(atanh(@as(f32, 0.0)) == atanh_32(0.0)); try expect(atanh(@as(f64, 0.0)) == atanh_64(0.0)); } test "math.atanh_32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, atanh_32(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, atanh_32(0.2), 0.202733, epsilon)); try expect(math.approxEqAbs(f32, atanh_32(0.8923), 1.433099, epsilon)); } test "math.atanh_64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, atanh_64(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, atanh_64(0.2), 0.202733, epsilon)); try expect(math.approxEqAbs(f64, atanh_64(0.8923), 1.433099, epsilon)); } test "math.atanh32.special" { try expect(math.isPositiveInf(atanh_32(1))); try expect(math.isNegativeInf(atanh_32(-1))); try expect(math.isSignalNan(atanh_32(1.5))); try expect(math.isSignalNan(atanh_32(-1.5))); try expect(math.isNan(atanh_32(math.nan(f32)))); } test "math.atanh64.special" { try expect(math.isPositiveInf(atanh_64(1))); try expect(math.isNegativeInf(atanh_64(-1))); try expect(math.isSignalNan(atanh_64(1.5))); try expect(math.isSignalNan(atanh_64(-1.5))); try expect(math.isNan(atanh_64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/acosh.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/acoshf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/acosh.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the hyperbolic arc-cosine of x. /// /// Special cases: /// - acosh(x) = snan if x < 1 /// - acosh(nan) = nan pub fn acosh(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => acosh32(x), f64 => acosh64(x), else => @compileError("acosh not implemented for " ++ @typeName(T)), }; } // acosh(x) = log(x + sqrt(x * x - 1)) fn acosh32(x: f32) f32 { const u = @as(u32, @bitCast(x)); const i = u & 0x7FFFFFFF; // |x| < 2, invalid if x < 1 or nan if (i < 0x3F800000 + (1 << 23)) { return math.log1p(x - 1 + math.sqrt((x - 1) * (x - 1) + 2 * (x - 1))); } // |x| < 0x1p12 else if (i < 0x3F800000 + (12 << 23)) { return math.ln(2 * x - 1 / (x + math.sqrt(x * x - 1))); } // |x| >= 0x1p12 else { return math.ln(x) + 0.693147180559945309417232121458176568; } } fn acosh64(x: f64) f64 { const u = @as(u64, @bitCast(x)); const e = (u >> 52) & 0x7FF; // |x| < 2, invalid if x < 1 or nan if (e < 0x3FF + 1) { return math.log1p(x - 1 + math.sqrt((x - 1) * (x - 1) + 2 * (x - 1))); } // |x| < 0x1p26 else if (e < 0x3FF + 26) { return math.ln(2 * x - 1 / (x + math.sqrt(x * x - 1))); } // |x| >= 0x1p26 or nan else { return math.ln(x) + 0.693147180559945309417232121458176568; } } test "math.acosh" { try expect(acosh(@as(f32, 1.5)) == acosh32(1.5)); try expect(acosh(@as(f64, 1.5)) == acosh64(1.5)); } test "math.acosh32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, acosh32(1.5), 0.962424, epsilon)); try expect(math.approxEqAbs(f32, acosh32(37.45), 4.315976, epsilon)); try expect(math.approxEqAbs(f32, acosh32(89.123), 5.183133, epsilon)); try expect(math.approxEqAbs(f32, acosh32(123123.234375), 12.414088, epsilon)); } test "math.acosh64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, acosh64(1.5), 0.962424, epsilon)); try expect(math.approxEqAbs(f64, acosh64(37.45), 4.315976, epsilon)); try expect(math.approxEqAbs(f64, acosh64(89.123), 5.183133, epsilon)); try expect(math.approxEqAbs(f64, acosh64(123123.234375), 12.414088, epsilon)); } test "math.acosh32.special" { try expect(math.isNan(acosh32(math.nan(f32)))); try expect(math.isSignalNan(acosh32(0.5))); } test "math.acosh64.special" { try expect(math.isNan(acosh64(math.nan(f64)))); try expect(math.isSignalNan(acosh64(0.5))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/tan.zig
// Ported from go, which is licensed under a BSD-3 license. // https://golang.org/LICENSE // // https://golang.org/src/math/tan.go const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the tangent of the radian value x. /// /// Special Cases: /// - tan(+-0) = +-0 /// - tan(+-inf) = nan /// - tan(nan) = nan pub fn tan(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => tan_(f32, x), f64 => tan_(f64, x), else => @compileError("tan not implemented for " ++ @typeName(T)), }; } const Tp0 = -1.30936939181383777646E4; const Tp1 = 1.15351664838587416140E6; const Tp2 = -1.79565251976484877988E7; const Tq1 = 1.36812963470692954678E4; const Tq2 = -1.32089234440210967447E6; const Tq3 = 2.50083801823357915839E7; const Tq4 = -5.38695755929454629881E7; const pi4a = 7.85398125648498535156e-1; const pi4b = 3.77489470793079817668E-8; const pi4c = 2.69515142907905952645E-15; const m4pi = 1.273239544735162542821171882678754627704620361328125; fn tan_(comptime T: type, x_: T) T { const I = std.meta.Int(.signed, @typeInfo(T).Float.bits); var x = x_; if (x == 0 or math.isNan(x)) { return x; } if (math.isInf(x)) { return math.nan(T); } var sign = x < 0; x = math.fabs(x); var y = math.floor(x * m4pi); var j = @as(I, @intFromFloat(y)); if (j & 1 == 1) { j += 1; y += 1; } const z = ((x - y * pi4a) - y * pi4b) - y * pi4c; const w = z * z; var r = if (w > 1e-14) z + z * (w * ((Tp0 * w + Tp1) * w + Tp2) / ((((w + Tq1) * w + Tq2) * w + Tq3) * w + Tq4)) else z; if (j & 2 == 2) { r = -1 / r; } return if (sign) -r else r; } test "math.tan" { try expect(tan(@as(f32, 0.0)) == tan_(f32, 0.0)); try expect(tan(@as(f64, 0.0)) == tan_(f64, 0.0)); } test "math.tan32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, tan_(f32, 0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, tan_(f32, 0.2), 0.202710, epsilon)); try expect(math.approxEqAbs(f32, tan_(f32, 0.8923), 1.240422, epsilon)); try expect(math.approxEqAbs(f32, tan_(f32, 1.5), 14.101420, epsilon)); try expect(math.approxEqAbs(f32, tan_(f32, 37.45), -0.254397, epsilon)); try expect(math.approxEqAbs(f32, tan_(f32, 89.123), 2.285852, epsilon)); } test "math.tan64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, tan_(f64, 0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, tan_(f64, 0.2), 0.202710, epsilon)); try expect(math.approxEqAbs(f64, tan_(f64, 0.8923), 1.240422, epsilon)); try expect(math.approxEqAbs(f64, tan_(f64, 1.5), 14.101420, epsilon)); try expect(math.approxEqAbs(f64, tan_(f64, 37.45), -0.254397, epsilon)); try expect(math.approxEqAbs(f64, tan_(f64, 89.123), 2.2858376, epsilon)); } test "math.tan32.special" { try expect(tan_(f32, 0.0) == 0.0); try expect(tan_(f32, -0.0) == -0.0); try expect(math.isNan(tan_(f32, math.inf(f32)))); try expect(math.isNan(tan_(f32, -math.inf(f32)))); try expect(math.isNan(tan_(f32, math.nan(f32)))); } test "math.tan64.special" { try expect(tan_(f64, 0.0) == 0.0); try expect(tan_(f64, -0.0) == -0.0); try expect(math.isNan(tan_(f64, math.inf(f64)))); try expect(math.isNan(tan_(f64, -math.inf(f64)))); try expect(math.isNan(tan_(f64, math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/ln.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/lnf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/ln.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the natural logarithm of x. /// /// Special Cases: /// - ln(+inf) = +inf /// - ln(0) = -inf /// - ln(x) = nan if x < 0 /// - ln(nan) = nan pub fn ln(x: anytype) @TypeOf(x) { const T = @TypeOf(x); switch (@typeInfo(T)) { .ComptimeFloat => { return @as(comptime_float, ln_64(x)); }, .Float => { return switch (T) { f32 => ln_32(x), f64 => ln_64(x), else => @compileError("ln not implemented for " ++ @typeName(T)), }; }, .ComptimeInt => { return @as(comptime_int, math.floor(ln_64(@as(f64, x)))); }, .Int => |IntType| switch (IntType.signedness) { .signed => @compileError("ln not implemented for signed integers"), .unsigned => return @as(T, math.floor(ln_64(@as(f64, x)))), }, else => @compileError("ln not implemented for " ++ @typeName(T)), } } pub fn ln_32(x_: f32) f32 { const ln2_hi: f32 = 6.9313812256e-01; const ln2_lo: f32 = 9.0580006145e-06; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; const Lg3: f32 = 0x91e9ee.0p-25; const Lg4: f32 = 0xf89e26.0p-26; var x = x_; var ix = @as(u32, @bitCast(x)); var k: i32 = 0; // x < 2^(-126) if (ix < 0x00800000 or ix >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -math.inf(f32); } // log(-#) = nan if (ix >> 31 != 0) { return math.nan(f32); } // subnormal, scale x k -= 25; x *= 0x1.0p25; ix = @as(u32, @bitCast(x)); } else if (ix >= 0x7F800000) { return x; } else if (ix == 0x3F800000) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; k += @as(i32, @intCast(ix >> 23)) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @as(f32, @bitCast(ix)); const f = x - 1.0; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * Lg4); const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; const dk = @as(f32, @floatFromInt(k)); return s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi; } pub fn ln_64(x_: f64) f64 { const ln2_hi: f64 = 6.93147180369123816490e-01; const ln2_lo: f64 = 1.90821492927058770002e-10; const Lg1: f64 = 6.666666666666735130e-01; const Lg2: f64 = 3.999999999940941908e-01; const Lg3: f64 = 2.857142874366239149e-01; const Lg4: f64 = 2.222219843214978396e-01; const Lg5: f64 = 1.818357216161805012e-01; const Lg6: f64 = 1.531383769920937332e-01; const Lg7: f64 = 1.479819860511658591e-01; var x = x_; var ix = @as(u64, @bitCast(x)); var hx = @as(u32, @intCast(ix >> 32)); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -math.inf(f64); } // log(-#) = nan if (hx >> 31 != 0) { return math.nan(f64); } // subnormal, scale x k -= 54; x *= 0x1.0p54; hx = @as(u32, @intCast(@as(u64, @bitCast(ix)) >> 32)); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; k += @as(i32, @intCast(hx >> 20)) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (@as(u64, hx) << 32) | (ix & 0xFFFFFFFF); x = @as(f64, @bitCast(ix)); const f = x - 1.0; const hfsq = 0.5 * f * f; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; const dk = @as(f64, @floatFromInt(k)); return s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi; } test "math.ln" { try expect(ln(@as(f32, 0.2)) == ln_32(0.2)); try expect(ln(@as(f64, 0.2)) == ln_64(0.2)); } test "math.ln32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, ln_32(0.2), -1.609438, epsilon)); try expect(math.approxEqAbs(f32, ln_32(0.8923), -0.113953, epsilon)); try expect(math.approxEqAbs(f32, ln_32(1.5), 0.405465, epsilon)); try expect(math.approxEqAbs(f32, ln_32(37.45), 3.623007, epsilon)); try expect(math.approxEqAbs(f32, ln_32(89.123), 4.490017, epsilon)); try expect(math.approxEqAbs(f32, ln_32(123123.234375), 11.720941, epsilon)); } test "math.ln64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, ln_64(0.2), -1.609438, epsilon)); try expect(math.approxEqAbs(f64, ln_64(0.8923), -0.113953, epsilon)); try expect(math.approxEqAbs(f64, ln_64(1.5), 0.405465, epsilon)); try expect(math.approxEqAbs(f64, ln_64(37.45), 3.623007, epsilon)); try expect(math.approxEqAbs(f64, ln_64(89.123), 4.490017, epsilon)); try expect(math.approxEqAbs(f64, ln_64(123123.234375), 11.720941, epsilon)); } test "math.ln32.special" { try expect(math.isPositiveInf(ln_32(math.inf(f32)))); try expect(math.isNegativeInf(ln_32(0.0))); try expect(math.isNan(ln_32(-1.0))); try expect(math.isNan(ln_32(math.nan(f32)))); } test "math.ln64.special" { try expect(math.isPositiveInf(ln_64(math.inf(f64)))); try expect(math.isNegativeInf(ln_64(0.0))); try expect(math.isNan(ln_64(-1.0))); try expect(math.isNan(ln_64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/isnormal.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; // Returns whether x has a normalized representation (i.e. integer part of mantissa is 1). pub fn isNormal(x: anytype) bool { const T = @TypeOf(x); switch (T) { f16 => { const bits = @as(u16, @bitCast(x)); return (bits + (1 << 10)) & (maxInt(u16) >> 1) >= (1 << 11); }, f32 => { const bits = @as(u32, @bitCast(x)); return (bits + (1 << 23)) & (maxInt(u32) >> 1) >= (1 << 24); }, f64 => { const bits = @as(u64, @bitCast(x)); return (bits + (1 << 52)) & (maxInt(u64) >> 1) >= (1 << 53); }, f128 => { const bits = @as(u128, @bitCast(x)); return (bits + (1 << 112)) & (maxInt(u128) >> 1) >= (1 << 113); }, else => { @compileError("isNormal not implemented for " ++ @typeName(T)); }, } } test "math.isNormal" { try expect(!isNormal(math.nan(f16))); try expect(!isNormal(math.nan(f32))); try expect(!isNormal(math.nan(f64))); try expect(!isNormal(math.nan(f128))); try expect(!isNormal(@as(f16, 0))); try expect(!isNormal(@as(f32, 0))); try expect(!isNormal(@as(f64, 0))); try expect(!isNormal(@as(f128, 0))); try expect(isNormal(@as(f16, 1.0))); try expect(isNormal(@as(f32, 1.0))); try expect(isNormal(@as(f64, 1.0))); try expect(isNormal(@as(f128, 1.0))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/log1p.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/log1pf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/log1p.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the natural logarithm of 1 + x with greater accuracy when x is near zero. /// /// Special Cases: /// - log1p(+inf) = +inf /// - log1p(+-0) = +-0 /// - log1p(-1) = -inf /// - log1p(x) = nan if x < -1 /// - log1p(nan) = nan pub fn log1p(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => log1p_32(x), f64 => log1p_64(x), else => @compileError("log1p not implemented for " ++ @typeName(T)), }; } fn log1p_32(x: f32) f32 { const ln2_hi = 6.9313812256e-01; const ln2_lo = 9.0580006145e-06; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; const Lg3: f32 = 0x91e9ee.0p-25; const Lg4: f32 = 0xf89e26.0p-26; const u = @as(u32, @bitCast(x)); var ix = u; var k: i32 = 1; var f: f32 = undefined; var c: f32 = undefined; // 1 + x < sqrt(2)+ if (ix < 0x3ED413D0 or ix >> 31 != 0) { // x <= -1.0 if (ix >= 0xBF800000) { // log1p(-1) = -inf if (x == -1.0) { return -math.inf(f32); } // log1p(x < -1) = nan else { return math.nan(f32); } } // |x| < 2^(-24) if ((ix << 1) < (0x33800000 << 1)) { // underflow if subnormal if (ix & 0x7F800000 == 0) { math.doNotOptimizeAway(x * x); } return x; } // sqrt(2) / 2- <= 1 + x < sqrt(2)+ if (ix <= 0xBE95F619) { k = 0; c = 0; f = x; } } else if (ix >= 0x7F800000) { return x; } if (k != 0) { const uf = 1 + x; var iu = @as(u32, @bitCast(uf)); iu += 0x3F800000 - 0x3F3504F3; k = @as(i32, @intCast(iu >> 23)) - 0x7F; // correction to avoid underflow in c / u if (k < 25) { c = if (k >= 2) 1 - (uf - x) else x - (uf - 1); c /= uf; } else { c = 0; } // u into [sqrt(2)/2, sqrt(2)] iu = (iu & 0x007FFFFF) + 0x3F3504F3; f = @as(f32, @bitCast(iu)) - 1; } const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * Lg4); const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; const dk = @as(f32, @floatFromInt(k)); return s * (hfsq + R) + (dk * ln2_lo + c) - hfsq + f + dk * ln2_hi; } fn log1p_64(x: f64) f64 { const ln2_hi: f64 = 6.93147180369123816490e-01; const ln2_lo: f64 = 1.90821492927058770002e-10; const Lg1: f64 = 6.666666666666735130e-01; const Lg2: f64 = 3.999999999940941908e-01; const Lg3: f64 = 2.857142874366239149e-01; const Lg4: f64 = 2.222219843214978396e-01; const Lg5: f64 = 1.818357216161805012e-01; const Lg6: f64 = 1.531383769920937332e-01; const Lg7: f64 = 1.479819860511658591e-01; var ix = @as(u64, @bitCast(x)); var hx = @as(u32, @intCast(ix >> 32)); var k: i32 = 1; var c: f64 = undefined; var f: f64 = undefined; // 1 + x < sqrt(2) if (hx < 0x3FDA827A or hx >> 31 != 0) { // x <= -1.0 if (hx >= 0xBFF00000) { // log1p(-1) = -inf if (x == -1.0) { return -math.inf(f64); } // log1p(x < -1) = nan else { return math.nan(f64); } } // |x| < 2^(-53) if ((hx << 1) < (0x3CA00000 << 1)) { if ((hx & 0x7FF00000) == 0) { math.raiseUnderflow(); } return x; } // sqrt(2) / 2- <= 1 + x < sqrt(2)+ if (hx <= 0xBFD2BEC4) { k = 0; c = 0; f = x; } } else if (hx >= 0x7FF00000) { return x; } if (k != 0) { const uf = 1 + x; const hu = @as(u64, @bitCast(uf)); var iu = @as(u32, @intCast(hu >> 32)); iu += 0x3FF00000 - 0x3FE6A09E; k = @as(i32, @intCast(iu >> 20)) - 0x3FF; // correction to avoid underflow in c / u if (k < 54) { c = if (k >= 2) 1 - (uf - x) else x - (uf - 1); c /= uf; } else { c = 0; } // u into [sqrt(2)/2, sqrt(2)] iu = (iu & 0x000FFFFF) + 0x3FE6A09E; const iq = (@as(u64, iu) << 32) | (hu & 0xFFFFFFFF); f = @as(f64, @bitCast(iq)) - 1; } const hfsq = 0.5 * f * f; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; const dk = @as(f64, @floatFromInt(k)); return s * (hfsq + R) + (dk * ln2_lo + c) - hfsq + f + dk * ln2_hi; } test "math.log1p" { try expect(log1p(@as(f32, 0.0)) == log1p_32(0.0)); try expect(log1p(@as(f64, 0.0)) == log1p_64(0.0)); } test "math.log1p_32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, log1p_32(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, log1p_32(0.2), 0.182322, epsilon)); try expect(math.approxEqAbs(f32, log1p_32(0.8923), 0.637793, epsilon)); try expect(math.approxEqAbs(f32, log1p_32(1.5), 0.916291, epsilon)); try expect(math.approxEqAbs(f32, log1p_32(37.45), 3.649359, epsilon)); try expect(math.approxEqAbs(f32, log1p_32(89.123), 4.501175, epsilon)); try expect(math.approxEqAbs(f32, log1p_32(123123.234375), 11.720949, epsilon)); } test "math.log1p_64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, log1p_64(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, log1p_64(0.2), 0.182322, epsilon)); try expect(math.approxEqAbs(f64, log1p_64(0.8923), 0.637793, epsilon)); try expect(math.approxEqAbs(f64, log1p_64(1.5), 0.916291, epsilon)); try expect(math.approxEqAbs(f64, log1p_64(37.45), 3.649359, epsilon)); try expect(math.approxEqAbs(f64, log1p_64(89.123), 4.501175, epsilon)); try expect(math.approxEqAbs(f64, log1p_64(123123.234375), 11.720949, epsilon)); } test "math.log1p_32.special" { try expect(math.isPositiveInf(log1p_32(math.inf(f32)))); try expect(log1p_32(0.0) == 0.0); try expect(log1p_32(-0.0) == -0.0); try expect(math.isNegativeInf(log1p_32(-1.0))); try expect(math.isNan(log1p_32(-2.0))); try expect(math.isNan(log1p_32(math.nan(f32)))); } test "math.log1p_64.special" { try expect(math.isPositiveInf(log1p_64(math.inf(f64)))); try expect(log1p_64(0.0) == 0.0); try expect(log1p_64(-0.0) == -0.0); try expect(math.isNegativeInf(log1p_64(-1.0))); try expect(math.isNan(log1p_64(-2.0))); try expect(math.isNan(log1p_64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/powi.zig
// Based on Rust, which is licensed under the MIT license. // https://github.com/rust-lang/rust/blob/360432f1e8794de58cd94f34c9c17ad65871e5b5/LICENSE-MIT // // https://github.com/rust-lang/rust/blob/360432f1e8794de58cd94f34c9c17ad65871e5b5/src/libcore/num/mod.rs#L3423 const std = @import("../std.zig"); const math = std.math; const assert = std.debug.assert; const testing = std.testing; /// Returns the power of x raised by the integer y (x^y). /// /// Special Cases: /// - powi(x, +-0) = 1 for any x /// - powi(0, y) = 0 for any y /// - powi(1, y) = 1 for any y /// - powi(-1, y) = -1 for y an odd integer /// - powi(-1, y) = 1 for y an even integer /// - powi(x, y) = Overflow for y >= @sizeOf(x) - 1 or y > 0 /// - powi(x, y) = Underflow for y > @sizeOf(x) - 1 or y < 0 pub fn powi(comptime T: type, x: T, y: T) (error{ Overflow, Underflow, }!T) { const info = @typeInfo(T); comptime assert(@typeInfo(T) == .Int); // powi(x, +-0) = 1 for any x if (y == 0 or y == -0) { return 1; } switch (x) { // powi(0, y) = 0 for any y 0 => return 0, // powi(1, y) = 1 for any y 1 => return 1, else => { // powi(x, y) = Overflow for for y >= @sizeOf(x) - 1 y > 0 // powi(x, y) = Underflow for for y > @sizeOf(x) - 1 y < 0 const bit_size = @sizeOf(T) * 8; if (info.Int.signedness == .signed) { if (x == -1) { // powi(-1, y) = -1 for for y an odd integer // powi(-1, y) = 1 for for y an even integer if (@mod(y, 2) == 0) { return 1; } else { return -1; } } if (x > 0 and y >= bit_size - 1) { return error.Overflow; } else if (x < 0 and y > bit_size - 1) { return error.Underflow; } } else { if (y >= bit_size) { return error.Overflow; } } var base = x; var exp = y; var acc: T = 1; while (exp > 1) { if (exp & 1 == 1) { const ov = @mulWithOverflow(acc, base); if (ov[1] != 0) return error.Overflow; acc = ov[0]; } exp >>= 1; const ov = @mulWithOverflow(base, base); if (ov[1] != 0) return error.Overflow; base = ov[0]; } if (exp == 1) { const ov = @mulWithOverflow(acc, base); if (ov[1] != 0) return error.Overflow; acc = ov[0]; } return acc; }, } } test "math.powi" { try testing.expectError(error.Underflow, powi(i8, -66, 6)); try testing.expectError(error.Underflow, powi(i16, -13, 13)); try testing.expectError(error.Underflow, powi(i32, -32, 21)); try testing.expectError(error.Underflow, powi(i64, -24, 61)); try testing.expectError(error.Underflow, powi(i17, -15, 15)); try testing.expectError(error.Underflow, powi(i42, -6, 40)); try testing.expect((try powi(i8, -5, 3)) == -125); try testing.expect((try powi(i16, -16, 3)) == -4096); try testing.expect((try powi(i32, -91, 3)) == -753571); try testing.expect((try powi(i64, -36, 6)) == 2176782336); try testing.expect((try powi(i17, -2, 15)) == -32768); try testing.expect((try powi(i42, -5, 7)) == -78125); try testing.expect((try powi(u8, 6, 2)) == 36); try testing.expect((try powi(u16, 5, 4)) == 625); try testing.expect((try powi(u32, 12, 6)) == 2985984); try testing.expect((try powi(u64, 34, 2)) == 1156); try testing.expect((try powi(u17, 16, 3)) == 4096); try testing.expect((try powi(u42, 34, 6)) == 1544804416); try testing.expectError(error.Overflow, powi(i8, 120, 7)); try testing.expectError(error.Overflow, powi(i16, 73, 15)); try testing.expectError(error.Overflow, powi(i32, 23, 31)); try testing.expectError(error.Overflow, powi(i64, 68, 61)); try testing.expectError(error.Overflow, powi(i17, 15, 15)); try testing.expectError(error.Overflow, powi(i42, 121312, 41)); try testing.expectError(error.Overflow, powi(u8, 123, 7)); try testing.expectError(error.Overflow, powi(u16, 2313, 15)); try testing.expectError(error.Overflow, powi(u32, 8968, 31)); try testing.expectError(error.Overflow, powi(u64, 2342, 63)); try testing.expectError(error.Overflow, powi(u17, 2723, 16)); try testing.expectError(error.Overflow, powi(u42, 8234, 41)); } test "math.powi.special" { try testing.expectError(error.Underflow, powi(i8, -2, 8)); try testing.expectError(error.Underflow, powi(i16, -2, 16)); try testing.expectError(error.Underflow, powi(i32, -2, 32)); try testing.expectError(error.Underflow, powi(i64, -2, 64)); try testing.expectError(error.Underflow, powi(i17, -2, 17)); try testing.expectError(error.Underflow, powi(i42, -2, 42)); try testing.expect((try powi(i8, -1, 3)) == -1); try testing.expect((try powi(i16, -1, 2)) == 1); try testing.expect((try powi(i32, -1, 16)) == 1); try testing.expect((try powi(i64, -1, 6)) == 1); try testing.expect((try powi(i17, -1, 15)) == -1); try testing.expect((try powi(i42, -1, 7)) == -1); try testing.expect((try powi(u8, 1, 2)) == 1); try testing.expect((try powi(u16, 1, 4)) == 1); try testing.expect((try powi(u32, 1, 6)) == 1); try testing.expect((try powi(u64, 1, 2)) == 1); try testing.expect((try powi(u17, 1, 3)) == 1); try testing.expect((try powi(u42, 1, 6)) == 1); try testing.expectError(error.Overflow, powi(i8, 2, 7)); try testing.expectError(error.Overflow, powi(i16, 2, 15)); try testing.expectError(error.Overflow, powi(i32, 2, 31)); try testing.expectError(error.Overflow, powi(i64, 2, 63)); try testing.expectError(error.Overflow, powi(i17, 2, 16)); try testing.expectError(error.Overflow, powi(i42, 2, 41)); try testing.expectError(error.Overflow, powi(u8, 2, 8)); try testing.expectError(error.Overflow, powi(u16, 2, 16)); try testing.expectError(error.Overflow, powi(u32, 2, 32)); try testing.expectError(error.Overflow, powi(u64, 2, 64)); try testing.expectError(error.Overflow, powi(u17, 2, 17)); try testing.expectError(error.Overflow, powi(u42, 2, 42)); try testing.expect((try powi(u8, 6, 0)) == 1); try testing.expect((try powi(u16, 5, 0)) == 1); try testing.expect((try powi(u32, 12, 0)) == 1); try testing.expect((try powi(u64, 34, 0)) == 1); try testing.expect((try powi(u17, 16, 0)) == 1); try testing.expect((try powi(u42, 34, 0)) == 1); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/cos.zig
// Ported from go, which is licensed under a BSD-3 license. // https://golang.org/LICENSE // // https://golang.org/src/math/sin.go const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the cosine of the radian value x. /// /// Special Cases: /// - cos(+-inf) = nan /// - cos(nan) = nan pub fn cos(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => cos_(f32, x), f64 => cos_(f64, x), else => @compileError("cos not implemented for " ++ @typeName(T)), }; } // sin polynomial coefficients const S0 = 1.58962301576546568060E-10; const S1 = -2.50507477628578072866E-8; const S2 = 2.75573136213857245213E-6; const S3 = -1.98412698295895385996E-4; const S4 = 8.33333333332211858878E-3; const S5 = -1.66666666666666307295E-1; // cos polynomial coeffiecients const C0 = -1.13585365213876817300E-11; const C1 = 2.08757008419747316778E-9; const C2 = -2.75573141792967388112E-7; const C3 = 2.48015872888517045348E-5; const C4 = -1.38888888888730564116E-3; const C5 = 4.16666666666665929218E-2; const pi4a = 7.85398125648498535156e-1; const pi4b = 3.77489470793079817668E-8; const pi4c = 2.69515142907905952645E-15; const m4pi = 1.273239544735162542821171882678754627704620361328125; fn cos_(comptime T: type, x_: T) T { const I = std.meta.Int(.signed, @typeInfo(T).Float.bits); var x = x_; if (math.isNan(x) or math.isInf(x)) { return math.nan(T); } var sign = false; x = math.fabs(x); var y = math.floor(x * m4pi); var j = @as(I, @intFromFloat(y)); if (j & 1 == 1) { j += 1; y += 1; } j &= 7; if (j > 3) { j -= 4; sign = !sign; } if (j > 1) { sign = !sign; } const z = ((x - y * pi4a) - y * pi4b) - y * pi4c; const w = z * z; const r = if (j == 1 or j == 2) z + z * w * (S5 + w * (S4 + w * (S3 + w * (S2 + w * (S1 + w * S0))))) else 1.0 - 0.5 * w + w * w * (C5 + w * (C4 + w * (C3 + w * (C2 + w * (C1 + w * C0))))); return if (sign) -r else r; } test "math.cos" { try expect(cos(@as(f32, 0.0)) == cos_(f32, 0.0)); try expect(cos(@as(f64, 0.0)) == cos_(f64, 0.0)); } test "math.cos32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, cos_(f32, 0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f32, cos_(f32, 0.2), 0.980067, epsilon)); try expect(math.approxEqAbs(f32, cos_(f32, 0.8923), 0.627623, epsilon)); try expect(math.approxEqAbs(f32, cos_(f32, 1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f32, cos_(f32, -1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f32, cos_(f32, 37.45), 0.969132, epsilon)); try expect(math.approxEqAbs(f32, cos_(f32, 89.123), 0.400798, epsilon)); } test "math.cos64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, cos_(f64, 0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f64, cos_(f64, 0.2), 0.980067, epsilon)); try expect(math.approxEqAbs(f64, cos_(f64, 0.8923), 0.627623, epsilon)); try expect(math.approxEqAbs(f64, cos_(f64, 1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f64, cos_(f64, -1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f64, cos_(f64, 37.45), 0.969132, epsilon)); try expect(math.approxEqAbs(f64, cos_(f64, 89.123), 0.40080, epsilon)); } test "math.cos32.special" { try expect(math.isNan(cos_(f32, math.inf(f32)))); try expect(math.isNan(cos_(f32, -math.inf(f32)))); try expect(math.isNan(cos_(f32, math.nan(f32)))); } test "math.cos64.special" { try expect(math.isNan(cos_(f64, math.inf(f64)))); try expect(math.isNan(cos_(f64, -math.inf(f64)))); try expect(math.isNan(cos_(f64, math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/cosh.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/coshf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/cosh.c const std = @import("../std.zig"); const math = std.math; const expo2 = @import("expo2.zig").expo2; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns the hyperbolic cosine of x. /// /// Special Cases: /// - cosh(+-0) = 1 /// - cosh(+-inf) = +inf /// - cosh(nan) = nan pub fn cosh(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => cosh32(x), f64 => cosh64(x), else => @compileError("cosh not implemented for " ++ @typeName(T)), }; } // cosh(x) = (exp(x) + 1 / exp(x)) / 2 // = 1 + 0.5 * (exp(x) - 1) * (exp(x) - 1) / exp(x) // = 1 + (x * x) / 2 + o(x^4) fn cosh32(x: f32) f32 { const u = @as(u32, @bitCast(x)); const ux = u & 0x7FFFFFFF; const ax = @as(f32, @bitCast(ux)); // |x| < log(2) if (ux < 0x3F317217) { if (ux < 0x3F800000 - (12 << 23)) { math.raiseOverflow(); return 1.0; } const t = math.expm1(ax); return 1 + t * t / (2 * (1 + t)); } // |x| < log(FLT_MAX) if (ux < 0x42B17217) { const t = math.exp(ax); return 0.5 * (t + 1 / t); } // |x| > log(FLT_MAX) or nan return expo2(ax); } fn cosh64(x: f64) f64 { const u = @as(u64, @bitCast(x)); const w = @as(u32, @intCast(u >> 32)) & (maxInt(u32) >> 1); const ax = @as(f64, @bitCast(u & (maxInt(u64) >> 1))); // TODO: Shouldn't need this explicit check. if (x == 0.0) { return 1.0; } // |x| < log(2) if (w < 0x3FE62E42) { if (w < 0x3FF00000 - (26 << 20)) { if (x != 0) { math.raiseInexact(); } return 1.0; } const t = math.expm1(ax); return 1 + t * t / (2 * (1 + t)); } // |x| < log(DBL_MAX) if (w < 0x40862E42) { const t = math.exp(ax); // NOTE: If x > log(0x1p26) then 1/t is not required. return 0.5 * (t + 1 / t); } // |x| > log(CBL_MAX) or nan return expo2(ax); } test "math.cosh" { try expect(cosh(@as(f32, 1.5)) == cosh32(1.5)); try expect(cosh(@as(f64, 1.5)) == cosh64(1.5)); } test "math.cosh32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, cosh32(0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f32, cosh32(0.2), 1.020067, epsilon)); try expect(math.approxEqAbs(f32, cosh32(0.8923), 1.425225, epsilon)); try expect(math.approxEqAbs(f32, cosh32(1.5), 2.352410, epsilon)); try expect(math.approxEqAbs(f32, cosh32(-0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f32, cosh32(-0.2), 1.020067, epsilon)); try expect(math.approxEqAbs(f32, cosh32(-0.8923), 1.425225, epsilon)); try expect(math.approxEqAbs(f32, cosh32(-1.5), 2.352410, epsilon)); } test "math.cosh64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, cosh64(0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f64, cosh64(0.2), 1.020067, epsilon)); try expect(math.approxEqAbs(f64, cosh64(0.8923), 1.425225, epsilon)); try expect(math.approxEqAbs(f64, cosh64(1.5), 2.352410, epsilon)); try expect(math.approxEqAbs(f64, cosh64(-0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f64, cosh64(-0.2), 1.020067, epsilon)); try expect(math.approxEqAbs(f64, cosh64(-0.8923), 1.425225, epsilon)); try expect(math.approxEqAbs(f64, cosh64(-1.5), 2.352410, epsilon)); } test "math.cosh32.special" { try expect(cosh32(0.0) == 1.0); try expect(cosh32(-0.0) == 1.0); try expect(math.isPositiveInf(cosh32(math.inf(f32)))); try expect(math.isPositiveInf(cosh32(-math.inf(f32)))); try expect(math.isNan(cosh32(math.nan(f32)))); } test "math.cosh64.special" { try expect(cosh64(0.0) == 1.0); try expect(cosh64(-0.0) == 1.0); try expect(math.isPositiveInf(cosh64(math.inf(f64)))); try expect(math.isPositiveInf(cosh64(-math.inf(f64)))); try expect(math.isNan(cosh64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/fabs.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/fabsf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/fabs.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns the absolute value of x. /// /// Special Cases: /// - fabs(+-inf) = +inf /// - fabs(nan) = nan pub fn fabs(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f16 => fabs16(x), f32 => fabs32(x), f64 => fabs64(x), f128 => fabs128(x), else => @compileError("fabs not implemented for " ++ @typeName(T)), }; } fn fabs16(x: f16) f16 { var u = @as(u16, @bitCast(x)); u &= 0x7FFF; return @as(f16, @bitCast(u)); } fn fabs32(x: f32) f32 { var u = @as(u32, @bitCast(x)); u &= 0x7FFFFFFF; return @as(f32, @bitCast(u)); } fn fabs64(x: f64) f64 { var u = @as(u64, @bitCast(x)); u &= maxInt(u64) >> 1; return @as(f64, @bitCast(u)); } fn fabs128(x: f128) f128 { var u = @as(u128, @bitCast(x)); u &= maxInt(u128) >> 1; return @as(f128, @bitCast(u)); } test "math.fabs" { try expect(fabs(@as(f16, 1.0)) == fabs16(1.0)); try expect(fabs(@as(f32, 1.0)) == fabs32(1.0)); try expect(fabs(@as(f64, 1.0)) == fabs64(1.0)); try expect(fabs(@as(f128, 1.0)) == fabs128(1.0)); } test "math.fabs16" { try expect(fabs16(1.0) == 1.0); try expect(fabs16(-1.0) == 1.0); } test "math.fabs32" { try expect(fabs32(1.0) == 1.0); try expect(fabs32(-1.0) == 1.0); } test "math.fabs64" { try expect(fabs64(1.0) == 1.0); try expect(fabs64(-1.0) == 1.0); } test "math.fabs128" { try expect(fabs128(1.0) == 1.0); try expect(fabs128(-1.0) == 1.0); } test "math.fabs16.special" { try expect(math.isPositiveInf(fabs(math.inf(f16)))); try expect(math.isPositiveInf(fabs(-math.inf(f16)))); try expect(math.isNan(fabs(math.nan(f16)))); } test "math.fabs32.special" { try expect(math.isPositiveInf(fabs(math.inf(f32)))); try expect(math.isPositiveInf(fabs(-math.inf(f32)))); try expect(math.isNan(fabs(math.nan(f32)))); } test "math.fabs64.special" { try expect(math.isPositiveInf(fabs(math.inf(f64)))); try expect(math.isPositiveInf(fabs(-math.inf(f64)))); try expect(math.isNan(fabs(math.nan(f64)))); } test "math.fabs128.special" { try expect(math.isPositiveInf(fabs(math.inf(f128)))); try expect(math.isPositiveInf(fabs(-math.inf(f128)))); try expect(math.isNan(fabs(math.nan(f128)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/isfinite.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns whether x is a finite value. pub fn isFinite(x: anytype) bool { const T = @TypeOf(x); switch (T) { f16 => { const bits = @as(u16, @bitCast(x)); return bits & 0x7FFF < 0x7C00; }, f32 => { const bits = @as(u32, @bitCast(x)); return bits & 0x7FFFFFFF < 0x7F800000; }, f64 => { const bits = @as(u64, @bitCast(x)); return bits & (maxInt(u64) >> 1) < (0x7FF << 52); }, f128 => { const bits = @as(u128, @bitCast(x)); return bits & (maxInt(u128) >> 1) < (0x7FFF << 112); }, else => { @compileError("isFinite not implemented for " ++ @typeName(T)); }, } } test "math.isFinite" { try expect(isFinite(@as(f16, 0.0))); try expect(isFinite(@as(f16, -0.0))); try expect(isFinite(@as(f32, 0.0))); try expect(isFinite(@as(f32, -0.0))); try expect(isFinite(@as(f64, 0.0))); try expect(isFinite(@as(f64, -0.0))); try expect(isFinite(@as(f128, 0.0))); try expect(isFinite(@as(f128, -0.0))); try expect(!isFinite(math.inf(f16))); try expect(!isFinite(-math.inf(f16))); try expect(!isFinite(math.inf(f32))); try expect(!isFinite(-math.inf(f32))); try expect(!isFinite(math.inf(f64))); try expect(!isFinite(-math.inf(f64))); try expect(!isFinite(math.inf(f128))); try expect(!isFinite(-math.inf(f128))); try expect(!isFinite(math.nan(f16))); try expect(!isFinite(-math.nan(f16))); try expect(!isFinite(math.nan(f32))); try expect(!isFinite(-math.nan(f32))); try expect(!isFinite(math.nan(f64))); try expect(!isFinite(-math.nan(f64))); try expect(!isFinite(math.nan(f128))); try expect(!isFinite(-math.nan(f128))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/acos.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/acosf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/acos.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the arc-cosine of x. /// /// Special cases: /// - acos(x) = nan if x < -1 or x > 1 pub fn acos(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => acos32(x), f64 => acos64(x), else => @compileError("acos not implemented for " ++ @typeName(T)), }; } fn r32(z: f32) f32 { const pS0 = 1.6666586697e-01; const pS1 = -4.2743422091e-02; const pS2 = -8.6563630030e-03; const qS1 = -7.0662963390e-01; const p = z * (pS0 + z * (pS1 + z * pS2)); const q = 1.0 + z * qS1; return p / q; } fn acos32(x: f32) f32 { const pio2_hi = 1.5707962513e+00; const pio2_lo = 7.5497894159e-08; const hx: u32 = @as(u32, @bitCast(x)); const ix: u32 = hx & 0x7FFFFFFF; // |x| >= 1 or nan if (ix >= 0x3F800000) { if (ix == 0x3F800000) { if (hx >> 31 != 0) { return 2.0 * pio2_hi + 0x1.0p-120; } else { return 0.0; } } else { return math.nan(f32); } } // |x| < 0.5 if (ix < 0x3F000000) { if (ix <= 0x32800000) { // |x| < 2^(-26) return pio2_hi + 0x1.0p-120; } else { return pio2_hi - (x - (pio2_lo - x * r32(x * x))); } } // x < -0.5 if (hx >> 31 != 0) { const z = (1 + x) * 0.5; const s = math.sqrt(z); const w = r32(z) * s - pio2_lo; return 2 * (pio2_hi - (s + w)); } // x > 0.5 const z = (1.0 - x) * 0.5; const s = math.sqrt(z); const jx = @as(u32, @bitCast(s)); const df = @as(f32, @bitCast(jx & 0xFFFFF000)); const c = (z - df * df) / (s + df); const w = r32(z) * s + c; return 2 * (df + w); } fn r64(z: f64) f64 { const pS0: f64 = 1.66666666666666657415e-01; const pS1: f64 = -3.25565818622400915405e-01; const pS2: f64 = 2.01212532134862925881e-01; const pS3: f64 = -4.00555345006794114027e-02; const pS4: f64 = 7.91534994289814532176e-04; const pS5: f64 = 3.47933107596021167570e-05; const qS1: f64 = -2.40339491173441421878e+00; const qS2: f64 = 2.02094576023350569471e+00; const qS3: f64 = -6.88283971605453293030e-01; const qS4: f64 = 7.70381505559019352791e-02; const p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5))))); const q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4))); return p / q; } fn acos64(x: f64) f64 { const pio2_hi: f64 = 1.57079632679489655800e+00; const pio2_lo: f64 = 6.12323399573676603587e-17; const ux = @as(u64, @bitCast(x)); const hx = @as(u32, @intCast(ux >> 32)); const ix = hx & 0x7FFFFFFF; // |x| >= 1 or nan if (ix >= 0x3FF00000) { const lx = @as(u32, @intCast(ux & 0xFFFFFFFF)); // acos(1) = 0, acos(-1) = pi if ((ix - 0x3FF00000) | lx == 0) { if (hx >> 31 != 0) { return 2 * pio2_hi + 0x1.0p-120; } else { return 0; } } return math.nan(f32); } // |x| < 0.5 if (ix < 0x3FE00000) { // |x| < 2^(-57) if (ix <= 0x3C600000) { return pio2_hi + 0x1.0p-120; } else { return pio2_hi - (x - (pio2_lo - x * r64(x * x))); } } // x < -0.5 if (hx >> 31 != 0) { const z = (1.0 + x) * 0.5; const s = math.sqrt(z); const w = r64(z) * s - pio2_lo; return 2 * (pio2_hi - (s + w)); } // x > 0.5 const z = (1.0 - x) * 0.5; const s = math.sqrt(z); const jx = @as(u64, @bitCast(s)); const df = @as(f64, @bitCast(jx & 0xFFFFFFFF00000000)); const c = (z - df * df) / (s + df); const w = r64(z) * s + c; return 2 * (df + w); } test "math.acos" { try expect(acos(@as(f32, 0.0)) == acos32(0.0)); try expect(acos(@as(f64, 0.0)) == acos64(0.0)); } test "math.acos32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, acos32(0.0), 1.570796, epsilon)); try expect(math.approxEqAbs(f32, acos32(0.2), 1.369438, epsilon)); try expect(math.approxEqAbs(f32, acos32(0.3434), 1.220262, epsilon)); try expect(math.approxEqAbs(f32, acos32(0.5), 1.047198, epsilon)); try expect(math.approxEqAbs(f32, acos32(0.8923), 0.468382, epsilon)); try expect(math.approxEqAbs(f32, acos32(-0.2), 1.772154, epsilon)); } test "math.acos64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, acos64(0.0), 1.570796, epsilon)); try expect(math.approxEqAbs(f64, acos64(0.2), 1.369438, epsilon)); try expect(math.approxEqAbs(f64, acos64(0.3434), 1.220262, epsilon)); try expect(math.approxEqAbs(f64, acos64(0.5), 1.047198, epsilon)); try expect(math.approxEqAbs(f64, acos64(0.8923), 0.468382, epsilon)); try expect(math.approxEqAbs(f64, acos64(-0.2), 1.772154, epsilon)); } test "math.acos32.special" { try expect(math.isNan(acos32(-2))); try expect(math.isNan(acos32(1.5))); } test "math.acos64.special" { try expect(math.isNan(acos64(-2))); try expect(math.isNan(acos64(1.5))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/pow.zig
// Ported from go, which is licensed under a BSD-3 license. // https://golang.org/LICENSE // // https://golang.org/src/math/pow.go const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns x raised to the power of y (x^y). /// /// Special Cases: /// - pow(x, +-0) = 1 for any x /// - pow(1, y) = 1 for any y /// - pow(x, 1) = x for any x /// - pow(nan, y) = nan /// - pow(x, nan) = nan /// - pow(+-0, y) = +-inf for y an odd integer < 0 /// - pow(+-0, -inf) = +inf /// - pow(+-0, +inf) = +0 /// - pow(+-0, y) = +inf for finite y < 0 and not an odd integer /// - pow(+-0, y) = +-0 for y an odd integer > 0 /// - pow(+-0, y) = +0 for finite y > 0 and not an odd integer /// - pow(-1, +-inf) = 1 /// - pow(x, +inf) = +inf for |x| > 1 /// - pow(x, -inf) = +0 for |x| > 1 /// - pow(x, +inf) = +0 for |x| < 1 /// - pow(x, -inf) = +inf for |x| < 1 /// - pow(+inf, y) = +inf for y > 0 /// - pow(+inf, y) = +0 for y < 0 /// - pow(-inf, y) = pow(-0, -y) /// - pow(x, y) = nan for finite x < 0 and finite non-integer y pub fn pow(comptime T: type, x: T, y: T) T { if (@typeInfo(T) == .Int) { return math.powi(T, x, y) catch unreachable; } if (T != f32 and T != f64) { @compileError("pow not implemented for " ++ @typeName(T)); } // pow(x, +-0) = 1 for all x // pow(1, y) = 1 for all y if (y == 0 or x == 1) { return 1; } // pow(nan, y) = nan for all y // pow(x, nan) = nan for all x if (math.isNan(x) or math.isNan(y)) { return math.nan(T); } // pow(x, 1) = x for all x if (y == 1) { return x; } if (x == 0) { if (y < 0) { // pow(+-0, y) = +- 0 for y an odd integer if (isOddInteger(y)) { return math.copysign(T, math.inf(T), x); } // pow(+-0, y) = +inf for y an even integer else { return math.inf(T); } } else { if (isOddInteger(y)) { return x; } else { return 0; } } } if (math.isInf(y)) { // pow(-1, inf) = 1 for all x if (x == -1) { return 1.0; } // pow(x, +inf) = +0 for |x| < 1 // pow(x, -inf) = +0 for |x| > 1 else if ((math.fabs(x) < 1) == math.isPositiveInf(y)) { return 0; } // pow(x, -inf) = +inf for |x| < 1 // pow(x, +inf) = +inf for |x| > 1 else { return math.inf(T); } } if (math.isInf(x)) { if (math.isNegativeInf(x)) { return pow(T, 1 / x, -y); } // pow(+inf, y) = +0 for y < 0 else if (y < 0) { return 0; } // pow(+inf, y) = +0 for y > 0 else if (y > 0) { return math.inf(T); } } // special case sqrt if (y == 0.5) { return math.sqrt(x); } if (y == -0.5) { return 1 / math.sqrt(x); } const r1 = math.modf(math.fabs(y)); var yi = r1.ipart; var yf = r1.fpart; if (yf != 0 and x < 0) { return math.nan(T); } if (yi >= 1 << (@typeInfo(T).Float.bits - 1)) { return math.exp(y * math.ln(x)); } // a = a1 * 2^ae var a1: T = 1.0; var ae: i32 = 0; // a *= x^yf if (yf != 0) { if (yf > 0.5) { yf -= 1; yi += 1; } a1 = math.exp(yf * math.ln(x)); } // a *= x^yi const r2 = math.frexp(x); var xe = r2.exponent; var x1 = r2.significand; var i = @as(std.meta.Int(.signed, @typeInfo(T).Float.bits), @intFromFloat(yi)); while (i != 0) : (i >>= 1) { const overflow_shift = math.floatExponentBits(T) + 1; if (xe < -(1 << overflow_shift) or (1 << overflow_shift) < xe) { // catch xe before it overflows the left shift below // Since i != 0 it has at least one bit still set, so ae will accumulate xe // on at least one more iteration, ae += xe is a lower bound on ae // the lower bound on ae exceeds the size of a float exp // so the final call to Ldexp will produce under/overflow (0/Inf) ae += xe; break; } if (i & 1 == 1) { a1 *= x1; ae += xe; } x1 *= x1; xe <<= 1; if (x1 < 0.5) { x1 += x1; xe -= 1; } } // a *= a1 * 2^ae if (y < 0) { a1 = 1 / a1; ae = -ae; } return math.scalbn(a1, ae); } fn isOddInteger(x: f64) bool { const r = math.modf(x); return r.fpart == 0.0 and @as(i64, @intFromFloat(r.ipart)) & 1 == 1; } test "math.pow" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, pow(f32, 0.0, 3.3), 0.0, epsilon)); try expect(math.approxEqAbs(f32, pow(f32, 0.8923, 3.3), 0.686572, epsilon)); try expect(math.approxEqAbs(f32, pow(f32, 0.2, 3.3), 0.004936, epsilon)); try expect(math.approxEqAbs(f32, pow(f32, 1.5, 3.3), 3.811546, epsilon)); try expect(math.approxEqAbs(f32, pow(f32, 37.45, 3.3), 155736.703125, epsilon)); try expect(math.approxEqAbs(f32, pow(f32, 89.123, 3.3), 2722489.5, epsilon)); try expect(math.approxEqAbs(f64, pow(f64, 0.0, 3.3), 0.0, epsilon)); try expect(math.approxEqAbs(f64, pow(f64, 0.8923, 3.3), 0.686572, epsilon)); try expect(math.approxEqAbs(f64, pow(f64, 0.2, 3.3), 0.004936, epsilon)); try expect(math.approxEqAbs(f64, pow(f64, 1.5, 3.3), 3.811546, epsilon)); try expect(math.approxEqAbs(f64, pow(f64, 37.45, 3.3), 155736.7160616, epsilon)); try expect(math.approxEqAbs(f64, pow(f64, 89.123, 3.3), 2722490.231436, epsilon)); } test "math.pow.special" { const epsilon = 0.000001; try expect(pow(f32, 4, 0.0) == 1.0); try expect(pow(f32, 7, -0.0) == 1.0); try expect(pow(f32, 45, 1.0) == 45); try expect(pow(f32, -45, 1.0) == -45); try expect(math.isNan(pow(f32, math.nan(f32), 5.0))); try expect(math.isPositiveInf(pow(f32, -math.inf(f32), 0.5))); try expect(math.isPositiveInf(pow(f32, -0, -0.5))); try expect(pow(f32, -0, 0.5) == 0); try expect(math.isNan(pow(f32, 5.0, math.nan(f32)))); try expect(math.isPositiveInf(pow(f32, 0.0, -1.0))); //expect(math.isNegativeInf(pow(f32, -0.0, -3.0))); TODO is this required? try expect(math.isPositiveInf(pow(f32, 0.0, -math.inf(f32)))); try expect(math.isPositiveInf(pow(f32, -0.0, -math.inf(f32)))); try expect(pow(f32, 0.0, math.inf(f32)) == 0.0); try expect(pow(f32, -0.0, math.inf(f32)) == 0.0); try expect(math.isPositiveInf(pow(f32, 0.0, -2.0))); try expect(math.isPositiveInf(pow(f32, -0.0, -2.0))); try expect(pow(f32, 0.0, 1.0) == 0.0); try expect(pow(f32, -0.0, 1.0) == -0.0); try expect(pow(f32, 0.0, 2.0) == 0.0); try expect(pow(f32, -0.0, 2.0) == 0.0); try expect(math.approxEqAbs(f32, pow(f32, -1.0, math.inf(f32)), 1.0, epsilon)); try expect(math.approxEqAbs(f32, pow(f32, -1.0, -math.inf(f32)), 1.0, epsilon)); try expect(math.isPositiveInf(pow(f32, 1.2, math.inf(f32)))); try expect(math.isPositiveInf(pow(f32, -1.2, math.inf(f32)))); try expect(pow(f32, 1.2, -math.inf(f32)) == 0.0); try expect(pow(f32, -1.2, -math.inf(f32)) == 0.0); try expect(pow(f32, 0.2, math.inf(f32)) == 0.0); try expect(pow(f32, -0.2, math.inf(f32)) == 0.0); try expect(math.isPositiveInf(pow(f32, 0.2, -math.inf(f32)))); try expect(math.isPositiveInf(pow(f32, -0.2, -math.inf(f32)))); try expect(math.isPositiveInf(pow(f32, math.inf(f32), 1.0))); try expect(pow(f32, math.inf(f32), -1.0) == 0.0); //expect(pow(f32, -math.inf(f32), 5.0) == pow(f32, -0.0, -5.0)); TODO support negative 0? try expect(pow(f32, -math.inf(f32), -5.2) == pow(f32, -0.0, 5.2)); try expect(math.isNan(pow(f32, -1.0, 1.2))); try expect(math.isNan(pow(f32, -12.4, 78.5))); } test "math.pow.overflow" { try expect(math.isPositiveInf(pow(f64, 2, 1 << 32))); try expect(pow(f64, 2, -(1 << 32)) == 0); try expect(math.isNegativeInf(pow(f64, -2, (1 << 32) + 1))); try expect(pow(f64, 0.5, 1 << 45) == 0); try expect(math.isPositiveInf(pow(f64, 0.5, -(1 << 45)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/sin.zig
// Ported from go, which is licensed under a BSD-3 license. // https://golang.org/LICENSE // // https://golang.org/src/math/sin.go const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the sine of the radian value x. /// /// Special Cases: /// - sin(+-0) = +-0 /// - sin(+-inf) = nan /// - sin(nan) = nan pub fn sin(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => sin_(T, x), f64 => sin_(T, x), else => @compileError("sin not implemented for " ++ @typeName(T)), }; } // sin polynomial coefficients const S0 = 1.58962301576546568060E-10; const S1 = -2.50507477628578072866E-8; const S2 = 2.75573136213857245213E-6; const S3 = -1.98412698295895385996E-4; const S4 = 8.33333333332211858878E-3; const S5 = -1.66666666666666307295E-1; // cos polynomial coeffiecients const C0 = -1.13585365213876817300E-11; const C1 = 2.08757008419747316778E-9; const C2 = -2.75573141792967388112E-7; const C3 = 2.48015872888517045348E-5; const C4 = -1.38888888888730564116E-3; const C5 = 4.16666666666665929218E-2; const pi4a = 7.85398125648498535156e-1; const pi4b = 3.77489470793079817668E-8; const pi4c = 2.69515142907905952645E-15; const m4pi = 1.273239544735162542821171882678754627704620361328125; fn sin_(comptime T: type, x_: T) T { const I = std.meta.Int(.signed, @typeInfo(T).Float.bits); var x = x_; if (x == 0 or math.isNan(x)) { return x; } if (math.isInf(x)) { return math.nan(T); } var sign = x < 0; x = math.fabs(x); var y = math.floor(x * m4pi); var j = @as(I, @intFromFloat(y)); if (j & 1 == 1) { j += 1; y += 1; } j &= 7; if (j > 3) { j -= 4; sign = !sign; } const z = ((x - y * pi4a) - y * pi4b) - y * pi4c; const w = z * z; const r = if (j == 1 or j == 2) 1.0 - 0.5 * w + w * w * (C5 + w * (C4 + w * (C3 + w * (C2 + w * (C1 + w * C0))))) else z + z * w * (S5 + w * (S4 + w * (S3 + w * (S2 + w * (S1 + w * S0))))); return if (sign) -r else r; } test "math.sin" { try expect(sin(@as(f32, 0.0)) == sin_(f32, 0.0)); try expect(sin(@as(f64, 0.0)) == sin_(f64, 0.0)); try expect(comptime (math.sin(@as(f64, 2))) == math.sin(@as(f64, 2))); } test "math.sin32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, sin_(f32, 0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, sin_(f32, 0.2), 0.198669, epsilon)); try expect(math.approxEqAbs(f32, sin_(f32, 0.8923), 0.778517, epsilon)); try expect(math.approxEqAbs(f32, sin_(f32, 1.5), 0.997495, epsilon)); try expect(math.approxEqAbs(f32, sin_(f32, -1.5), -0.997495, epsilon)); try expect(math.approxEqAbs(f32, sin_(f32, 37.45), -0.246544, epsilon)); try expect(math.approxEqAbs(f32, sin_(f32, 89.123), 0.916166, epsilon)); } test "math.sin64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, sin_(f64, 0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, sin_(f64, 0.2), 0.198669, epsilon)); try expect(math.approxEqAbs(f64, sin_(f64, 0.8923), 0.778517, epsilon)); try expect(math.approxEqAbs(f64, sin_(f64, 1.5), 0.997495, epsilon)); try expect(math.approxEqAbs(f64, sin_(f64, -1.5), -0.997495, epsilon)); try expect(math.approxEqAbs(f64, sin_(f64, 37.45), -0.246543, epsilon)); try expect(math.approxEqAbs(f64, sin_(f64, 89.123), 0.916166, epsilon)); } test "math.sin32.special" { try expect(sin_(f32, 0.0) == 0.0); try expect(sin_(f32, -0.0) == -0.0); try expect(math.isNan(sin_(f32, math.inf(f32)))); try expect(math.isNan(sin_(f32, -math.inf(f32)))); try expect(math.isNan(sin_(f32, math.nan(f32)))); } test "math.sin64.special" { try expect(sin_(f64, 0.0) == 0.0); try expect(sin_(f64, -0.0) == -0.0); try expect(math.isNan(sin_(f64, math.inf(f64)))); try expect(math.isNan(sin_(f64, -math.inf(f64)))); try expect(math.isNan(sin_(f64, math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/nan.zig
const math = @import("../math.zig"); /// Returns the nan representation for type T. pub fn nan(comptime T: type) T { return switch (T) { f16 => math.nan_f16, f32 => math.nan_f32, f64 => math.nan_f64, f128 => math.nan_f128, else => @compileError("nan not implemented for " ++ @typeName(T)), }; } /// Returns the signalling nan representation for type T. pub fn snan(comptime T: type) T { // Note: A signalling nan is identical to a standard right now by may have a different bit // representation in the future when required. return switch (T) { f16 => @as(f16, @bitCast(math.nan_u16)), f32 => @as(f32, @bitCast(math.nan_u32)), f64 => @as(f64, @bitCast(math.nan_u64)), else => @compileError("snan not implemented for " ++ @typeName(T)), }; }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/fma.zig
// Ported from musl, which is MIT licensed: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/fmal.c // https://git.musl-libc.org/cgit/musl/tree/src/math/fmaf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/fma.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns x * y + z with a single rounding error. pub fn fma(comptime T: type, x: T, y: T, z: T) T { return switch (T) { f32 => fma32(x, y, z), f64 => fma64(x, y, z), f128 => fma128(x, y, z), // TODO this is not correct for some targets c_longdouble => @as(c_longdouble, @floatCast(fma128(x, y, z))), else => @compileError("fma not implemented for " ++ @typeName(T)), }; } fn fma32(x: f32, y: f32, z: f32) f32 { const xy = @as(f64, x) * y; const xy_z = xy + z; const u = @as(u64, @bitCast(xy_z)); const e = (u >> 52) & 0x7FF; if ((u & 0x1FFFFFFF) != 0x10000000 or e == 0x7FF or (xy_z - xy == z and xy_z - z == xy)) { return @as(f32, @floatCast(xy_z)); } else { // TODO: Handle inexact case with double-rounding return @as(f32, @floatCast(xy_z)); } } // NOTE: Upstream fma.c has been rewritten completely to raise fp exceptions more accurately. fn fma64(x: f64, y: f64, z: f64) f64 { if (!math.isFinite(x) or !math.isFinite(y)) { return x * y + z; } if (!math.isFinite(z)) { return z; } if (x == 0.0 or y == 0.0) { return x * y + z; } if (z == 0.0) { return x * y; } const x1 = math.frexp(x); var ex = x1.exponent; var xs = x1.significand; const x2 = math.frexp(y); var ey = x2.exponent; var ys = x2.significand; const x3 = math.frexp(z); var ez = x3.exponent; var zs = x3.significand; var spread = ex + ey - ez; if (spread <= 53 * 2) { zs = math.scalbn(zs, -spread); } else { zs = math.copysign(f64, math.f64_min, zs); } const xy = dd_mul(xs, ys); const r = dd_add(xy.hi, zs); spread = ex + ey; if (r.hi == 0.0) { return xy.hi + zs + math.scalbn(xy.lo, spread); } const adj = add_adjusted(r.lo, xy.lo); if (spread + math.ilogb(r.hi) > -1023) { return math.scalbn(r.hi + adj, spread); } else { return add_and_denorm(r.hi, adj, spread); } } const dd = struct { hi: f64, lo: f64, }; fn dd_add(a: f64, b: f64) dd { var ret: dd = undefined; ret.hi = a + b; const s = ret.hi - a; ret.lo = (a - (ret.hi - s)) + (b - s); return ret; } fn dd_mul(a: f64, b: f64) dd { var ret: dd = undefined; const split: f64 = 0x1.0p27 + 1.0; var p = a * split; var ha = a - p; ha += p; var la = a - ha; p = b * split; var hb = b - p; hb += p; var lb = b - hb; p = ha * hb; var q = ha * lb + la * hb; ret.hi = p + q; ret.lo = p - ret.hi + q + la * lb; return ret; } fn add_adjusted(a: f64, b: f64) f64 { var sum = dd_add(a, b); if (sum.lo != 0) { var uhii = @as(u64, @bitCast(sum.hi)); if (uhii & 1 == 0) { // hibits += copysign(1.0, sum.hi, sum.lo) const uloi = @as(u64, @bitCast(sum.lo)); uhii += 1 - ((uhii ^ uloi) >> 62); sum.hi = @as(f64, @bitCast(uhii)); } } return sum.hi; } fn add_and_denorm(a: f64, b: f64, scale: i32) f64 { var sum = dd_add(a, b); if (sum.lo != 0) { var uhii = @as(u64, @bitCast(sum.hi)); const bits_lost = -@as(i32, @intCast((uhii >> 52) & 0x7FF)) - scale + 1; if ((bits_lost != 1) == (uhii & 1 != 0)) { const uloi = @as(u64, @bitCast(sum.lo)); uhii += 1 - (((uhii ^ uloi) >> 62) & 2); sum.hi = @as(f64, @bitCast(uhii)); } } return math.scalbn(sum.hi, scale); } /// A struct that represents a floating-point number with twice the precision /// of f128. We maintain the invariant that "hi" stores the high-order /// bits of the result. const dd128 = struct { hi: f128, lo: f128, }; /// Compute a+b exactly, returning the exact result in a struct dd. We assume /// that both a and b are finite, but make no assumptions about their relative /// magnitudes. fn dd_add128(a: f128, b: f128) dd128 { var ret: dd128 = undefined; ret.hi = a + b; const s = ret.hi - a; ret.lo = (a - (ret.hi - s)) + (b - s); return ret; } /// Compute a+b, with a small tweak: The least significant bit of the /// result is adjusted into a sticky bit summarizing all the bits that /// were lost to rounding. This adjustment negates the effects of double /// rounding when the result is added to another number with a higher /// exponent. For an explanation of round and sticky bits, see any reference /// on FPU design, e.g., /// /// J. Coonen. An Implementation Guide to a Proposed Standard for /// Floating-Point Arithmetic. Computer, vol. 13, no. 1, Jan 1980. fn add_adjusted128(a: f128, b: f128) f128 { var sum = dd_add128(a, b); if (sum.lo != 0) { var uhii = @as(u128, @bitCast(sum.hi)); if (uhii & 1 == 0) { // hibits += copysign(1.0, sum.hi, sum.lo) const uloi = @as(u128, @bitCast(sum.lo)); uhii += 1 - ((uhii ^ uloi) >> 126); sum.hi = @as(f128, @bitCast(uhii)); } } return sum.hi; } /// Compute ldexp(a+b, scale) with a single rounding error. It is assumed /// that the result will be subnormal, and care is taken to ensure that /// double rounding does not occur. fn add_and_denorm128(a: f128, b: f128, scale: i32) f128 { var sum = dd_add128(a, b); // If we are losing at least two bits of accuracy to denormalization, // then the first lost bit becomes a round bit, and we adjust the // lowest bit of sum.hi to make it a sticky bit summarizing all the // bits in sum.lo. With the sticky bit adjusted, the hardware will // break any ties in the correct direction. // // If we are losing only one bit to denormalization, however, we must // break the ties manually. if (sum.lo != 0) { var uhii = @as(u128, @bitCast(sum.hi)); const bits_lost = -@as(i32, @intCast((uhii >> 112) & 0x7FFF)) - scale + 1; if ((bits_lost != 1) == (uhii & 1 != 0)) { const uloi = @as(u128, @bitCast(sum.lo)); uhii += 1 - (((uhii ^ uloi) >> 126) & 2); sum.hi = @as(f128, @bitCast(uhii)); } } return math.scalbn(sum.hi, scale); } /// Compute a*b exactly, returning the exact result in a struct dd. We assume /// that both a and b are normalized, so no underflow or overflow will occur. /// The current rounding mode must be round-to-nearest. fn dd_mul128(a: f128, b: f128) dd128 { var ret: dd128 = undefined; const split: f128 = 0x1.0p57 + 1.0; var p = a * split; var ha = a - p; ha += p; var la = a - ha; p = b * split; var hb = b - p; hb += p; var lb = b - hb; p = ha * hb; var q = ha * lb + la * hb; ret.hi = p + q; ret.lo = p - ret.hi + q + la * lb; return ret; } /// Fused multiply-add: Compute x * y + z with a single rounding error. /// /// We use scaling to avoid overflow/underflow, along with the /// canonical precision-doubling technique adapted from: /// /// Dekker, T. A Floating-Point Technique for Extending the /// Available Precision. Numer. Math. 18, 224-242 (1971). fn fma128(x: f128, y: f128, z: f128) f128 { if (!math.isFinite(x) or !math.isFinite(y)) { return x * y + z; } if (!math.isFinite(z)) { return z; } if (x == 0.0 or y == 0.0) { return x * y + z; } if (z == 0.0) { return x * y; } const x1 = math.frexp(x); var ex = x1.exponent; var xs = x1.significand; const x2 = math.frexp(y); var ey = x2.exponent; var ys = x2.significand; const x3 = math.frexp(z); var ez = x3.exponent; var zs = x3.significand; var spread = ex + ey - ez; if (spread <= 113 * 2) { zs = math.scalbn(zs, -spread); } else { zs = math.copysign(f128, math.f128_min, zs); } const xy = dd_mul128(xs, ys); const r = dd_add128(xy.hi, zs); spread = ex + ey; if (r.hi == 0.0) { return xy.hi + zs + math.scalbn(xy.lo, spread); } const adj = add_adjusted128(r.lo, xy.lo); if (spread + math.ilogb(r.hi) > -16383) { return math.scalbn(r.hi + adj, spread); } else { return add_and_denorm128(r.hi, adj, spread); } } test "type dispatch" { try expect(fma(f32, 0.0, 1.0, 1.0) == fma32(0.0, 1.0, 1.0)); try expect(fma(f64, 0.0, 1.0, 1.0) == fma64(0.0, 1.0, 1.0)); try expect(fma(f128, 0.0, 1.0, 1.0) == fma128(0.0, 1.0, 1.0)); } test "32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, fma32(0.0, 5.0, 9.124), 9.124, epsilon)); try expect(math.approxEqAbs(f32, fma32(0.2, 5.0, 9.124), 10.124, epsilon)); try expect(math.approxEqAbs(f32, fma32(0.8923, 5.0, 9.124), 13.5855, epsilon)); try expect(math.approxEqAbs(f32, fma32(1.5, 5.0, 9.124), 16.624, epsilon)); try expect(math.approxEqAbs(f32, fma32(37.45, 5.0, 9.124), 196.374004, epsilon)); try expect(math.approxEqAbs(f32, fma32(89.123, 5.0, 9.124), 454.739005, epsilon)); try expect(math.approxEqAbs(f32, fma32(123123.234375, 5.0, 9.124), 615625.295875, epsilon)); } test "64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, fma64(0.0, 5.0, 9.124), 9.124, epsilon)); try expect(math.approxEqAbs(f64, fma64(0.2, 5.0, 9.124), 10.124, epsilon)); try expect(math.approxEqAbs(f64, fma64(0.8923, 5.0, 9.124), 13.5855, epsilon)); try expect(math.approxEqAbs(f64, fma64(1.5, 5.0, 9.124), 16.624, epsilon)); try expect(math.approxEqAbs(f64, fma64(37.45, 5.0, 9.124), 196.374, epsilon)); try expect(math.approxEqAbs(f64, fma64(89.123, 5.0, 9.124), 454.739, epsilon)); try expect(math.approxEqAbs(f64, fma64(123123.234375, 5.0, 9.124), 615625.295875, epsilon)); } test "128" { const epsilon = 0.000001; try expect(math.approxEqAbs(f128, fma128(0.0, 5.0, 9.124), 9.124, epsilon)); try expect(math.approxEqAbs(f128, fma128(0.2, 5.0, 9.124), 10.124, epsilon)); try expect(math.approxEqAbs(f128, fma128(0.8923, 5.0, 9.124), 13.5855, epsilon)); try expect(math.approxEqAbs(f128, fma128(1.5, 5.0, 9.124), 16.624, epsilon)); try expect(math.approxEqAbs(f128, fma128(37.45, 5.0, 9.124), 196.374, epsilon)); try expect(math.approxEqAbs(f128, fma128(89.123, 5.0, 9.124), 454.739, epsilon)); try expect(math.approxEqAbs(f128, fma128(123123.234375, 5.0, 9.124), 615625.295875, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/trunc.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/truncf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/trunc.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns the integer value of x. /// /// Special Cases: /// - trunc(+-0) = +-0 /// - trunc(+-inf) = +-inf /// - trunc(nan) = nan pub fn trunc(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => trunc32(x), f64 => trunc64(x), f128 => trunc128(x), // TODO this is not correct for some targets c_longdouble => @as(c_longdouble, @floatCast(trunc128(x))), else => @compileError("trunc not implemented for " ++ @typeName(T)), }; } fn trunc32(x: f32) f32 { const u = @as(u32, @bitCast(x)); var e = @as(i32, @intCast(((u >> 23) & 0xFF))) - 0x7F + 9; var m: u32 = undefined; if (e >= 23 + 9) { return x; } if (e < 9) { e = 1; } m = @as(u32, maxInt(u32)) >> @as(u5, @intCast(e)); if (u & m == 0) { return x; } else { math.doNotOptimizeAway(x + 0x1p120); return @as(f32, @bitCast(u & ~m)); } } fn trunc64(x: f64) f64 { const u = @as(u64, @bitCast(x)); var e = @as(i32, @intCast(((u >> 52) & 0x7FF))) - 0x3FF + 12; var m: u64 = undefined; if (e >= 52 + 12) { return x; } if (e < 12) { e = 1; } m = @as(u64, maxInt(u64)) >> @as(u6, @intCast(e)); if (u & m == 0) { return x; } else { math.doNotOptimizeAway(x + 0x1p120); return @as(f64, @bitCast(u & ~m)); } } fn trunc128(x: f128) f128 { const u = @as(u128, @bitCast(x)); var e = @as(i32, @intCast(((u >> 112) & 0x7FFF))) - 0x3FFF + 16; var m: u128 = undefined; if (e >= 112 + 16) { return x; } if (e < 16) { e = 1; } m = @as(u128, maxInt(u128)) >> @as(u7, @intCast(e)); if (u & m == 0) { return x; } else { math.doNotOptimizeAway(x + 0x1p120); return @as(f128, @bitCast(u & ~m)); } } test "math.trunc" { try expect(trunc(@as(f32, 1.3)) == trunc32(1.3)); try expect(trunc(@as(f64, 1.3)) == trunc64(1.3)); try expect(trunc(@as(f128, 1.3)) == trunc128(1.3)); } test "math.trunc32" { try expect(trunc32(1.3) == 1.0); try expect(trunc32(-1.3) == -1.0); try expect(trunc32(0.2) == 0.0); } test "math.trunc64" { try expect(trunc64(1.3) == 1.0); try expect(trunc64(-1.3) == -1.0); try expect(trunc64(0.2) == 0.0); } test "math.trunc128" { try expect(trunc128(1.3) == 1.0); try expect(trunc128(-1.3) == -1.0); try expect(trunc128(0.2) == 0.0); } test "math.trunc32.special" { try expect(trunc32(0.0) == 0.0); // 0x3F800000 try expect(trunc32(-0.0) == -0.0); try expect(math.isPositiveInf(trunc32(math.inf(f32)))); try expect(math.isNegativeInf(trunc32(-math.inf(f32)))); try expect(math.isNan(trunc32(math.nan(f32)))); } test "math.trunc64.special" { try expect(trunc64(0.0) == 0.0); try expect(trunc64(-0.0) == -0.0); try expect(math.isPositiveInf(trunc64(math.inf(f64)))); try expect(math.isNegativeInf(trunc64(-math.inf(f64)))); try expect(math.isNan(trunc64(math.nan(f64)))); } test "math.trunc128.special" { try expect(trunc128(0.0) == 0.0); try expect(trunc128(-0.0) == -0.0); try expect(math.isPositiveInf(trunc128(math.inf(f128)))); try expect(math.isNegativeInf(trunc128(-math.inf(f128)))); try expect(math.isNan(trunc128(math.nan(f128)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/asinh.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/asinhf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/asinh.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns the hyperbolic arc-sin of x. /// /// Special Cases: /// - asinh(+-0) = +-0 /// - asinh(+-inf) = +-inf /// - asinh(nan) = nan pub fn asinh(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => asinh32(x), f64 => asinh64(x), else => @compileError("asinh not implemented for " ++ @typeName(T)), }; } // asinh(x) = sign(x) * log(|x| + sqrt(x * x + 1)) ~= x - x^3/6 + o(x^5) fn asinh32(x: f32) f32 { const u = @as(u32, @bitCast(x)); const i = u & 0x7FFFFFFF; const s = i >> 31; var rx = @as(f32, @bitCast(i)); // |x| // TODO: Shouldn't need this explicit check. if (math.isNegativeInf(x)) { return x; } // |x| >= 0x1p12 or inf or nan if (i >= 0x3F800000 + (12 << 23)) { rx = math.ln(rx) + 0.69314718055994530941723212145817656; } // |x| >= 2 else if (i >= 0x3F800000 + (1 << 23)) { rx = math.ln(2 * x + 1 / (math.sqrt(x * x + 1) + x)); } // |x| >= 0x1p-12, up to 1.6ulp error else if (i >= 0x3F800000 - (12 << 23)) { rx = math.log1p(x + x * x / (math.sqrt(x * x + 1) + 1)); } // |x| < 0x1p-12, inexact if x != 0 else { math.doNotOptimizeAway(x + 0x1.0p120); } return if (s != 0) -rx else rx; } fn asinh64(x: f64) f64 { const u = @as(u64, @bitCast(x)); const e = (u >> 52) & 0x7FF; const s = e >> 63; var rx = @as(f64, @bitCast(u & (maxInt(u64) >> 1))); // |x| if (math.isNegativeInf(x)) { return x; } // |x| >= 0x1p26 or inf or nan if (e >= 0x3FF + 26) { rx = math.ln(rx) + 0.693147180559945309417232121458176568; } // |x| >= 2 else if (e >= 0x3FF + 1) { rx = math.ln(2 * x + 1 / (math.sqrt(x * x + 1) + x)); } // |x| >= 0x1p-12, up to 1.6ulp error else if (e >= 0x3FF - 26) { rx = math.log1p(x + x * x / (math.sqrt(x * x + 1) + 1)); } // |x| < 0x1p-12, inexact if x != 0 else { math.doNotOptimizeAway(x + 0x1.0p120); } return if (s != 0) -rx else rx; } test "math.asinh" { try expect(asinh(@as(f32, 0.0)) == asinh32(0.0)); try expect(asinh(@as(f64, 0.0)) == asinh64(0.0)); } test "math.asinh32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, asinh32(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, asinh32(-0.2), -0.198690, epsilon)); try expect(math.approxEqAbs(f32, asinh32(0.2), 0.198690, epsilon)); try expect(math.approxEqAbs(f32, asinh32(0.8923), 0.803133, epsilon)); try expect(math.approxEqAbs(f32, asinh32(1.5), 1.194763, epsilon)); try expect(math.approxEqAbs(f32, asinh32(37.45), 4.316332, epsilon)); try expect(math.approxEqAbs(f32, asinh32(89.123), 5.183196, epsilon)); try expect(math.approxEqAbs(f32, asinh32(123123.234375), 12.414088, epsilon)); } test "math.asinh64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, asinh64(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, asinh64(-0.2), -0.198690, epsilon)); try expect(math.approxEqAbs(f64, asinh64(0.2), 0.198690, epsilon)); try expect(math.approxEqAbs(f64, asinh64(0.8923), 0.803133, epsilon)); try expect(math.approxEqAbs(f64, asinh64(1.5), 1.194763, epsilon)); try expect(math.approxEqAbs(f64, asinh64(37.45), 4.316332, epsilon)); try expect(math.approxEqAbs(f64, asinh64(89.123), 5.183196, epsilon)); try expect(math.approxEqAbs(f64, asinh64(123123.234375), 12.414088, epsilon)); } test "math.asinh32.special" { try expect(asinh32(0.0) == 0.0); try expect(asinh32(-0.0) == -0.0); try expect(math.isPositiveInf(asinh32(math.inf(f32)))); try expect(math.isNegativeInf(asinh32(-math.inf(f32)))); try expect(math.isNan(asinh32(math.nan(f32)))); } test "math.asinh64.special" { try expect(asinh64(0.0) == 0.0); try expect(asinh64(-0.0) == -0.0); try expect(math.isPositiveInf(asinh64(math.inf(f64)))); try expect(math.isNegativeInf(asinh64(-math.inf(f64)))); try expect(math.isNan(asinh64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/expm1.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/expmf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/expm.c // TODO: Updated recently. const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns e raised to the power of x, minus 1 (e^x - 1). This is more accurate than exp(e, x) - 1 /// when x is near 0. /// /// Special Cases: /// - expm1(+inf) = +inf /// - expm1(-inf) = -1 /// - expm1(nan) = nan pub fn expm1(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => expm1_32(x), f64 => expm1_64(x), else => @compileError("exp1m not implemented for " ++ @typeName(T)), }; } fn expm1_32(x_: f32) f32 { if (math.isNan(x_)) return math.nan(f32); const o_threshold: f32 = 8.8721679688e+01; const ln2_hi: f32 = 6.9313812256e-01; const ln2_lo: f32 = 9.0580006145e-06; const invln2: f32 = 1.4426950216e+00; const Q1: f32 = -3.3333212137e-2; const Q2: f32 = 1.5807170421e-3; var x = x_; const ux = @as(u32, @bitCast(x)); const hx = ux & 0x7FFFFFFF; const sign = hx >> 31; // TODO: Shouldn't need this check explicitly. if (math.isNegativeInf(x)) { return -1.0; } // |x| >= 27 * ln2 if (hx >= 0x4195B844) { // nan if (hx > 0x7F800000) { return x; } if (sign != 0) { return -1; } if (x > o_threshold) { x *= 0x1.0p127; return x; } } var hi: f32 = undefined; var lo: f32 = undefined; var c: f32 = undefined; var k: i32 = undefined; // |x| > 0.5 * ln2 if (hx > 0x3EB17218) { // |x| < 1.5 * ln2 if (hx < 0x3F851592) { if (sign == 0) { hi = x - ln2_hi; lo = ln2_lo; k = 1; } else { hi = x + ln2_hi; lo = -ln2_lo; k = -1; } } else { var kf = invln2 * x; if (sign != 0) { kf -= 0.5; } else { kf += 0.5; } k = @as(i32, @intFromFloat(kf)); const t = @as(f32, @floatFromInt(k)); hi = x - t * ln2_hi; lo = t * ln2_lo; } x = hi - lo; c = (hi - x) - lo; } // |x| < 2^(-25) else if (hx < 0x33000000) { if (hx < 0x00800000) { math.doNotOptimizeAway(x * x); } return x; } else { k = 0; } const hfx = 0.5 * x; const hxs = x * hfx; const r1 = 1.0 + hxs * (Q1 + hxs * Q2); const t = 3.0 - r1 * hfx; var e = hxs * ((r1 - t) / (6.0 - x * t)); // c is 0 if (k == 0) { return x - (x * e - hxs); } e = x * (e - c) - c; e -= hxs; // exp(x) ~ 2^k (x_reduced - e + 1) if (k == -1) { return 0.5 * (x - e) - 0.5; } if (k == 1) { if (x < -0.25) { return -2.0 * (e - (x + 0.5)); } else { return 1.0 + 2.0 * (x - e); } } const twopk = @as(f32, @bitCast(@as(u32, @intCast((0x7F +% k) << 23)))); if (k < 0 or k > 56) { var y = x - e + 1.0; if (k == 128) { y = y * 2.0 * 0x1.0p127; } else { y = y * twopk; } return y - 1.0; } const uf = @as(f32, @bitCast(@as(u32, @intCast(0x7F -% k)) << 23)); if (k < 23) { return (x - e + (1 - uf)) * twopk; } else { return (x - (e + uf) + 1) * twopk; } } fn expm1_64(x_: f64) f64 { if (math.isNan(x_)) return math.nan(f64); const o_threshold: f64 = 7.09782712893383973096e+02; const ln2_hi: f64 = 6.93147180369123816490e-01; const ln2_lo: f64 = 1.90821492927058770002e-10; const invln2: f64 = 1.44269504088896338700e+00; const Q1: f64 = -3.33333333333331316428e-02; const Q2: f64 = 1.58730158725481460165e-03; const Q3: f64 = -7.93650757867487942473e-05; const Q4: f64 = 4.00821782732936239552e-06; const Q5: f64 = -2.01099218183624371326e-07; var x = x_; const ux = @as(u64, @bitCast(x)); const hx = @as(u32, @intCast(ux >> 32)) & 0x7FFFFFFF; const sign = ux >> 63; if (math.isNegativeInf(x)) { return -1.0; } // |x| >= 56 * ln2 if (hx >= 0x4043687A) { // exp1md(nan) = nan if (hx > 0x7FF00000) { return x; } // exp1md(-ve) = -1 if (sign != 0) { return -1; } if (x > o_threshold) { math.raiseOverflow(); return math.inf(f64); } } var hi: f64 = undefined; var lo: f64 = undefined; var c: f64 = undefined; var k: i32 = undefined; // |x| > 0.5 * ln2 if (hx > 0x3FD62E42) { // |x| < 1.5 * ln2 if (hx < 0x3FF0A2B2) { if (sign == 0) { hi = x - ln2_hi; lo = ln2_lo; k = 1; } else { hi = x + ln2_hi; lo = -ln2_lo; k = -1; } } else { var kf = invln2 * x; if (sign != 0) { kf -= 0.5; } else { kf += 0.5; } k = @as(i32, @intFromFloat(kf)); const t = @as(f64, @floatFromInt(k)); hi = x - t * ln2_hi; lo = t * ln2_lo; } x = hi - lo; c = (hi - x) - lo; } // |x| < 2^(-54) else if (hx < 0x3C900000) { if (hx < 0x00100000) { math.doNotOptimizeAway(@as(f32, @floatCast(x))); } return x; } else { k = 0; } const hfx = 0.5 * x; const hxs = x * hfx; const r1 = 1.0 + hxs * (Q1 + hxs * (Q2 + hxs * (Q3 + hxs * (Q4 + hxs * Q5)))); const t = 3.0 - r1 * hfx; var e = hxs * ((r1 - t) / (6.0 - x * t)); // c is 0 if (k == 0) { return x - (x * e - hxs); } e = x * (e - c) - c; e -= hxs; // exp(x) ~ 2^k (x_reduced - e + 1) if (k == -1) { return 0.5 * (x - e) - 0.5; } if (k == 1) { if (x < -0.25) { return -2.0 * (e - (x + 0.5)); } else { return 1.0 + 2.0 * (x - e); } } const twopk = @as(f64, @bitCast(@as(u64, @intCast(0x3FF +% k)) << 52)); if (k < 0 or k > 56) { var y = x - e + 1.0; if (k == 1024) { y = y * 2.0 * 0x1.0p1023; } else { y = y * twopk; } return y - 1.0; } const uf = @as(f64, @bitCast(@as(u64, @intCast(0x3FF -% k)) << 52)); if (k < 20) { return (x - e + (1 - uf)) * twopk; } else { return (x - (e + uf) + 1) * twopk; } } test "math.exp1m" { try expect(expm1(@as(f32, 0.0)) == expm1_32(0.0)); try expect(expm1(@as(f64, 0.0)) == expm1_64(0.0)); } test "math.expm1_32" { const epsilon = 0.000001; try expect(expm1_32(0.0) == 0.0); try expect(math.approxEqAbs(f32, expm1_32(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, expm1_32(0.2), 0.221403, epsilon)); try expect(math.approxEqAbs(f32, expm1_32(0.8923), 1.440737, epsilon)); try expect(math.approxEqAbs(f32, expm1_32(1.5), 3.481689, epsilon)); } test "math.expm1_64" { const epsilon = 0.000001; try expect(expm1_64(0.0) == 0.0); try expect(math.approxEqAbs(f64, expm1_64(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, expm1_64(0.2), 0.221403, epsilon)); try expect(math.approxEqAbs(f64, expm1_64(0.8923), 1.440737, epsilon)); try expect(math.approxEqAbs(f64, expm1_64(1.5), 3.481689, epsilon)); } test "math.expm1_32.special" { try expect(math.isPositiveInf(expm1_32(math.inf(f32)))); try expect(expm1_32(-math.inf(f32)) == -1.0); try expect(math.isNan(expm1_32(math.nan(f32)))); } test "math.expm1_64.special" { try expect(math.isPositiveInf(expm1_64(math.inf(f64)))); try expect(expm1_64(-math.inf(f64)) == -1.0); try expect(math.isNan(expm1_64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/round.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/roundf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/round.c const expect = std.testing.expect; const std = @import("../std.zig"); const math = std.math; /// Returns x rounded to the nearest integer, rounding half away from zero. /// /// Special Cases: /// - round(+-0) = +-0 /// - round(+-inf) = +-inf /// - round(nan) = nan pub fn round(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => round32(x), f64 => round64(x), f128 => round128(x), else => @compileError("round not implemented for " ++ @typeName(T)), }; } fn round32(x_: f32) f32 { var x = x_; const u = @as(u32, @bitCast(x)); const e = (u >> 23) & 0xFF; var y: f32 = undefined; if (e >= 0x7F + 23) { return x; } if (u >> 31 != 0) { x = -x; } if (e < 0x7F - 1) { math.doNotOptimizeAway(x + math.f32_toint); return 0 * @as(f32, @bitCast(u)); } y = x + math.f32_toint - math.f32_toint - x; if (y > 0.5) { y = y + x - 1; } else if (y <= -0.5) { y = y + x + 1; } else { y = y + x; } if (u >> 31 != 0) { return -y; } else { return y; } } fn round64(x_: f64) f64 { var x = x_; const u = @as(u64, @bitCast(x)); const e = (u >> 52) & 0x7FF; var y: f64 = undefined; if (e >= 0x3FF + 52) { return x; } if (u >> 63 != 0) { x = -x; } if (e < 0x3ff - 1) { math.doNotOptimizeAway(x + math.f64_toint); return 0 * @as(f64, @bitCast(u)); } y = x + math.f64_toint - math.f64_toint - x; if (y > 0.5) { y = y + x - 1; } else if (y <= -0.5) { y = y + x + 1; } else { y = y + x; } if (u >> 63 != 0) { return -y; } else { return y; } } fn round128(x_: f128) f128 { var x = x_; const u = @as(u128, @bitCast(x)); const e = (u >> 112) & 0x7FFF; var y: f128 = undefined; if (e >= 0x3FFF + 112) { return x; } if (u >> 127 != 0) { x = -x; } if (e < 0x3FFF - 1) { math.doNotOptimizeAway(x + math.f64_toint); return 0 * @as(f128, @bitCast(u)); } y = x + math.f128_toint - math.f128_toint - x; if (y > 0.5) { y = y + x - 1; } else if (y <= -0.5) { y = y + x + 1; } else { y = y + x; } if (u >> 127 != 0) { return -y; } else { return y; } } test "math.round" { try expect(round(@as(f32, 1.3)) == round32(1.3)); try expect(round(@as(f64, 1.3)) == round64(1.3)); try expect(round(@as(f128, 1.3)) == round128(1.3)); } test "math.round32" { try expect(round32(1.3) == 1.0); try expect(round32(-1.3) == -1.0); try expect(round32(0.2) == 0.0); try expect(round32(1.8) == 2.0); } test "math.round64" { try expect(round64(1.3) == 1.0); try expect(round64(-1.3) == -1.0); try expect(round64(0.2) == 0.0); try expect(round64(1.8) == 2.0); } test "math.round128" { try expect(round128(1.3) == 1.0); try expect(round128(-1.3) == -1.0); try expect(round128(0.2) == 0.0); try expect(round128(1.8) == 2.0); } test "math.round32.special" { try expect(round32(0.0) == 0.0); try expect(round32(-0.0) == -0.0); try expect(math.isPositiveInf(round32(math.inf(f32)))); try expect(math.isNegativeInf(round32(-math.inf(f32)))); try expect(math.isNan(round32(math.nan(f32)))); } test "math.round64.special" { try expect(round64(0.0) == 0.0); try expect(round64(-0.0) == -0.0); try expect(math.isPositiveInf(round64(math.inf(f64)))); try expect(math.isNegativeInf(round64(-math.inf(f64)))); try expect(math.isNan(round64(math.nan(f64)))); } test "math.round128.special" { try expect(round128(0.0) == 0.0); try expect(round128(-0.0) == -0.0); try expect(math.isPositiveInf(round128(math.inf(f128)))); try expect(math.isNegativeInf(round128(-math.inf(f128)))); try expect(math.isNan(round128(math.nan(f128)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex.zig
const std = @import("../std.zig"); const testing = std.testing; const math = std.math; pub const abs = @import("complex/abs.zig").abs; pub const acosh = @import("complex/acosh.zig").acosh; pub const acos = @import("complex/acos.zig").acos; pub const arg = @import("complex/arg.zig").arg; pub const asinh = @import("complex/asinh.zig").asinh; pub const asin = @import("complex/asin.zig").asin; pub const atanh = @import("complex/atanh.zig").atanh; pub const atan = @import("complex/atan.zig").atan; pub const conj = @import("complex/conj.zig").conj; pub const cosh = @import("complex/cosh.zig").cosh; pub const cos = @import("complex/cos.zig").cos; pub const exp = @import("complex/exp.zig").exp; pub const log = @import("complex/log.zig").log; pub const pow = @import("complex/pow.zig").pow; pub const proj = @import("complex/proj.zig").proj; pub const sinh = @import("complex/sinh.zig").sinh; pub const sin = @import("complex/sin.zig").sin; pub const sqrt = @import("complex/sqrt.zig").sqrt; pub const tanh = @import("complex/tanh.zig").tanh; pub const tan = @import("complex/tan.zig").tan; /// A complex number consisting of a real an imaginary part. T must be a floating-point value. pub fn Complex(comptime T: type) type { return struct { const Self = @This(); /// Real part. re: T, /// Imaginary part. im: T, /// Deprecated, use init() pub const new = init; /// Create a new Complex number from the given real and imaginary parts. pub fn init(re: T, im: T) Self { return Self{ .re = re, .im = im, }; } /// Returns the sum of two complex numbers. pub fn add(self: Self, other: Self) Self { return Self{ .re = self.re + other.re, .im = self.im + other.im, }; } /// Returns the subtraction of two complex numbers. pub fn sub(self: Self, other: Self) Self { return Self{ .re = self.re - other.re, .im = self.im - other.im, }; } /// Returns the product of two complex numbers. pub fn mul(self: Self, other: Self) Self { return Self{ .re = self.re * other.re - self.im * other.im, .im = self.im * other.re + self.re * other.im, }; } /// Returns the quotient of two complex numbers. pub fn div(self: Self, other: Self) Self { const re_num = self.re * other.re + self.im * other.im; const im_num = self.im * other.re - self.re * other.im; const den = other.re * other.re + other.im * other.im; return Self{ .re = re_num / den, .im = im_num / den, }; } /// Returns the complex conjugate of a number. pub fn conjugate(self: Self) Self { return Self{ .re = self.re, .im = -self.im, }; } /// Returns the reciprocal of a complex number. pub fn reciprocal(self: Self) Self { const m = self.re * self.re + self.im * self.im; return Self{ .re = self.re / m, .im = -self.im / m, }; } /// Returns the magnitude of a complex number. pub fn magnitude(self: Self) T { return math.sqrt(self.re * self.re + self.im * self.im); } }; } const epsilon = 0.0001; test "complex.add" { const a = Complex(f32).init(5, 3); const b = Complex(f32).init(2, 7); const c = a.add(b); try testing.expect(c.re == 7 and c.im == 10); } test "complex.sub" { const a = Complex(f32).init(5, 3); const b = Complex(f32).init(2, 7); const c = a.sub(b); try testing.expect(c.re == 3 and c.im == -4); } test "complex.mul" { const a = Complex(f32).init(5, 3); const b = Complex(f32).init(2, 7); const c = a.mul(b); try testing.expect(c.re == -11 and c.im == 41); } test "complex.div" { const a = Complex(f32).init(5, 3); const b = Complex(f32).init(2, 7); const c = a.div(b); try testing.expect(math.approxEqAbs(f32, c.re, @as(f32, 31) / 53, epsilon) and math.approxEqAbs(f32, c.im, @as(f32, -29) / 53, epsilon)); } test "complex.conjugate" { const a = Complex(f32).init(5, 3); const c = a.conjugate(); try testing.expect(c.re == 5 and c.im == -3); } test "complex.reciprocal" { const a = Complex(f32).init(5, 3); const c = a.reciprocal(); try testing.expect(math.approxEqAbs(f32, c.re, @as(f32, 5) / 34, epsilon) and math.approxEqAbs(f32, c.im, @as(f32, -3) / 34, epsilon)); } test "complex.magnitude" { const a = Complex(f32).init(5, 3); const c = a.magnitude(); try testing.expect(math.approxEqAbs(f32, c, 5.83095, epsilon)); } test "complex.cmath" { _ = @import("complex/abs.zig"); _ = @import("complex/acosh.zig"); _ = @import("complex/acos.zig"); _ = @import("complex/arg.zig"); _ = @import("complex/asinh.zig"); _ = @import("complex/asin.zig"); _ = @import("complex/atanh.zig"); _ = @import("complex/atan.zig"); _ = @import("complex/conj.zig"); _ = @import("complex/cosh.zig"); _ = @import("complex/cos.zig"); _ = @import("complex/exp.zig"); _ = @import("complex/log.zig"); _ = @import("complex/pow.zig"); _ = @import("complex/proj.zig"); _ = @import("complex/sinh.zig"); _ = @import("complex/sin.zig"); _ = @import("complex/sqrt.zig"); _ = @import("complex/tanh.zig"); _ = @import("complex/tan.zig"); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/frexp.zig
// Ported from musl, which is MIT licensed: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/frexpl.c // https://git.musl-libc.org/cgit/musl/tree/src/math/frexpf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/frexp.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; pub fn Frexp(comptime T: type) type { return struct { significand: T, exponent: i32, }; } /// Breaks x into a normalized fraction and an integral power of two. /// f == frac * 2^exp, with |frac| in the interval [0.5, 1). /// /// Special Cases: /// - frexp(+-0) = +-0, 0 /// - frexp(+-inf) = +-inf, 0 /// - frexp(nan) = nan, undefined pub fn frexp(x: anytype) Frexp(@TypeOf(x)) { const T = @TypeOf(x); return switch (T) { f32 => frexp32(x), f64 => frexp64(x), f128 => frexp128(x), else => @compileError("frexp not implemented for " ++ @typeName(T)), }; } // TODO: unify all these implementations using generics fn frexp32(x: f32) Frexp(f32) { var result: Frexp(f32) = undefined; var y = @as(u32, @bitCast(x)); const e = @as(i32, @intCast(y >> 23)) & 0xFF; if (e == 0) { if (x != 0) { // subnormal result = frexp32(x * 0x1.0p64); result.exponent -= 64; } else { // frexp(+-0) = (+-0, 0) result.significand = x; result.exponent = 0; } return result; } else if (e == 0xFF) { // frexp(nan) = (nan, undefined) result.significand = x; result.exponent = undefined; // frexp(+-inf) = (+-inf, 0) if (math.isInf(x)) { result.exponent = 0; } return result; } result.exponent = e - 0x7E; y &= 0x807FFFFF; y |= 0x3F000000; result.significand = @as(f32, @bitCast(y)); return result; } fn frexp64(x: f64) Frexp(f64) { var result: Frexp(f64) = undefined; var y = @as(u64, @bitCast(x)); const e = @as(i32, @intCast(y >> 52)) & 0x7FF; if (e == 0) { if (x != 0) { // subnormal result = frexp64(x * 0x1.0p64); result.exponent -= 64; } else { // frexp(+-0) = (+-0, 0) result.significand = x; result.exponent = 0; } return result; } else if (e == 0x7FF) { // frexp(nan) = (nan, undefined) result.significand = x; result.exponent = undefined; // frexp(+-inf) = (+-inf, 0) if (math.isInf(x)) { result.exponent = 0; } return result; } result.exponent = e - 0x3FE; y &= 0x800FFFFFFFFFFFFF; y |= 0x3FE0000000000000; result.significand = @as(f64, @bitCast(y)); return result; } fn frexp128(x: f128) Frexp(f128) { var result: Frexp(f128) = undefined; var y = @as(u128, @bitCast(x)); const e = @as(i32, @intCast(y >> 112)) & 0x7FFF; if (e == 0) { if (x != 0) { // subnormal result = frexp128(x * 0x1.0p120); result.exponent -= 120; } else { // frexp(+-0) = (+-0, 0) result.significand = x; result.exponent = 0; } return result; } else if (e == 0x7FFF) { // frexp(nan) = (nan, undefined) result.significand = x; result.exponent = undefined; // frexp(+-inf) = (+-inf, 0) if (math.isInf(x)) { result.exponent = 0; } return result; } result.exponent = e - 0x3FFE; y &= 0x8000FFFFFFFFFFFFFFFFFFFFFFFFFFFF; y |= 0x3FFE0000000000000000000000000000; result.significand = @as(f128, @bitCast(y)); return result; } test "type dispatch" { const a = frexp(@as(f32, 1.3)); const b = frexp32(1.3); try expect(a.significand == b.significand and a.exponent == b.exponent); const c = frexp(@as(f64, 1.3)); const d = frexp64(1.3); try expect(c.significand == d.significand and c.exponent == d.exponent); const e = frexp(@as(f128, 1.3)); const f = frexp128(1.3); try expect(e.significand == f.significand and e.exponent == f.exponent); } test "32" { const epsilon = 0.000001; var r: Frexp(f32) = undefined; r = frexp32(1.3); try expect(math.approxEqAbs(f32, r.significand, 0.65, epsilon) and r.exponent == 1); r = frexp32(78.0234); try expect(math.approxEqAbs(f32, r.significand, 0.609558, epsilon) and r.exponent == 7); } test "64" { const epsilon = 0.000001; var r: Frexp(f64) = undefined; r = frexp64(1.3); try expect(math.approxEqAbs(f64, r.significand, 0.65, epsilon) and r.exponent == 1); r = frexp64(78.0234); try expect(math.approxEqAbs(f64, r.significand, 0.609558, epsilon) and r.exponent == 7); } test "128" { const epsilon = 0.000001; var r: Frexp(f128) = undefined; r = frexp128(1.3); try expect(math.approxEqAbs(f128, r.significand, 0.65, epsilon) and r.exponent == 1); r = frexp128(78.0234); try expect(math.approxEqAbs(f128, r.significand, 0.609558, epsilon) and r.exponent == 7); } test "32 special" { var r: Frexp(f32) = undefined; r = frexp32(0.0); try expect(r.significand == 0.0 and r.exponent == 0); r = frexp32(-0.0); try expect(r.significand == -0.0 and r.exponent == 0); r = frexp32(math.inf(f32)); try expect(math.isPositiveInf(r.significand) and r.exponent == 0); r = frexp32(-math.inf(f32)); try expect(math.isNegativeInf(r.significand) and r.exponent == 0); r = frexp32(math.nan(f32)); try expect(math.isNan(r.significand)); } test "64 special" { var r: Frexp(f64) = undefined; r = frexp64(0.0); try expect(r.significand == 0.0 and r.exponent == 0); r = frexp64(-0.0); try expect(r.significand == -0.0 and r.exponent == 0); r = frexp64(math.inf(f64)); try expect(math.isPositiveInf(r.significand) and r.exponent == 0); r = frexp64(-math.inf(f64)); try expect(math.isNegativeInf(r.significand) and r.exponent == 0); r = frexp64(math.nan(f64)); try expect(math.isNan(r.significand)); } test "128 special" { var r: Frexp(f128) = undefined; r = frexp128(0.0); try expect(r.significand == 0.0 and r.exponent == 0); r = frexp128(-0.0); try expect(r.significand == -0.0 and r.exponent == 0); r = frexp128(math.inf(f128)); try expect(math.isPositiveInf(r.significand) and r.exponent == 0); r = frexp128(-math.inf(f128)); try expect(math.isNegativeInf(r.significand) and r.exponent == 0); r = frexp128(math.nan(f128)); try expect(math.isNan(r.significand)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/log2.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/log2f.c // https://git.musl-libc.org/cgit/musl/tree/src/math/log2.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns the base-2 logarithm of x. /// /// Special Cases: /// - log2(+inf) = +inf /// - log2(0) = -inf /// - log2(x) = nan if x < 0 /// - log2(nan) = nan pub fn log2(x: anytype) @TypeOf(x) { const T = @TypeOf(x); switch (@typeInfo(T)) { .ComptimeFloat => { return @as(comptime_float, log2_64(x)); }, .Float => { return switch (T) { f32 => log2_32(x), f64 => log2_64(x), else => @compileError("log2 not implemented for " ++ @typeName(T)), }; }, .ComptimeInt => comptime { var result = 0; var x_shifted = x; while (b: { x_shifted >>= 1; break :b x_shifted != 0; }) : (result += 1) {} return result; }, .Int => |IntType| switch (IntType.signedness) { .signed => @compileError("log2 not implemented for signed integers"), .unsigned => return math.log2_int(T, x), }, else => @compileError("log2 not implemented for " ++ @typeName(T)), } } pub fn log2_32(x_: f32) f32 { const ivln2hi: f32 = 1.4428710938e+00; const ivln2lo: f32 = -1.7605285393e-04; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; const Lg3: f32 = 0x91e9ee.0p-25; const Lg4: f32 = 0xf89e26.0p-26; var x = x_; var u = @as(u32, @bitCast(x)); var ix = u; var k: i32 = 0; // x < 2^(-126) if (ix < 0x00800000 or ix >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -math.inf(f32); } // log(-#) = nan if (ix >> 31 != 0) { return math.nan(f32); } k -= 25; x *= 0x1.0p25; ix = @as(u32, @bitCast(x)); } else if (ix >= 0x7F800000) { return x; } else if (ix == 0x3F800000) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; k += @as(i32, @intCast(ix >> 23)) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @as(f32, @bitCast(ix)); const f = x - 1.0; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * Lg4); const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; var hi = f - hfsq; u = @as(u32, @bitCast(hi)); u &= 0xFFFFF000; hi = @as(f32, @bitCast(u)); const lo = f - hi - hfsq + s * (hfsq + R); return (lo + hi) * ivln2lo + lo * ivln2hi + hi * ivln2hi + @as(f32, @floatFromInt(k)); } pub fn log2_64(x_: f64) f64 { const ivln2hi: f64 = 1.44269504072144627571e+00; const ivln2lo: f64 = 1.67517131648865118353e-10; const Lg1: f64 = 6.666666666666735130e-01; const Lg2: f64 = 3.999999999940941908e-01; const Lg3: f64 = 2.857142874366239149e-01; const Lg4: f64 = 2.222219843214978396e-01; const Lg5: f64 = 1.818357216161805012e-01; const Lg6: f64 = 1.531383769920937332e-01; const Lg7: f64 = 1.479819860511658591e-01; var x = x_; var ix = @as(u64, @bitCast(x)); var hx = @as(u32, @intCast(ix >> 32)); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { // log(+-0) = -inf if (ix << 1 == 0) { return -math.inf(f64); } // log(-#) = nan if (hx >> 31 != 0) { return math.nan(f64); } // subnormal, scale x k -= 54; x *= 0x1.0p54; hx = @as(u32, @intCast(@as(u64, @bitCast(x)) >> 32)); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { return 0; } // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; k += @as(i32, @intCast(hx >> 20)) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (@as(u64, hx) << 32) | (ix & 0xFFFFFFFF); x = @as(f64, @bitCast(ix)); const f = x - 1.0; const hfsq = 0.5 * f * f; const s = f / (2.0 + f); const z = s * s; const w = z * z; const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; // hi + lo = f - hfsq + s * (hfsq + R) ~ log(1 + f) var hi = f - hfsq; var hii = @as(u64, @bitCast(hi)); hii &= @as(u64, maxInt(u64)) << 32; hi = @as(f64, @bitCast(hii)); const lo = f - hi - hfsq + s * (hfsq + R); var val_hi = hi * ivln2hi; var val_lo = (lo + hi) * ivln2lo + lo * ivln2hi; // spadd(val_hi, val_lo, y) const y = @as(f64, @floatFromInt(k)); const ww = y + val_hi; val_lo += (y - ww) + val_hi; val_hi = ww; return val_lo + val_hi; } test "math.log2" { try expect(log2(@as(f32, 0.2)) == log2_32(0.2)); try expect(log2(@as(f64, 0.2)) == log2_64(0.2)); } test "math.log2_32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, log2_32(0.2), -2.321928, epsilon)); try expect(math.approxEqAbs(f32, log2_32(0.8923), -0.164399, epsilon)); try expect(math.approxEqAbs(f32, log2_32(1.5), 0.584962, epsilon)); try expect(math.approxEqAbs(f32, log2_32(37.45), 5.226894, epsilon)); try expect(math.approxEqAbs(f32, log2_32(123123.234375), 16.909744, epsilon)); } test "math.log2_64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, log2_64(0.2), -2.321928, epsilon)); try expect(math.approxEqAbs(f64, log2_64(0.8923), -0.164399, epsilon)); try expect(math.approxEqAbs(f64, log2_64(1.5), 0.584962, epsilon)); try expect(math.approxEqAbs(f64, log2_64(37.45), 5.226894, epsilon)); try expect(math.approxEqAbs(f64, log2_64(123123.234375), 16.909744, epsilon)); } test "math.log2_32.special" { try expect(math.isPositiveInf(log2_32(math.inf(f32)))); try expect(math.isNegativeInf(log2_32(0.0))); try expect(math.isNan(log2_32(-1.0))); try expect(math.isNan(log2_32(math.nan(f32)))); } test "math.log2_64.special" { try expect(math.isPositiveInf(log2_64(math.inf(f64)))); try expect(math.isNegativeInf(log2_64(0.0))); try expect(math.isNan(log2_64(-1.0))); try expect(math.isNan(log2_64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/atan.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/atanf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/atan.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the arc-tangent of x. /// /// Special Cases: /// - atan(+-0) = +-0 /// - atan(+-inf) = +-pi/2 pub fn atan(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => atan32(x), f64 => atan64(x), else => @compileError("atan not implemented for " ++ @typeName(T)), }; } fn atan32(x_: f32) f32 { const atanhi = [_]f32{ 4.6364760399e-01, // atan(0.5)hi 7.8539812565e-01, // atan(1.0)hi 9.8279368877e-01, // atan(1.5)hi 1.5707962513e+00, // atan(inf)hi }; const atanlo = [_]f32{ 5.0121582440e-09, // atan(0.5)lo 3.7748947079e-08, // atan(1.0)lo 3.4473217170e-08, // atan(1.5)lo 7.5497894159e-08, // atan(inf)lo }; const aT = [_]f32{ 3.3333328366e-01, -1.9999158382e-01, 1.4253635705e-01, -1.0648017377e-01, 6.1687607318e-02, }; var x = x_; var ix: u32 = @as(u32, @bitCast(x)); const sign = ix >> 31; ix &= 0x7FFFFFFF; // |x| >= 2^26 if (ix >= 0x4C800000) { if (math.isNan(x)) { return x; } else { const z = atanhi[3] + 0x1.0p-120; return if (sign != 0) -z else z; } } var id: ?usize = undefined; // |x| < 0.4375 if (ix < 0x3EE00000) { // |x| < 2^(-12) if (ix < 0x39800000) { if (ix < 0x00800000) { math.doNotOptimizeAway(x * x); } return x; } id = null; } else { x = math.fabs(x); // |x| < 1.1875 if (ix < 0x3F980000) { // 7/16 <= |x| < 11/16 if (ix < 0x3F300000) { id = 0; x = (2.0 * x - 1.0) / (2.0 + x); } // 11/16 <= |x| < 19/16 else { id = 1; x = (x - 1.0) / (x + 1.0); } } else { // |x| < 2.4375 if (ix < 0x401C0000) { id = 2; x = (x - 1.5) / (1.0 + 1.5 * x); } // 2.4375 <= |x| < 2^26 else { id = 3; x = -1.0 / x; } } } const z = x * x; const w = z * z; const s1 = z * (aT[0] + w * (aT[2] + w * aT[4])); const s2 = w * (aT[1] + w * aT[3]); if (id) |id_value| { const zz = atanhi[id_value] - ((x * (s1 + s2) - atanlo[id_value]) - x); return if (sign != 0) -zz else zz; } else { return x - x * (s1 + s2); } } fn atan64(x_: f64) f64 { const atanhi = [_]f64{ 4.63647609000806093515e-01, // atan(0.5)hi 7.85398163397448278999e-01, // atan(1.0)hi 9.82793723247329054082e-01, // atan(1.5)hi 1.57079632679489655800e+00, // atan(inf)hi }; const atanlo = [_]f64{ 2.26987774529616870924e-17, // atan(0.5)lo 3.06161699786838301793e-17, // atan(1.0)lo 1.39033110312309984516e-17, // atan(1.5)lo 6.12323399573676603587e-17, // atan(inf)lo }; const aT = [_]f64{ 3.33333333333329318027e-01, -1.99999999998764832476e-01, 1.42857142725034663711e-01, -1.11111104054623557880e-01, 9.09088713343650656196e-02, -7.69187620504482999495e-02, 6.66107313738753120669e-02, -5.83357013379057348645e-02, 4.97687799461593236017e-02, -3.65315727442169155270e-02, 1.62858201153657823623e-02, }; var x = x_; var ux = @as(u64, @bitCast(x)); var ix = @as(u32, @intCast(ux >> 32)); const sign = ix >> 31; ix &= 0x7FFFFFFF; // |x| >= 2^66 if (ix >= 0x44100000) { if (math.isNan(x)) { return x; } else { const z = atanhi[3] + 0x1.0p-120; return if (sign != 0) -z else z; } } var id: ?usize = undefined; // |x| < 0.4375 if (ix < 0x3DFC0000) { // |x| < 2^(-27) if (ix < 0x3E400000) { if (ix < 0x00100000) { math.doNotOptimizeAway(@as(f32, @floatCast(x))); } return x; } id = null; } else { x = math.fabs(x); // |x| < 1.1875 if (ix < 0x3FF30000) { // 7/16 <= |x| < 11/16 if (ix < 0x3FE60000) { id = 0; x = (2.0 * x - 1.0) / (2.0 + x); } // 11/16 <= |x| < 19/16 else { id = 1; x = (x - 1.0) / (x + 1.0); } } else { // |x| < 2.4375 if (ix < 0x40038000) { id = 2; x = (x - 1.5) / (1.0 + 1.5 * x); } // 2.4375 <= |x| < 2^66 else { id = 3; x = -1.0 / x; } } } const z = x * x; const w = z * z; const s1 = z * (aT[0] + w * (aT[2] + w * (aT[4] + w * (aT[6] + w * (aT[8] + w * aT[10]))))); const s2 = w * (aT[1] + w * (aT[3] + w * (aT[5] + w * (aT[7] + w * aT[9])))); if (id) |id_value| { const zz = atanhi[id_value] - ((x * (s1 + s2) - atanlo[id_value]) - x); return if (sign != 0) -zz else zz; } else { return x - x * (s1 + s2); } } test "math.atan" { try expect(@as(u32, @bitCast(atan(@as(f32, 0.2)))) == @as(u32, @bitCast(atan32(0.2)))); try expect(atan(@as(f64, 0.2)) == atan64(0.2)); } test "math.atan32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, atan32(0.2), 0.197396, epsilon)); try expect(math.approxEqAbs(f32, atan32(-0.2), -0.197396, epsilon)); try expect(math.approxEqAbs(f32, atan32(0.3434), 0.330783, epsilon)); try expect(math.approxEqAbs(f32, atan32(0.8923), 0.728545, epsilon)); try expect(math.approxEqAbs(f32, atan32(1.5), 0.982794, epsilon)); } test "math.atan64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, atan64(0.2), 0.197396, epsilon)); try expect(math.approxEqAbs(f64, atan64(-0.2), -0.197396, epsilon)); try expect(math.approxEqAbs(f64, atan64(0.3434), 0.330783, epsilon)); try expect(math.approxEqAbs(f64, atan64(0.8923), 0.728545, epsilon)); try expect(math.approxEqAbs(f64, atan64(1.5), 0.982794, epsilon)); } test "math.atan32.special" { const epsilon = 0.000001; try expect(atan32(0.0) == 0.0); try expect(atan32(-0.0) == -0.0); try expect(math.approxEqAbs(f32, atan32(math.inf(f32)), math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f32, atan32(-math.inf(f32)), -math.pi / 2.0, epsilon)); } test "math.atan64.special" { const epsilon = 0.000001; try expect(atan64(0.0) == 0.0); try expect(atan64(-0.0) == -0.0); try expect(math.approxEqAbs(f64, atan64(math.inf(f64)), math.pi / 2.0, epsilon)); try expect(math.approxEqAbs(f64, atan64(-math.inf(f64)), -math.pi / 2.0, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/exp.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/expf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/exp.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns e raised to the power of x (e^x). /// /// Special Cases: /// - exp(+inf) = +inf /// - exp(nan) = nan pub fn exp(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => exp32(x), f64 => exp64(x), else => @compileError("exp not implemented for " ++ @typeName(T)), }; } fn exp32(x_: f32) f32 { const half = [_]f32{ 0.5, -0.5 }; const ln2hi = 6.9314575195e-1; const ln2lo = 1.4286067653e-6; const invln2 = 1.4426950216e+0; const P1 = 1.6666625440e-1; const P2 = -2.7667332906e-3; var x = x_; var hx = @as(u32, @bitCast(x)); const sign = @as(i32, @intCast(hx >> 31)); hx &= 0x7FFFFFFF; if (math.isNan(x)) { return x; } // |x| >= -87.33655 or nan if (hx >= 0x42AEAC50) { // nan if (hx > 0x7F800000) { return x; } // x >= 88.722839 if (hx >= 0x42b17218 and sign == 0) { return x * 0x1.0p127; } if (sign != 0) { math.doNotOptimizeAway(-0x1.0p-149 / x); // overflow // x <= -103.972084 if (hx >= 0x42CFF1B5) { return 0; } } } var k: i32 = undefined; var hi: f32 = undefined; var lo: f32 = undefined; // |x| > 0.5 * ln2 if (hx > 0x3EB17218) { // |x| > 1.5 * ln2 if (hx > 0x3F851592) { k = @as(i32, @intFromFloat(invln2 * x + half[@as(usize, @intCast(sign))])); } else { k = 1 - sign - sign; } const fk = @as(f32, @floatFromInt(k)); hi = x - fk * ln2hi; lo = fk * ln2lo; x = hi - lo; } // |x| > 2^(-14) else if (hx > 0x39000000) { k = 0; hi = x; lo = 0; } else { math.doNotOptimizeAway(0x1.0p127 + x); // inexact return 1 + x; } const xx = x * x; const c = x - xx * (P1 + xx * P2); const y = 1 + (x * c / (2 - c) - lo + hi); if (k == 0) { return y; } else { return math.scalbn(y, k); } } fn exp64(x_: f64) f64 { const half = [_]f64{ 0.5, -0.5 }; const ln2hi: f64 = 6.93147180369123816490e-01; const ln2lo: f64 = 1.90821492927058770002e-10; const invln2: f64 = 1.44269504088896338700e+00; const P1: f64 = 1.66666666666666019037e-01; const P2: f64 = -2.77777777770155933842e-03; const P3: f64 = 6.61375632143793436117e-05; const P4: f64 = -1.65339022054652515390e-06; const P5: f64 = 4.13813679705723846039e-08; var x = x_; var ux = @as(u64, @bitCast(x)); var hx = ux >> 32; const sign = @as(i32, @intCast(hx >> 31)); hx &= 0x7FFFFFFF; if (math.isNan(x)) { return x; } // |x| >= 708.39 or nan if (hx >= 0x4086232B) { // nan if (hx > 0x7FF00000) { return x; } if (x > 709.782712893383973096) { // overflow if x != inf if (!math.isInf(x)) { math.raiseOverflow(); } return math.inf(f64); } if (x < -708.39641853226410622) { // underflow if x != -inf // math.doNotOptimizeAway(@as(f32, -0x1.0p-149 / x)); if (x < -745.13321910194110842) { return 0; } } } // argument reduction var k: i32 = undefined; var hi: f64 = undefined; var lo: f64 = undefined; // |x| > 0.5 * ln2 if (hx > 0x3EB17218) { // |x| >= 1.5 * ln2 if (hx > 0x3FF0A2B2) { k = @as(i32, @intFromFloat(invln2 * x + half[@as(usize, @intCast(sign))])); } else { k = 1 - sign - sign; } const dk = @as(f64, @floatFromInt(k)); hi = x - dk * ln2hi; lo = dk * ln2lo; x = hi - lo; } // |x| > 2^(-28) else if (hx > 0x3E300000) { k = 0; hi = x; lo = 0; } else { // inexact if x != 0 // math.doNotOptimizeAway(0x1.0p1023 + x); return 1 + x; } const xx = x * x; const c = x - xx * (P1 + xx * (P2 + xx * (P3 + xx * (P4 + xx * P5)))); const y = 1 + (x * c / (2 - c) - lo + hi); if (k == 0) { return y; } else { return math.scalbn(y, k); } } test "math.exp" { try expect(exp(@as(f32, 0.0)) == exp32(0.0)); try expect(exp(@as(f64, 0.0)) == exp64(0.0)); } test "math.exp32" { const epsilon = 0.000001; try expect(exp32(0.0) == 1.0); try expect(math.approxEqAbs(f32, exp32(0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f32, exp32(0.2), 1.221403, epsilon)); try expect(math.approxEqAbs(f32, exp32(0.8923), 2.440737, epsilon)); try expect(math.approxEqAbs(f32, exp32(1.5), 4.481689, epsilon)); } test "math.exp64" { const epsilon = 0.000001; try expect(exp64(0.0) == 1.0); try expect(math.approxEqAbs(f64, exp64(0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f64, exp64(0.2), 1.221403, epsilon)); try expect(math.approxEqAbs(f64, exp64(0.8923), 2.440737, epsilon)); try expect(math.approxEqAbs(f64, exp64(1.5), 4.481689, epsilon)); } test "math.exp32.special" { try expect(math.isPositiveInf(exp32(math.inf(f32)))); try expect(math.isNan(exp32(math.nan(f32)))); } test "math.exp64.special" { try expect(math.isPositiveInf(exp64(math.inf(f64)))); try expect(math.isNan(exp64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/cbrt.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/cbrtf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/cbrt.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the cube root of x. /// /// Special Cases: /// - cbrt(+-0) = +-0 /// - cbrt(+-inf) = +-inf /// - cbrt(nan) = nan pub fn cbrt(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => cbrt32(x), f64 => cbrt64(x), else => @compileError("cbrt not implemented for " ++ @typeName(T)), }; } fn cbrt32(x: f32) f32 { const B1: u32 = 709958130; // (127 - 127.0 / 3 - 0.03306235651) * 2^23 const B2: u32 = 642849266; // (127 - 127.0 / 3 - 24 / 3 - 0.03306235651) * 2^23 var u = @as(u32, @bitCast(x)); var hx = u & 0x7FFFFFFF; // cbrt(nan, inf) = itself if (hx >= 0x7F800000) { return x + x; } // cbrt to ~5bits if (hx < 0x00800000) { // cbrt(+-0) = itself if (hx == 0) { return x; } u = @as(u32, @bitCast(x * 0x1.0p24)); hx = u & 0x7FFFFFFF; hx = hx / 3 + B2; } else { hx = hx / 3 + B1; } u &= 0x80000000; u |= hx; // first step newton to 16 bits var t: f64 = @as(f32, @bitCast(u)); var r: f64 = t * t * t; t = t * (@as(f64, x) + x + r) / (x + r + r); // second step newton to 47 bits r = t * t * t; t = t * (@as(f64, x) + x + r) / (x + r + r); return @as(f32, @floatCast(t)); } fn cbrt64(x: f64) f64 { const B1: u32 = 715094163; // (1023 - 1023 / 3 - 0.03306235651 * 2^20 const B2: u32 = 696219795; // (1023 - 1023 / 3 - 54 / 3 - 0.03306235651 * 2^20 // |1 / cbrt(x) - p(x)| < 2^(23.5) const P0: f64 = 1.87595182427177009643; const P1: f64 = -1.88497979543377169875; const P2: f64 = 1.621429720105354466140; const P3: f64 = -0.758397934778766047437; const P4: f64 = 0.145996192886612446982; var u = @as(u64, @bitCast(x)); var hx = @as(u32, @intCast(u >> 32)) & 0x7FFFFFFF; // cbrt(nan, inf) = itself if (hx >= 0x7FF00000) { return x + x; } // cbrt to ~5bits if (hx < 0x00100000) { u = @as(u64, @bitCast(x * 0x1.0p54)); hx = @as(u32, @intCast(u >> 32)) & 0x7FFFFFFF; // cbrt(0) is itself if (hx == 0) { return 0; } hx = hx / 3 + B2; } else { hx = hx / 3 + B1; } u &= 1 << 63; u |= @as(u64, hx) << 32; var t = @as(f64, @bitCast(u)); // cbrt to 23 bits // cbrt(x) = t * cbrt(x / t^3) ~= t * P(t^3 / x) var r = (t * t) * (t / x); t = t * ((P0 + r * (P1 + r * P2)) + ((r * r) * r) * (P3 + r * P4)); // Round t away from 0 to 23 bits u = @as(u64, @bitCast(t)); u = (u + 0x80000000) & 0xFFFFFFFFC0000000; t = @as(f64, @bitCast(u)); // one step newton to 53 bits const s = t * t; var q = x / s; var w = t + t; q = (q - t) / (w + q); return t + t * q; } test "math.cbrt" { try expect(cbrt(@as(f32, 0.0)) == cbrt32(0.0)); try expect(cbrt(@as(f64, 0.0)) == cbrt64(0.0)); } test "math.cbrt32" { const epsilon = 0.000001; try expect(cbrt32(0.0) == 0.0); try expect(math.approxEqAbs(f32, cbrt32(0.2), 0.584804, epsilon)); try expect(math.approxEqAbs(f32, cbrt32(0.8923), 0.962728, epsilon)); try expect(math.approxEqAbs(f32, cbrt32(1.5), 1.144714, epsilon)); try expect(math.approxEqAbs(f32, cbrt32(37.45), 3.345676, epsilon)); try expect(math.approxEqAbs(f32, cbrt32(123123.234375), 49.748501, epsilon)); } test "math.cbrt64" { const epsilon = 0.000001; try expect(cbrt64(0.0) == 0.0); try expect(math.approxEqAbs(f64, cbrt64(0.2), 0.584804, epsilon)); try expect(math.approxEqAbs(f64, cbrt64(0.8923), 0.962728, epsilon)); try expect(math.approxEqAbs(f64, cbrt64(1.5), 1.144714, epsilon)); try expect(math.approxEqAbs(f64, cbrt64(37.45), 3.345676, epsilon)); try expect(math.approxEqAbs(f64, cbrt64(123123.234375), 49.748501, epsilon)); } test "math.cbrt.special" { try expect(cbrt32(0.0) == 0.0); try expect(cbrt32(-0.0) == -0.0); try expect(math.isPositiveInf(cbrt32(math.inf(f32)))); try expect(math.isNegativeInf(cbrt32(-math.inf(f32)))); try expect(math.isNan(cbrt32(math.nan(f32)))); } test "math.cbrt64.special" { try expect(cbrt64(0.0) == 0.0); try expect(cbrt64(-0.0) == -0.0); try expect(math.isPositiveInf(cbrt64(math.inf(f64)))); try expect(math.isNegativeInf(cbrt64(-math.inf(f64)))); try expect(math.isNan(cbrt64(math.nan(f64)))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/log.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/logf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/log.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the logarithm of x for the provided base. pub fn log(comptime T: type, base: T, x: T) T { if (base == 2) { return math.log2(x); } else if (base == 10) { return math.log10(x); } else if ((@typeInfo(T) == .Float or @typeInfo(T) == .ComptimeFloat) and base == math.e) { return math.ln(x); } const float_base = math.lossyCast(f64, base); switch (@typeInfo(T)) { .ComptimeFloat => { return @as(comptime_float, math.ln(@as(f64, x)) / math.ln(float_base)); }, .ComptimeInt => { return @as(comptime_int, math.floor(math.ln(@as(f64, x)) / math.ln(float_base))); }, // TODO implement integer log without using float math .Int => |IntType| switch (IntType.signedness) { .signed => @compileError("log not implemented for signed integers"), .unsigned => return @as(T, @intFromFloat(math.floor(math.ln(@as(f64, @floatFromInt(x))) / math.ln(float_base)))), }, .Float => { switch (T) { f32 => return @as(f32, @floatCast(math.ln(@as(f64, x)) / math.ln(float_base))), f64 => return math.ln(x) / math.ln(float_base), else => @compileError("log not implemented for " ++ @typeName(T)), } }, else => { @compileError("log expects integer or float, found '" ++ @typeName(T) ++ "'"); }, } } test "math.log integer" { try expect(log(u8, 2, 0x1) == 0); try expect(log(u8, 2, 0x2) == 1); try expect(log(u16, 2, 0x72) == 6); try expect(log(u32, 2, 0xFFFFFF) == 23); try expect(log(u64, 2, 0x7FF0123456789ABC) == 62); } test "math.log float" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, log(f32, 6, 0.23947), -0.797723, epsilon)); try expect(math.approxEqAbs(f32, log(f32, 89, 0.23947), -0.318432, epsilon)); try expect(math.approxEqAbs(f64, log(f64, 123897, 12389216414), 1.981724596, epsilon)); } test "math.log float_special" { try expect(log(f32, 2, 0.2301974) == math.log2(@as(f32, 0.2301974))); try expect(log(f32, 10, 0.2301974) == math.log10(@as(f32, 0.2301974))); try expect(log(f64, 2, 213.23019799993) == math.log2(@as(f64, 213.23019799993))); try expect(log(f64, 10, 213.23019799993) == math.log10(@as(f64, 213.23019799993))); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/asin.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; // Returns the arc-sine of z. pub fn asin(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); const x = z.re; const y = z.im; const p = Complex(T).init(1.0 - (x - y) * (x + y), -2.0 * x * y); const q = Complex(T).init(-y, x); const r = cmath.log(q.add(cmath.sqrt(p))); return Complex(T).init(r.im, -r.re); } const epsilon = 0.0001; test "complex.casin" { const a = Complex(f32).init(5, 3); const c = asin(a); try testing.expect(math.approxEqAbs(f32, c.re, 1.023822, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 2.452914, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/sinh.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/complex/csinhf.c // https://git.musl-libc.org/cgit/musl/tree/src/complex/csinh.c const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; const ldexp_cexp = @import("ldexp.zig").ldexp_cexp; /// Returns the hyperbolic sine of z. pub fn sinh(z: anytype) @TypeOf(z) { const T = @TypeOf(z.re); return switch (T) { f32 => sinh32(z), f64 => sinh64(z), else => @compileError("tan not implemented for " ++ @typeName(z)), }; } fn sinh32(z: Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; const hx = @as(u32, @bitCast(x)); const ix = hx & 0x7fffffff; const hy = @as(u32, @bitCast(y)); const iy = hy & 0x7fffffff; if (ix < 0x7f800000 and iy < 0x7f800000) { if (iy == 0) { return Complex(f32).init(math.sinh(x), y); } // small x: normal case if (ix < 0x41100000) { return Complex(f32).init(math.sinh(x) * math.cos(y), math.cosh(x) * math.sin(y)); } // |x|>= 9, so cosh(x) ~= exp(|x|) if (ix < 0x42b17218) { // x < 88.7: exp(|x|) won't overflow const h = math.exp(math.fabs(x)) * 0.5; return Complex(f32).init(math.copysign(f32, h, x) * math.cos(y), h * math.sin(y)); } // x < 192.7: scale to avoid overflow else if (ix < 0x4340b1e7) { const v = Complex(f32).init(math.fabs(x), y); const r = ldexp_cexp(v, -1); return Complex(f32).init(r.re * math.copysign(f32, 1, x), r.im); } // x >= 192.7: result always overflows else { const h = 0x1p127 * x; return Complex(f32).init(h * math.cos(y), h * h * math.sin(y)); } } if (ix == 0 and iy >= 0x7f800000) { return Complex(f32).init(math.copysign(f32, 0, x * (y - y)), y - y); } if (iy == 0 and ix >= 0x7f800000) { if (hx & 0x7fffff == 0) { return Complex(f32).init(x, y); } return Complex(f32).init(x, math.copysign(f32, 0, y)); } if (ix < 0x7f800000 and iy >= 0x7f800000) { return Complex(f32).init(y - y, x * (y - y)); } if (ix >= 0x7f800000 and (hx & 0x7fffff) == 0) { if (iy >= 0x7f800000) { return Complex(f32).init(x * x, x * (y - y)); } return Complex(f32).init(x * math.cos(y), math.inf_f32 * math.sin(y)); } return Complex(f32).init((x * x) * (y - y), (x + x) * (y - y)); } fn sinh64(z: Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; const fx = @as(u64, @bitCast(x)); const hx = @as(u32, @intCast(fx >> 32)); const lx = @as(u32, @truncate(fx)); const ix = hx & 0x7fffffff; const fy = @as(u64, @bitCast(y)); const hy = @as(u32, @intCast(fy >> 32)); const ly = @as(u32, @truncate(fy)); const iy = hy & 0x7fffffff; if (ix < 0x7ff00000 and iy < 0x7ff00000) { if (iy | ly == 0) { return Complex(f64).init(math.sinh(x), y); } // small x: normal case if (ix < 0x40360000) { return Complex(f64).init(math.sinh(x) * math.cos(y), math.cosh(x) * math.sin(y)); } // |x|>= 22, so cosh(x) ~= exp(|x|) if (ix < 0x40862e42) { // x < 710: exp(|x|) won't overflow const h = math.exp(math.fabs(x)) * 0.5; return Complex(f64).init(math.copysign(f64, h, x) * math.cos(y), h * math.sin(y)); } // x < 1455: scale to avoid overflow else if (ix < 0x4096bbaa) { const v = Complex(f64).init(math.fabs(x), y); const r = ldexp_cexp(v, -1); return Complex(f64).init(r.re * math.copysign(f64, 1, x), r.im); } // x >= 1455: result always overflows else { const h = 0x1p1023 * x; return Complex(f64).init(h * math.cos(y), h * h * math.sin(y)); } } if (ix | lx == 0 and iy >= 0x7ff00000) { return Complex(f64).init(math.copysign(f64, 0, x * (y - y)), y - y); } if (iy | ly == 0 and ix >= 0x7ff00000) { if ((hx & 0xfffff) | lx == 0) { return Complex(f64).init(x, y); } return Complex(f64).init(x, math.copysign(f64, 0, y)); } if (ix < 0x7ff00000 and iy >= 0x7ff00000) { return Complex(f64).init(y - y, x * (y - y)); } if (ix >= 0x7ff00000 and (hx & 0xfffff) | lx == 0) { if (iy >= 0x7ff00000) { return Complex(f64).init(x * x, x * (y - y)); } return Complex(f64).init(x * math.cos(y), math.inf_f64 * math.sin(y)); } return Complex(f64).init((x * x) * (y - y), (x + x) * (y - y)); } const epsilon = 0.0001; test "complex.csinh32" { const a = Complex(f32).init(5, 3); const c = sinh(a); try testing.expect(math.approxEqAbs(f32, c.re, -73.460617, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 10.472508, epsilon)); } test "complex.csinh64" { const a = Complex(f64).init(5, 3); const c = sinh(a); try testing.expect(math.approxEqAbs(f64, c.re, -73.460617, epsilon)); try testing.expect(math.approxEqAbs(f64, c.im, 10.472508, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/sqrt.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/complex/csqrtf.c // https://git.musl-libc.org/cgit/musl/tree/src/complex/csqrt.c const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the square root of z. The real and imaginary parts of the result have the same sign /// as the imaginary part of z. pub fn sqrt(z: anytype) @TypeOf(z) { const T = @TypeOf(z.re); return switch (T) { f32 => sqrt32(z), f64 => sqrt64(z), else => @compileError("sqrt not implemented for " ++ @typeName(T)), }; } fn sqrt32(z: Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; if (x == 0 and y == 0) { return Complex(f32).init(0, y); } if (math.isInf(y)) { return Complex(f32).init(math.inf(f32), y); } if (math.isNan(x)) { // raise invalid if y is not nan const t = (y - y) / (y - y); return Complex(f32).init(x, t); } if (math.isInf(x)) { // sqrt(inf + i nan) = inf + nan i // sqrt(inf + iy) = inf + i0 // sqrt(-inf + i nan) = nan +- inf i // sqrt(-inf + iy) = 0 + inf i if (math.signbit(x)) { return Complex(f32).init(math.fabs(x - y), math.copysign(f32, x, y)); } else { return Complex(f32).init(x, math.copysign(f32, y - y, y)); } } // y = nan special case is handled fine below // double-precision avoids overflow with correct rounding. const dx = @as(f64, x); const dy = @as(f64, y); if (dx >= 0) { const t = math.sqrt((dx + math.hypot(f64, dx, dy)) * 0.5); return Complex(f32).init( @as(f32, @floatCast(t)), @as(f32, @floatCast(dy / (2.0 * t))), ); } else { const t = math.sqrt((-dx + math.hypot(f64, dx, dy)) * 0.5); return Complex(f32).init( @as(f32, @floatCast(math.fabs(y) / (2.0 * t))), @as(f32, @floatCast(math.copysign(f64, t, y))), ); } } fn sqrt64(z: Complex(f64)) Complex(f64) { // may encounter overflow for im,re >= DBL_MAX / (1 + sqrt(2)) const threshold = 0x1.a827999fcef32p+1022; var x = z.re; var y = z.im; if (x == 0 and y == 0) { return Complex(f64).init(0, y); } if (math.isInf(y)) { return Complex(f64).init(math.inf(f64), y); } if (math.isNan(x)) { // raise invalid if y is not nan const t = (y - y) / (y - y); return Complex(f64).init(x, t); } if (math.isInf(x)) { // sqrt(inf + i nan) = inf + nan i // sqrt(inf + iy) = inf + i0 // sqrt(-inf + i nan) = nan +- inf i // sqrt(-inf + iy) = 0 + inf i if (math.signbit(x)) { return Complex(f64).init(math.fabs(x - y), math.copysign(f64, x, y)); } else { return Complex(f64).init(x, math.copysign(f64, y - y, y)); } } // y = nan special case is handled fine below // scale to avoid overflow var scale = false; if (math.fabs(x) >= threshold or math.fabs(y) >= threshold) { x *= 0.25; y *= 0.25; scale = true; } var result: Complex(f64) = undefined; if (x >= 0) { const t = math.sqrt((x + math.hypot(f64, x, y)) * 0.5); result = Complex(f64).init(t, y / (2.0 * t)); } else { const t = math.sqrt((-x + math.hypot(f64, x, y)) * 0.5); result = Complex(f64).init(math.fabs(y) / (2.0 * t), math.copysign(f64, t, y)); } if (scale) { result.re *= 2; result.im *= 2; } return result; } const epsilon = 0.0001; test "complex.csqrt32" { const a = Complex(f32).init(5, 3); const c = sqrt(a); try testing.expect(math.approxEqAbs(f32, c.re, 2.327117, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 0.644574, epsilon)); } test "complex.csqrt64" { const a = Complex(f64).init(5, 3); const c = sqrt(a); try testing.expect(math.approxEqAbs(f64, c.re, 2.3271175190399496, epsilon)); try testing.expect(math.approxEqAbs(f64, c.im, 0.6445742373246469, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/tanh.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/complex/ctanhf.c // https://git.musl-libc.org/cgit/musl/tree/src/complex/ctanh.c const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the hyperbolic tangent of z. pub fn tanh(z: anytype) @TypeOf(z) { const T = @TypeOf(z.re); return switch (T) { f32 => tanh32(z), f64 => tanh64(z), else => @compileError("tan not implemented for " ++ @typeName(z)), }; } fn tanh32(z: Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; const hx = @as(u32, @bitCast(x)); const ix = hx & 0x7fffffff; if (ix >= 0x7f800000) { if (ix & 0x7fffff != 0) { const r = if (y == 0) y else x * y; return Complex(f32).init(x, r); } const xx = @as(f32, @bitCast(hx - 0x40000000)); const r = if (math.isInf(y)) y else math.sin(y) * math.cos(y); return Complex(f32).init(xx, math.copysign(f32, 0, r)); } if (!math.isFinite(y)) { const r = if (ix != 0) y - y else x; return Complex(f32).init(r, y - y); } // x >= 11 if (ix >= 0x41300000) { const exp_mx = math.exp(-math.fabs(x)); return Complex(f32).init(math.copysign(f32, 1, x), 4 * math.sin(y) * math.cos(y) * exp_mx * exp_mx); } // Kahan's algorithm const t = math.tan(y); const beta = 1.0 + t * t; const s = math.sinh(x); const rho = math.sqrt(1 + s * s); const den = 1 + beta * s * s; return Complex(f32).init((beta * rho * s) / den, t / den); } fn tanh64(z: Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; const fx = @as(u64, @bitCast(x)); // TODO: zig should allow this conversion implicitly because it can notice that the value necessarily // fits in range. const hx = @as(u32, @intCast(fx >> 32)); const lx = @as(u32, @truncate(fx)); const ix = hx & 0x7fffffff; if (ix >= 0x7ff00000) { if ((ix & 0x7fffff) | lx != 0) { const r = if (y == 0) y else x * y; return Complex(f64).init(x, r); } const xx = @as(f64, @bitCast((@as(u64, hx - 0x40000000) << 32) | lx)); const r = if (math.isInf(y)) y else math.sin(y) * math.cos(y); return Complex(f64).init(xx, math.copysign(f64, 0, r)); } if (!math.isFinite(y)) { const r = if (ix != 0) y - y else x; return Complex(f64).init(r, y - y); } // x >= 22 if (ix >= 0x40360000) { const exp_mx = math.exp(-math.fabs(x)); return Complex(f64).init(math.copysign(f64, 1, x), 4 * math.sin(y) * math.cos(y) * exp_mx * exp_mx); } // Kahan's algorithm const t = math.tan(y); const beta = 1.0 + t * t; const s = math.sinh(x); const rho = math.sqrt(1 + s * s); const den = 1 + beta * s * s; return Complex(f64).init((beta * rho * s) / den, t / den); } const epsilon = 0.0001; test "complex.ctanh32" { const a = Complex(f32).init(5, 3); const c = tanh(a); try testing.expect(math.approxEqAbs(f32, c.re, 0.999913, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, -0.000025, epsilon)); } test "complex.ctanh64" { const a = Complex(f64).init(5, 3); const c = tanh(a); try testing.expect(math.approxEqAbs(f64, c.re, 0.999913, epsilon)); try testing.expect(math.approxEqAbs(f64, c.im, -0.000025, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/ldexp.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/complex/__cexpf.c // https://git.musl-libc.org/cgit/musl/tree/src/complex/__cexp.c const std = @import("../../std.zig"); const debug = std.debug; const math = std.math; const testing = std.testing; const cmath = math.complex; const Complex = cmath.Complex; /// Returns exp(z) scaled to avoid overflow. pub fn ldexp_cexp(z: anytype, expt: i32) @TypeOf(z) { const T = @TypeOf(z.re); return switch (T) { f32 => ldexp_cexp32(z, expt), f64 => ldexp_cexp64(z, expt), else => unreachable, }; } fn frexp_exp32(x: f32, expt: *i32) f32 { const k = 235; // reduction constant const kln2 = 162.88958740; // k * ln2 const exp_x = math.exp(x - kln2); const hx = @as(u32, @bitCast(exp_x)); // TODO zig should allow this cast implicitly because it should know the value is in range expt.* = @as(i32, @intCast(hx >> 23)) - (0x7f + 127) + k; return @as(f32, @bitCast((hx & 0x7fffff) | ((0x7f + 127) << 23))); } fn ldexp_cexp32(z: Complex(f32), expt: i32) Complex(f32) { var ex_expt: i32 = undefined; const exp_x = frexp_exp32(z.re, &ex_expt); const exptf = expt + ex_expt; const half_expt1 = @divTrunc(exptf, 2); const scale1 = @as(f32, @bitCast((0x7f + half_expt1) << 23)); const half_expt2 = exptf - half_expt1; const scale2 = @as(f32, @bitCast((0x7f + half_expt2) << 23)); return Complex(f32).init( math.cos(z.im) * exp_x * scale1 * scale2, math.sin(z.im) * exp_x * scale1 * scale2, ); } fn frexp_exp64(x: f64, expt: *i32) f64 { const k = 1799; // reduction constant const kln2 = 1246.97177782734161156; // k * ln2 const exp_x = math.exp(x - kln2); const fx = @as(u64, @bitCast(exp_x)); const hx = @as(u32, @intCast(fx >> 32)); const lx = @as(u32, @truncate(fx)); expt.* = @as(i32, @intCast(hx >> 20)) - (0x3ff + 1023) + k; const high_word = (hx & 0xfffff) | ((0x3ff + 1023) << 20); return @as(f64, @bitCast((@as(u64, high_word) << 32) | lx)); } fn ldexp_cexp64(z: Complex(f64), expt: i32) Complex(f64) { var ex_expt: i32 = undefined; const exp_x = frexp_exp64(z.re, &ex_expt); const exptf = @as(i64, expt + ex_expt); const half_expt1 = @divTrunc(exptf, 2); const scale1 = @as(f64, @bitCast((0x3ff + half_expt1) << (20 + 32))); const half_expt2 = exptf - half_expt1; const scale2 = @as(f64, @bitCast((0x3ff + half_expt2) << (20 + 32))); return Complex(f64).init( math.cos(z.im) * exp_x * scale1 * scale2, math.sin(z.im) * exp_x * scale1 * scale2, ); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/atanh.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the hyperbolic arc-tangent of z. pub fn atanh(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); const q = Complex(T).init(-z.im, z.re); const r = cmath.atan(q); return Complex(T).init(r.im, -r.re); } const epsilon = 0.0001; test "complex.catanh" { const a = Complex(f32).init(5, 3); const c = atanh(a); try testing.expect(math.approxEqAbs(f32, c.re, 0.146947, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 1.480870, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/acosh.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the hyperbolic arc-cosine of z. pub fn acosh(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); const q = cmath.acos(z); return Complex(T).init(-q.im, q.re); } const epsilon = 0.0001; test "complex.cacosh" { const a = Complex(f32).init(5, 3); const c = acosh(a); try testing.expect(math.approxEqAbs(f32, c.re, 2.452914, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 0.546975, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/tan.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the tanget of z. pub fn tan(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); const q = Complex(T).init(-z.im, z.re); const r = cmath.tanh(q); return Complex(T).init(r.im, -r.re); } const epsilon = 0.0001; test "complex.ctan" { const a = Complex(f32).init(5, 3); const c = tan(a); try testing.expect(math.approxEqAbs(f32, c.re, -0.002708233, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 1.004165, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/abs.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the absolute value (modulus) of z. pub fn abs(z: anytype) @TypeOf(z.re) { const T = @TypeOf(z.re); return math.hypot(T, z.re, z.im); } const epsilon = 0.0001; test "complex.cabs" { const a = Complex(f32).init(5, 3); const c = abs(a); try testing.expect(math.approxEqAbs(f32, c, 5.83095, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/proj.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the projection of z onto the riemann sphere. pub fn proj(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); if (math.isInf(z.re) or math.isInf(z.im)) { return Complex(T).init(math.inf(T), math.copysign(T, 0, z.re)); } return Complex(T).init(z.re, z.im); } const epsilon = 0.0001; test "complex.cproj" { const a = Complex(f32).init(5, 3); const c = proj(a); try testing.expect(c.re == 5 and c.im == 3); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/cos.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the cosine of z. pub fn cos(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); const p = Complex(T).init(-z.im, z.re); return cmath.cosh(p); } const epsilon = 0.0001; test "complex.ccos" { const a = Complex(f32).init(5, 3); const c = cos(a); try testing.expect(math.approxEqAbs(f32, c.re, 2.855815, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 9.606383, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/cosh.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/complex/ccoshf.c // https://git.musl-libc.org/cgit/musl/tree/src/complex/ccosh.c const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; const ldexp_cexp = @import("ldexp.zig").ldexp_cexp; /// Returns the hyperbolic arc-cosine of z. pub fn cosh(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); return switch (T) { f32 => cosh32(z), f64 => cosh64(z), else => @compileError("cosh not implemented for " ++ @typeName(z)), }; } fn cosh32(z: Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; const hx = @as(u32, @bitCast(x)); const ix = hx & 0x7fffffff; const hy = @as(u32, @bitCast(y)); const iy = hy & 0x7fffffff; if (ix < 0x7f800000 and iy < 0x7f800000) { if (iy == 0) { return Complex(f32).init(math.cosh(x), y); } // small x: normal case if (ix < 0x41100000) { return Complex(f32).init(math.cosh(x) * math.cos(y), math.sinh(x) * math.sin(y)); } // |x|>= 9, so cosh(x) ~= exp(|x|) if (ix < 0x42b17218) { // x < 88.7: exp(|x|) won't overflow const h = math.exp(math.fabs(x)) * 0.5; return Complex(f32).init(math.copysign(f32, h, x) * math.cos(y), h * math.sin(y)); } // x < 192.7: scale to avoid overflow else if (ix < 0x4340b1e7) { const v = Complex(f32).init(math.fabs(x), y); const r = ldexp_cexp(v, -1); return Complex(f32).init(r.re, r.im * math.copysign(f32, 1, x)); } // x >= 192.7: result always overflows else { const h = 0x1p127 * x; return Complex(f32).init(h * h * math.cos(y), h * math.sin(y)); } } if (ix == 0 and iy >= 0x7f800000) { return Complex(f32).init(y - y, math.copysign(f32, 0, x * (y - y))); } if (iy == 0 and ix >= 0x7f800000) { if (hx & 0x7fffff == 0) { return Complex(f32).init(x * x, math.copysign(f32, 0, x) * y); } return Complex(f32).init(x, math.copysign(f32, 0, (x + x) * y)); } if (ix < 0x7f800000 and iy >= 0x7f800000) { return Complex(f32).init(y - y, x * (y - y)); } if (ix >= 0x7f800000 and (hx & 0x7fffff) == 0) { if (iy >= 0x7f800000) { return Complex(f32).init(x * x, x * (y - y)); } return Complex(f32).init((x * x) * math.cos(y), x * math.sin(y)); } return Complex(f32).init((x * x) * (y - y), (x + x) * (y - y)); } fn cosh64(z: Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; const fx = @as(u64, @bitCast(x)); const hx = @as(u32, @intCast(fx >> 32)); const lx = @as(u32, @truncate(fx)); const ix = hx & 0x7fffffff; const fy = @as(u64, @bitCast(y)); const hy = @as(u32, @intCast(fy >> 32)); const ly = @as(u32, @truncate(fy)); const iy = hy & 0x7fffffff; // nearly non-exceptional case where x, y are finite if (ix < 0x7ff00000 and iy < 0x7ff00000) { if (iy | ly == 0) { return Complex(f64).init(math.cosh(x), x * y); } // small x: normal case if (ix < 0x40360000) { return Complex(f64).init(math.cosh(x) * math.cos(y), math.sinh(x) * math.sin(y)); } // |x|>= 22, so cosh(x) ~= exp(|x|) if (ix < 0x40862e42) { // x < 710: exp(|x|) won't overflow const h = math.exp(math.fabs(x)) * 0.5; return Complex(f64).init(h * math.cos(y), math.copysign(f64, h, x) * math.sin(y)); } // x < 1455: scale to avoid overflow else if (ix < 0x4096bbaa) { const v = Complex(f64).init(math.fabs(x), y); const r = ldexp_cexp(v, -1); return Complex(f64).init(r.re, r.im * math.copysign(f64, 1, x)); } // x >= 1455: result always overflows else { const h = 0x1p1023; return Complex(f64).init(h * h * math.cos(y), h * math.sin(y)); } } if (ix | lx == 0 and iy >= 0x7ff00000) { return Complex(f64).init(y - y, math.copysign(f64, 0, x * (y - y))); } if (iy | ly == 0 and ix >= 0x7ff00000) { if ((hx & 0xfffff) | lx == 0) { return Complex(f64).init(x * x, math.copysign(f64, 0, x) * y); } return Complex(f64).init(x * x, math.copysign(f64, 0, (x + x) * y)); } if (ix < 0x7ff00000 and iy >= 0x7ff00000) { return Complex(f64).init(y - y, x * (y - y)); } if (ix >= 0x7ff00000 and (hx & 0xfffff) | lx == 0) { if (iy >= 0x7ff00000) { return Complex(f64).init(x * x, x * (y - y)); } return Complex(f64).init(x * x * math.cos(y), x * math.sin(y)); } return Complex(f64).init((x * x) * (y - y), (x + x) * (y - y)); } const epsilon = 0.0001; test "complex.ccosh32" { const a = Complex(f32).init(5, 3); const c = cosh(a); try testing.expect(math.approxEqAbs(f32, c.re, -73.467300, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 10.471557, epsilon)); } test "complex.ccosh64" { const a = Complex(f64).init(5, 3); const c = cosh(a); try testing.expect(math.approxEqAbs(f64, c.re, -73.467300, epsilon)); try testing.expect(math.approxEqAbs(f64, c.im, 10.471557, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/acos.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the arc-cosine of z. pub fn acos(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); const q = cmath.asin(z); return Complex(T).init(@as(T, math.pi) / 2 - q.re, -q.im); } const epsilon = 0.0001; test "complex.cacos" { const a = Complex(f32).init(5, 3); const c = acos(a); try testing.expect(math.approxEqAbs(f32, c.re, 0.546975, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, -2.452914, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/pow.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns z raised to the complex power of c. pub fn pow(comptime T: type, z: T, c: T) T { const p = cmath.log(z); const q = c.mul(p); return cmath.exp(q); } const epsilon = 0.0001; test "complex.cpow" { const a = Complex(f32).init(5, 3); const b = Complex(f32).init(2.3, -1.3); const c = pow(Complex(f32), a, b); try testing.expect(math.approxEqAbs(f32, c.re, 58.049110, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, -101.003433, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/sin.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the sine of z. pub fn sin(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); const p = Complex(T).init(-z.im, z.re); const q = cmath.sinh(p); return Complex(T).init(q.im, -q.re); } const epsilon = 0.0001; test "complex.csin" { const a = Complex(f32).init(5, 3); const c = sin(a); try testing.expect(math.approxEqAbs(f32, c.re, -9.654126, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 2.841692, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/asinh.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the hyperbolic arc-sine of z. pub fn asinh(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); const q = Complex(T).init(-z.im, z.re); const r = cmath.asin(q); return Complex(T).init(r.im, -r.re); } const epsilon = 0.0001; test "complex.casinh" { const a = Complex(f32).init(5, 3); const c = asinh(a); try testing.expect(math.approxEqAbs(f32, c.re, 2.459831, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 0.533999, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/conj.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the complex conjugate of z. pub fn conj(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); return Complex(T).init(z.re, -z.im); } test "complex.conj" { const a = Complex(f32).init(5, 3); const c = a.conjugate(); try testing.expect(c.re == 5 and c.im == -3); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/atan.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/complex/catanf.c // https://git.musl-libc.org/cgit/musl/tree/src/complex/catan.c const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the arc-tangent of z. pub fn atan(z: anytype) @TypeOf(z) { const T = @TypeOf(z.re); return switch (T) { f32 => atan32(z), f64 => atan64(z), else => @compileError("atan not implemented for " ++ @typeName(z)), }; } fn redupif32(x: f32) f32 { const DP1 = 3.140625; const DP2 = 9.67502593994140625e-4; const DP3 = 1.509957990978376432e-7; var t = x / math.pi; if (t >= 0.0) { t += 0.5; } else { t -= 0.5; } const u = @as(f32, @floatFromInt(@as(i32, @intFromFloat(t)))); return ((x - u * DP1) - u * DP2) - t * DP3; } fn atan32(z: Complex(f32)) Complex(f32) { const maxnum = 1.0e38; const x = z.re; const y = z.im; if ((x == 0.0) and (y > 1.0)) { // overflow return Complex(f32).init(maxnum, maxnum); } const x2 = x * x; var a = 1.0 - x2 - (y * y); if (a == 0.0) { // overflow return Complex(f32).init(maxnum, maxnum); } var t = 0.5 * math.atan2(f32, 2.0 * x, a); var w = redupif32(t); t = y - 1.0; a = x2 + t * t; if (a == 0.0) { // overflow return Complex(f32).init(maxnum, maxnum); } t = y + 1.0; a = (x2 + (t * t)) / a; return Complex(f32).init(w, 0.25 * math.ln(a)); } fn redupif64(x: f64) f64 { const DP1 = 3.14159265160560607910; const DP2 = 1.98418714791870343106e-9; const DP3 = 1.14423774522196636802e-17; var t = x / math.pi; if (t >= 0.0) { t += 0.5; } else { t -= 0.5; } const u = @as(f64, @floatFromInt(@as(i64, @intFromFloat(t)))); return ((x - u * DP1) - u * DP2) - t * DP3; } fn atan64(z: Complex(f64)) Complex(f64) { const maxnum = 1.0e308; const x = z.re; const y = z.im; if ((x == 0.0) and (y > 1.0)) { // overflow return Complex(f64).init(maxnum, maxnum); } const x2 = x * x; var a = 1.0 - x2 - (y * y); if (a == 0.0) { // overflow return Complex(f64).init(maxnum, maxnum); } var t = 0.5 * math.atan2(f64, 2.0 * x, a); var w = redupif64(t); t = y - 1.0; a = x2 + t * t; if (a == 0.0) { // overflow return Complex(f64).init(maxnum, maxnum); } t = y + 1.0; a = (x2 + (t * t)) / a; return Complex(f64).init(w, 0.25 * math.ln(a)); } const epsilon = 0.0001; test "complex.catan32" { const a = Complex(f32).init(5, 3); const c = atan(a); try testing.expect(math.approxEqAbs(f32, c.re, 1.423679, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 0.086569, epsilon)); } test "complex.catan64" { const a = Complex(f64).init(5, 3); const c = atan(a); try testing.expect(math.approxEqAbs(f64, c.re, 1.423679, epsilon)); try testing.expect(math.approxEqAbs(f64, c.im, 0.086569, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/arg.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the angular component (in radians) of z. pub fn arg(z: anytype) @TypeOf(z.re) { const T = @TypeOf(z.re); return math.atan2(T, z.im, z.re); } const epsilon = 0.0001; test "complex.carg" { const a = Complex(f32).init(5, 3); const c = arg(a); try testing.expect(math.approxEqAbs(f32, c, 0.540420, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/exp.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/complex/cexpf.c // https://git.musl-libc.org/cgit/musl/tree/src/complex/cexp.c const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; const ldexp_cexp = @import("ldexp.zig").ldexp_cexp; /// Returns e raised to the power of z (e^z). pub fn exp(z: anytype) @TypeOf(z) { const T = @TypeOf(z.re); return switch (T) { f32 => exp32(z), f64 => exp64(z), else => @compileError("exp not implemented for " ++ @typeName(z)), }; } fn exp32(z: Complex(f32)) Complex(f32) { const exp_overflow = 0x42b17218; // max_exp * ln2 ~= 88.72283955 const cexp_overflow = 0x43400074; // (max_exp - min_denom_exp) * ln2 const x = z.re; const y = z.im; const hy = @as(u32, @bitCast(y)) & 0x7fffffff; // cexp(x + i0) = exp(x) + i0 if (hy == 0) { return Complex(f32).init(math.exp(x), y); } const hx = @as(u32, @bitCast(x)); // cexp(0 + iy) = cos(y) + isin(y) if ((hx & 0x7fffffff) == 0) { return Complex(f32).init(math.cos(y), math.sin(y)); } if (hy >= 0x7f800000) { // cexp(finite|nan +- i inf|nan) = nan + i nan if ((hx & 0x7fffffff) != 0x7f800000) { return Complex(f32).init(y - y, y - y); } // cexp(-inf +- i inf|nan) = 0 + i0 else if (hx & 0x80000000 != 0) { return Complex(f32).init(0, 0); } // cexp(+inf +- i inf|nan) = inf + i nan else { return Complex(f32).init(x, y - y); } } // 88.7 <= x <= 192 so must scale if (hx >= exp_overflow and hx <= cexp_overflow) { return ldexp_cexp(z, 0); } // - x < exp_overflow => exp(x) won't overflow (common) // - x > cexp_overflow, so exp(x) * s overflows for s > 0 // - x = +-inf // - x = nan else { const exp_x = math.exp(x); return Complex(f32).init(exp_x * math.cos(y), exp_x * math.sin(y)); } } fn exp64(z: Complex(f64)) Complex(f64) { const exp_overflow = 0x40862e42; // high bits of max_exp * ln2 ~= 710 const cexp_overflow = 0x4096b8e4; // (max_exp - min_denorm_exp) * ln2 const x = z.re; const y = z.im; const fy = @as(u64, @bitCast(y)); const hy = @as(u32, @intCast((fy >> 32) & 0x7fffffff)); const ly = @as(u32, @truncate(fy)); // cexp(x + i0) = exp(x) + i0 if (hy | ly == 0) { return Complex(f64).init(math.exp(x), y); } const fx = @as(u64, @bitCast(x)); const hx = @as(u32, @intCast(fx >> 32)); const lx = @as(u32, @truncate(fx)); // cexp(0 + iy) = cos(y) + isin(y) if ((hx & 0x7fffffff) | lx == 0) { return Complex(f64).init(math.cos(y), math.sin(y)); } if (hy >= 0x7ff00000) { // cexp(finite|nan +- i inf|nan) = nan + i nan if (lx != 0 or (hx & 0x7fffffff) != 0x7ff00000) { return Complex(f64).init(y - y, y - y); } // cexp(-inf +- i inf|nan) = 0 + i0 else if (hx & 0x80000000 != 0) { return Complex(f64).init(0, 0); } // cexp(+inf +- i inf|nan) = inf + i nan else { return Complex(f64).init(x, y - y); } } // 709.7 <= x <= 1454.3 so must scale if (hx >= exp_overflow and hx <= cexp_overflow) { return ldexp_cexp(z, 0); } // - x < exp_overflow => exp(x) won't overflow (common) // - x > cexp_overflow, so exp(x) * s overflows for s > 0 // - x = +-inf // - x = nan else { const exp_x = math.exp(x); return Complex(f64).init(exp_x * math.cos(y), exp_x * math.sin(y)); } } test "complex.cexp32" { const tolerance_f32 = math.sqrt(math.epsilon(f32)); { const a = Complex(f32).init(5, 3); const c = exp(a); try testing.expectApproxEqRel(@as(f32, -1.46927917e+02), c.re, tolerance_f32); try testing.expectApproxEqRel(@as(f32, 2.0944065e+01), c.im, tolerance_f32); } { const a = Complex(f32).init(88.8, 0x1p-149); const c = exp(a); try testing.expectApproxEqAbs(math.inf(f32), c.re, tolerance_f32); try testing.expectApproxEqAbs(@as(f32, 5.15088629e-07), c.im, tolerance_f32); } } test "complex.cexp64" { const tolerance_f64 = math.sqrt(math.epsilon(f64)); { const a = Complex(f64).init(5, 3); const c = exp(a); try testing.expectApproxEqRel(@as(f64, -1.469279139083189e+02), c.re, tolerance_f64); try testing.expectApproxEqRel(@as(f64, 2.094406620874596e+01), c.im, tolerance_f64); } { const a = Complex(f64).init(709.8, 0x1p-1074); const c = exp(a); try testing.expectApproxEqAbs(math.inf(f64), c.re, tolerance_f64); try testing.expectApproxEqAbs(@as(f64, 9.036659362159884e-16), c.im, tolerance_f64); } }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/complex/log.zig
const std = @import("../../std.zig"); const testing = std.testing; const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; /// Returns the natural logarithm of z. pub fn log(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); const r = cmath.abs(z); const phi = cmath.arg(z); return Complex(T).init(math.ln(r), phi); } const epsilon = 0.0001; test "complex.clog" { const a = Complex(f32).init(5, 3); const c = log(a); try testing.expect(math.approxEqAbs(f32, c.re, 1.763180, epsilon)); try testing.expect(math.approxEqAbs(f32, c.im, 0.540419, epsilon)); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/big/int.zig
const std = @import("../../std.zig"); const math = std.math; const Limb = std.math.big.Limb; const limb_bits = @typeInfo(Limb).Int.bits; const DoubleLimb = std.math.big.DoubleLimb; const SignedDoubleLimb = std.math.big.SignedDoubleLimb; const Log2Limb = std.math.big.Log2Limb; const Allocator = std.mem.Allocator; const mem = std.mem; const maxInt = std.math.maxInt; const minInt = std.math.minInt; const assert = std.debug.assert; const Endian = std.builtin.Endian; const Signedness = std.builtin.Signedness; const debug_safety = false; /// Returns the number of limbs needed to store `scalar`, which must be a /// primitive integer value. pub fn calcLimbLen(scalar: anytype) usize { if (scalar == 0) { return 1; } const w_value = std.math.absCast(scalar); return @divFloor(@as(Limb, @intCast(math.log2(w_value))), limb_bits) + 1; } pub fn calcToStringLimbsBufferLen(a_len: usize, base: u8) usize { if (math.isPowerOfTwo(base)) return 0; return a_len + 2 + a_len + calcDivLimbsBufferLen(a_len, 1); } pub fn calcDivLimbsBufferLen(a_len: usize, b_len: usize) usize { return a_len + b_len + 4; } pub fn calcMulLimbsBufferLen(a_len: usize, b_len: usize, aliases: usize) usize { return aliases * math.max(a_len, b_len); } pub fn calcMulWrapLimbsBufferLen(bit_count: usize, a_len: usize, b_len: usize, aliases: usize) usize { const req_limbs = calcTwosCompLimbCount(bit_count); return aliases * math.min(req_limbs, math.max(a_len, b_len)); } pub fn calcSetStringLimbsBufferLen(base: u8, string_len: usize) usize { const limb_count = calcSetStringLimbCount(base, string_len); return calcMulLimbsBufferLen(limb_count, limb_count, 2); } pub fn calcSetStringLimbCount(base: u8, string_len: usize) usize { return (string_len + (limb_bits / base - 1)) / (limb_bits / base); } pub fn calcPowLimbsBufferLen(a_bit_count: usize, y: usize) usize { // The 2 accounts for the minimum space requirement for llmulacc return 2 + (a_bit_count * y + (limb_bits - 1)) / limb_bits; } // Compute the number of limbs required to store a 2s-complement number of `bit_count` bits. pub fn calcTwosCompLimbCount(bit_count: usize) usize { return std.math.divCeil(usize, bit_count, @bitSizeOf(Limb)) catch unreachable; } /// a + b * c + *carry, sets carry to the overflow bits pub fn addMulLimbWithCarry(a: Limb, b: Limb, c: Limb, carry: *Limb) Limb { @setRuntimeSafety(debug_safety); // ov1[0] = a + *carry const ov1 = @addWithOverflow(a, carry.*); // r2 = b * c const bc = @as(DoubleLimb, math.mulWide(Limb, b, c)); const r2 = @as(Limb, @truncate(bc)); const c2 = @as(Limb, @truncate(bc >> limb_bits)); // ov2[0] = ov1[0] + r2 const ov2 = @addWithOverflow(ov1[0], r2); // This never overflows, c1, c3 are either 0 or 1 and if both are 1 then // c2 is at least <= maxInt(Limb) - 2. carry.* = ov1[1] + c2 + ov2[1]; return ov2[0]; } /// a - b * c - *carry, sets carry to the overflow bits fn subMulLimbWithBorrow(a: Limb, b: Limb, c: Limb, carry: *Limb) Limb { // ov1[0] = a - *carry const ov1 = @subWithOverflow(a, carry.*); // r2 = b * c const bc = @as(DoubleLimb, std.math.mulWide(Limb, b, c)); const r2 = @as(Limb, @truncate(bc)); const c2 = @as(Limb, @truncate(bc >> limb_bits)); // ov2[0] = ov1[0] - r2 const ov2 = @subWithOverflow(ov1[0], r2); carry.* = ov1[1] + c2 + ov2[1]; return ov2[0]; } /// Used to indicate either limit of a 2s-complement integer. pub const TwosCompIntLimit = enum { // The low limit, either 0x00 (unsigned) or (-)0x80 (signed) for an 8-bit integer. min, // The high limit, either 0xFF (unsigned) or 0x7F (signed) for an 8-bit integer. max, }; /// A arbitrary-precision big integer, with a fixed set of mutable limbs. pub const Mutable = struct { /// Raw digits. These are: /// /// * Little-endian ordered /// * limbs.len >= 1 /// * Zero is represented as limbs.len == 1 with limbs[0] == 0. /// /// Accessing limbs directly should be avoided. /// These are allocated limbs; the `len` field tells the valid range. limbs: []Limb, len: usize, positive: bool, pub fn toConst(self: Mutable) Const { return .{ .limbs = self.limbs[0..self.len], .positive = self.positive, }; } /// Returns true if `a == 0`. pub fn eqZero(self: Mutable) bool { return self.toConst().eqZero(); } /// Asserts that the allocator owns the limbs memory. If this is not the case, /// use `toConst().toManaged()`. pub fn toManaged(self: Mutable, allocator: *Allocator) Managed { return .{ .allocator = allocator, .limbs = self.limbs, .metadata = if (self.positive) self.len & ~Managed.sign_bit else self.len | Managed.sign_bit, }; } /// `value` is a primitive integer type. /// Asserts the value fits within the provided `limbs_buffer`. /// Note: `calcLimbLen` can be used to figure out how big an array to allocate for `limbs_buffer`. pub fn init(limbs_buffer: []Limb, value: anytype) Mutable { limbs_buffer[0] = 0; var self: Mutable = .{ .limbs = limbs_buffer, .len = 1, .positive = true, }; self.set(value); return self; } /// Copies the value of a Const to an existing Mutable so that they both have the same value. /// Asserts the value fits in the limbs buffer. pub fn copy(self: *Mutable, other: Const) void { if (self.limbs.ptr != other.limbs.ptr) { mem.copy(Limb, self.limbs[0..], other.limbs[0..other.limbs.len]); } self.positive = other.positive; self.len = other.limbs.len; } /// Efficiently swap an Mutable with another. This swaps the limb pointers and a full copy is not /// performed. The address of the limbs field will not be the same after this function. pub fn swap(self: *Mutable, other: *Mutable) void { mem.swap(Mutable, self, other); } pub fn dump(self: Mutable) void { for (self.limbs[0..self.len]) |limb| { std.debug.warn("{x} ", .{limb}); } std.debug.warn("capacity={} positive={}\n", .{ self.limbs.len, self.positive }); } /// Clones an Mutable and returns a new Mutable with the same value. The new Mutable is a deep copy and /// can be modified separately from the original. /// Asserts that limbs is big enough to store the value. pub fn clone(other: Mutable, limbs: []Limb) Mutable { mem.copy(Limb, limbs, other.limbs[0..other.len]); return .{ .limbs = limbs, .len = other.len, .positive = other.positive, }; } pub fn negate(self: *Mutable) void { self.positive = !self.positive; } /// Modify to become the absolute value pub fn abs(self: *Mutable) void { self.positive = true; } /// Sets the Mutable to value. Value must be an primitive integer type. /// Asserts the value fits within the limbs buffer. /// Note: `calcLimbLen` can be used to figure out how big the limbs buffer /// needs to be to store a specific value. pub fn set(self: *Mutable, value: anytype) void { const T = @TypeOf(value); const needed_limbs = calcLimbLen(value); assert(needed_limbs <= self.limbs.len); // value too big self.len = needed_limbs; self.positive = value >= 0; switch (@typeInfo(T)) { .Int => |info| { var w_value = std.math.absCast(value); if (info.bits <= limb_bits) { self.limbs[0] = w_value; } else { var i: usize = 0; while (w_value != 0) : (i += 1) { self.limbs[i] = @as(Limb, @truncate(w_value)); // TODO: shift == 64 at compile-time fails. Fails on u128 limbs. w_value >>= limb_bits / 2; w_value >>= limb_bits / 2; } } }, .ComptimeInt => { comptime var w_value = std.math.absCast(value); if (w_value <= maxInt(Limb)) { self.limbs[0] = w_value; } else { const mask = (1 << limb_bits) - 1; comptime var i = 0; inline while (w_value != 0) : (i += 1) { self.limbs[i] = w_value & mask; w_value >>= limb_bits / 2; w_value >>= limb_bits / 2; } } }, else => @compileError("cannot set Mutable using type " ++ @typeName(T)), } } /// Set self from the string representation `value`. /// /// `value` must contain only digits <= `base` and is case insensitive. Base prefixes are /// not allowed (e.g. 0x43 should simply be 43). Underscores in the input string are /// ignored and can be used as digit separators. /// /// Asserts there is enough memory for the value in `self.limbs`. An upper bound on number of limbs can /// be determined with `calcSetStringLimbCount`. /// Asserts the base is in the range [2, 16]. /// /// Returns an error if the value has invalid digits for the requested base. /// /// `limbs_buffer` is used for temporary storage. The size required can be found with /// `calcSetStringLimbsBufferLen`. /// /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. pub fn setString( self: *Mutable, base: u8, value: []const u8, limbs_buffer: []Limb, allocator: ?*Allocator, ) error{InvalidCharacter}!void { assert(base >= 2 and base <= 16); var i: usize = 0; var positive = true; if (value.len > 0 and value[0] == '-') { positive = false; i += 1; } const ap_base: Const = .{ .limbs = &[_]Limb{base}, .positive = true }; self.set(0); for (value[i..]) |ch| { if (ch == '_') { continue; } const d = try std.fmt.charToDigit(ch, base); const ap_d: Const = .{ .limbs = &[_]Limb{d}, .positive = true }; self.mul(self.toConst(), ap_base, limbs_buffer, allocator); self.add(self.toConst(), ap_d); } self.positive = positive; } /// Set self to either bound of a 2s-complement integer. /// Note: The result is still sign-magnitude, not twos complement! In order to convert the /// result to twos complement, it is sufficient to take the absolute value. /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by /// r is `calcTwosCompLimbCount(bit_count)`. pub fn setTwosCompIntLimit( r: *Mutable, limit: TwosCompIntLimit, signedness: Signedness, bit_count: usize, ) void { // Handle zero-bit types. if (bit_count == 0) { r.set(0); return; } const req_limbs = calcTwosCompLimbCount(bit_count); const bit = @as(Log2Limb, @truncate(bit_count - 1)); const signmask = @as(Limb, 1) << bit; // 0b0..010..0 where 1 is the sign bit. const mask = (signmask << 1) -% 1; // 0b0..011..1 where the leftmost 1 is the sign bit. r.positive = true; switch (signedness) { .signed => switch (limit) { .min => { // Negative bound, signed = -0x80. r.len = req_limbs; mem.set(Limb, r.limbs[0 .. r.len - 1], 0); r.limbs[r.len - 1] = signmask; r.positive = false; }, .max => { // Positive bound, signed = 0x7F // Note, in this branch we need to normalize because the first bit is // supposed to be 0. // Special case for 1-bit integers. if (bit_count == 1) { r.set(0); } else { const new_req_limbs = calcTwosCompLimbCount(bit_count - 1); const msb = @as(Log2Limb, @truncate(bit_count - 2)); const new_signmask = @as(Limb, 1) << msb; // 0b0..010..0 where 1 is the sign bit. const new_mask = (new_signmask << 1) -% 1; // 0b0..001..1 where the rightmost 0 is the sign bit. r.len = new_req_limbs; std.mem.set(Limb, r.limbs[0 .. r.len - 1], maxInt(Limb)); r.limbs[r.len - 1] = new_mask; } }, }, .unsigned => switch (limit) { .min => { // Min bound, unsigned = 0x00 r.set(0); }, .max => { // Max bound, unsigned = 0xFF r.len = req_limbs; std.mem.set(Limb, r.limbs[0 .. r.len - 1], maxInt(Limb)); r.limbs[r.len - 1] = mask; }, }, } } /// r = a + scalar /// /// r and a may be aliases. /// scalar is a primitive integer type. /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by /// r is `math.max(a.limbs.len, calcLimbLen(scalar)) + 1`. pub fn addScalar(r: *Mutable, a: Const, scalar: anytype) void { var limbs: [calcLimbLen(scalar)]Limb = undefined; const operand = init(&limbs, scalar).toConst(); return add(r, a, operand); } /// Base implementation for addition. Adds `max(a.limbs.len, b.limbs.len)` elements from a and b, /// and returns whether any overflow occured. /// r, a and b may be aliases. /// /// Asserts r has enough elements to hold the result. The upper bound is `max(a.limbs.len, b.limbs.len)`. fn addCarry(r: *Mutable, a: Const, b: Const) bool { if (a.eqZero()) { r.copy(b); return false; } else if (b.eqZero()) { r.copy(a); return false; } else if (a.positive != b.positive) { if (a.positive) { // (a) + (-b) => a - b return r.subCarry(a, b.abs()); } else { // (-a) + (b) => b - a return r.subCarry(b, a.abs()); } } else { r.positive = a.positive; if (a.limbs.len >= b.limbs.len) { const c = lladdcarry(r.limbs, a.limbs, b.limbs); r.normalize(a.limbs.len); return c != 0; } else { const c = lladdcarry(r.limbs, b.limbs, a.limbs); r.normalize(b.limbs.len); return c != 0; } } } /// r = a + b /// r, a and b may be aliases. /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by /// r is `math.max(a.limbs.len, b.limbs.len) + 1`. pub fn add(r: *Mutable, a: Const, b: Const) void { if (r.addCarry(a, b)) { // Fix up the result. Note that addCarry normalizes by a.limbs.len or b.limbs.len, // so we need to set the length here. const msl = math.max(a.limbs.len, b.limbs.len); // `[add|sub]Carry` normalizes by `msl`, so we need to fix up the result manually here. // Note, the fact that it normalized means that the intermediary limbs are zero here. r.len = msl + 1; r.limbs[msl] = 1; // If this panics, there wasn't enough space in `r`. } } /// r = a + b with 2s-complement wrapping semantics. /// r, a and b may be aliases /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by /// r is `calcTwosCompLimbCount(bit_count)`. pub fn addWrap(r: *Mutable, a: Const, b: Const, signedness: Signedness, bit_count: usize) void { const req_limbs = calcTwosCompLimbCount(bit_count); // Slice of the upper bits if they exist, these will be ignored and allows us to use addCarry to determine // if an overflow occured. const x = Const{ .positive = a.positive, .limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)], }; const y = Const{ .positive = b.positive, .limbs = b.limbs[0..math.min(req_limbs, b.limbs.len)], }; if (r.addCarry(x, y)) { // There are two possibilities here: // - We overflowed req_limbs. In this case, the carry is ignored, as it would be removed by // truncate anyway. // - a and b had less elements than req_limbs, and those were overflowed. This case needs to be handled. // Note: after this we still might need to wrap. const msl = math.max(a.limbs.len, b.limbs.len); if (msl < req_limbs) { r.limbs[msl] = 1; r.len = req_limbs; } } r.truncate(r.toConst(), signedness, bit_count); } /// r = a + b with 2s-complement saturating semantics. /// r, a and b may be aliases. /// /// Assets the result fits in `r`. Upper bound on the number of limbs needed by /// r is `calcTwosCompLimbCount(bit_count)`. pub fn addSat(r: *Mutable, a: Const, b: Const, signedness: Signedness, bit_count: usize) void { const req_limbs = calcTwosCompLimbCount(bit_count); // Slice of the upper bits if they exist, these will be ignored and allows us to use addCarry to determine // if an overflow occured. const x = Const{ .positive = a.positive, .limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)], }; const y = Const{ .positive = b.positive, .limbs = b.limbs[0..math.min(req_limbs, b.limbs.len)], }; if (r.addCarry(x, y)) { // There are two possibilities here: // - We overflowed req_limbs, in which case we need to saturate. // - a and b had less elements than req_limbs, and those were overflowed. // Note: In this case, might _also_ need to saturate. const msl = math.max(a.limbs.len, b.limbs.len); if (msl < req_limbs) { r.limbs[msl] = 1; r.len = req_limbs; // Note: Saturation may still be required if msl == req_limbs - 1 } else { // Overflowed req_limbs, definitely saturate. r.setTwosCompIntLimit(if (r.positive) .max else .min, signedness, bit_count); } } // Saturate if the result didn't fit. r.saturate(r.toConst(), signedness, bit_count); } /// Base implementation for subtraction. Subtracts `max(a.limbs.len, b.limbs.len)` elements from a and b, /// and returns whether any overflow occured. /// r, a and b may be aliases. /// /// Asserts r has enough elements to hold the result. The upper bound is `max(a.limbs.len, b.limbs.len)`. fn subCarry(r: *Mutable, a: Const, b: Const) bool { if (a.eqZero()) { r.copy(b); r.positive = !b.positive; return false; } else if (b.eqZero()) { r.copy(a); return false; } else if (a.positive != b.positive) { if (a.positive) { // (a) - (-b) => a + b return r.addCarry(a, b.abs()); } else { // (-a) - (b) => -a + -b return r.addCarry(a, b.negate()); } } else if (a.positive) { if (a.order(b) != .lt) { // (a) - (b) => a - b const c = llsubcarry(r.limbs, a.limbs, b.limbs); r.normalize(a.limbs.len); r.positive = true; return c != 0; } else { // (a) - (b) => -b + a => -(b - a) const c = llsubcarry(r.limbs, b.limbs, a.limbs); r.normalize(b.limbs.len); r.positive = false; return c != 0; } } else { if (a.order(b) == .lt) { // (-a) - (-b) => -(a - b) const c = llsubcarry(r.limbs, a.limbs, b.limbs); r.normalize(a.limbs.len); r.positive = false; return c != 0; } else { // (-a) - (-b) => --b + -a => b - a const c = llsubcarry(r.limbs, b.limbs, a.limbs); r.normalize(b.limbs.len); r.positive = true; return c != 0; } } } /// r = a - b /// /// r, a and b may be aliases. /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by /// r is `math.max(a.limbs.len, b.limbs.len) + 1`. The +1 is not needed if both operands are positive. pub fn sub(r: *Mutable, a: Const, b: Const) void { r.add(a, b.negate()); } /// r = a - b with 2s-complement wrapping semantics. /// /// r, a and b may be aliases /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by /// r is `calcTwosCompLimbCount(bit_count)`. pub fn subWrap(r: *Mutable, a: Const, b: Const, signedness: Signedness, bit_count: usize) void { r.addWrap(a, b.negate(), signedness, bit_count); } /// r = a - b with 2s-complement saturating semantics. /// r, a and b may be aliases. /// /// Assets the result fits in `r`. Upper bound on the number of limbs needed by /// r is `calcTwosCompLimbCount(bit_count)`. pub fn subSat(r: *Mutable, a: Const, b: Const, signedness: Signedness, bit_count: usize) void { r.addSat(a, b.negate(), signedness, bit_count); } /// rma = a * b /// /// `rma` may alias with `a` or `b`. /// `a` and `b` may alias with each other. /// /// Asserts the result fits in `rma`. An upper bound on the number of limbs needed by /// rma is given by `a.limbs.len + b.limbs.len`. /// /// `limbs_buffer` is used for temporary storage. The amount required is given by `calcMulLimbsBufferLen`. pub fn mul(rma: *Mutable, a: Const, b: Const, limbs_buffer: []Limb, allocator: ?*Allocator) void { var buf_index: usize = 0; const a_copy = if (rma.limbs.ptr == a.limbs.ptr) blk: { const start = buf_index; mem.copy(Limb, limbs_buffer[buf_index..], a.limbs); buf_index += a.limbs.len; break :blk a.toMutable(limbs_buffer[start..buf_index]).toConst(); } else a; const b_copy = if (rma.limbs.ptr == b.limbs.ptr) blk: { const start = buf_index; mem.copy(Limb, limbs_buffer[buf_index..], b.limbs); buf_index += b.limbs.len; break :blk b.toMutable(limbs_buffer[start..buf_index]).toConst(); } else b; return rma.mulNoAlias(a_copy, b_copy, allocator); } /// rma = a * b /// /// `rma` may not alias with `a` or `b`. /// `a` and `b` may alias with each other. /// /// Asserts the result fits in `rma`. An upper bound on the number of limbs needed by /// rma is given by `a.limbs.len + b.limbs.len`. /// /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. pub fn mulNoAlias(rma: *Mutable, a: Const, b: Const, allocator: ?*Allocator) void { assert(rma.limbs.ptr != a.limbs.ptr); // illegal aliasing assert(rma.limbs.ptr != b.limbs.ptr); // illegal aliasing if (a.limbs.len == 1 and b.limbs.len == 1) { const ov = @mulWithOverflow(a.limbs[0], b.limbs[0]); rma.limbs[0] = ov[0]; if (ov[1] == 0) { rma.len = 1; rma.positive = (a.positive == b.positive); return; } } mem.set(Limb, rma.limbs[0 .. a.limbs.len + b.limbs.len], 0); llmulacc(.add, allocator, rma.limbs, a.limbs, b.limbs); rma.normalize(a.limbs.len + b.limbs.len); rma.positive = (a.positive == b.positive); } /// rma = a * b with 2s-complement wrapping semantics. /// /// `rma` may alias with `a` or `b`. /// `a` and `b` may alias with each other. /// /// Asserts the result fits in `rma`. An upper bound on the number of limbs needed by /// rma is given by `a.limbs.len + b.limbs.len`. /// /// `limbs_buffer` is used for temporary storage. The amount required is given by `calcMulWrapLimbsBufferLen`. pub fn mulWrap( rma: *Mutable, a: Const, b: Const, signedness: Signedness, bit_count: usize, limbs_buffer: []Limb, allocator: ?*Allocator, ) void { var buf_index: usize = 0; const req_limbs = calcTwosCompLimbCount(bit_count); const a_copy = if (rma.limbs.ptr == a.limbs.ptr) blk: { const start = buf_index; const a_len = math.min(req_limbs, a.limbs.len); mem.copy(Limb, limbs_buffer[buf_index..], a.limbs[0..a_len]); buf_index += a_len; break :blk a.toMutable(limbs_buffer[start..buf_index]).toConst(); } else a; const b_copy = if (rma.limbs.ptr == b.limbs.ptr) blk: { const start = buf_index; const b_len = math.min(req_limbs, b.limbs.len); mem.copy(Limb, limbs_buffer[buf_index..], b.limbs[0..b_len]); buf_index += b_len; break :blk a.toMutable(limbs_buffer[start..buf_index]).toConst(); } else b; return rma.mulWrapNoAlias(a_copy, b_copy, signedness, bit_count, allocator); } /// rma = a * b with 2s-complement wrapping semantics. /// /// `rma` may not alias with `a` or `b`. /// `a` and `b` may alias with each other. /// /// Asserts the result fits in `rma`. An upper bound on the number of limbs needed by /// rma is given by `a.limbs.len + b.limbs.len`. /// /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. pub fn mulWrapNoAlias( rma: *Mutable, a: Const, b: Const, signedness: Signedness, bit_count: usize, allocator: ?*Allocator, ) void { assert(rma.limbs.ptr != a.limbs.ptr); // illegal aliasing assert(rma.limbs.ptr != b.limbs.ptr); // illegal aliasing const req_limbs = calcTwosCompLimbCount(bit_count); // We can ignore the upper bits here, those results will be discarded anyway. const a_limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)]; const b_limbs = b.limbs[0..math.min(req_limbs, b.limbs.len)]; mem.set(Limb, rma.limbs[0..req_limbs], 0); llmulacc(.add, allocator, rma.limbs, a_limbs, b_limbs); rma.normalize(math.min(req_limbs, a.limbs.len + b.limbs.len)); rma.positive = (a.positive == b.positive); rma.truncate(rma.toConst(), signedness, bit_count); } /// r = @popCount(a) with 2s-complement semantics. /// r and a may be aliases. /// /// Assets the result fits in `r`. Upper bound on the number of limbs needed by /// r is `calcTwosCompLimbCount(bit_count)`. pub fn popCount(r: *Mutable, a: Const, bit_count: usize) void { r.copy(a); if (!a.positive) { r.positive = true; // Negate. r.bitNotWrap(r.toConst(), .unsigned, bit_count); // Bitwise NOT. r.addScalar(r.toConst(), 1); // Add one. } var sum: Limb = 0; for (r.limbs[0..r.len]) |limb| { sum += @popCount(limb); } r.set(sum); } /// rma = a * a /// /// `rma` may not alias with `a`. /// /// Asserts the result fits in `rma`. An upper bound on the number of limbs needed by /// rma is given by `2 * a.limbs.len + 1`. /// /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. pub fn sqrNoAlias(rma: *Mutable, a: Const, opt_allocator: ?*Allocator) void { _ = opt_allocator; assert(rma.limbs.ptr != a.limbs.ptr); // illegal aliasing mem.set(Limb, rma.limbs, 0); llsquareBasecase(rma.limbs, a.limbs); rma.normalize(2 * a.limbs.len + 1); rma.positive = true; } /// q = a / b (rem r) /// /// a / b are floored (rounded towards 0). /// q may alias with a or b. /// /// Asserts there is enough memory to store q and r. /// The upper bound for r limb count is `b.limbs.len`. /// The upper bound for q limb count is given by `a.limbs`. /// /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. /// /// `limbs_buffer` is used for temporary storage. The amount required is given by `calcDivLimbsBufferLen`. pub fn divFloor( q: *Mutable, r: *Mutable, a: Const, b: Const, limbs_buffer: []Limb, ) void { const sep = a.limbs.len + 2; var x = a.toMutable(limbs_buffer[0..sep]); var y = b.toMutable(limbs_buffer[sep..]); div(q, r, &x, &y); // Note, `div` performs truncating division, which satisfies // @divTrunc(a, b) * b + @rem(a, b) = a // so r = a - @divTrunc(a, b) * b // Note, @rem(a, -b) = @rem(-b, a) = -@rem(a, b) = -@rem(-a, -b) // For divTrunc, we want to perform // @divFloor(a, b) * b + @mod(a, b) = a // Note: // @divFloor(-a, b) // = @divFloor(a, -b) // = -@divCeil(a, b) // = -@divFloor(a + b - 1, b) // = -@divTrunc(a + b - 1, b) // Note (1): // @divTrunc(a + b - 1, b) * b + @rem(a + b - 1, b) = a + b - 1 // = @divTrunc(a + b - 1, b) * b + @rem(a - 1, b) = a + b - 1 // = @divTrunc(a + b - 1, b) * b + @rem(a - 1, b) - b + 1 = a if (a.positive and b.positive) { // Positive-positive case, don't need to do anything. } else if (a.positive and !b.positive) { // a/-b -> q is negative, and so we need to fix flooring. // Subtract one to make the division flooring. // @divFloor(a, -b) * -b + @mod(a, -b) = a // If b divides a exactly, we have @divFloor(a, -b) * -b = a // Else, we have @divFloor(a, -b) * -b > a, so @mod(a, -b) becomes negative // We have: // @divFloor(a, -b) * -b + @mod(a, -b) = a // = -@divTrunc(a + b - 1, b) * -b + @mod(a, -b) = a // = @divTrunc(a + b - 1, b) * b + @mod(a, -b) = a // Substitute a for (1): // @divTrunc(a + b - 1, b) * b + @rem(a - 1, b) - b + 1 = @divTrunc(a + b - 1, b) * b + @mod(a, -b) // Yields: // @mod(a, -b) = @rem(a - 1, b) - b + 1 // Note that `r` holds @rem(a, b) at this point. // // If @rem(a, b) is not 0: // @rem(a - 1, b) = @rem(a, b) - 1 // => @mod(a, -b) = @rem(a, b) - 1 - b + 1 = @rem(a, b) - b // Else: // @rem(a - 1, b) = @rem(a + b - 1, b) = @rem(b - 1, b) = b - 1 // => @mod(a, -b) = b - 1 - b + 1 = 0 if (!r.eqZero()) { q.addScalar(q.toConst(), -1); r.positive = true; r.sub(r.toConst(), y.toConst().abs()); } } else if (!a.positive and b.positive) { // -a/b -> q is negative, and so we need to fix flooring. // Subtract one to make the division flooring. // @divFloor(-a, b) * b + @mod(-a, b) = a // If b divides a exactly, we have @divFloor(-a, b) * b = -a // Else, we have @divFloor(-a, b) * b < -a, so @mod(-a, b) becomes positive // We have: // @divFloor(-a, b) * b + @mod(-a, b) = -a // = -@divTrunc(a + b - 1, b) * b + @mod(-a, b) = -a // = @divTrunc(a + b - 1, b) * b - @mod(-a, b) = a // Substitute a for (1): // @divTrunc(a + b - 1, b) * b + @rem(a - 1, b) - b + 1 = @divTrunc(a + b - 1, b) * b - @mod(-a, b) // Yields: // @rem(a - 1, b) - b + 1 = -@mod(-a, b) // => -@mod(-a, b) = @rem(a - 1, b) - b + 1 // => @mod(-a, b) = -(@rem(a - 1, b) - b + 1) = -@rem(a - 1, b) + b - 1 // // If @rem(a, b) is not 0: // @rem(a - 1, b) = @rem(a, b) - 1 // => @mod(-a, b) = -(@rem(a, b) - 1) + b - 1 = -@rem(a, b) + 1 + b - 1 = -@rem(a, b) + b // Else : // @rem(a - 1, b) = b - 1 // => @mod(-a, b) = -(b - 1) + b - 1 = 0 if (!r.eqZero()) { q.addScalar(q.toConst(), -1); r.positive = false; r.add(r.toConst(), y.toConst().abs()); } } else if (!a.positive and !b.positive) { // a/b -> q is positive, don't need to do anything to fix flooring. // @divFloor(-a, -b) * -b + @mod(-a, -b) = -a // If b divides a exactly, we have @divFloor(-a, -b) * -b = -a // Else, we have @divFloor(-a, -b) * -b > -a, so @mod(-a, -b) becomes negative // We have: // @divFloor(-a, -b) * -b + @mod(-a, -b) = -a // = @divTrunc(a, b) * -b + @mod(-a, -b) = -a // = @divTrunc(a, b) * b - @mod(-a, -b) = a // We also have: // @divTrunc(a, b) * b + @rem(a, b) = a // Substitute a: // @divTrunc(a, b) * b + @rem(a, b) = @divTrunc(a, b) * b - @mod(-a, -b) // => @rem(a, b) = -@mod(-a, -b) // => @mod(-a, -b) = -@rem(a, b) r.positive = false; } } /// q = a / b (rem r) /// /// a / b are truncated (rounded towards -inf). /// q may alias with a or b. /// /// Asserts there is enough memory to store q and r. /// The upper bound for r limb count is `b.limbs.len`. /// The upper bound for q limb count is given by `a.limbs.len`. /// /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. /// /// `limbs_buffer` is used for temporary storage. The amount required is given by `calcDivLimbsBufferLen`. pub fn divTrunc( q: *Mutable, r: *Mutable, a: Const, b: Const, limbs_buffer: []Limb, ) void { const sep = a.limbs.len + 2; var x = a.toMutable(limbs_buffer[0..sep]); var y = b.toMutable(limbs_buffer[sep..]); div(q, r, &x, &y); } /// r = a << shift, in other words, r = a * 2^shift /// /// r and a may alias. /// /// Asserts there is enough memory to fit the result. The upper bound Limb count is /// `a.limbs.len + (shift / (@sizeOf(Limb) * 8))`. pub fn shiftLeft(r: *Mutable, a: Const, shift: usize) void { llshl(r.limbs[0..], a.limbs[0..a.limbs.len], shift); r.normalize(a.limbs.len + (shift / limb_bits) + 1); r.positive = a.positive; } /// r = a <<| shift with 2s-complement saturating semantics. /// /// r and a may alias. /// /// Asserts there is enough memory to fit the result. The upper bound Limb count is /// r is `calcTwosCompLimbCount(bit_count)`. pub fn shiftLeftSat(r: *Mutable, a: Const, shift: usize, signedness: Signedness, bit_count: usize) void { // Special case: When the argument is negative, but the result is supposed to be unsigned, // return 0 in all cases. if (!a.positive and signedness == .unsigned) { r.set(0); return; } // Check whether the shift is going to overflow. This is the case // when (in 2s complement) any bit above `bit_count - shift` is set in the unshifted value. // Note, the sign bit is not counted here. // Handle shifts larger than the target type. This also deals with // 0-bit integers. if (bit_count <= shift) { // In this case, there is only no overflow if `a` is zero. if (a.eqZero()) { r.set(0); } else { r.setTwosCompIntLimit(if (a.positive) .max else .min, signedness, bit_count); } return; } const checkbit = bit_count - shift - @intFromBool(signedness == .signed); // If `checkbit` and more significant bits are zero, no overflow will take place. if (checkbit >= a.limbs.len * limb_bits) { // `checkbit` is outside the range of a, so definitely no overflow will take place. We // can defer to a normal shift. // Note that if `a` is normalized (which we assume), this checks for set bits in the upper limbs. // Note, in this case r should already have enough limbs required to perform the normal shift. // In this case the shift of the most significant limb may still overflow. r.shiftLeft(a, shift); return; } else if (checkbit < (a.limbs.len - 1) * limb_bits) { // `checkbit` is not in the most significant limb. If `a` is normalized the most significant // limb will not be zero, so in this case we need to saturate. Note that `a.limbs.len` must be // at least one according to normalization rules. r.setTwosCompIntLimit(if (a.positive) .max else .min, signedness, bit_count); return; } // Generate a mask with the bits to check in the most signficant limb. We'll need to check // all bits with equal or more significance than checkbit. // const msb = @truncate(Log2Limb, checkbit); // const checkmask = (@as(Limb, 1) << msb) -% 1; if (a.limbs[a.limbs.len - 1] >> @as(Log2Limb, @truncate(checkbit)) != 0) { // Need to saturate. r.setTwosCompIntLimit(if (a.positive) .max else .min, signedness, bit_count); return; } // This shift should not be able to overflow, so invoke llshl and normalize manually // to avoid the extra required limb. llshl(r.limbs[0..], a.limbs[0..a.limbs.len], shift); r.normalize(a.limbs.len + (shift / limb_bits)); r.positive = a.positive; } /// r = a >> shift /// r and a may alias. /// /// Asserts there is enough memory to fit the result. The upper bound Limb count is /// `a.limbs.len - (shift / (@sizeOf(Limb) * 8))`. pub fn shiftRight(r: *Mutable, a: Const, shift: usize) void { if (a.limbs.len <= shift / limb_bits) { r.len = 1; r.positive = true; r.limbs[0] = 0; return; } llshr(r.limbs[0..], a.limbs[0..a.limbs.len], shift); r.normalize(a.limbs.len - (shift / limb_bits)); r.positive = a.positive; } /// r = ~a under 2s complement wrapping semantics. /// r may alias with a. /// /// Assets that r has enough limbs to store the result. The upper bound Limb count is /// r is `calcTwosCompLimbCount(bit_count)`. pub fn bitNotWrap(r: *Mutable, a: Const, signedness: Signedness, bit_count: usize) void { r.copy(a.negate()); const negative_one = Const{ .limbs = &.{1}, .positive = false }; r.addWrap(r.toConst(), negative_one, signedness, bit_count); } /// r = a | b under 2s complement semantics. /// r may alias with a or b. /// /// a and b are zero-extended to the longer of a or b. /// /// Asserts that r has enough limbs to store the result. Upper bound is `math.max(a.limbs.len, b.limbs.len)`. pub fn bitOr(r: *Mutable, a: Const, b: Const) void { // Trivial cases, llsignedor does not support zero. if (a.eqZero()) { r.copy(b); return; } else if (b.eqZero()) { r.copy(a); return; } if (a.limbs.len >= b.limbs.len) { r.positive = llsignedor(r.limbs, a.limbs, a.positive, b.limbs, b.positive); r.normalize(if (b.positive) a.limbs.len else b.limbs.len); } else { r.positive = llsignedor(r.limbs, b.limbs, b.positive, a.limbs, a.positive); r.normalize(if (a.positive) b.limbs.len else a.limbs.len); } } /// r = a & b under 2s complement semantics. /// r may alias with a or b. /// /// Asserts that r has enough limbs to store the result. /// If a or b is positive, the upper bound is `math.min(a.limbs.len, b.limbs.len)`. /// If a and b are negative, the upper bound is `math.max(a.limbs.len, b.limbs.len) + 1`. pub fn bitAnd(r: *Mutable, a: Const, b: Const) void { // Trivial cases, llsignedand does not support zero. if (a.eqZero()) { r.copy(a); return; } else if (b.eqZero()) { r.copy(b); return; } if (a.limbs.len >= b.limbs.len) { r.positive = llsignedand(r.limbs, a.limbs, a.positive, b.limbs, b.positive); r.normalize(if (a.positive or b.positive) b.limbs.len else a.limbs.len + 1); } else { r.positive = llsignedand(r.limbs, b.limbs, b.positive, a.limbs, a.positive); r.normalize(if (a.positive or b.positive) a.limbs.len else b.limbs.len + 1); } } /// r = a ^ b under 2s complement semantics. /// r may alias with a or b. /// /// Asserts that r has enough limbs to store the result. If a and b share the same signedness, the /// upper bound is `math.max(a.limbs.len, b.limbs.len)`. Otherwise, if either a or b is negative /// but not both, the upper bound is `math.max(a.limbs.len, b.limbs.len) + 1`. pub fn bitXor(r: *Mutable, a: Const, b: Const) void { // Trivial cases, because llsignedxor does not support negative zero. if (a.eqZero()) { r.copy(b); return; } else if (b.eqZero()) { r.copy(a); return; } if (a.limbs.len > b.limbs.len) { r.positive = llsignedxor(r.limbs, a.limbs, a.positive, b.limbs, b.positive); r.normalize(a.limbs.len + @intFromBool(a.positive != b.positive)); } else { r.positive = llsignedxor(r.limbs, b.limbs, b.positive, a.limbs, a.positive); r.normalize(b.limbs.len + @intFromBool(a.positive != b.positive)); } } /// rma may alias x or y. /// x and y may alias each other. /// Asserts that `rma` has enough limbs to store the result. Upper bound is /// `math.min(x.limbs.len, y.limbs.len)`. /// /// `limbs_buffer` is used for temporary storage during the operation. When this function returns, /// it will have the same length as it had when the function was called. pub fn gcd(rma: *Mutable, x: Const, y: Const, limbs_buffer: *std.ArrayList(Limb)) !void { const prev_len = limbs_buffer.items.len; defer limbs_buffer.shrinkRetainingCapacity(prev_len); const x_copy = if (rma.limbs.ptr == x.limbs.ptr) blk: { const start = limbs_buffer.items.len; try limbs_buffer.appendSlice(x.limbs); break :blk x.toMutable(limbs_buffer.items[start..]).toConst(); } else x; const y_copy = if (rma.limbs.ptr == y.limbs.ptr) blk: { const start = limbs_buffer.items.len; try limbs_buffer.appendSlice(y.limbs); break :blk y.toMutable(limbs_buffer.items[start..]).toConst(); } else y; return gcdLehmer(rma, x_copy, y_copy, limbs_buffer); } /// q = a ^ b /// /// r may not alias a. /// /// Asserts that `r` has enough limbs to store the result. Upper bound is /// `calcPowLimbsBufferLen(a.bitCountAbs(), b)`. /// /// `limbs_buffer` is used for temporary storage. /// The amount required is given by `calcPowLimbsBufferLen`. pub fn pow(r: *Mutable, a: Const, b: u32, limbs_buffer: []Limb) !void { assert(r.limbs.ptr != a.limbs.ptr); // illegal aliasing // Handle all the trivial cases first switch (b) { 0 => { // a^0 = 1 return r.set(1); }, 1 => { // a^1 = a return r.copy(a); }, else => {}, } if (a.eqZero()) { // 0^b = 0 return r.set(0); } else if (a.limbs.len == 1 and a.limbs[0] == 1) { // 1^b = 1 and -1^b = ±1 r.set(1); r.positive = a.positive or (b & 1) == 0; return; } // Here a>1 and b>1 const needed_limbs = calcPowLimbsBufferLen(a.bitCountAbs(), b); assert(r.limbs.len >= needed_limbs); assert(limbs_buffer.len >= needed_limbs); llpow(r.limbs, a.limbs, b, limbs_buffer); r.normalize(needed_limbs); r.positive = a.positive or (b & 1) == 0; } /// rma may not alias x or y. /// x and y may alias each other. /// Asserts that `rma` has enough limbs to store the result. Upper bound is given by `calcGcdNoAliasLimbLen`. /// /// `limbs_buffer` is used for temporary storage during the operation. pub fn gcdNoAlias(rma: *Mutable, x: Const, y: Const, limbs_buffer: *std.ArrayList(Limb)) !void { assert(rma.limbs.ptr != x.limbs.ptr); // illegal aliasing assert(rma.limbs.ptr != y.limbs.ptr); // illegal aliasing return gcdLehmer(rma, x, y, limbs_buffer); } fn gcdLehmer(result: *Mutable, xa: Const, ya: Const, limbs_buffer: *std.ArrayList(Limb)) !void { var x = try xa.toManaged(limbs_buffer.allocator); defer x.deinit(); x.abs(); var y = try ya.toManaged(limbs_buffer.allocator); defer y.deinit(); y.abs(); if (x.toConst().order(y.toConst()) == .lt) { x.swap(&y); } var t_big = try Managed.init(limbs_buffer.allocator); defer t_big.deinit(); var r = try Managed.init(limbs_buffer.allocator); defer r.deinit(); var tmp_x = try Managed.init(limbs_buffer.allocator); defer tmp_x.deinit(); while (y.len() > 1) { assert(x.isPositive() and y.isPositive()); assert(x.len() >= y.len()); var xh: SignedDoubleLimb = x.limbs[x.len() - 1]; var yh: SignedDoubleLimb = if (x.len() > y.len()) 0 else y.limbs[x.len() - 1]; var A: SignedDoubleLimb = 1; var B: SignedDoubleLimb = 0; var C: SignedDoubleLimb = 0; var D: SignedDoubleLimb = 1; while (yh + C != 0 and yh + D != 0) { const q = @divFloor(xh + A, yh + C); const qp = @divFloor(xh + B, yh + D); if (q != qp) { break; } var t = A - q * C; A = C; C = t; t = B - q * D; B = D; D = t; t = xh - q * yh; xh = yh; yh = t; } if (B == 0) { // t_big = x % y, r is unused try r.divTrunc(&t_big, x.toConst(), y.toConst()); assert(t_big.isPositive()); x.swap(&y); y.swap(&t_big); } else { var storage: [8]Limb = undefined; const Ap = fixedIntFromSignedDoubleLimb(A, storage[0..2]).toConst(); const Bp = fixedIntFromSignedDoubleLimb(B, storage[2..4]).toConst(); const Cp = fixedIntFromSignedDoubleLimb(C, storage[4..6]).toConst(); const Dp = fixedIntFromSignedDoubleLimb(D, storage[6..8]).toConst(); // t_big = Ax + By try r.mul(x.toConst(), Ap); try t_big.mul(y.toConst(), Bp); try t_big.add(r.toConst(), t_big.toConst()); // u = Cx + Dy, r as u try tmp_x.copy(x.toConst()); try x.mul(tmp_x.toConst(), Cp); try r.mul(y.toConst(), Dp); try r.add(x.toConst(), r.toConst()); x.swap(&t_big); y.swap(&r); } } // euclidean algorithm assert(x.toConst().order(y.toConst()) != .lt); while (!y.toConst().eqZero()) { try t_big.divTrunc(&r, x.toConst(), y.toConst()); x.swap(&y); y.swap(&r); } result.copy(x.toConst()); } // Truncates by default. fn div(q: *Mutable, r: *Mutable, x: *Mutable, y: *Mutable) void { assert(!y.eqZero()); // division by zero assert(q != r); // illegal aliasing const q_positive = (x.positive == y.positive); const r_positive = x.positive; if (x.toConst().orderAbs(y.toConst()) == .lt) { // q may alias x so handle r first. r.copy(x.toConst()); r.positive = r_positive; q.set(0); return; } // Handle trailing zero-words of divisor/dividend. These are not handled in the following // algorithms. // Note, there must be a non-zero limb for either. // const x_trailing = std.mem.indexOfScalar(Limb, x.limbs[0..x.len], 0).?; // const y_trailing = std.mem.indexOfScalar(Limb, y.limbs[0..y.len], 0).?; const x_trailing = for (x.limbs[0..x.len], 0..) |xi, i| { if (xi != 0) break i; } else unreachable; const y_trailing = for (y.limbs[0..y.len], 0..) |yi, i| { if (yi != 0) break i; } else unreachable; const xy_trailing = math.min(x_trailing, y_trailing); if (y.len - xy_trailing == 1) { lldiv1(q.limbs, &r.limbs[0], x.limbs[xy_trailing..x.len], y.limbs[y.len - 1]); q.normalize(x.len - xy_trailing); q.positive = q_positive; r.len = 1; r.positive = r_positive; } else { // Shrink x, y such that the trailing zero limbs shared between are removed. var x0 = Mutable{ .limbs = x.limbs[xy_trailing..], .len = x.len - xy_trailing, .positive = true, }; var y0 = Mutable{ .limbs = y.limbs[xy_trailing..], .len = y.len - xy_trailing, .positive = true, }; divmod(q, r, &x0, &y0); q.positive = q_positive; r.positive = r_positive; } if (xy_trailing != 0) { // Manually shift here since we know its limb aligned. mem.copyBackwards(Limb, r.limbs[xy_trailing..], r.limbs[0..r.len]); mem.set(Limb, r.limbs[0..xy_trailing], 0); r.len += xy_trailing; } } /// Handbook of Applied Cryptography, 14.20 /// /// x = qy + r where 0 <= r < y /// y is modified but returned intact. fn divmod( q: *Mutable, r: *Mutable, x: *Mutable, y: *Mutable, ) void { // 0. // Normalize so that y[t] > b/2 const lz = @clz(y.limbs[y.len - 1]); const norm_shift = if (lz == 0 and y.toConst().isOdd()) limb_bits // Force an extra limb so that y is even. else lz; x.shiftLeft(x.toConst(), norm_shift); y.shiftLeft(y.toConst(), norm_shift); const n = x.len - 1; const t = y.len - 1; const shift = n - t; // 1. // for 0 <= j <= n - t, set q[j] to 0 q.len = shift + 1; q.positive = true; mem.set(Limb, q.limbs[0..q.len], 0); // 2. // while x >= y * b^(n - t): // x -= y * b^(n - t) // q[n - t] += 1 // Note, this algorithm is performed only once if y[t] > radix/2 and y is even, which we // enforced in step 0. This means we can replace the while with an if. // Note, multiplication by b^(n - t) comes down to shifting to the right by n - t limbs. // We can also replace x >= y * b^(n - t) by x/b^(n - t) >= y, and use shifts for that. { // x >= y * b^(n - t) can be replaced by x/b^(n - t) >= y. // 'divide' x by b^(n - t) var tmp = Mutable{ .limbs = x.limbs[shift..], .len = x.len - shift, .positive = true, }; if (tmp.toConst().order(y.toConst()) != .lt) { // Perform x -= y * b^(n - t) // Note, we can subtract y from x[n - t..] and get the result without shifting. // We can also re-use tmp which already contains the relevant part of x. Note that // this also edits x. // Due to the check above, this cannot underflow. tmp.sub(tmp.toConst(), y.toConst()); // tmp.sub normalized tmp, but we need to normalize x now. x.limbs.len = tmp.limbs.len + shift; q.limbs[shift] += 1; } } // 3. // for i from n down to t + 1, do var i = n; while (i >= t + 1) : (i -= 1) { const k = i - t - 1; // 3.1. // if x_i == y_t: // q[i - t - 1] = b - 1 // else: // q[i - t - 1] = (x[i] * b + x[i - 1]) / y[t] if (x.limbs[i] == y.limbs[t]) { q.limbs[k] = maxInt(Limb); } else { const q0 = (@as(DoubleLimb, x.limbs[i]) << limb_bits) | @as(DoubleLimb, x.limbs[i - 1]); const n0 = @as(DoubleLimb, y.limbs[t]); q.limbs[k] = @as(Limb, @intCast(q0 / n0)); } // 3.2 // while q[i - t - 1] * (y[t] * b + y[t - 1] > x[i] * b * b + x[i - 1] + x[i - 2]: // q[i - t - 1] -= 1 // Note, if y[t] > b / 2 this part is repeated no more than twice. // Extract from y. const y0 = if (t > 0) y.limbs[t - 1] else 0; const y1 = y.limbs[t]; // Extract from x. // Note, big endian. const tmp0 = [_]Limb{ x.limbs[i], if (i >= 1) x.limbs[i - 1] else 0, if (i >= 2) x.limbs[i - 2] else 0, }; while (true) { // Ad-hoc 2x1 multiplication with q[i - t - 1]. // Note, big endian. var tmp1 = [_]Limb{ 0, undefined, undefined }; tmp1[2] = addMulLimbWithCarry(0, y0, q.limbs[k], &tmp1[0]); tmp1[1] = addMulLimbWithCarry(0, y1, q.limbs[k], &tmp1[0]); // Big-endian compare if (mem.order(Limb, &tmp1, &tmp0) != .gt) break; q.limbs[k] -= 1; } // 3.3. // x -= q[i - t - 1] * y * b^(i - t - 1) // Note, we multiply by a single limb here. // The shift doesn't need to be performed if we add the result of the first multiplication // to x[i - t - 1]. // mem.set(Limb, x.limbs, 0); const underflow = llmulLimb(.sub, x.limbs[k..x.len], y.limbs[0..y.len], q.limbs[k]); // 3.4. // if x < 0: // x += y * b^(i - t - 1) // q[i - t - 1] -= 1 // Note, we check for x < 0 using the underflow flag from the previous operation. if (underflow) { // While we didn't properly set the signedness of x, this operation should 'flow' it back to positive. llaccum(.add, x.limbs[k..x.len], y.limbs[0..y.len]); q.limbs[k] -= 1; } x.normalize(x.len); } q.normalize(q.len); // De-normalize r and y. r.shiftRight(x.toConst(), norm_shift); y.shiftRight(y.toConst(), norm_shift); } /// Truncate an integer to a number of bits, following 2s-complement semantics. /// r may alias a. /// /// Asserts `r` has enough storage to store the result. /// The upper bound is `calcTwosCompLimbCount(a.len)`. pub fn truncate(r: *Mutable, a: Const, signedness: Signedness, bit_count: usize) void { const req_limbs = calcTwosCompLimbCount(bit_count); // Handle 0-bit integers. if (req_limbs == 0 or a.eqZero()) { r.set(0); return; } const bit = @as(Log2Limb, @truncate(bit_count - 1)); const signmask = @as(Limb, 1) << bit; // 0b0..010...0 where 1 is the sign bit. const mask = (signmask << 1) -% 1; // 0b0..01..1 where the leftmost 1 is the sign bit. if (!a.positive) { // Convert the integer from sign-magnitude into twos-complement. // -x = ~(x - 1) // Note, we simply take req_limbs * @bitSizeOf(Limb) as the // target bit count. r.addScalar(a.abs(), -1); // Zero-extend the result if (req_limbs > r.len) { mem.set(Limb, r.limbs[r.len..req_limbs], 0); } // Truncate to required number of limbs. assert(r.limbs.len >= req_limbs); r.len = req_limbs; // Without truncating, we can already peek at the sign bit of the result here. // Note that it will be 0 if the result is negative, as we did not apply the flip here. // If the result is negative, we have // -(-x & mask) // = ~(~(x - 1) & mask) + 1 // = ~(~((x - 1) | ~mask)) + 1 // = ((x - 1) | ~mask)) + 1 // Note, this is only valid for the target bits and not the upper bits // of the most significant limb. Those still need to be cleared. // Also note that `mask` is zero for all other bits, reducing to the identity. // This means that we still need to use & mask to clear off the upper bits. if (signedness == .signed and r.limbs[r.len - 1] & signmask == 0) { // Re-add the one and negate to get the result. r.limbs[r.len - 1] &= mask; // Note, addition cannot require extra limbs here as we did a subtraction before. r.addScalar(r.toConst(), 1); r.normalize(r.len); r.positive = false; } else { llnot(r.limbs[0..r.len]); r.limbs[r.len - 1] &= mask; r.normalize(r.len); } } else { if (a.limbs.len < req_limbs) { // Integer fits within target bits, no wrapping required. r.copy(a); return; } r.copy(.{ .positive = a.positive, .limbs = a.limbs[0..req_limbs], }); r.limbs[r.len - 1] &= mask; r.normalize(r.len); if (signedness == .signed and r.limbs[r.len - 1] & signmask != 0) { // Convert 2s-complement back to sign-magnitude. // Sign-extend the upper bits so that they are inverted correctly. r.limbs[r.len - 1] |= ~mask; llnot(r.limbs[0..r.len]); // Note, can only overflow if r holds 0xFFF...F which can only happen if // a holds 0. r.addScalar(r.toConst(), 1); r.positive = false; } } } /// Saturate an integer to a number of bits, following 2s-complement semantics. /// r may alias a. /// /// Asserts `r` has enough storage to store the result. /// The upper bound is `calcTwosCompLimbCount(a.len)`. pub fn saturate(r: *Mutable, a: Const, signedness: Signedness, bit_count: usize) void { if (!a.fitsInTwosComp(signedness, bit_count)) { r.setTwosCompIntLimit(if (r.positive) .max else .min, signedness, bit_count); } } pub fn readTwosComplement( x: *Mutable, buffer: []const u8, bit_count: usize, endian: Endian, signedness: Signedness, ) void { if (bit_count == 0) { x.limbs[0] = 0; x.len = 1; x.positive = true; return; } // zig fmt: off switch (signedness) { .signed => { if (bit_count <= 8) return x.set(mem.readInt( i8, buffer[0.. 1], endian)); if (bit_count <= 16) return x.set(mem.readInt( i16, buffer[0.. 2], endian)); if (bit_count <= 32) return x.set(mem.readInt( i32, buffer[0.. 4], endian)); if (bit_count <= 64) return x.set(mem.readInt( i64, buffer[0.. 8], endian)); if (bit_count <= 128) return x.set(mem.readInt(i128, buffer[0..16], endian)); }, .unsigned => { if (bit_count <= 8) return x.set(mem.readInt( u8, buffer[0.. 1], endian)); if (bit_count <= 16) return x.set(mem.readInt( u16, buffer[0.. 2], endian)); if (bit_count <= 32) return x.set(mem.readInt( u32, buffer[0.. 4], endian)); if (bit_count <= 64) return x.set(mem.readInt( u64, buffer[0.. 8], endian)); if (bit_count <= 128) return x.set(mem.readInt(u128, buffer[0..16], endian)); }, } // zig fmt: on @panic("TODO implement std lib big int readTwosComplement"); } /// Normalize a possible sequence of leading zeros. /// /// [1, 2, 3, 4, 0] -> [1, 2, 3, 4] /// [1, 2, 0, 0, 0] -> [1, 2] /// [0, 0, 0, 0, 0] -> [0] fn normalize(r: *Mutable, length: usize) void { r.len = llnormalize(r.limbs[0..length]); } }; /// A arbitrary-precision big integer, with a fixed set of immutable limbs. pub const Const = struct { /// Raw digits. These are: /// /// * Little-endian ordered /// * limbs.len >= 1 /// * Zero is represented as limbs.len == 1 with limbs[0] == 0. /// /// Accessing limbs directly should be avoided. limbs: []const Limb, positive: bool, /// The result is an independent resource which is managed by the caller. pub fn toManaged(self: Const, allocator: *Allocator) Allocator.Error!Managed { const limbs = try allocator.alloc(Limb, math.max(Managed.default_capacity, self.limbs.len)); mem.copy(Limb, limbs, self.limbs); return Managed{ .allocator = allocator, .limbs = limbs, .metadata = if (self.positive) self.limbs.len & ~Managed.sign_bit else self.limbs.len | Managed.sign_bit, }; } /// Asserts `limbs` is big enough to store the value. pub fn toMutable(self: Const, limbs: []Limb) Mutable { mem.copy(Limb, limbs, self.limbs[0..self.limbs.len]); return .{ .limbs = limbs, .positive = self.positive, .len = self.limbs.len, }; } pub fn dump(self: Const) void { for (self.limbs[0..self.limbs.len]) |limb| { std.debug.warn("{x} ", .{limb}); } std.debug.warn("positive={}\n", .{self.positive}); } pub fn abs(self: Const) Const { return .{ .limbs = self.limbs, .positive = true, }; } pub fn negate(self: Const) Const { return .{ .limbs = self.limbs, .positive = !self.positive, }; } pub fn isOdd(self: Const) bool { return self.limbs[0] & 1 != 0; } pub fn isEven(self: Const) bool { return !self.isOdd(); } /// Returns the number of bits required to represent the absolute value of an integer. pub fn bitCountAbs(self: Const) usize { return (self.limbs.len - 1) * limb_bits + (limb_bits - @clz(self.limbs[self.limbs.len - 1])); } /// Returns the number of bits required to represent the integer in twos-complement form. /// /// If the integer is negative the value returned is the number of bits needed by a signed /// integer to represent the value. If positive the value is the number of bits for an /// unsigned integer. Any unsigned integer will fit in the signed integer with bitcount /// one greater than the returned value. /// /// e.g. -127 returns 8 as it will fit in an i8. 127 returns 7 since it fits in a u7. pub fn bitCountTwosComp(self: Const) usize { var bits = self.bitCountAbs(); // If the entire value has only one bit set (e.g. 0b100000000) then the negation in twos // complement requires one less bit. if (!self.positive) block: { bits += 1; if (@popCount(self.limbs[self.limbs.len - 1]) == 1) { for (self.limbs[0 .. self.limbs.len - 1]) |limb| { if (@popCount(limb) != 0) { break :block; } } bits -= 1; } } return bits; } pub fn fitsInTwosComp(self: Const, signedness: Signedness, bit_count: usize) bool { if (self.eqZero()) { return true; } if (signedness == .unsigned and !self.positive) { return false; } const req_bits = self.bitCountTwosComp() + @intFromBool(self.positive and signedness == .signed); return bit_count >= req_bits; } /// Returns whether self can fit into an integer of the requested type. pub fn fits(self: Const, comptime T: type) bool { const info = @typeInfo(T).Int; return self.fitsInTwosComp(info.signedness, info.bits); } /// Returns the approximate size of the integer in the given base. Negative values accommodate for /// the minus sign. This is used for determining the number of characters needed to print the /// value. It is inexact and may exceed the given value by ~1-2 bytes. /// TODO See if we can make this exact. pub fn sizeInBaseUpperBound(self: Const, base: usize) usize { const bit_count = @as(usize, @intFromBool(!self.positive)) + self.bitCountAbs(); return (bit_count / math.log2(base)) + 2; } pub const ConvertError = error{ NegativeIntoUnsigned, TargetTooSmall, }; /// Convert self to type T. /// /// Returns an error if self cannot be narrowed into the requested type without truncation. pub fn to(self: Const, comptime T: type) ConvertError!T { switch (@typeInfo(T)) { .Int => |info| { const UT = std.meta.Int(.unsigned, info.bits); if (self.bitCountTwosComp() > info.bits) { return error.TargetTooSmall; } var r: UT = 0; if (@sizeOf(UT) <= @sizeOf(Limb)) { r = @as(UT, @intCast(self.limbs[0])); } else { for (self.limbs[0..self.limbs.len], 0..) |_, ri| { const limb = self.limbs[self.limbs.len - ri - 1]; r <<= limb_bits; r |= limb; } } if (info.signedness == .unsigned) { return if (self.positive) @as(T, @intCast(r)) else error.NegativeIntoUnsigned; } else { if (self.positive) { return @as(T, @intCast(r)); } else { if (math.cast(T, r)) |ok| { return -ok; } else |_| { return minInt(T); } } } }, else => @compileError("cannot convert Const to type " ++ @typeName(T)), } } /// To allow `std.fmt.format` to work with this type. /// If the integer is larger than `pow(2, 64 * @sizeOf(usize) * 8), this function will fail /// to print the string, printing "(BigInt)" instead of a number. /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory. /// See `toString` and `toStringAlloc` for a way to print big integers without failure. pub fn format( self: Const, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype, ) !void { _ = options; comptime var radix = 10; comptime var case: std.fmt.Case = .lower; if (fmt.len == 0 or comptime mem.eql(u8, fmt, "d")) { radix = 10; case = .lower; } else if (comptime mem.eql(u8, fmt, "b")) { radix = 2; case = .lower; } else if (comptime mem.eql(u8, fmt, "x")) { radix = 16; case = .lower; } else if (comptime mem.eql(u8, fmt, "X")) { radix = 16; case = .upper; } else { @compileError("Unknown format string: '" ++ fmt ++ "'"); } var limbs: [128]Limb = undefined; const needed_limbs = calcDivLimbsBufferLen(self.limbs.len, 1); if (needed_limbs > limbs.len) return out_stream.writeAll("(BigInt)"); // This is the inverse of calcDivLimbsBufferLen const available_len = (limbs.len / 3) - 2; const biggest: Const = .{ .limbs = &([1]Limb{math.maxInt(Limb)} ** available_len), .positive = false, }; var buf: [biggest.sizeInBaseUpperBound(radix)]u8 = undefined; const len = self.toString(&buf, radix, case, &limbs); return out_stream.writeAll(buf[0..len]); } /// Converts self to a string in the requested base. /// Caller owns returned memory. /// Asserts that `base` is in the range [2, 16]. /// See also `toString`, a lower level function than this. pub fn toStringAlloc(self: Const, allocator: *Allocator, base: u8, case: std.fmt.Case) Allocator.Error![]u8 { assert(base >= 2); assert(base <= 16); if (self.eqZero()) { return allocator.dupe(u8, "0"); } const string = try allocator.alloc(u8, self.sizeInBaseUpperBound(base)); errdefer allocator.free(string); const limbs = try allocator.alloc(Limb, calcToStringLimbsBufferLen(self.limbs.len, base)); defer allocator.free(limbs); return allocator.shrink(string, self.toString(string, base, case, limbs)); } /// Converts self to a string in the requested base. /// Asserts that `base` is in the range [2, 16]. /// `string` is a caller-provided slice of at least `sizeInBaseUpperBound` bytes, /// where the result is written to. /// Returns the length of the string. /// `limbs_buffer` is caller-provided memory for `toString` to use as a working area. It must have /// length of at least `calcToStringLimbsBufferLen`. /// In the case of power-of-two base, `limbs_buffer` is ignored. /// See also `toStringAlloc`, a higher level function than this. pub fn toString(self: Const, string: []u8, base: u8, case: std.fmt.Case, limbs_buffer: []Limb) usize { assert(base >= 2); assert(base <= 16); if (self.eqZero()) { string[0] = '0'; return 1; } var digits_len: usize = 0; // Power of two: can do a single pass and use masks to extract digits. if (math.isPowerOfTwo(base)) { const base_shift = math.log2_int(Limb, base); outer: for (self.limbs[0..self.limbs.len]) |limb| { var shift: usize = 0; while (shift < limb_bits) : (shift += base_shift) { const r = @as(u8, @intCast((limb >> @as(Log2Limb, @intCast(shift))) & @as(Limb, base - 1))); const ch = std.fmt.digitToChar(r, case); string[digits_len] = ch; digits_len += 1; // If we hit the end, it must be all zeroes from here. if (digits_len == string.len) break :outer; } } // Always will have a non-zero digit somewhere. while (string[digits_len - 1] == '0') { digits_len -= 1; } } else { // Non power-of-two: batch divisions per word size. const digits_per_limb = math.log(Limb, base, maxInt(Limb)); var limb_base: Limb = 1; var j: usize = 0; while (j < digits_per_limb) : (j += 1) { limb_base *= base; } const b: Const = .{ .limbs = &[_]Limb{limb_base}, .positive = true }; var q: Mutable = .{ .limbs = limbs_buffer[0 .. self.limbs.len + 2], .positive = true, // Make absolute by ignoring self.positive. .len = self.limbs.len, }; mem.copy(Limb, q.limbs, self.limbs); var r: Mutable = .{ .limbs = limbs_buffer[q.limbs.len..][0..self.limbs.len], .positive = true, .len = 1, }; r.limbs[0] = 0; const rest_of_the_limbs_buf = limbs_buffer[q.limbs.len + r.limbs.len ..]; while (q.len >= 2) { // Passing an allocator here would not be helpful since this division is destroying // information, not creating it. [TODO citation needed] q.divTrunc(&r, q.toConst(), b, rest_of_the_limbs_buf); var r_word = r.limbs[0]; var i: usize = 0; while (i < digits_per_limb) : (i += 1) { const ch = std.fmt.digitToChar(@as(u8, @intCast(r_word % base)), case); r_word /= base; string[digits_len] = ch; digits_len += 1; } } { assert(q.len == 1); var r_word = q.limbs[0]; while (r_word != 0) { const ch = std.fmt.digitToChar(@as(u8, @intCast(r_word % base)), case); r_word /= base; string[digits_len] = ch; digits_len += 1; } } } if (!self.positive) { string[digits_len] = '-'; digits_len += 1; } const s = string[0..digits_len]; mem.reverse(u8, s); return s.len; } /// Asserts that `buffer` and `bit_count` are large enough to store the value. pub fn writeTwosComplement(x: Const, buffer: []u8, bit_count: usize, endian: Endian) void { if (bit_count == 0) return; // zig fmt: off if (x.positive) { if (bit_count <= 8) return mem.writeInt( u8, buffer[0.. 1], x.to( u8) catch unreachable, endian); if (bit_count <= 16) return mem.writeInt( u16, buffer[0.. 2], x.to( u16) catch unreachable, endian); if (bit_count <= 32) return mem.writeInt( u32, buffer[0.. 4], x.to( u32) catch unreachable, endian); if (bit_count <= 64) return mem.writeInt( u64, buffer[0.. 8], x.to( u64) catch unreachable, endian); if (bit_count <= 128) return mem.writeInt(u128, buffer[0..16], x.to(u128) catch unreachable, endian); } else { if (bit_count <= 8) return mem.writeInt( i8, buffer[0.. 1], x.to( i8) catch unreachable, endian); if (bit_count <= 16) return mem.writeInt( i16, buffer[0.. 2], x.to( i16) catch unreachable, endian); if (bit_count <= 32) return mem.writeInt( i32, buffer[0.. 4], x.to( i32) catch unreachable, endian); if (bit_count <= 64) return mem.writeInt( i64, buffer[0.. 8], x.to( i64) catch unreachable, endian); if (bit_count <= 128) return mem.writeInt(i128, buffer[0..16], x.to(i128) catch unreachable, endian); } // zig fmt: on @panic("TODO implement std lib big int writeTwosComplement for larger than 128 bits"); } /// Returns `math.Order.lt`, `math.Order.eq`, `math.Order.gt` if /// `|a| < |b|`, `|a| == |b|`, or `|a| > |b|` respectively. pub fn orderAbs(a: Const, b: Const) math.Order { if (a.limbs.len < b.limbs.len) { return .lt; } if (a.limbs.len > b.limbs.len) { return .gt; } var i: usize = a.limbs.len - 1; while (i != 0) : (i -= 1) { if (a.limbs[i] != b.limbs[i]) { break; } } if (a.limbs[i] < b.limbs[i]) { return .lt; } else if (a.limbs[i] > b.limbs[i]) { return .gt; } else { return .eq; } } /// Returns `math.Order.lt`, `math.Order.eq`, `math.Order.gt` if `a < b`, `a == b` or `a > b` respectively. pub fn order(a: Const, b: Const) math.Order { if (a.positive != b.positive) { return if (a.positive) .gt else .lt; } else { const r = orderAbs(a, b); return if (a.positive) r else switch (r) { .lt => math.Order.gt, .eq => math.Order.eq, .gt => math.Order.lt, }; } } /// Same as `order` but the right-hand operand is a primitive integer. pub fn orderAgainstScalar(lhs: Const, scalar: anytype) math.Order { var limbs: [calcLimbLen(scalar)]Limb = undefined; const rhs = Mutable.init(&limbs, scalar); return order(lhs, rhs.toConst()); } /// Returns true if `a == 0`. pub fn eqZero(a: Const) bool { var d: Limb = 0; for (a.limbs) |limb| d |= limb; return d == 0; } /// Returns true if `|a| == |b|`. pub fn eqAbs(a: Const, b: Const) bool { return orderAbs(a, b) == .eq; } /// Returns true if `a == b`. pub fn eq(a: Const, b: Const) bool { return order(a, b) == .eq; } }; /// An arbitrary-precision big integer along with an allocator which manages the memory. /// /// Memory is allocated as needed to ensure operations never overflow. The range /// is bounded only by available memory. pub const Managed = struct { pub const sign_bit: usize = 1 << (@typeInfo(usize).Int.bits - 1); /// Default number of limbs to allocate on creation of a `Managed`. pub const default_capacity = 4; /// Allocator used by the Managed when requesting memory. allocator: *Allocator, /// Raw digits. These are: /// /// * Little-endian ordered /// * limbs.len >= 1 /// * Zero is represent as Managed.len() == 1 with limbs[0] == 0. /// /// Accessing limbs directly should be avoided. limbs: []Limb, /// High bit is the sign bit. If set, Managed is negative, else Managed is positive. /// The remaining bits represent the number of limbs used by Managed. metadata: usize, /// Creates a new `Managed`. `default_capacity` limbs will be allocated immediately. /// The integer value after initializing is `0`. pub fn init(allocator: *Allocator) !Managed { return initCapacity(allocator, default_capacity); } pub fn toMutable(self: Managed) Mutable { return .{ .limbs = self.limbs, .positive = self.isPositive(), .len = self.len(), }; } pub fn toConst(self: Managed) Const { return .{ .limbs = self.limbs[0..self.len()], .positive = self.isPositive(), }; } /// Creates a new `Managed` with value `value`. /// /// This is identical to an `init`, followed by a `set`. pub fn initSet(allocator: *Allocator, value: anytype) !Managed { var s = try Managed.init(allocator); try s.set(value); return s; } /// Creates a new Managed with a specific capacity. If capacity < default_capacity then the /// default capacity will be used instead. /// The integer value after initializing is `0`. pub fn initCapacity(allocator: *Allocator, capacity: usize) !Managed { return Managed{ .allocator = allocator, .metadata = 1, .limbs = block: { const limbs = try allocator.alloc(Limb, math.max(default_capacity, capacity)); limbs[0] = 0; break :block limbs; }, }; } /// Returns the number of limbs currently in use. pub fn len(self: Managed) usize { return self.metadata & ~sign_bit; } /// Returns whether an Managed is positive. pub fn isPositive(self: Managed) bool { return self.metadata & sign_bit == 0; } /// Sets the sign of an Managed. pub fn setSign(self: *Managed, positive: bool) void { if (positive) { self.metadata &= ~sign_bit; } else { self.metadata |= sign_bit; } } /// Sets the length of an Managed. /// /// If setLen is used, then the Managed must be normalized to suit. pub fn setLen(self: *Managed, new_len: usize) void { self.metadata &= sign_bit; self.metadata |= new_len; } pub fn setMetadata(self: *Managed, positive: bool, length: usize) void { self.metadata = if (positive) length & ~sign_bit else length | sign_bit; } /// Ensures an Managed has enough space allocated for capacity limbs. If the Managed does not have /// sufficient capacity, the exact amount will be allocated. This occurs even if the requested /// capacity is only greater than the current capacity by one limb. pub fn ensureCapacity(self: *Managed, capacity: usize) !void { if (capacity <= self.limbs.len) { return; } self.limbs = try self.allocator.realloc(self.limbs, capacity); } /// Frees all associated memory. pub fn deinit(self: *Managed) void { self.allocator.free(self.limbs); self.* = undefined; } /// Returns a `Managed` with the same value. The returned `Managed` is a deep copy and /// can be modified separately from the original, and its resources are managed /// separately from the original. pub fn clone(other: Managed) !Managed { return other.cloneWithDifferentAllocator(other.allocator); } pub fn cloneWithDifferentAllocator(other: Managed, allocator: *Allocator) !Managed { return Managed{ .allocator = allocator, .metadata = other.metadata, .limbs = block: { var limbs = try allocator.alloc(Limb, other.len()); mem.copy(Limb, limbs[0..], other.limbs[0..other.len()]); break :block limbs; }, }; } /// Copies the value of the integer to an existing `Managed` so that they both have the same value. /// Extra memory will be allocated if the receiver does not have enough capacity. pub fn copy(self: *Managed, other: Const) !void { if (self.limbs.ptr == other.limbs.ptr) return; try self.ensureCapacity(other.limbs.len); mem.copy(Limb, self.limbs[0..], other.limbs[0..other.limbs.len]); self.setMetadata(other.positive, other.limbs.len); } /// Efficiently swap a `Managed` with another. This swaps the limb pointers and a full copy is not /// performed. The address of the limbs field will not be the same after this function. pub fn swap(self: *Managed, other: *Managed) void { mem.swap(Managed, self, other); } /// Debugging tool: prints the state to stderr. pub fn dump(self: Managed) void { for (self.limbs[0..self.len()]) |limb| { std.debug.warn("{x} ", .{limb}); } std.debug.warn("capacity={} positive={}\n", .{ self.limbs.len, self.isPositive() }); } /// Negate the sign. pub fn negate(self: *Managed) void { self.metadata ^= sign_bit; } /// Make positive. pub fn abs(self: *Managed) void { self.metadata &= ~sign_bit; } pub fn isOdd(self: Managed) bool { return self.limbs[0] & 1 != 0; } pub fn isEven(self: Managed) bool { return !self.isOdd(); } /// Returns the number of bits required to represent the absolute value of an integer. pub fn bitCountAbs(self: Managed) usize { return self.toConst().bitCountAbs(); } /// Returns the number of bits required to represent the integer in twos-complement form. /// /// If the integer is negative the value returned is the number of bits needed by a signed /// integer to represent the value. If positive the value is the number of bits for an /// unsigned integer. Any unsigned integer will fit in the signed integer with bitcount /// one greater than the returned value. /// /// e.g. -127 returns 8 as it will fit in an i8. 127 returns 7 since it fits in a u7. pub fn bitCountTwosComp(self: Managed) usize { return self.toConst().bitCountTwosComp(); } pub fn fitsInTwosComp(self: Managed, signedness: Signedness, bit_count: usize) bool { return self.toConst().fitsInTwosComp(signedness, bit_count); } /// Returns whether self can fit into an integer of the requested type. pub fn fits(self: Managed, comptime T: type) bool { return self.toConst().fits(T); } /// Returns the approximate size of the integer in the given base. Negative values accommodate for /// the minus sign. This is used for determining the number of characters needed to print the /// value. It is inexact and may exceed the given value by ~1-2 bytes. pub fn sizeInBaseUpperBound(self: Managed, base: usize) usize { return self.toConst().sizeInBaseUpperBound(base); } /// Sets an Managed to value. Value must be an primitive integer type. pub fn set(self: *Managed, value: anytype) Allocator.Error!void { try self.ensureCapacity(calcLimbLen(value)); var m = self.toMutable(); m.set(value); self.setMetadata(m.positive, m.len); } pub const ConvertError = Const.ConvertError; /// Convert self to type T. /// /// Returns an error if self cannot be narrowed into the requested type without truncation. pub fn to(self: Managed, comptime T: type) ConvertError!T { return self.toConst().to(T); } /// Set self from the string representation `value`. /// /// `value` must contain only digits <= `base` and is case insensitive. Base prefixes are /// not allowed (e.g. 0x43 should simply be 43). Underscores in the input string are /// ignored and can be used as digit separators. /// /// Returns an error if memory could not be allocated or `value` has invalid digits for the /// requested base. /// /// self's allocator is used for temporary storage to boost multiplication performance. pub fn setString(self: *Managed, base: u8, value: []const u8) !void { if (base < 2 or base > 16) return error.InvalidBase; try self.ensureCapacity(calcSetStringLimbCount(base, value.len)); const limbs_buffer = try self.allocator.alloc(Limb, calcSetStringLimbsBufferLen(base, value.len)); defer self.allocator.free(limbs_buffer); var m = self.toMutable(); try m.setString(base, value, limbs_buffer, self.allocator); self.setMetadata(m.positive, m.len); } /// Set self to either bound of a 2s-complement integer. /// Note: The result is still sign-magnitude, not twos complement! In order to convert the /// result to twos complement, it is sufficient to take the absolute value. pub fn setTwosCompIntLimit( r: *Managed, limit: TwosCompIntLimit, signedness: Signedness, bit_count: usize, ) !void { try r.ensureCapacity(calcTwosCompLimbCount(bit_count)); var m = r.toMutable(); m.setTwosCompIntLimit(limit, signedness, bit_count); r.setMetadata(m.positive, m.len); } /// Converts self to a string in the requested base. Memory is allocated from the provided /// allocator and not the one present in self. pub fn toString(self: Managed, allocator: *Allocator, base: u8, case: std.fmt.Case) ![]u8 { _ = allocator; if (base < 2 or base > 16) return error.InvalidBase; return self.toConst().toStringAlloc(self.allocator, base, case); } /// To allow `std.fmt.format` to work with `Managed`. /// If the integer is larger than `pow(2, 64 * @sizeOf(usize) * 8), this function will fail /// to print the string, printing "(BigInt)" instead of a number. /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory. /// See `toString` and `toStringAlloc` for a way to print big integers without failure. pub fn format( self: Managed, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype, ) !void { return self.toConst().format(fmt, options, out_stream); } /// Returns math.Order.lt, math.Order.eq, math.Order.gt if |a| < |b|, |a| == /// |b| or |a| > |b| respectively. pub fn orderAbs(a: Managed, b: Managed) math.Order { return a.toConst().orderAbs(b.toConst()); } /// Returns math.Order.lt, math.Order.eq, math.Order.gt if a < b, a == b or a /// > b respectively. pub fn order(a: Managed, b: Managed) math.Order { return a.toConst().order(b.toConst()); } /// Returns true if a == 0. pub fn eqZero(a: Managed) bool { return a.toConst().eqZero(); } /// Returns true if |a| == |b|. pub fn eqAbs(a: Managed, b: Managed) bool { return a.toConst().eqAbs(b.toConst()); } /// Returns true if a == b. pub fn eq(a: Managed, b: Managed) bool { return a.toConst().eq(b.toConst()); } /// Normalize a possible sequence of leading zeros. /// /// [1, 2, 3, 4, 0] -> [1, 2, 3, 4] /// [1, 2, 0, 0, 0] -> [1, 2] /// [0, 0, 0, 0, 0] -> [0] pub fn normalize(r: *Managed, length: usize) void { assert(length > 0); assert(length <= r.limbs.len); var j = length; while (j > 0) : (j -= 1) { if (r.limbs[j - 1] != 0) { break; } } // Handle zero r.setLen(if (j != 0) j else 1); } /// r = a + scalar /// /// r and a may be aliases. If r aliases a, then caller must call /// `r.ensureAddScalarCapacity` prior to calling `add`. /// scalar is a primitive integer type. /// /// Returns an error if memory could not be allocated. pub fn addScalar(r: *Managed, a: Const, scalar: anytype) Allocator.Error!void { assert((r.limbs.ptr != a.limbs.ptr) or r.limbs.len >= math.max(a.limbs.len, calcLimbLen(scalar)) + 1); try r.ensureAddScalarCapacity(a, scalar); var m = r.toMutable(); m.addScalar(a, scalar); r.setMetadata(m.positive, m.len); } /// r = a + b /// /// r, a and b may be aliases. If r aliases a or b, then caller must call /// `r.ensureAddCapacity` prior to calling `add`. /// /// Returns an error if memory could not be allocated. pub fn add(r: *Managed, a: Const, b: Const) Allocator.Error!void { assert((r.limbs.ptr != a.limbs.ptr and r.limbs.ptr != b.limbs.ptr) or r.limbs.len >= math.max(a.limbs.len, b.limbs.len) + 1); try r.ensureAddCapacity(a, b); var m = r.toMutable(); m.add(a, b); r.setMetadata(m.positive, m.len); } /// r = a + b with 2s-complement wrapping semantics. /// /// r, a and b may be aliases. If r aliases a or b, then caller must call /// `r.ensureTwosCompCapacity` prior to calling `add`. /// /// Returns an error if memory could not be allocated. pub fn addWrap(r: *Managed, a: Const, b: Const, signedness: Signedness, bit_count: usize) Allocator.Error!void { try r.ensureTwosCompCapacity(bit_count); var m = r.toMutable(); m.addWrap(a, b, signedness, bit_count); r.setMetadata(m.positive, m.len); } /// r = a + b with 2s-complement saturating semantics. /// /// r, a and b may be aliases. If r aliases a or b, then caller must call /// `r.ensureTwosCompCapacity` prior to calling `add`. /// /// Returns an error if memory could not be allocated. pub fn addSat(r: *Managed, a: Const, b: Const, signedness: Signedness, bit_count: usize) Allocator.Error!void { try r.ensureTwosCompCapacity(bit_count); var m = r.toMutable(); m.addSat(a, b, signedness, bit_count); r.setMetadata(m.positive, m.len); } /// r = a - b /// /// r, a and b may be aliases. /// /// Returns an error if memory could not be allocated. pub fn sub(r: *Managed, a: Const, b: Const) !void { try r.ensureCapacity(math.max(a.limbs.len, b.limbs.len) + 1); var m = r.toMutable(); m.sub(a, b); r.setMetadata(m.positive, m.len); } /// r = a - b with 2s-complement wrapping semantics. /// /// r, a and b may be aliases. If r aliases a or b, then caller must call /// `r.ensureTwosCompCapacity` prior to calling `add`. /// /// Returns an error if memory could not be allocated. pub fn subWrap(r: *Managed, a: Const, b: Const, signedness: Signedness, bit_count: usize) Allocator.Error!void { try r.ensureTwosCompCapacity(bit_count); var m = r.toMutable(); m.subWrap(a, b, signedness, bit_count); r.setMetadata(m.positive, m.len); } /// r = a - b with 2s-complement saturating semantics. /// /// r, a and b may be aliases. If r aliases a or b, then caller must call /// `r.ensureTwosCompCapacity` prior to calling `add`. /// /// Returns an error if memory could not be allocated. pub fn subSat(r: *Managed, a: Const, b: Const, signedness: Signedness, bit_count: usize) Allocator.Error!void { try r.ensureTwosCompCapacity(bit_count); var m = r.toMutable(); m.subSat(a, b, signedness, bit_count); r.setMetadata(m.positive, m.len); } /// rma = a * b /// /// rma, a and b may be aliases. However, it is more efficient if rma does not alias a or b. /// If rma aliases a or b, then caller must call `rma.ensureMulCapacity` prior to calling `mul`. /// /// Returns an error if memory could not be allocated. /// /// rma's allocator is used for temporary storage to speed up the multiplication. pub fn mul(rma: *Managed, a: Const, b: Const) !void { var alias_count: usize = 0; if (rma.limbs.ptr == a.limbs.ptr) alias_count += 1; if (rma.limbs.ptr == b.limbs.ptr) alias_count += 1; assert(alias_count == 0 or rma.limbs.len >= a.limbs.len + b.limbs.len + 1); try rma.ensureMulCapacity(a, b); var m = rma.toMutable(); if (alias_count == 0) { m.mulNoAlias(a, b, rma.allocator); } else { const limb_count = calcMulLimbsBufferLen(a.limbs.len, b.limbs.len, alias_count); const limbs_buffer = try rma.allocator.alloc(Limb, limb_count); defer rma.allocator.free(limbs_buffer); m.mul(a, b, limbs_buffer, rma.allocator); } rma.setMetadata(m.positive, m.len); } /// rma = a * b with 2s-complement wrapping semantics. /// /// rma, a and b may be aliases. However, it is more efficient if rma does not alias a or b. /// If rma aliases a or b, then caller must call `ensureTwosCompCapacity` /// prior to calling `mul`. /// /// Returns an error if memory could not be allocated. /// /// rma's allocator is used for temporary storage to speed up the multiplication. pub fn mulWrap(rma: *Managed, a: Const, b: Const, signedness: Signedness, bit_count: usize) !void { var alias_count: usize = 0; if (rma.limbs.ptr == a.limbs.ptr) alias_count += 1; if (rma.limbs.ptr == b.limbs.ptr) alias_count += 1; try rma.ensureTwosCompCapacity(bit_count); var m = rma.toMutable(); if (alias_count == 0) { m.mulWrapNoAlias(a, b, signedness, bit_count, rma.allocator); } else { const limb_count = calcMulWrapLimbsBufferLen(bit_count, a.limbs.len, b.limbs.len, alias_count); const limbs_buffer = try rma.allocator.alloc(Limb, limb_count); defer rma.allocator.free(limbs_buffer); m.mulWrap(a, b, signedness, bit_count, limbs_buffer, rma.allocator); } rma.setMetadata(m.positive, m.len); } pub fn ensureTwosCompCapacity(r: *Managed, bit_count: usize) !void { try r.ensureCapacity(calcTwosCompLimbCount(bit_count)); } pub fn ensureAddScalarCapacity(r: *Managed, a: Const, scalar: anytype) !void { try r.ensureCapacity(math.max(a.limbs.len, calcLimbLen(scalar)) + 1); } pub fn ensureAddCapacity(r: *Managed, a: Const, b: Const) !void { try r.ensureCapacity(math.max(a.limbs.len, b.limbs.len) + 1); } pub fn ensureMulCapacity(rma: *Managed, a: Const, b: Const) !void { try rma.ensureCapacity(a.limbs.len + b.limbs.len + 1); } /// q = a / b (rem r) /// /// a / b are floored (rounded towards 0). /// /// Returns an error if memory could not be allocated. pub fn divFloor(q: *Managed, r: *Managed, a: Const, b: Const) !void { try q.ensureCapacity(a.limbs.len); try r.ensureCapacity(b.limbs.len); var mq = q.toMutable(); var mr = r.toMutable(); const limbs_buffer = try q.allocator.alloc(Limb, calcDivLimbsBufferLen(a.limbs.len, b.limbs.len)); defer q.allocator.free(limbs_buffer); mq.divFloor(&mr, a, b, limbs_buffer); q.setMetadata(mq.positive, mq.len); r.setMetadata(mr.positive, mr.len); } /// q = a / b (rem r) /// /// a / b are truncated (rounded towards -inf). /// /// Returns an error if memory could not be allocated. pub fn divTrunc(q: *Managed, r: *Managed, a: Const, b: Const) !void { try q.ensureCapacity(a.limbs.len); try r.ensureCapacity(b.limbs.len); var mq = q.toMutable(); var mr = r.toMutable(); const limbs_buffer = try q.allocator.alloc(Limb, calcDivLimbsBufferLen(a.limbs.len, b.limbs.len)); defer q.allocator.free(limbs_buffer); mq.divTrunc(&mr, a, b, limbs_buffer); q.setMetadata(mq.positive, mq.len); r.setMetadata(mr.positive, mr.len); } /// r = a << shift, in other words, r = a * 2^shift pub fn shiftLeft(r: *Managed, a: Managed, shift: usize) !void { try r.ensureCapacity(a.len() + (shift / limb_bits) + 1); var m = r.toMutable(); m.shiftLeft(a.toConst(), shift); r.setMetadata(m.positive, m.len); } /// r = a <<| shift with 2s-complement saturating semantics. pub fn shiftLeftSat(r: *Managed, a: Managed, shift: usize, signedness: Signedness, bit_count: usize) !void { try r.ensureTwosCompCapacity(bit_count); var m = r.toMutable(); m.shiftLeftSat(a.toConst(), shift, signedness, bit_count); r.setMetadata(m.positive, m.len); } /// r = a >> shift pub fn shiftRight(r: *Managed, a: Managed, shift: usize) !void { if (a.len() <= shift / limb_bits) { r.metadata = 1; r.limbs[0] = 0; return; } try r.ensureCapacity(a.len() - (shift / limb_bits)); var m = r.toMutable(); m.shiftRight(a.toConst(), shift); r.setMetadata(m.positive, m.len); } /// r = ~a under 2s-complement wrapping semantics. pub fn bitNotWrap(r: *Managed, a: Managed, signedness: Signedness, bit_count: usize) !void { try r.ensureTwosCompCapacity(bit_count); var m = r.toMutable(); m.bitNotWrap(a.toConst(), signedness, bit_count); r.setMetadata(m.positive, m.len); } /// r = a | b /// /// a and b are zero-extended to the longer of a or b. pub fn bitOr(r: *Managed, a: Managed, b: Managed) !void { try r.ensureCapacity(math.max(a.len(), b.len())); var m = r.toMutable(); m.bitOr(a.toConst(), b.toConst()); r.setMetadata(m.positive, m.len); } /// r = a & b pub fn bitAnd(r: *Managed, a: Managed, b: Managed) !void { const cap = if (a.isPositive() or b.isPositive()) math.min(a.len(), b.len()) else math.max(a.len(), b.len()) + 1; try r.ensureCapacity(cap); var m = r.toMutable(); m.bitAnd(a.toConst(), b.toConst()); r.setMetadata(m.positive, m.len); } /// r = a ^ b pub fn bitXor(r: *Managed, a: Managed, b: Managed) !void { var cap = math.max(a.len(), b.len()) + @intFromBool(a.isPositive() != b.isPositive()); try r.ensureCapacity(cap); var m = r.toMutable(); m.bitXor(a.toConst(), b.toConst()); r.setMetadata(m.positive, m.len); } /// rma may alias x or y. /// x and y may alias each other. /// /// rma's allocator is used for temporary storage to boost multiplication performance. pub fn gcd(rma: *Managed, x: Managed, y: Managed) !void { try rma.ensureCapacity(math.min(x.len(), y.len())); var m = rma.toMutable(); var limbs_buffer = std.ArrayList(Limb).init(rma.allocator); defer limbs_buffer.deinit(); try m.gcd(x.toConst(), y.toConst(), &limbs_buffer); rma.setMetadata(m.positive, m.len); } /// r = a * a pub fn sqr(rma: *Managed, a: Const) !void { const needed_limbs = 2 * a.limbs.len + 1; if (rma.limbs.ptr == a.limbs.ptr) { var m = try Managed.initCapacity(rma.allocator, needed_limbs); errdefer m.deinit(); var m_mut = m.toMutable(); m_mut.sqrNoAlias(a, rma.allocator); m.setMetadata(m_mut.positive, m_mut.len); rma.deinit(); rma.swap(&m); } else { try rma.ensureCapacity(needed_limbs); var rma_mut = rma.toMutable(); rma_mut.sqrNoAlias(a, rma.allocator); rma.setMetadata(rma_mut.positive, rma_mut.len); } } pub fn pow(rma: *Managed, a: Const, b: u32) !void { const needed_limbs = calcPowLimbsBufferLen(a.bitCountAbs(), b); const limbs_buffer = try rma.allocator.alloc(Limb, needed_limbs); defer rma.allocator.free(limbs_buffer); if (rma.limbs.ptr == a.limbs.ptr) { var m = try Managed.initCapacity(rma.allocator, needed_limbs); errdefer m.deinit(); var m_mut = m.toMutable(); try m_mut.pow(a, b, limbs_buffer); m.setMetadata(m_mut.positive, m_mut.len); rma.deinit(); rma.swap(&m); } else { try rma.ensureCapacity(needed_limbs); var rma_mut = rma.toMutable(); try rma_mut.pow(a, b, limbs_buffer); rma.setMetadata(rma_mut.positive, rma_mut.len); } } /// r = truncate(Int(signedness, bit_count), a) pub fn truncate(r: *Managed, a: Const, signedness: Signedness, bit_count: usize) !void { try r.ensureCapacity(calcTwosCompLimbCount(bit_count)); var m = r.toMutable(); m.truncate(a, signedness, bit_count); r.setMetadata(m.positive, m.len); } /// r = saturate(Int(signedness, bit_count), a) pub fn saturate(r: *Managed, a: Const, signedness: Signedness, bit_count: usize) !void { try r.ensureCapacity(calcTwosCompLimbCount(bit_count)); var m = r.toMutable(); m.saturate(a, signedness, bit_count); r.setMetadata(m.positive, m.len); } /// r = @popCount(a) with 2s-complement semantics. /// r and a may be aliases. pub fn popCount(r: *Managed, a: Const, bit_count: usize) !void { try r.ensureCapacity(calcTwosCompLimbCount(bit_count)); var m = r.toMutable(); m.popCount(a, bit_count); r.setMetadata(m.positive, m.len); } }; /// Different operators which can be used in accumulation style functions /// (llmulacc, llmulaccKaratsuba, llmulaccLong, llmulLimb). In all these functions, /// a computed value is accumulated with an existing result. const AccOp = enum { /// The computed value is added to the result. add, /// The computed value is subtracted from the result. sub, }; /// Knuth 4.3.1, Algorithm M. /// /// r = r (op) a * b /// r MUST NOT alias any of a or b. /// /// The result is computed modulo `r.len`. When `r.len >= a.len + b.len`, no overflow occurs. fn llmulacc(comptime op: AccOp, opt_allocator: ?*Allocator, r: []Limb, a: []const Limb, b: []const Limb) void { @setRuntimeSafety(debug_safety); assert(r.len >= a.len); assert(r.len >= b.len); // Order greatest first. var x = a; var y = b; if (a.len < b.len) { x = b; y = a; } k_mul: { if (y.len > 48) { if (opt_allocator) |allocator| { llmulaccKaratsuba(op, allocator, r, x, y) catch |err| switch (err) { error.OutOfMemory => break :k_mul, // handled below }; return; } } } llmulaccLong(op, r, x, y); } /// Knuth 4.3.1, Algorithm M. /// /// r = r (op) a * b /// r MUST NOT alias any of a or b. /// /// The result is computed modulo `r.len`. When `r.len >= a.len + b.len`, no overflow occurs. fn llmulaccKaratsuba( comptime op: AccOp, allocator: *Allocator, r: []Limb, a: []const Limb, b: []const Limb, ) error{OutOfMemory}!void { @setRuntimeSafety(debug_safety); assert(r.len >= a.len); assert(a.len >= b.len); // Classical karatsuba algorithm: // a = a1 * B + a0 // b = b1 * B + b0 // Where a0, b0 < B // // We then have: // ab = a * b // = (a1 * B + a0) * (b1 * B + b0) // = a1 * b1 * B * B + a1 * B * b0 + a0 * b1 * B + a0 * b0 // = a1 * b1 * B * B + (a1 * b0 + a0 * b1) * B + a0 * b0 // // Note that: // a1 * b0 + a0 * b1 // = (a1 + a0)(b1 + b0) - a1 * b1 - a0 * b0 // = (a0 - a1)(b1 - b0) + a1 * b1 + a0 * b0 // // This yields: // ab = p2 * B^2 + (p0 + p1 + p2) * B + p0 // // Where: // p0 = a0 * b0 // p1 = (a0 - a1)(b1 - b0) // p2 = a1 * b1 // // Note, (a0 - a1) and (b1 - b0) produce values -B < x < B, and so we need to mind the sign here. // We also have: // 0 <= p0 <= 2B // -2B <= p1 <= 2B // // Note, when B is a multiple of the limb size, multiplies by B amount to shifts or // slices of a limbs array. // // This function computes the result of the multiplication modulo r.len. This means: // - p2 and p1 only need to be computed modulo r.len - B. // - In the case of p2, p2 * B^2 needs to be added modulo r.len - 2 * B. const split = b.len / 2; // B const limbs_after_split = r.len - split; // Limbs to compute for p1 and p2. const limbs_after_split2 = r.len - split * 2; // Limbs to add for p2 * B^2. // For a0 and b0 we need the full range. const a0 = a[0..llnormalize(a[0..split])]; const b0 = b[0..llnormalize(b[0..split])]; // For a1 and b1 we only need `limbs_after_split` limbs. const a1 = blk: { var a1 = a[split..]; a1.len = math.min(llnormalize(a1), limbs_after_split); break :blk a1; }; const b1 = blk: { var b1 = b[split..]; b1.len = math.min(llnormalize(b1), limbs_after_split); break :blk b1; }; // Note that the above slices relative to `split` work because we have a.len > b.len. // We need some temporary memory to store intermediate results. // Note, we can reduce the amount of temporaries we need by reordering the computation here: // ab = p2 * B^2 + (p0 + p1 + p2) * B + p0 // = p2 * B^2 + (p0 * B + p1 * B + p2 * B) + p0 // = (p2 * B^2 + p2 * B) + (p0 * B + p0) + p1 * B // Allocate at least enough memory to be able to multiply the upper two segments of a and b, assuming // no overflow. const tmp = try allocator.alloc(Limb, a.len - split + b.len - split); defer allocator.free(tmp); // Compute p2. // Note, we don't need to compute all of p2, just enough limbs to satisfy r. const p2_limbs = math.min(limbs_after_split, a1.len + b1.len); mem.set(Limb, tmp[0..p2_limbs], 0); llmulacc(.add, allocator, tmp[0..p2_limbs], a1[0..math.min(a1.len, p2_limbs)], b1[0..math.min(b1.len, p2_limbs)]); const p2 = tmp[0..llnormalize(tmp[0..p2_limbs])]; // Add p2 * B to the result. llaccum(op, r[split..], p2); // Add p2 * B^2 to the result if required. if (limbs_after_split2 > 0) { llaccum(op, r[split * 2 ..], p2[0..math.min(p2.len, limbs_after_split2)]); } // Compute p0. // Since a0.len, b0.len <= split and r.len >= split * 2, the full width of p0 needs to be computed. const p0_limbs = a0.len + b0.len; mem.set(Limb, tmp[0..p0_limbs], 0); llmulacc(.add, allocator, tmp[0..p0_limbs], a0, b0); const p0 = tmp[0..llnormalize(tmp[0..p0_limbs])]; // Add p0 to the result. llaccum(op, r, p0); // Add p0 * B to the result. In this case, we may not need all of it. llaccum(op, r[split..], p0[0..math.min(limbs_after_split, p0.len)]); // Finally, compute and add p1. // From now on we only need `limbs_after_split` limbs for a0 and b0, since the result of the // following computation will be added * B. const a0x = a0[0..std.math.min(a0.len, limbs_after_split)]; const b0x = b0[0..std.math.min(b0.len, limbs_after_split)]; const j0_sign = llcmp(a0x, a1); const j1_sign = llcmp(b1, b0x); if (j0_sign * j1_sign == 0) { // p1 is zero, we don't need to do any computation at all. return; } mem.set(Limb, tmp, 0); // p1 is nonzero, so compute the intermediary terms j0 = a0 - a1 and j1 = b1 - b0. // Note that in this case, we again need some storage for intermediary results // j0 and j1. Since we have tmp.len >= 2B, we can store both // intermediaries in the already allocated array. const j0 = tmp[0 .. a.len - split]; const j1 = tmp[a.len - split ..]; // Ensure that no subtraction overflows. if (j0_sign == 1) { // a0 > a1. _ = llsubcarry(j0, a0x, a1); } else { // a0 < a1. _ = llsubcarry(j0, a1, a0x); } if (j1_sign == 1) { // b1 > b0. _ = llsubcarry(j1, b1, b0x); } else { // b1 > b0. _ = llsubcarry(j1, b0x, b1); } if (j0_sign * j1_sign == 1) { // If j0 and j1 are both positive, we now have: // p1 = j0 * j1 // If j0 and j1 are both negative, we now have: // p1 = -j0 * -j1 = j0 * j1 // In this case we can add p1 to the result using llmulacc. llmulacc(op, allocator, r[split..], j0[0..llnormalize(j0)], j1[0..llnormalize(j1)]); } else { // In this case either j0 or j1 is negative, an we have: // p1 = -(j0 * j1) // Now we need to subtract instead of accumulate. const inverted_op = if (op == .add) .sub else .add; llmulacc(inverted_op, allocator, r[split..], j0[0..llnormalize(j0)], j1[0..llnormalize(j1)]); } } /// r = r (op) a. /// The result is computed modulo `r.len`. fn llaccum(comptime op: AccOp, r: []Limb, a: []const Limb) void { @setRuntimeSafety(debug_safety); if (op == .sub) { _ = llsubcarry(r, r, a); return; } assert(r.len != 0 and a.len != 0); assert(r.len >= a.len); var i: usize = 0; var carry: Limb = 0; while (i < a.len) : (i += 1) { const ov1 = @addWithOverflow(r[i], a[i]); r[i] = ov1[0]; const ov2 = @addWithOverflow(r[i], carry); r[i] = ov2[0]; carry = @as(Limb, ov1[1]) + ov2[1]; } while ((carry != 0) and i < r.len) : (i += 1) { const ov = @addWithOverflow(r[i], carry); r[i] = ov[0]; carry = ov[1]; } } /// Returns -1, 0, 1 if |a| < |b|, |a| == |b| or |a| > |b| respectively for limbs. pub fn llcmp(a: []const Limb, b: []const Limb) i8 { @setRuntimeSafety(debug_safety); const a_len = llnormalize(a); const b_len = llnormalize(b); if (a_len < b_len) { return -1; } if (a_len > b_len) { return 1; } var i: usize = a_len - 1; while (i != 0) : (i -= 1) { if (a[i] != b[i]) { break; } } if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } else { return 0; } } /// r = r (op) y * xi /// The result is computed modulo `r.len`. When `r.len >= a.len + b.len`, no overflow occurs. fn llmulaccLong(comptime op: AccOp, r: []Limb, a: []const Limb, b: []const Limb) void { @setRuntimeSafety(debug_safety); assert(r.len >= a.len); assert(a.len >= b.len); var i: usize = 0; while (i < b.len) : (i += 1) { _ = llmulLimb(op, r[i..], a, b[i]); } } /// r = r (op) y * xi /// The result is computed modulo `r.len`. /// Returns whether the operation overflowed. fn llmulLimb(comptime op: AccOp, acc: []Limb, y: []const Limb, xi: Limb) bool { @setRuntimeSafety(debug_safety); if (xi == 0) { return false; } const split = std.math.min(y.len, acc.len); var a_lo = acc[0..split]; var a_hi = acc[split..]; switch (op) { .add => { var carry: Limb = 0; var j: usize = 0; while (j < a_lo.len) : (j += 1) { a_lo[j] = addMulLimbWithCarry(a_lo[j], y[j], xi, &carry); } j = 0; while ((carry != 0) and (j < a_hi.len)) : (j += 1) { const ov = @addWithOverflow(a_hi[j], carry); a_hi[j] = ov[0]; carry = ov[1]; } return carry != 0; }, .sub => { var borrow: Limb = 0; var j: usize = 0; while (j < a_lo.len) : (j += 1) { a_lo[j] = subMulLimbWithBorrow(a_lo[j], y[j], xi, &borrow); } j = 0; while ((borrow != 0) and (j < a_hi.len)) : (j += 1) { const ov = @subWithOverflow(a_hi[j], borrow); a_hi[j] = ov[0]; borrow = ov[1]; } return borrow != 0; }, } } /// returns the min length the limb could be. fn llnormalize(a: []const Limb) usize { @setRuntimeSafety(debug_safety); var j = a.len; while (j > 0) : (j -= 1) { if (a[j - 1] != 0) { break; } } // Handle zero return if (j != 0) j else 1; } /// Knuth 4.3.1, Algorithm S. fn llsubcarry(r: []Limb, a: []const Limb, b: []const Limb) Limb { @setRuntimeSafety(debug_safety); assert(a.len != 0 and b.len != 0); assert(a.len >= b.len); assert(r.len >= a.len); var i: usize = 0; var borrow: Limb = 0; while (i < b.len) : (i += 1) { const ov1 = @subWithOverflow(a[i], b[i]); r[i] = ov1[0]; const ov2 = @subWithOverflow(r[i], borrow); r[i] = ov2[0]; borrow = @as(Limb, ov1[1]) + ov2[1]; } while (i < a.len) : (i += 1) { const ov = @subWithOverflow(a[i], borrow); r[i] = ov[0]; borrow = ov[1]; } return borrow; } fn llsub(r: []Limb, a: []const Limb, b: []const Limb) void { @setRuntimeSafety(debug_safety); assert(a.len > b.len or (a.len == b.len and a[a.len - 1] >= b[b.len - 1])); assert(llsubcarry(r, a, b) == 0); } /// Knuth 4.3.1, Algorithm A. fn lladdcarry(r: []Limb, a: []const Limb, b: []const Limb) Limb { @setRuntimeSafety(debug_safety); assert(a.len != 0 and b.len != 0); assert(a.len >= b.len); assert(r.len >= a.len); var i: usize = 0; var carry: Limb = 0; while (i < b.len) : (i += 1) { const ov1 = @addWithOverflow(a[i], b[i]); r[i] = ov1[0]; const ov2 = @addWithOverflow(r[i], carry); r[i] = ov2[0]; carry = @as(Limb, ov1[1]) + ov2[1]; } while (i < a.len) : (i += 1) { const ov = @addWithOverflow(a[i], carry); r[i] = ov[0]; carry = ov[1]; } return carry; } fn lladd(r: []Limb, a: []const Limb, b: []const Limb) void { @setRuntimeSafety(debug_safety); assert(r.len >= a.len + 1); r[a.len] = lladdcarry(r, a, b); } /// Knuth 4.3.1, Exercise 16. fn lldiv1(quo: []Limb, rem: *Limb, a: []const Limb, b: Limb) void { @setRuntimeSafety(debug_safety); assert(a.len > 1 or a[0] >= b); assert(quo.len >= a.len); rem.* = 0; for (a, 0..) |_, ri| { const i = a.len - ri - 1; const pdiv = ((@as(DoubleLimb, rem.*) << limb_bits) | a[i]); if (pdiv == 0) { quo[i] = 0; rem.* = 0; } else if (pdiv < b) { quo[i] = 0; rem.* = @as(Limb, @truncate(pdiv)); } else if (pdiv == b) { quo[i] = 1; rem.* = 0; } else { quo[i] = @as(Limb, @truncate(@divTrunc(pdiv, b))); rem.* = @as(Limb, @truncate(pdiv - (quo[i] *% b))); } } } fn llshl(r: []Limb, a: []const Limb, shift: usize) void { @setRuntimeSafety(debug_safety); assert(a.len >= 1); const interior_limb_shift = @as(Log2Limb, @truncate(shift)); // We only need the extra limb if the shift of the last element overflows. // This is useful for the implementation of `shiftLeftSat`. if (a[a.len - 1] << interior_limb_shift >> interior_limb_shift != a[a.len - 1]) { assert(r.len >= a.len + (shift / limb_bits) + 1); } else { assert(r.len >= a.len + (shift / limb_bits)); } const limb_shift = shift / limb_bits + 1; var carry: Limb = 0; var i: usize = 0; while (i < a.len) : (i += 1) { const src_i = a.len - i - 1; const dst_i = src_i + limb_shift; const src_digit = a[src_i]; r[dst_i] = carry | @call(.{ .modifier = .always_inline }, math.shr, .{ Limb, src_digit, limb_bits - @as(Limb, @intCast(interior_limb_shift)), }); carry = (src_digit << interior_limb_shift); } r[limb_shift - 1] = carry; mem.set(Limb, r[0 .. limb_shift - 1], 0); } fn llshr(r: []Limb, a: []const Limb, shift: usize) void { @setRuntimeSafety(debug_safety); assert(a.len >= 1); assert(r.len >= a.len - (shift / limb_bits)); const limb_shift = shift / limb_bits; const interior_limb_shift = @as(Log2Limb, @truncate(shift)); var carry: Limb = 0; var i: usize = 0; while (i < a.len - limb_shift) : (i += 1) { const src_i = a.len - i - 1; const dst_i = src_i - limb_shift; const src_digit = a[src_i]; r[dst_i] = carry | (src_digit >> interior_limb_shift); carry = @call(.{ .modifier = .always_inline }, math.shl, .{ Limb, src_digit, limb_bits - @as(Limb, @intCast(interior_limb_shift)), }); } } // r = ~r fn llnot(r: []Limb) void { @setRuntimeSafety(debug_safety); for (r) |*elem| { elem.* = ~elem.*; } } // r = a | b with 2s complement semantics. // r may alias. // a and b must not be 0. // Returns `true` when the result is positive. // When b is positive, r requires at least `a.len` limbs of storage. // When b is negative, r requires at least `b.len` limbs of storage. fn llsignedor(r: []Limb, a: []const Limb, a_positive: bool, b: []const Limb, b_positive: bool) bool { @setRuntimeSafety(debug_safety); assert(r.len >= a.len); assert(a.len >= b.len); if (a_positive and b_positive) { // Trivial case, result is positive. var i: usize = 0; while (i < b.len) : (i += 1) { r[i] = a[i] | b[i]; } while (i < a.len) : (i += 1) { r[i] = a[i]; } return true; } else if (!a_positive and b_positive) { // Result is negative. // r = (--a) | b // = ~(-a - 1) | b // = ~(-a - 1) | ~~b // = ~((-a - 1) & ~b) // = -(((-a - 1) & ~b) + 1) var i: usize = 0; var a_borrow: u1 = 1; var r_carry: u1 = 1; while (i < b.len) : (i += 1) { const ov1 = @subWithOverflow(a[i], a_borrow); a_borrow = ov1[1]; const ov2 = @addWithOverflow(ov1[0] & ~b[i], r_carry); r[i] = ov2[0]; r_carry = ov2[1]; } // In order for r_carry to be nonzero at this point, ~b[i] would need to be // all ones, which would require b[i] to be zero. This cannot be when // b is normalized, so there cannot be a carry here. // Also, x & ~b can only clear bits, so (x & ~b) <= x, meaning (-a - 1) + 1 never overflows. assert(r_carry == 0); // With b = 0, we get (-a - 1) & ~0 = -a - 1. // Note, if a_borrow is zero we do not need to compute anything for // the higher limbs so we can early return here. while (i < a.len and a_borrow == 1) : (i += 1) { const ov = @subWithOverflow(a[i], a_borrow); r[i] = ov[0]; a_borrow = ov[1]; } assert(a_borrow == 0); // a was 0. return false; } else if (a_positive and !b_positive) { // Result is negative. // r = a | (--b) // = a | ~(-b - 1) // = ~~a | ~(-b - 1) // = ~(~a & (-b - 1)) // = -((~a & (-b - 1)) + 1) var i: usize = 0; var b_borrow: u1 = 1; var r_carry: u1 = 1; while (i < b.len) : (i += 1) { const ov1 = @subWithOverflow(b[i], b_borrow); b_borrow = ov1[1]; const ov2 = @addWithOverflow(~a[i] & ov1[0], r_carry); r[i] = ov2[0]; r_carry = ov2[1]; } // b is at least 1, so this should never underflow. assert(b_borrow == 0); // b was 0 // x & ~a can only clear bits, so (x & ~a) <= x, meaning (-b - 1) + 1 never overflows. assert(r_carry == 0); // With b = 0 and b_borrow = 0, we get ~a & (-0 - 0) = ~a & 0 = 0. // Omit setting the upper bytes, just deal with those when calling llsignedor. return false; } else { // Result is negative. // r = (--a) | (--b) // = ~(-a - 1) | ~(-b - 1) // = ~((-a - 1) & (-b - 1)) // = -(~(~((-a - 1) & (-b - 1))) + 1) // = -((-a - 1) & (-b - 1) + 1) var i: usize = 0; var a_borrow: u1 = 1; var b_borrow: u1 = 1; var r_carry: u1 = 1; while (i < b.len) : (i += 1) { const ov1 = @subWithOverflow(a[i], a_borrow); a_borrow = ov1[1]; const ov2 = @subWithOverflow(b[i], b_borrow); b_borrow = ov2[1]; const ov3 = @addWithOverflow(ov1[0] & ov2[0], r_carry); r[i] = ov3[0]; r_carry = ov3[1]; } // b is at least 1, so this should never underflow. assert(b_borrow == 0); // b was 0 // Can never overflow because in order for b_limb to be maxInt(Limb), // b_borrow would need to equal 1. // x & y can only clear bits, meaning x & y <= x and x & y <= y. This implies that // for x = a - 1 and y = b - 1, the +1 term would never cause an overflow. assert(r_carry == 0); // With b = 0 and b_borrow = 0 we get (-a - 1) & (-0 - 0) = (-a - 1) & 0 = 0. // Omit setting the upper bytes, just deal with those when calling llsignedor. return false; } } // r = a & b with 2s complement semantics. // r may alias. // a and b must not be 0. // Returns `true` when the result is positive. // When either or both of a and b are positive, r requires at least `b.len` limbs of storage. // When both a and b are negative, r requires at least `a.limbs.len + 1` limbs of storage. fn llsignedand(r: []Limb, a: []const Limb, a_positive: bool, b: []const Limb, b_positive: bool) bool { @setRuntimeSafety(debug_safety); assert(a.len != 0 and b.len != 0); assert(r.len >= a.len); assert(a.len >= b.len); if (a_positive and b_positive) { // Trivial case, result is positive. var i: usize = 0; while (i < b.len) : (i += 1) { r[i] = a[i] & b[i]; } // With b = 0 we have a & 0 = 0, so the upper bytes are zero. // Omit setting them here and simply discard them whenever // llsignedand is called. return true; } else if (!a_positive and b_positive) { // Result is positive. // r = (--a) & b // = ~(-a - 1) & b var i: usize = 0; var a_borrow: u1 = 1; while (i < b.len) : (i += 1) { const ov = @subWithOverflow(a[i], a_borrow); a_borrow = ov[1]; r[i] = ~ov[0] & b[i]; } // With b = 0 we have ~(a - 1) & 0 = 0, so the upper bytes are zero. // Omit setting them here and simply discard them whenever // llsignedand is called. return true; } else if (a_positive and !b_positive) { // Result is positive. // r = a & (--b) // = a & ~(-b - 1) var i: usize = 0; var b_borrow: u1 = 1; while (i < b.len) : (i += 1) { const ov = @subWithOverflow(b[i], b_borrow); b_borrow = ov[1]; r[i] = a[i] & ~ov[0]; } assert(b_borrow == 0); // b was 0 // With b = 0 and b_borrow = 0 we have a & ~(-0 - 0) = a & 0 = 0, so // the upper bytes are zero. Omit setting them here and simply discard // them whenever llsignedand is called. return true; } else { // Result is negative. // r = (--a) & (--b) // = ~(-a - 1) & ~(-b - 1) // = ~((-a - 1) | (-b - 1)) // = -(((-a - 1) | (-b - 1)) + 1) var i: usize = 0; var a_borrow: u1 = 1; var b_borrow: u1 = 1; var r_carry: u1 = 1; while (i < b.len) : (i += 1) { const ov1 = @subWithOverflow(a[i], a_borrow); a_borrow = ov1[1]; const ov2 = @subWithOverflow(b[i], b_borrow); b_borrow = ov2[1]; const ov3 = @addWithOverflow(ov1[0] | ov2[0], r_carry); r[i] = ov3[0]; r_carry = ov3[1]; } // b is at least 1, so this should never underflow. assert(b_borrow == 0); // b was 0 // With b = 0 and b_borrow = 0 we get (-a - 1) | (-0 - 0) = (-a - 1) | 0 = -a - 1. while (i < a.len) : (i += 1) { const ov1 = @subWithOverflow(a[i], a_borrow); a_borrow = ov1[1]; const ov2 = @addWithOverflow(ov1[0], r_carry); r[i] = ov2[0]; r_carry = ov2[1]; } assert(a_borrow == 0); // a was 0. // The final addition can overflow here, so we need to keep that in mind. r[i] = r_carry; return false; } } // r = a ^ b with 2s complement semantics. // r may alias. // a and b must not be -0. // Returns `true` when the result is positive. // If the sign of a and b is equal, then r requires at least `max(a.len, b.len)` limbs are required. // Otherwise, r requires at least `max(a.len, b.len) + 1` limbs. fn llsignedxor(r: []Limb, a: []const Limb, a_positive: bool, b: []const Limb, b_positive: bool) bool { @setRuntimeSafety(debug_safety); assert(a.len != 0 and b.len != 0); assert(r.len >= a.len); assert(a.len >= b.len); // If a and b are positive, the result is positive and r = a ^ b. // If a negative, b positive, result is negative and we have // r = --(--a ^ b) // = --(~(-a - 1) ^ b) // = -(~(~(-a - 1) ^ b) + 1) // = -(((-a - 1) ^ b) + 1) // Same if a is positive and b is negative, sides switched. // If both a and b are negative, the result is positive and we have // r = (--a) ^ (--b) // = ~(-a - 1) ^ ~(-b - 1) // = (-a - 1) ^ (-b - 1) // These operations can be made more generic as follows: // - If a is negative, subtract 1 from |a| before the xor. // - If b is negative, subtract 1 from |b| before the xor. // - if the result is supposed to be negative, add 1. var i: usize = 0; var a_borrow = @intFromBool(!a_positive); var b_borrow = @intFromBool(!b_positive); var r_carry = @intFromBool(a_positive != b_positive); while (i < b.len) : (i += 1) { const ov1 = @subWithOverflow(a[i], a_borrow); a_borrow = ov1[1]; const ov2 = @subWithOverflow(b[i], b_borrow); b_borrow = ov2[1]; const ov3 = @addWithOverflow(ov1[0] ^ ov2[0], r_carry); r[i] = ov3[0]; r_carry = ov3[1]; } while (i < a.len) : (i += 1) { const ov1 = @subWithOverflow(a[i], a_borrow); a_borrow = ov1[1]; const ov2 = @addWithOverflow(ov1[0], r_carry); r[i] = ov2[0]; r_carry = ov2[1]; } // If both inputs don't share the same sign, an extra limb is required. if (a_positive != b_positive) { r[i] = r_carry; } else { assert(r_carry == 0); } assert(a_borrow == 0); assert(b_borrow == 0); return a_positive == b_positive; } /// r MUST NOT alias x. fn llsquareBasecase(r: []Limb, x: []const Limb) void { @setRuntimeSafety(debug_safety); const x_norm = x; assert(r.len >= 2 * x_norm.len + 1); // Compute the square of a N-limb bigint with only (N^2 + N)/2 // multiplications by exploting the symmetry of the coefficients around the // diagonal: // // a b c * // a b c = // ------------------- // ca cb cc + // ba bb bc + // aa ab ac // // Note that: // - Each mixed-product term appears twice for each column, // - Squares are always in the 2k (0 <= k < N) column for (x_norm, 0..) |v, i| { // Accumulate all the x[i]*x[j] (with x!=j) products const overflow = llmulLimb(.add, r[2 * i + 1 ..], x_norm[i + 1 ..], v); assert(!overflow); } // Each product appears twice, multiply by 2 llshl(r, r[0 .. 2 * x_norm.len], 1); for (x_norm, 0..) |v, i| { // Compute and add the squares const overflow = llmulLimb(.add, r[2 * i ..], x[i .. i + 1], v); assert(!overflow); } } /// Knuth 4.6.3 fn llpow(r: []Limb, a: []const Limb, b: u32, tmp_limbs: []Limb) void { var tmp1: []Limb = undefined; var tmp2: []Limb = undefined; // Multiplication requires no aliasing between the operand and the result // variable, use the output limbs and another temporary set to overcome this // limitation. // The initial assignment makes the result end in `r` so an extra memory // copy is saved, each 1 flips the index twice so it's only the zeros that // matter. const b_leading_zeros = @clz(b); const exp_zeros = @popCount(~b) - b_leading_zeros; if (exp_zeros & 1 != 0) { tmp1 = tmp_limbs; tmp2 = r; } else { tmp1 = r; tmp2 = tmp_limbs; } mem.copy(Limb, tmp1, a); mem.set(Limb, tmp1[a.len..], 0); // Scan the exponent as a binary number, from left to right, dropping the // most significant bit set. // Square the result if the current bit is zero, square and multiply by a if // it is one. var exp_bits = 32 - 1 - b_leading_zeros; var exp = b << @as(u5, @intCast(1 + b_leading_zeros)); var i: usize = 0; while (i < exp_bits) : (i += 1) { // Square mem.set(Limb, tmp2, 0); llsquareBasecase(tmp2, tmp1[0..llnormalize(tmp1)]); mem.swap([]Limb, &tmp1, &tmp2); // Multiply by a const ov = @shlWithOverflow(exp, 1); exp = ov[0]; if (ov[1] != 0) { @memset(tmp2, 0); llmulacc(.add, null, tmp2, tmp1[0..llnormalize(tmp1)], a); mem.swap([]Limb, &tmp1, &tmp2); } } } // Storage must live for the lifetime of the returned value fn fixedIntFromSignedDoubleLimb(A: SignedDoubleLimb, storage: []Limb) Mutable { assert(storage.len >= 2); const A_is_positive = A >= 0; const Au = @as(DoubleLimb, @intCast(if (A < 0) -A else A)); storage[0] = @as(Limb, @truncate(Au)); storage[1] = @as(Limb, @truncate(Au >> limb_bits)); return .{ .limbs = storage[0..2], .positive = A_is_positive, .len = 2, }; } test { _ = @import("int_test.zig"); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/big/rational.zig
const std = @import("../../std.zig"); const debug = std.debug; const math = std.math; const mem = std.mem; const testing = std.testing; const Allocator = mem.Allocator; const Limb = std.math.big.Limb; const DoubleLimb = std.math.big.DoubleLimb; const Int = std.math.big.int.Managed; const IntConst = std.math.big.int.Const; /// An arbitrary-precision rational number. /// /// Memory is allocated as needed for operations to ensure full precision is kept. The precision /// of a Rational is only bounded by memory. /// /// Rational's are always normalized. That is, for a Rational r = p/q where p and q are integers, /// gcd(p, q) = 1 always. /// /// TODO rework this to store its own allocator and use a non-managed big int, to avoid double /// allocator storage. pub const Rational = struct { /// Numerator. Determines the sign of the Rational. p: Int, /// Denominator. Sign is ignored. q: Int, /// Create a new Rational. A small amount of memory will be allocated on initialization. /// This will be 2 * Int.default_capacity. pub fn init(a: *Allocator) !Rational { return Rational{ .p = try Int.init(a), .q = try Int.initSet(a, 1), }; } /// Frees all memory associated with a Rational. pub fn deinit(self: *Rational) void { self.p.deinit(); self.q.deinit(); } /// Set a Rational from a primitive integer type. pub fn setInt(self: *Rational, a: anytype) !void { try self.p.set(a); try self.q.set(1); } /// Set a Rational from a string of the form `A/B` where A and B are base-10 integers. pub fn setFloatString(self: *Rational, str: []const u8) !void { // TODO: Accept a/b fractions and exponent form if (str.len == 0) { return error.InvalidFloatString; } const State = enum { Integer, Fractional, }; var state = State.Integer; var point: ?usize = null; var start: usize = 0; if (str[0] == '-') { start += 1; } for (str, 0..) |c, i| { switch (state) { State.Integer => { switch (c) { '.' => { state = State.Fractional; point = i; }, '0'...'9' => { // okay }, else => { return error.InvalidFloatString; }, } }, State.Fractional => { switch (c) { '0'...'9' => { // okay }, else => { return error.InvalidFloatString; }, } }, } } // TODO: batch the multiplies by 10 if (point) |i| { try self.p.setString(10, str[0..i]); const base = IntConst{ .limbs = &[_]Limb{10}, .positive = true }; var j: usize = start; while (j < str.len - i - 1) : (j += 1) { try self.p.ensureMulCapacity(self.p.toConst(), base); try self.p.mul(self.p.toConst(), base); } try self.q.setString(10, str[i + 1 ..]); try self.p.add(self.p.toConst(), self.q.toConst()); try self.q.set(1); var k: usize = i + 1; while (k < str.len) : (k += 1) { try self.q.mul(self.q.toConst(), base); } try self.reduce(); } else { try self.p.setString(10, str[0..]); try self.q.set(1); } } /// Set a Rational from a floating-point value. The rational will have enough precision to /// completely represent the provided float. pub fn setFloat(self: *Rational, comptime T: type, f: T) !void { // Translated from golang.go/src/math/big/rat.go. debug.assert(@typeInfo(T) == .Float); const UnsignedInt = std.meta.Int(.unsigned, @typeInfo(T).Float.bits); const f_bits = @as(UnsignedInt, @bitCast(f)); const exponent_bits = math.floatExponentBits(T); const exponent_bias = (1 << (exponent_bits - 1)) - 1; const mantissa_bits = math.floatMantissaBits(T); const exponent_mask = (1 << exponent_bits) - 1; const mantissa_mask = (1 << mantissa_bits) - 1; var exponent = @as(i16, @intCast((f_bits >> mantissa_bits) & exponent_mask)); var mantissa = f_bits & mantissa_mask; switch (exponent) { exponent_mask => { return error.NonFiniteFloat; }, 0 => { // denormal exponent -= exponent_bias - 1; }, else => { // normal mantissa |= 1 << mantissa_bits; exponent -= exponent_bias; }, } var shift: i16 = mantissa_bits - exponent; // factor out powers of two early from rational while (mantissa & 1 == 0 and shift > 0) { mantissa >>= 1; shift -= 1; } try self.p.set(mantissa); self.p.setSign(f >= 0); try self.q.set(1); if (shift >= 0) { try self.q.shiftLeft(self.q, @as(usize, @intCast(shift))); } else { try self.p.shiftLeft(self.p, @as(usize, @intCast(-shift))); } try self.reduce(); } /// Return a floating-point value that is the closest value to a Rational. /// /// The result may not be exact if the Rational is too precise or too large for the /// target type. pub fn toFloat(self: Rational, comptime T: type) !T { // Translated from golang.go/src/math/big/rat.go. // TODO: Indicate whether the result is not exact. debug.assert(@typeInfo(T) == .Float); const fsize = @typeInfo(T).Float.bits; const BitReprType = std.meta.Int(.unsigned, fsize); const msize = math.floatMantissaBits(T); const msize1 = msize + 1; const msize2 = msize1 + 1; const esize = math.floatExponentBits(T); const ebias = (1 << (esize - 1)) - 1; const emin = 1 - ebias; if (self.p.eqZero()) { return 0; } // 1. left-shift a or sub so that a/b is in [1 << msize1, 1 << (msize2 + 1)] var exp = @as(isize, @intCast(self.p.bitCountTwosComp())) - @as(isize, @intCast(self.q.bitCountTwosComp())); var a2 = try self.p.clone(); defer a2.deinit(); var b2 = try self.q.clone(); defer b2.deinit(); const shift = msize2 - exp; if (shift >= 0) { try a2.shiftLeft(a2, @as(usize, @intCast(shift))); } else { try b2.shiftLeft(b2, @as(usize, @intCast(-shift))); } // 2. compute quotient and remainder var q = try Int.init(self.p.allocator); defer q.deinit(); // unused var r = try Int.init(self.p.allocator); defer r.deinit(); try Int.divTrunc(&q, &r, a2.toConst(), b2.toConst()); var mantissa = extractLowBits(q, BitReprType); var have_rem = r.len() > 0; // 3. q didn't fit in msize2 bits, redo division b2 << 1 if (mantissa >> msize2 == 1) { if (mantissa & 1 == 1) { have_rem = true; } mantissa >>= 1; exp += 1; } if (mantissa >> msize1 != 1) { // NOTE: This can be hit if the limb size is small (u8/16). @panic("unexpected bits in result"); } // 4. Rounding if (emin - msize <= exp and exp <= emin) { // denormal const shift1 = @as(math.Log2Int(BitReprType), @intCast(emin - (exp - 1))); const lost_bits = mantissa & ((@as(BitReprType, @intCast(1)) << shift1) - 1); have_rem = have_rem or lost_bits != 0; mantissa >>= shift1; exp = 2 - ebias; } // round q using round-half-to-even var exact = !have_rem; if (mantissa & 1 != 0) { exact = false; if (have_rem or (mantissa & 2 != 0)) { mantissa += 1; if (mantissa >= 1 << msize2) { // 11...1 => 100...0 mantissa >>= 1; exp += 1; } } } mantissa >>= 1; const f = math.scalbn(@as(T, @floatFromInt(mantissa)), @as(i32, @intCast(exp - msize1))); if (math.isInf(f)) { exact = false; } return if (self.p.isPositive()) f else -f; } /// Set a rational from an integer ratio. pub fn setRatio(self: *Rational, p: anytype, q: anytype) !void { try self.p.set(p); try self.q.set(q); self.p.setSign(@intFromBool(self.p.isPositive()) ^ @intFromBool(self.q.isPositive()) == 0); self.q.setSign(true); try self.reduce(); if (self.q.eqZero()) { @panic("cannot set rational with denominator = 0"); } } /// Set a Rational directly from an Int. pub fn copyInt(self: *Rational, a: Int) !void { try self.p.copy(a.toConst()); try self.q.set(1); } /// Set a Rational directly from a ratio of two Int's. pub fn copyRatio(self: *Rational, a: Int, b: Int) !void { try self.p.copy(a.toConst()); try self.q.copy(b.toConst()); self.p.setSign(@intFromBool(self.p.isPositive()) ^ @intFromBool(self.q.isPositive()) == 0); self.q.setSign(true); try self.reduce(); } /// Make a Rational positive. pub fn abs(r: *Rational) void { r.p.abs(); } /// Negate the sign of a Rational. pub fn negate(r: *Rational) void { r.p.negate(); } /// Efficiently swap a Rational with another. This swaps the limb pointers and a full copy is not /// performed. The address of the limbs field will not be the same after this function. pub fn swap(r: *Rational, other: *Rational) void { r.p.swap(&other.p); r.q.swap(&other.q); } /// Returns math.Order.lt, math.Order.eq, math.Order.gt if a < b, a == b or a /// > b respectively. pub fn order(a: Rational, b: Rational) !math.Order { return cmpInternal(a, b, true); } /// Returns math.Order.lt, math.Order.eq, math.Order.gt if |a| < |b|, |a| == /// |b| or |a| > |b| respectively. pub fn orderAbs(a: Rational, b: Rational) !math.Order { return cmpInternal(a, b, false); } // p/q > x/y iff p*y > x*q fn cmpInternal(a: Rational, b: Rational, is_abs: bool) !math.Order { // TODO: Would a div compare algorithm of sorts be viable and quicker? Can we avoid // the memory allocations here? var q = try Int.init(a.p.allocator); defer q.deinit(); var p = try Int.init(b.p.allocator); defer p.deinit(); try q.mul(a.p.toConst(), b.q.toConst()); try p.mul(b.p.toConst(), a.q.toConst()); return if (is_abs) q.orderAbs(p) else q.order(p); } /// rma = a + b. /// /// rma, a and b may be aliases. However, it is more efficient if rma does not alias a or b. /// /// Returns an error if memory could not be allocated. pub fn add(rma: *Rational, a: Rational, b: Rational) !void { var r = rma; var aliased = rma.p.limbs.ptr == a.p.limbs.ptr or rma.p.limbs.ptr == b.p.limbs.ptr; var sr: Rational = undefined; if (aliased) { sr = try Rational.init(rma.p.allocator); r = &sr; aliased = true; } defer if (aliased) { rma.swap(r); r.deinit(); }; try r.p.mul(a.p.toConst(), b.q.toConst()); try r.q.mul(b.p.toConst(), a.q.toConst()); try r.p.add(r.p.toConst(), r.q.toConst()); try r.q.mul(a.q.toConst(), b.q.toConst()); try r.reduce(); } /// rma = a - b. /// /// rma, a and b may be aliases. However, it is more efficient if rma does not alias a or b. /// /// Returns an error if memory could not be allocated. pub fn sub(rma: *Rational, a: Rational, b: Rational) !void { var r = rma; var aliased = rma.p.limbs.ptr == a.p.limbs.ptr or rma.p.limbs.ptr == b.p.limbs.ptr; var sr: Rational = undefined; if (aliased) { sr = try Rational.init(rma.p.allocator); r = &sr; aliased = true; } defer if (aliased) { rma.swap(r); r.deinit(); }; try r.p.mul(a.p.toConst(), b.q.toConst()); try r.q.mul(b.p.toConst(), a.q.toConst()); try r.p.sub(r.p.toConst(), r.q.toConst()); try r.q.mul(a.q.toConst(), b.q.toConst()); try r.reduce(); } /// rma = a * b. /// /// rma, a and b may be aliases. However, it is more efficient if rma does not alias a or b. /// /// Returns an error if memory could not be allocated. pub fn mul(r: *Rational, a: Rational, b: Rational) !void { try r.p.mul(a.p.toConst(), b.p.toConst()); try r.q.mul(a.q.toConst(), b.q.toConst()); try r.reduce(); } /// rma = a / b. /// /// rma, a and b may be aliases. However, it is more efficient if rma does not alias a or b. /// /// Returns an error if memory could not be allocated. pub fn div(r: *Rational, a: Rational, b: Rational) !void { if (b.p.eqZero()) { @panic("division by zero"); } try r.p.mul(a.p.toConst(), b.q.toConst()); try r.q.mul(b.p.toConst(), a.q.toConst()); try r.reduce(); } /// Invert the numerator and denominator fields of a Rational. p/q => q/p. pub fn invert(r: *Rational) void { Int.swap(&r.p, &r.q); } // reduce r/q such that gcd(r, q) = 1 fn reduce(r: *Rational) !void { var a = try Int.init(r.p.allocator); defer a.deinit(); const sign = r.p.isPositive(); r.p.abs(); try a.gcd(r.p, r.q); r.p.setSign(sign); const one = IntConst{ .limbs = &[_]Limb{1}, .positive = true }; if (a.toConst().order(one) != .eq) { var unused = try Int.init(r.p.allocator); defer unused.deinit(); // TODO: divexact would be useful here // TODO: don't copy r.q for div try Int.divTrunc(&r.p, &unused, r.p.toConst(), a.toConst()); try Int.divTrunc(&r.q, &unused, r.q.toConst(), a.toConst()); } } }; fn extractLowBits(a: Int, comptime T: type) T { debug.assert(@typeInfo(T) == .Int); const t_bits = @typeInfo(T).Int.bits; const limb_bits = @typeInfo(Limb).Int.bits; if (t_bits <= limb_bits) { return @as(T, @truncate(a.limbs[0])); } else { var r: T = 0; comptime var i: usize = 0; // Remainder is always 0 since if t_bits >= limb_bits -> Limb | T and both // are powers of two. inline while (i < t_bits / limb_bits) : (i += 1) { r |= math.shl(T, a.limbs[i], i * limb_bits); } return r; } } test "big.rational extractLowBits" { var a = try Int.initSet(testing.allocator, 0x11112222333344441234567887654321); defer a.deinit(); const a1 = extractLowBits(a, u8); try testing.expect(a1 == 0x21); const a2 = extractLowBits(a, u16); try testing.expect(a2 == 0x4321); const a3 = extractLowBits(a, u32); try testing.expect(a3 == 0x87654321); const a4 = extractLowBits(a, u64); try testing.expect(a4 == 0x1234567887654321); const a5 = extractLowBits(a, u128); try testing.expect(a5 == 0x11112222333344441234567887654321); } test "big.rational set" { var a = try Rational.init(testing.allocator); defer a.deinit(); try a.setInt(5); try testing.expect((try a.p.to(u32)) == 5); try testing.expect((try a.q.to(u32)) == 1); try a.setRatio(7, 3); try testing.expect((try a.p.to(u32)) == 7); try testing.expect((try a.q.to(u32)) == 3); try a.setRatio(9, 3); try testing.expect((try a.p.to(i32)) == 3); try testing.expect((try a.q.to(i32)) == 1); try a.setRatio(-9, 3); try testing.expect((try a.p.to(i32)) == -3); try testing.expect((try a.q.to(i32)) == 1); try a.setRatio(9, -3); try testing.expect((try a.p.to(i32)) == -3); try testing.expect((try a.q.to(i32)) == 1); try a.setRatio(-9, -3); try testing.expect((try a.p.to(i32)) == 3); try testing.expect((try a.q.to(i32)) == 1); } test "big.rational setFloat" { var a = try Rational.init(testing.allocator); defer a.deinit(); try a.setFloat(f64, 2.5); try testing.expect((try a.p.to(i32)) == 5); try testing.expect((try a.q.to(i32)) == 2); try a.setFloat(f32, -2.5); try testing.expect((try a.p.to(i32)) == -5); try testing.expect((try a.q.to(i32)) == 2); try a.setFloat(f32, 3.141593); // = 3.14159297943115234375 try testing.expect((try a.p.to(u32)) == 3294199); try testing.expect((try a.q.to(u32)) == 1048576); try a.setFloat(f64, 72.141593120712409172417410926841290461290467124); // = 72.1415931207124145885245525278151035308837890625 try testing.expect((try a.p.to(u128)) == 5076513310880537); try testing.expect((try a.q.to(u128)) == 70368744177664); } test "big.rational setFloatString" { var a = try Rational.init(testing.allocator); defer a.deinit(); try a.setFloatString("72.14159312071241458852455252781510353"); // = 72.1415931207124145885245525278151035308837890625 try testing.expect((try a.p.to(u128)) == 7214159312071241458852455252781510353); try testing.expect((try a.q.to(u128)) == 100000000000000000000000000000000000); } test "big.rational toFloat" { var a = try Rational.init(testing.allocator); defer a.deinit(); // = 3.14159297943115234375 try a.setRatio(3294199, 1048576); try testing.expect((try a.toFloat(f64)) == 3.14159297943115234375); // = 72.1415931207124145885245525278151035308837890625 try a.setRatio(5076513310880537, 70368744177664); try testing.expect((try a.toFloat(f64)) == 72.141593120712409172417410926841290461290467124); } test "big.rational set/to Float round-trip" { var a = try Rational.init(testing.allocator); defer a.deinit(); var prng = std.rand.DefaultPrng.init(0x5EED); const random = prng.random(); var i: usize = 0; while (i < 512) : (i += 1) { const r = random.float(f64); try a.setFloat(f64, r); try testing.expect((try a.toFloat(f64)) == r); } } test "big.rational copy" { var a = try Rational.init(testing.allocator); defer a.deinit(); var b = try Int.initSet(testing.allocator, 5); defer b.deinit(); try a.copyInt(b); try testing.expect((try a.p.to(u32)) == 5); try testing.expect((try a.q.to(u32)) == 1); var c = try Int.initSet(testing.allocator, 7); defer c.deinit(); var d = try Int.initSet(testing.allocator, 3); defer d.deinit(); try a.copyRatio(c, d); try testing.expect((try a.p.to(u32)) == 7); try testing.expect((try a.q.to(u32)) == 3); var e = try Int.initSet(testing.allocator, 9); defer e.deinit(); var f = try Int.initSet(testing.allocator, 3); defer f.deinit(); try a.copyRatio(e, f); try testing.expect((try a.p.to(u32)) == 3); try testing.expect((try a.q.to(u32)) == 1); } test "big.rational negate" { var a = try Rational.init(testing.allocator); defer a.deinit(); try a.setInt(-50); try testing.expect((try a.p.to(i32)) == -50); try testing.expect((try a.q.to(i32)) == 1); a.negate(); try testing.expect((try a.p.to(i32)) == 50); try testing.expect((try a.q.to(i32)) == 1); a.negate(); try testing.expect((try a.p.to(i32)) == -50); try testing.expect((try a.q.to(i32)) == 1); } test "big.rational abs" { var a = try Rational.init(testing.allocator); defer a.deinit(); try a.setInt(-50); try testing.expect((try a.p.to(i32)) == -50); try testing.expect((try a.q.to(i32)) == 1); a.abs(); try testing.expect((try a.p.to(i32)) == 50); try testing.expect((try a.q.to(i32)) == 1); a.abs(); try testing.expect((try a.p.to(i32)) == 50); try testing.expect((try a.q.to(i32)) == 1); } test "big.rational swap" { var a = try Rational.init(testing.allocator); defer a.deinit(); var b = try Rational.init(testing.allocator); defer b.deinit(); try a.setRatio(50, 23); try b.setRatio(17, 3); try testing.expect((try a.p.to(u32)) == 50); try testing.expect((try a.q.to(u32)) == 23); try testing.expect((try b.p.to(u32)) == 17); try testing.expect((try b.q.to(u32)) == 3); a.swap(&b); try testing.expect((try a.p.to(u32)) == 17); try testing.expect((try a.q.to(u32)) == 3); try testing.expect((try b.p.to(u32)) == 50); try testing.expect((try b.q.to(u32)) == 23); } test "big.rational order" { var a = try Rational.init(testing.allocator); defer a.deinit(); var b = try Rational.init(testing.allocator); defer b.deinit(); try a.setRatio(500, 231); try b.setRatio(18903, 8584); try testing.expect((try a.order(b)) == .lt); try a.setRatio(890, 10); try b.setRatio(89, 1); try testing.expect((try a.order(b)) == .eq); } test "big.rational add single-limb" { var a = try Rational.init(testing.allocator); defer a.deinit(); var b = try Rational.init(testing.allocator); defer b.deinit(); try a.setRatio(500, 231); try b.setRatio(18903, 8584); try testing.expect((try a.order(b)) == .lt); try a.setRatio(890, 10); try b.setRatio(89, 1); try testing.expect((try a.order(b)) == .eq); } test "big.rational add" { var a = try Rational.init(testing.allocator); defer a.deinit(); var b = try Rational.init(testing.allocator); defer b.deinit(); var r = try Rational.init(testing.allocator); defer r.deinit(); try a.setRatio(78923, 23341); try b.setRatio(123097, 12441414); try a.add(a, b); try r.setRatio(984786924199, 290395044174); try testing.expect((try a.order(r)) == .eq); } test "big.rational sub" { var a = try Rational.init(testing.allocator); defer a.deinit(); var b = try Rational.init(testing.allocator); defer b.deinit(); var r = try Rational.init(testing.allocator); defer r.deinit(); try a.setRatio(78923, 23341); try b.setRatio(123097, 12441414); try a.sub(a, b); try r.setRatio(979040510045, 290395044174); try testing.expect((try a.order(r)) == .eq); } test "big.rational mul" { var a = try Rational.init(testing.allocator); defer a.deinit(); var b = try Rational.init(testing.allocator); defer b.deinit(); var r = try Rational.init(testing.allocator); defer r.deinit(); try a.setRatio(78923, 23341); try b.setRatio(123097, 12441414); try a.mul(a, b); try r.setRatio(571481443, 17082061422); try testing.expect((try a.order(r)) == .eq); } test "big.rational div" { var a = try Rational.init(testing.allocator); defer a.deinit(); var b = try Rational.init(testing.allocator); defer b.deinit(); var r = try Rational.init(testing.allocator); defer r.deinit(); try a.setRatio(78923, 23341); try b.setRatio(123097, 12441414); try a.div(a, b); try r.setRatio(75531824394, 221015929); try testing.expect((try a.order(r)) == .eq); } test "big.rational div" { var a = try Rational.init(testing.allocator); defer a.deinit(); var r = try Rational.init(testing.allocator); defer r.deinit(); try a.setRatio(78923, 23341); a.invert(); try r.setRatio(23341, 78923); try testing.expect((try a.order(r)) == .eq); try a.setRatio(-78923, 23341); a.invert(); try r.setRatio(-23341, 78923); try testing.expect((try a.order(r)) == .eq); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math
repos/gotta-go-fast/src/self-hosted-parser/input_dir/math/big/int_test.zig
const std = @import("../../std.zig"); const mem = std.mem; const testing = std.testing; const Managed = std.math.big.int.Managed; const Mutable = std.math.big.int.Mutable; const Limb = std.math.big.Limb; const SignedLimb = std.math.big.SignedLimb; const DoubleLimb = std.math.big.DoubleLimb; const SignedDoubleLimb = std.math.big.SignedDoubleLimb; const maxInt = std.math.maxInt; const minInt = std.math.minInt; // NOTE: All the following tests assume the max machine-word will be 64-bit. // // They will still run on larger than this and should pass, but the multi-limb code-paths // may be untested in some cases. test "big.int comptime_int set" { comptime var s = 0xefffffff00000001eeeeeeefaaaaaaab; var a = try Managed.initSet(testing.allocator, s); defer a.deinit(); const s_limb_count = 128 / @typeInfo(Limb).Int.bits; comptime var i: usize = 0; inline while (i < s_limb_count) : (i += 1) { const result = @as(Limb, s & maxInt(Limb)); s >>= @typeInfo(Limb).Int.bits / 2; s >>= @typeInfo(Limb).Int.bits / 2; try testing.expect(a.limbs[i] == result); } } test "big.int comptime_int set negative" { var a = try Managed.initSet(testing.allocator, -10); defer a.deinit(); try testing.expect(a.limbs[0] == 10); try testing.expect(a.isPositive() == false); } test "big.int int set unaligned small" { var a = try Managed.initSet(testing.allocator, @as(u7, 45)); defer a.deinit(); try testing.expect(a.limbs[0] == 45); try testing.expect(a.isPositive() == true); } test "big.int comptime_int to" { var a = try Managed.initSet(testing.allocator, 0xefffffff00000001eeeeeeefaaaaaaab); defer a.deinit(); try testing.expect((try a.to(u128)) == 0xefffffff00000001eeeeeeefaaaaaaab); } test "big.int sub-limb to" { var a = try Managed.initSet(testing.allocator, 10); defer a.deinit(); try testing.expect((try a.to(u8)) == 10); } test "big.int set negative minimum" { var a = try Managed.initSet(testing.allocator, @as(i64, minInt(i64))); defer a.deinit(); try testing.expect((try a.to(i64)) == minInt(i64)); } test "big.int to target too small error" { var a = try Managed.initSet(testing.allocator, 0xffffffff); defer a.deinit(); try testing.expectError(error.TargetTooSmall, a.to(u8)); } test "big.int normalize" { var a = try Managed.init(testing.allocator); defer a.deinit(); try a.ensureCapacity(8); a.limbs[0] = 1; a.limbs[1] = 2; a.limbs[2] = 3; a.limbs[3] = 0; a.normalize(4); try testing.expect(a.len() == 3); a.limbs[0] = 1; a.limbs[1] = 2; a.limbs[2] = 3; a.normalize(3); try testing.expect(a.len() == 3); a.limbs[0] = 0; a.limbs[1] = 0; a.normalize(2); try testing.expect(a.len() == 1); a.limbs[0] = 0; a.normalize(1); try testing.expect(a.len() == 1); } test "big.int normalize multi" { var a = try Managed.init(testing.allocator); defer a.deinit(); try a.ensureCapacity(8); a.limbs[0] = 1; a.limbs[1] = 2; a.limbs[2] = 0; a.limbs[3] = 0; a.normalize(4); try testing.expect(a.len() == 2); a.limbs[0] = 1; a.limbs[1] = 2; a.limbs[2] = 3; a.normalize(3); try testing.expect(a.len() == 3); a.limbs[0] = 0; a.limbs[1] = 0; a.limbs[2] = 0; a.limbs[3] = 0; a.normalize(4); try testing.expect(a.len() == 1); a.limbs[0] = 0; a.normalize(1); try testing.expect(a.len() == 1); } test "big.int parity" { var a = try Managed.init(testing.allocator); defer a.deinit(); try a.set(0); try testing.expect(a.isEven()); try testing.expect(!a.isOdd()); try a.set(7); try testing.expect(!a.isEven()); try testing.expect(a.isOdd()); } test "big.int bitcount + sizeInBaseUpperBound" { var a = try Managed.init(testing.allocator); defer a.deinit(); try a.set(0b100); try testing.expect(a.bitCountAbs() == 3); try testing.expect(a.sizeInBaseUpperBound(2) >= 3); try testing.expect(a.sizeInBaseUpperBound(10) >= 1); a.negate(); try testing.expect(a.bitCountAbs() == 3); try testing.expect(a.sizeInBaseUpperBound(2) >= 4); try testing.expect(a.sizeInBaseUpperBound(10) >= 2); try a.set(0xffffffff); try testing.expect(a.bitCountAbs() == 32); try testing.expect(a.sizeInBaseUpperBound(2) >= 32); try testing.expect(a.sizeInBaseUpperBound(10) >= 10); try a.shiftLeft(a, 5000); try testing.expect(a.bitCountAbs() == 5032); try testing.expect(a.sizeInBaseUpperBound(2) >= 5032); a.setSign(false); try testing.expect(a.bitCountAbs() == 5032); try testing.expect(a.sizeInBaseUpperBound(2) >= 5033); } test "big.int bitcount/to" { var a = try Managed.init(testing.allocator); defer a.deinit(); try a.set(0); try testing.expect(a.bitCountTwosComp() == 0); try testing.expect((try a.to(u0)) == 0); try testing.expect((try a.to(i0)) == 0); try a.set(-1); try testing.expect(a.bitCountTwosComp() == 1); try testing.expect((try a.to(i1)) == -1); try a.set(-8); try testing.expect(a.bitCountTwosComp() == 4); try testing.expect((try a.to(i4)) == -8); try a.set(127); try testing.expect(a.bitCountTwosComp() == 7); try testing.expect((try a.to(u7)) == 127); try a.set(-128); try testing.expect(a.bitCountTwosComp() == 8); try testing.expect((try a.to(i8)) == -128); try a.set(-129); try testing.expect(a.bitCountTwosComp() == 9); try testing.expect((try a.to(i9)) == -129); } test "big.int fits" { var a = try Managed.init(testing.allocator); defer a.deinit(); try a.set(0); try testing.expect(a.fits(u0)); try testing.expect(a.fits(i0)); try a.set(255); try testing.expect(!a.fits(u0)); try testing.expect(!a.fits(u1)); try testing.expect(!a.fits(i8)); try testing.expect(a.fits(u8)); try testing.expect(a.fits(u9)); try testing.expect(a.fits(i9)); try a.set(-128); try testing.expect(!a.fits(i7)); try testing.expect(a.fits(i8)); try testing.expect(a.fits(i9)); try testing.expect(!a.fits(u9)); try a.set(0x1ffffffffeeeeeeee); try testing.expect(!a.fits(u32)); try testing.expect(!a.fits(u64)); try testing.expect(a.fits(u65)); } test "big.int string set" { var a = try Managed.init(testing.allocator); defer a.deinit(); try a.setString(10, "120317241209124781241290847124"); try testing.expect((try a.to(u128)) == 120317241209124781241290847124); } test "big.int string negative" { var a = try Managed.init(testing.allocator); defer a.deinit(); try a.setString(10, "-1023"); try testing.expect((try a.to(i32)) == -1023); } test "big.int string set number with underscores" { var a = try Managed.init(testing.allocator); defer a.deinit(); try a.setString(10, "__1_2_0_3_1_7_2_4_1_2_0_____9_1__2__4_7_8_1_2_4_1_2_9_0_8_4_7_1_2_4___"); try testing.expect((try a.to(u128)) == 120317241209124781241290847124); } test "big.int string set case insensitive number" { var a = try Managed.init(testing.allocator); defer a.deinit(); try a.setString(16, "aB_cD_eF"); try testing.expect((try a.to(u32)) == 0xabcdef); } test "big.int string set bad char error" { var a = try Managed.init(testing.allocator); defer a.deinit(); try testing.expectError(error.InvalidCharacter, a.setString(10, "x")); } test "big.int string set bad base error" { var a = try Managed.init(testing.allocator); defer a.deinit(); try testing.expectError(error.InvalidBase, a.setString(45, "10")); } test "big.int twos complement limit set" { const test_types = [_]type{ u64, i64, u1, i1, u0, i0, u65, i65, }; inline for (test_types) |T| { // To work around 'control flow attempts to use compile-time variable at runtime' const U = T; const int_info = @typeInfo(U).Int; var a = try Managed.init(testing.allocator); defer a.deinit(); try a.setTwosCompIntLimit(.max, int_info.signedness, int_info.bits); var max: U = maxInt(U); try testing.expect(max == try a.to(U)); try a.setTwosCompIntLimit(.min, int_info.signedness, int_info.bits); var min: U = minInt(U); try testing.expect(min == try a.to(U)); } } test "big.int string to" { var a = try Managed.initSet(testing.allocator, 120317241209124781241290847124); defer a.deinit(); const as = try a.toString(testing.allocator, 10, .lower); defer testing.allocator.free(as); const es = "120317241209124781241290847124"; try testing.expect(mem.eql(u8, as, es)); } test "big.int string to base base error" { var a = try Managed.initSet(testing.allocator, 0xffffffff); defer a.deinit(); try testing.expectError(error.InvalidBase, a.toString(testing.allocator, 45, .lower)); } test "big.int string to base 2" { var a = try Managed.initSet(testing.allocator, -0b1011); defer a.deinit(); const as = try a.toString(testing.allocator, 2, .lower); defer testing.allocator.free(as); const es = "-1011"; try testing.expect(mem.eql(u8, as, es)); } test "big.int string to base 16" { var a = try Managed.initSet(testing.allocator, 0xefffffff00000001eeeeeeefaaaaaaab); defer a.deinit(); const as = try a.toString(testing.allocator, 16, .lower); defer testing.allocator.free(as); const es = "efffffff00000001eeeeeeefaaaaaaab"; try testing.expect(mem.eql(u8, as, es)); } test "big.int neg string to" { var a = try Managed.initSet(testing.allocator, -123907434); defer a.deinit(); const as = try a.toString(testing.allocator, 10, .lower); defer testing.allocator.free(as); const es = "-123907434"; try testing.expect(mem.eql(u8, as, es)); } test "big.int zero string to" { var a = try Managed.initSet(testing.allocator, 0); defer a.deinit(); const as = try a.toString(testing.allocator, 10, .lower); defer testing.allocator.free(as); const es = "0"; try testing.expect(mem.eql(u8, as, es)); } test "big.int clone" { var a = try Managed.initSet(testing.allocator, 1234); defer a.deinit(); var b = try a.clone(); defer b.deinit(); try testing.expect((try a.to(u32)) == 1234); try testing.expect((try b.to(u32)) == 1234); try a.set(77); try testing.expect((try a.to(u32)) == 77); try testing.expect((try b.to(u32)) == 1234); } test "big.int swap" { var a = try Managed.initSet(testing.allocator, 1234); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 5678); defer b.deinit(); try testing.expect((try a.to(u32)) == 1234); try testing.expect((try b.to(u32)) == 5678); a.swap(&b); try testing.expect((try a.to(u32)) == 5678); try testing.expect((try b.to(u32)) == 1234); } test "big.int to negative" { var a = try Managed.initSet(testing.allocator, -10); defer a.deinit(); try testing.expect((try a.to(i32)) == -10); } test "big.int compare" { var a = try Managed.initSet(testing.allocator, -11); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 10); defer b.deinit(); try testing.expect(a.orderAbs(b) == .gt); try testing.expect(a.order(b) == .lt); } test "big.int compare similar" { var a = try Managed.initSet(testing.allocator, 0xffffffffeeeeeeeeffffffffeeeeeeee); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0xffffffffeeeeeeeeffffffffeeeeeeef); defer b.deinit(); try testing.expect(a.orderAbs(b) == .lt); try testing.expect(b.orderAbs(a) == .gt); } test "big.int compare different limb size" { var a = try Managed.initSet(testing.allocator, maxInt(Limb) + 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 1); defer b.deinit(); try testing.expect(a.orderAbs(b) == .gt); try testing.expect(b.orderAbs(a) == .lt); } test "big.int compare multi-limb" { var a = try Managed.initSet(testing.allocator, -0x7777777799999999ffffeeeeffffeeeeffffeeeef); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x7777777799999999ffffeeeeffffeeeeffffeeeee); defer b.deinit(); try testing.expect(a.orderAbs(b) == .gt); try testing.expect(a.order(b) == .lt); } test "big.int equality" { var a = try Managed.initSet(testing.allocator, 0xffffffff1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -0xffffffff1); defer b.deinit(); try testing.expect(a.eqAbs(b)); try testing.expect(!a.eq(b)); } test "big.int abs" { var a = try Managed.initSet(testing.allocator, -5); defer a.deinit(); a.abs(); try testing.expect((try a.to(u32)) == 5); a.abs(); try testing.expect((try a.to(u32)) == 5); } test "big.int negate" { var a = try Managed.initSet(testing.allocator, 5); defer a.deinit(); a.negate(); try testing.expect((try a.to(i32)) == -5); a.negate(); try testing.expect((try a.to(i32)) == 5); } test "big.int add single-single" { var a = try Managed.initSet(testing.allocator, 50); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 5); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.add(a.toConst(), b.toConst()); try testing.expect((try c.to(u32)) == 55); } test "big.int add multi-single" { var a = try Managed.initSet(testing.allocator, maxInt(Limb) + 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 1); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.add(a.toConst(), b.toConst()); try testing.expect((try c.to(DoubleLimb)) == maxInt(Limb) + 2); try c.add(b.toConst(), a.toConst()); try testing.expect((try c.to(DoubleLimb)) == maxInt(Limb) + 2); } test "big.int add multi-multi" { const op1 = 0xefefefef7f7f7f7f; const op2 = 0xfefefefe9f9f9f9f; var a = try Managed.initSet(testing.allocator, op1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, op2); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.add(a.toConst(), b.toConst()); try testing.expect((try c.to(u128)) == op1 + op2); } test "big.int add zero-zero" { var a = try Managed.initSet(testing.allocator, 0); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.add(a.toConst(), b.toConst()); try testing.expect((try c.to(u32)) == 0); } test "big.int add alias multi-limb nonzero-zero" { const op1 = 0xffffffff777777771; var a = try Managed.initSet(testing.allocator, op1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0); defer b.deinit(); try a.add(a.toConst(), b.toConst()); try testing.expect((try a.to(u128)) == op1); } test "big.int add sign" { var a = try Managed.init(testing.allocator); defer a.deinit(); var one = try Managed.initSet(testing.allocator, 1); defer one.deinit(); var two = try Managed.initSet(testing.allocator, 2); defer two.deinit(); var neg_one = try Managed.initSet(testing.allocator, -1); defer neg_one.deinit(); var neg_two = try Managed.initSet(testing.allocator, -2); defer neg_two.deinit(); try a.add(one.toConst(), two.toConst()); try testing.expect((try a.to(i32)) == 3); try a.add(neg_one.toConst(), two.toConst()); try testing.expect((try a.to(i32)) == 1); try a.add(one.toConst(), neg_two.toConst()); try testing.expect((try a.to(i32)) == -1); try a.add(neg_one.toConst(), neg_two.toConst()); try testing.expect((try a.to(i32)) == -3); } test "big.int add scalar" { var a = try Managed.initSet(testing.allocator, 50); defer a.deinit(); var b = try Managed.init(testing.allocator); defer b.deinit(); try b.addScalar(a.toConst(), 5); try testing.expect((try b.to(u32)) == 55); } test "big.int addWrap single-single, unsigned" { var a = try Managed.initSet(testing.allocator, maxInt(u17)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 10); defer b.deinit(); try a.addWrap(a.toConst(), b.toConst(), .unsigned, 17); try testing.expect((try a.to(u17)) == 9); } test "big.int subWrap single-single, unsigned" { var a = try Managed.initSet(testing.allocator, 0); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(u17)); defer b.deinit(); try a.subWrap(a.toConst(), b.toConst(), .unsigned, 17); try testing.expect((try a.to(u17)) == 1); } test "big.int addWrap multi-multi, unsigned, limb aligned" { var a = try Managed.initSet(testing.allocator, maxInt(DoubleLimb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(DoubleLimb)); defer b.deinit(); try a.addWrap(a.toConst(), b.toConst(), .unsigned, @bitSizeOf(DoubleLimb)); try testing.expect((try a.to(DoubleLimb)) == maxInt(DoubleLimb) - 1); } test "big.int subWrap single-multi, unsigned, limb aligned" { var a = try Managed.initSet(testing.allocator, 10); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(DoubleLimb) + 100); defer b.deinit(); try a.subWrap(a.toConst(), b.toConst(), .unsigned, @bitSizeOf(DoubleLimb)); try testing.expect((try a.to(DoubleLimb)) == maxInt(DoubleLimb) - 88); } test "big.int addWrap single-single, signed" { var a = try Managed.initSet(testing.allocator, maxInt(i21)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 1 + 1 + maxInt(u21)); defer b.deinit(); try a.addWrap(a.toConst(), b.toConst(), .signed, @bitSizeOf(i21)); try testing.expect((try a.to(i21)) == minInt(i21)); } test "big.int subWrap single-single, signed" { var a = try Managed.initSet(testing.allocator, minInt(i21)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 1); defer b.deinit(); try a.subWrap(a.toConst(), b.toConst(), .signed, @bitSizeOf(i21)); try testing.expect((try a.to(i21)) == maxInt(i21)); } test "big.int addWrap multi-multi, signed, limb aligned" { var a = try Managed.initSet(testing.allocator, maxInt(SignedDoubleLimb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(SignedDoubleLimb)); defer b.deinit(); try a.addWrap(a.toConst(), b.toConst(), .signed, @bitSizeOf(SignedDoubleLimb)); try testing.expect((try a.to(SignedDoubleLimb)) == -2); } test "big.int subWrap single-multi, signed, limb aligned" { var a = try Managed.initSet(testing.allocator, minInt(SignedDoubleLimb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 1); defer b.deinit(); try a.subWrap(a.toConst(), b.toConst(), .signed, @bitSizeOf(SignedDoubleLimb)); try testing.expect((try a.to(SignedDoubleLimb)) == maxInt(SignedDoubleLimb)); } test "big.int addSat single-single, unsigned" { var a = try Managed.initSet(testing.allocator, maxInt(u17) - 5); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 10); defer b.deinit(); try a.addSat(a.toConst(), b.toConst(), .unsigned, 17); try testing.expect((try a.to(u17)) == maxInt(u17)); } test "big.int subSat single-single, unsigned" { var a = try Managed.initSet(testing.allocator, 123); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 4000); defer b.deinit(); try a.subSat(a.toConst(), b.toConst(), .unsigned, 17); try testing.expect((try a.to(u17)) == 0); } test "big.int addSat multi-multi, unsigned, limb aligned" { var a = try Managed.initSet(testing.allocator, maxInt(DoubleLimb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(DoubleLimb)); defer b.deinit(); try a.addSat(a.toConst(), b.toConst(), .unsigned, @bitSizeOf(DoubleLimb)); try testing.expect((try a.to(DoubleLimb)) == maxInt(DoubleLimb)); } test "big.int subSat single-multi, unsigned, limb aligned" { var a = try Managed.initSet(testing.allocator, 10); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(DoubleLimb) + 100); defer b.deinit(); try a.subSat(a.toConst(), b.toConst(), .unsigned, @bitSizeOf(DoubleLimb)); try testing.expect((try a.to(DoubleLimb)) == 0); } test "big.int addSat single-single, signed" { var a = try Managed.initSet(testing.allocator, maxInt(i14)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 1); defer b.deinit(); try a.addSat(a.toConst(), b.toConst(), .signed, @bitSizeOf(i14)); try testing.expect((try a.to(i14)) == maxInt(i14)); } test "big.int subSat single-single, signed" { var a = try Managed.initSet(testing.allocator, minInt(i21)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 1); defer b.deinit(); try a.subSat(a.toConst(), b.toConst(), .signed, @bitSizeOf(i21)); try testing.expect((try a.to(i21)) == minInt(i21)); } test "big.int addSat multi-multi, signed, limb aligned" { var a = try Managed.initSet(testing.allocator, maxInt(SignedDoubleLimb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(SignedDoubleLimb)); defer b.deinit(); try a.addSat(a.toConst(), b.toConst(), .signed, @bitSizeOf(SignedDoubleLimb)); try testing.expect((try a.to(SignedDoubleLimb)) == maxInt(SignedDoubleLimb)); } test "big.int subSat single-multi, signed, limb aligned" { var a = try Managed.initSet(testing.allocator, minInt(SignedDoubleLimb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 1); defer b.deinit(); try a.subSat(a.toConst(), b.toConst(), .signed, @bitSizeOf(SignedDoubleLimb)); try testing.expect((try a.to(SignedDoubleLimb)) == minInt(SignedDoubleLimb)); } test "big.int sub single-single" { var a = try Managed.initSet(testing.allocator, 50); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 5); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.sub(a.toConst(), b.toConst()); try testing.expect((try c.to(u32)) == 45); } test "big.int sub multi-single" { var a = try Managed.initSet(testing.allocator, maxInt(Limb) + 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 1); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.sub(a.toConst(), b.toConst()); try testing.expect((try c.to(Limb)) == maxInt(Limb)); } test "big.int sub multi-multi" { const op1 = 0xefefefefefefefefefefefef; const op2 = 0xabababababababababababab; var a = try Managed.initSet(testing.allocator, op1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, op2); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.sub(a.toConst(), b.toConst()); try testing.expect((try c.to(u128)) == op1 - op2); } test "big.int sub equal" { var a = try Managed.initSet(testing.allocator, 0x11efefefefefefefefefefefef); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x11efefefefefefefefefefefef); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.sub(a.toConst(), b.toConst()); try testing.expect((try c.to(u32)) == 0); } test "big.int sub sign" { var a = try Managed.init(testing.allocator); defer a.deinit(); var one = try Managed.initSet(testing.allocator, 1); defer one.deinit(); var two = try Managed.initSet(testing.allocator, 2); defer two.deinit(); var neg_one = try Managed.initSet(testing.allocator, -1); defer neg_one.deinit(); var neg_two = try Managed.initSet(testing.allocator, -2); defer neg_two.deinit(); try a.sub(one.toConst(), two.toConst()); try testing.expect((try a.to(i32)) == -1); try a.sub(neg_one.toConst(), two.toConst()); try testing.expect((try a.to(i32)) == -3); try a.sub(one.toConst(), neg_two.toConst()); try testing.expect((try a.to(i32)) == 3); try a.sub(neg_one.toConst(), neg_two.toConst()); try testing.expect((try a.to(i32)) == 1); try a.sub(neg_two.toConst(), neg_one.toConst()); try testing.expect((try a.to(i32)) == -1); } test "big.int mul single-single" { var a = try Managed.initSet(testing.allocator, 50); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 5); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.mul(a.toConst(), b.toConst()); try testing.expect((try c.to(u64)) == 250); } test "big.int mul multi-single" { var a = try Managed.initSet(testing.allocator, maxInt(Limb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 2); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.mul(a.toConst(), b.toConst()); try testing.expect((try c.to(DoubleLimb)) == 2 * maxInt(Limb)); } test "big.int mul multi-multi" { const op1 = 0x998888efefefefefefefef; const op2 = 0x333000abababababababab; var a = try Managed.initSet(testing.allocator, op1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, op2); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.mul(a.toConst(), b.toConst()); try testing.expect((try c.to(u256)) == op1 * op2); } test "big.int mul alias r with a" { var a = try Managed.initSet(testing.allocator, maxInt(Limb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 2); defer b.deinit(); try a.mul(a.toConst(), b.toConst()); try testing.expect((try a.to(DoubleLimb)) == 2 * maxInt(Limb)); } test "big.int mul alias r with b" { var a = try Managed.initSet(testing.allocator, maxInt(Limb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 2); defer b.deinit(); try a.mul(b.toConst(), a.toConst()); try testing.expect((try a.to(DoubleLimb)) == 2 * maxInt(Limb)); } test "big.int mul alias r with a and b" { var a = try Managed.initSet(testing.allocator, maxInt(Limb)); defer a.deinit(); try a.mul(a.toConst(), a.toConst()); try testing.expect((try a.to(DoubleLimb)) == maxInt(Limb) * maxInt(Limb)); } test "big.int mul a*0" { var a = try Managed.initSet(testing.allocator, 0xefefefefefefefef); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.mul(a.toConst(), b.toConst()); try testing.expect((try c.to(u32)) == 0); } test "big.int mul 0*0" { var a = try Managed.initSet(testing.allocator, 0); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.mul(a.toConst(), b.toConst()); try testing.expect((try c.to(u32)) == 0); } test "big.int mul large" { var a = try Managed.initCapacity(testing.allocator, 50); defer a.deinit(); var b = try Managed.initCapacity(testing.allocator, 100); defer b.deinit(); var c = try Managed.initCapacity(testing.allocator, 100); defer c.deinit(); // Generate a number that's large enough to cross the thresholds for the use // of subquadratic algorithms for (a.limbs) |*p| { p.* = std.math.maxInt(Limb); } a.setMetadata(true, 50); try b.mul(a.toConst(), a.toConst()); try c.sqr(a.toConst()); try testing.expect(b.eq(c)); } test "big.int mulWrap single-single unsigned" { var a = try Managed.initSet(testing.allocator, 1234); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 5678); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.mulWrap(a.toConst(), b.toConst(), .unsigned, 17); try testing.expect((try c.to(u17)) == 59836); } test "big.int mulWrap single-single signed" { var a = try Managed.initSet(testing.allocator, 1234); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -5678); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.mulWrap(a.toConst(), b.toConst(), .signed, 17); try testing.expect((try c.to(i17)) == -59836); } test "big.int mulWrap multi-multi unsigned" { const op1 = 0x998888efefefefefefefef; const op2 = 0x333000abababababababab; var a = try Managed.initSet(testing.allocator, op1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, op2); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.mulWrap(a.toConst(), b.toConst(), .unsigned, 65); try testing.expect((try c.to(u128)) == (op1 * op2) & ((1 << 65) - 1)); } test "big.int mulWrap multi-multi signed" { var a = try Managed.initSet(testing.allocator, maxInt(SignedDoubleLimb) - 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(SignedDoubleLimb)); defer b.deinit(); var c = try Managed.init(testing.allocator); defer c.deinit(); try c.mulWrap(a.toConst(), b.toConst(), .signed, @bitSizeOf(SignedDoubleLimb)); try testing.expect((try c.to(SignedDoubleLimb)) == minInt(SignedDoubleLimb) + 2); } test "big.int mulWrap large" { var a = try Managed.initCapacity(testing.allocator, 50); defer a.deinit(); var b = try Managed.initCapacity(testing.allocator, 100); defer b.deinit(); var c = try Managed.initCapacity(testing.allocator, 100); defer c.deinit(); // Generate a number that's large enough to cross the thresholds for the use // of subquadratic algorithms for (a.limbs) |*p| { p.* = std.math.maxInt(Limb); } a.setMetadata(true, 50); const testbits = @bitSizeOf(Limb) * 64 + 45; try b.mulWrap(a.toConst(), a.toConst(), .signed, testbits); try c.sqr(a.toConst()); try c.truncate(c.toConst(), .signed, testbits); try testing.expect(b.eq(c)); } test "big.int div single-single no rem" { var a = try Managed.initSet(testing.allocator, 50); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 5); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u32)) == 10); try testing.expect((try r.to(u32)) == 0); } test "big.int div single-single with rem" { var a = try Managed.initSet(testing.allocator, 49); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 5); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u32)) == 9); try testing.expect((try r.to(u32)) == 4); } test "big.int div multi-single no rem" { const op1 = 0xffffeeeeddddcccc; const op2 = 34; var a = try Managed.initSet(testing.allocator, op1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, op2); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u64)) == op1 / op2); try testing.expect((try r.to(u64)) == 0); } test "big.int div multi-single with rem" { const op1 = 0xffffeeeeddddcccf; const op2 = 34; var a = try Managed.initSet(testing.allocator, op1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, op2); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u64)) == op1 / op2); try testing.expect((try r.to(u64)) == 3); } test "big.int div multi>2-single" { const op1 = 0xfefefefefefefefefefefefefefefefe; const op2 = 0xefab8; var a = try Managed.initSet(testing.allocator, op1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, op2); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u128)) == op1 / op2); try testing.expect((try r.to(u32)) == 0x3e4e); } test "big.int div single-single q < r" { var a = try Managed.initSet(testing.allocator, 0x0078f432); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x01000000); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u64)) == 0); try testing.expect((try r.to(u64)) == 0x0078f432); } test "big.int div single-single q == r" { var a = try Managed.initSet(testing.allocator, 10); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 10); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u64)) == 1); try testing.expect((try r.to(u64)) == 0); } test "big.int div q=0 alias" { var a = try Managed.initSet(testing.allocator, 3); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 10); defer b.deinit(); try Managed.divTrunc(&a, &b, a.toConst(), b.toConst()); try testing.expect((try a.to(u64)) == 0); try testing.expect((try b.to(u64)) == 3); } test "big.int div multi-multi q < r" { const op1 = 0x1ffffffff0078f432; const op2 = 0x1ffffffff01000000; var a = try Managed.initSet(testing.allocator, op1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, op2); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u128)) == 0); try testing.expect((try r.to(u128)) == op1); } test "big.int div trunc single-single +/+" { const u: i32 = 5; const v: i32 = 3; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); // n = q * d + r // 5 = 1 * 3 + 2 const eq = @divTrunc(u, v); const er = @mod(u, v); try testing.expect((try q.to(i32)) == eq); try testing.expect((try r.to(i32)) == er); } test "big.int div trunc single-single -/+" { const u: i32 = -5; const v: i32 = 3; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); // n = q * d + r // -5 = 1 * -3 - 2 const eq = -1; const er = -2; try testing.expect((try q.to(i32)) == eq); try testing.expect((try r.to(i32)) == er); } test "big.int div trunc single-single +/-" { const u: i32 = 5; const v: i32 = -3; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); // n = q * d + r // 5 = -1 * -3 + 2 const eq = -1; const er = 2; try testing.expect((try q.to(i32)) == eq); try testing.expect((try r.to(i32)) == er); } test "big.int div trunc single-single -/-" { const u: i32 = -5; const v: i32 = -3; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); // n = q * d + r // -5 = 1 * -3 - 2 const eq = 1; const er = -2; try testing.expect((try q.to(i32)) == eq); try testing.expect((try r.to(i32)) == er); } test "big.int div floor single-single +/+" { const u: i32 = 5; const v: i32 = 3; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divFloor(&q, &r, a.toConst(), b.toConst()); // n = q * d + r // 5 = 1 * 3 + 2 const eq = 1; const er = 2; try testing.expect((try q.to(i32)) == eq); try testing.expect((try r.to(i32)) == er); } test "big.int div floor single-single -/+" { const u: i32 = -5; const v: i32 = 3; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divFloor(&q, &r, a.toConst(), b.toConst()); // n = q * d + r // -5 = -2 * 3 + 1 const eq = -2; const er = 1; try testing.expect((try q.to(i32)) == eq); try testing.expect((try r.to(i32)) == er); } test "big.int div floor single-single +/-" { const u: i32 = 5; const v: i32 = -3; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divFloor(&q, &r, a.toConst(), b.toConst()); // n = q * d + r // 5 = -2 * -3 - 1 const eq = -2; const er = -1; try testing.expect((try q.to(i32)) == eq); try testing.expect((try r.to(i32)) == er); } test "big.int div floor single-single -/-" { const u: i32 = -5; const v: i32 = -3; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divFloor(&q, &r, a.toConst(), b.toConst()); // n = q * d + r // -5 = 2 * -3 + 1 const eq = 1; const er = -2; try testing.expect((try q.to(i32)) == eq); try testing.expect((try r.to(i32)) == er); } test "big.int div floor no remainder negative quotient" { const u: i32 = -0x80000000; const v: i32 = 1; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divFloor(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(i32)) == -0x80000000); try testing.expect((try r.to(i32)) == 0); } test "big.int div floor negative close to zero" { const u: i32 = -2; const v: i32 = 12; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divFloor(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(i32)) == -1); try testing.expect((try r.to(i32)) == 10); } test "big.int div floor positive close to zero" { const u: i32 = 10; const v: i32 = 12; var a = try Managed.initSet(testing.allocator, u); defer a.deinit(); var b = try Managed.initSet(testing.allocator, v); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divFloor(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(i32)) == 0); try testing.expect((try r.to(i32)) == 10); } test "big.int div multi-multi with rem" { var a = try Managed.initSet(testing.allocator, 0x8888999911110000ffffeeeeddddccccbbbbaaaa9999); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x99990000111122223333); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u128)) == 0xe38f38e39161aaabd03f0f1b); try testing.expect((try r.to(u128)) == 0x28de0acacd806823638); } test "big.int div multi-multi no rem" { var a = try Managed.initSet(testing.allocator, 0x8888999911110000ffffeeeedb4fec200ee3a4286361); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x99990000111122223333); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u128)) == 0xe38f38e39161aaabd03f0f1b); try testing.expect((try r.to(u128)) == 0); } test "big.int div multi-multi (2 branch)" { var a = try Managed.initSet(testing.allocator, 0x866666665555555588888887777777761111111111111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x86666666555555554444444433333333); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u128)) == 0x10000000000000000); try testing.expect((try r.to(u128)) == 0x44444443444444431111111111111111); } test "big.int div multi-multi (3.1/3.3 branch)" { var a = try Managed.initSet(testing.allocator, 0x11111111111111111111111111111111111111111111111111111111111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x1111111111111111111111111111111111111111171); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u128)) == 0xfffffffffffffffffff); try testing.expect((try r.to(u256)) == 0x1111111111111111111110b12222222222222222282); } test "big.int div multi-single zero-limb trailing" { var a = try Managed.initSet(testing.allocator, 0x60000000000000000000000000000000000000000000000000000000000000000); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x10000000000000000); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); var expected = try Managed.initSet(testing.allocator, 0x6000000000000000000000000000000000000000000000000); defer expected.deinit(); try testing.expect(q.eq(expected)); try testing.expect(r.eqZero()); } test "big.int div multi-multi zero-limb trailing (with rem)" { var a = try Managed.initSet(testing.allocator, 0x86666666555555558888888777777776111111111111111100000000000000000000000000000000); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x8666666655555555444444443333333300000000000000000000000000000000); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u128)) == 0x10000000000000000); const rs = try r.toString(testing.allocator, 16, .lower); defer testing.allocator.free(rs); try testing.expect(std.mem.eql(u8, rs, "4444444344444443111111111111111100000000000000000000000000000000")); } test "big.int div multi-multi zero-limb trailing (with rem) and dividend zero-limb count > divisor zero-limb count" { var a = try Managed.initSet(testing.allocator, 0x8666666655555555888888877777777611111111111111110000000000000000); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x8666666655555555444444443333333300000000000000000000000000000000); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); try testing.expect((try q.to(u128)) == 0x1); const rs = try r.toString(testing.allocator, 16, .lower); defer testing.allocator.free(rs); try testing.expect(std.mem.eql(u8, rs, "444444434444444311111111111111110000000000000000")); } test "big.int div multi-multi zero-limb trailing (with rem) and dividend zero-limb count < divisor zero-limb count" { var a = try Managed.initSet(testing.allocator, 0x86666666555555558888888777777776111111111111111100000000000000000000000000000000); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x866666665555555544444444333333330000000000000000); defer b.deinit(); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); const qs = try q.toString(testing.allocator, 16, .lower); defer testing.allocator.free(qs); try testing.expect(std.mem.eql(u8, qs, "10000000000000000820820803105186f")); const rs = try r.toString(testing.allocator, 16, .lower); defer testing.allocator.free(rs); try testing.expect(std.mem.eql(u8, rs, "4e11f2baa5896a321d463b543d0104e30000000000000000")); } test "big.int div multi-multi fuzz case #1" { var a = try Managed.init(testing.allocator); defer a.deinit(); var b = try Managed.init(testing.allocator); defer b.deinit(); try a.setString(16, "ffffffffffffffffffffffffffffc00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); try b.setString(16, "3ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0000000000000000000000000000000000001ffffffffffffffffffffffffffffffffffffffffffffffffffc000000000000000000000000000000007fffffffffff"); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); const qs = try q.toString(testing.allocator, 16, .lower); defer testing.allocator.free(qs); try testing.expect(std.mem.eql(u8, qs, "3ffffffffffffffffffffffffffff0000000000000000000000000000000000001ffffffffffffffffffffffffffff7fffffffe000000000000000000000000000180000000000000000000003fffffbfffffffdfffffffffffffeffff800000100101000000100000000020003fffffdfbfffffe3ffffffffffffeffff7fffc00800a100000017ffe000002000400007efbfff7fe9f00000037ffff3fff7fffa004006100000009ffe00000190038200bf7d2ff7fefe80400060000f7d7f8fbf9401fe38e0403ffc0bdffffa51102c300d7be5ef9df4e5060007b0127ad3fa69f97d0f820b6605ff617ddf7f32ad7a05c0d03f2e7bc78a6000e087a8bbcdc59e07a5a079128a7861f553ddebed7e8e56701756f9ead39b48cd1b0831889ea6ec1fddf643d0565b075ff07e6caea4e2854ec9227fd635ed60a2f5eef2893052ffd54718fa08604acbf6a15e78a467c4a3c53c0278af06c4416573f925491b195e8fd79302cb1aaf7caf4ecfc9aec1254cc969786363ac729f914c6ddcc26738d6b0facd54eba026580aba2eb6482a088b0d224a8852420b91ec1")); const rs = try r.toString(testing.allocator, 16, .lower); defer testing.allocator.free(rs); try testing.expect(std.mem.eql(u8, rs, "310d1d4c414426b4836c2635bad1df3a424e50cbdd167ffccb4dfff57d36b4aae0d6ca0910698220171a0f3373c1060a046c2812f0027e321f72979daa5e7973214170d49e885de0c0ecc167837d44502430674a82522e5df6a0759548052420b91ec1")); } test "big.int div multi-multi fuzz case #2" { var a = try Managed.init(testing.allocator); defer a.deinit(); var b = try Managed.init(testing.allocator); defer b.deinit(); try a.setString(16, "3ffffffffe00000000000000000000000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffe000000000000000000000000000000000000000000000000000000000000001fffffffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffc000000000000000000000000000000000000000000000000000000000000000"); try b.setString(16, "ffc0000000000000000000000000000000000000000000000000"); var q = try Managed.init(testing.allocator); defer q.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try Managed.divTrunc(&q, &r, a.toConst(), b.toConst()); const qs = try q.toString(testing.allocator, 16, .lower); defer testing.allocator.free(qs); try testing.expect(std.mem.eql(u8, qs, "40100400fe3f8fe3f8fe3f8fe3f8fe3f8fe4f93e4f93e4f93e4f93e4f93e4f93e4f93e4f93e4f93e4f93e4f93e4f91e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4992649926499264991e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4791e4792e4b92e4b92e4b92e4b92a4a92a4a92a4")); const rs = try r.toString(testing.allocator, 16, .lower); defer testing.allocator.free(rs); try testing.expect(std.mem.eql(u8, rs, "a900000000000000000000000000000000000000000000000000")); } test "big.int truncate single unsigned" { var a = try Managed.initSet(testing.allocator, maxInt(u47)); defer a.deinit(); try a.truncate(a.toConst(), .unsigned, 17); try testing.expect((try a.to(u17)) == maxInt(u17)); } test "big.int truncate single signed" { var a = try Managed.initSet(testing.allocator, 0x1_0000); defer a.deinit(); try a.truncate(a.toConst(), .signed, 17); try testing.expect((try a.to(i17)) == minInt(i17)); } test "big.int truncate multi to single unsigned" { var a = try Managed.initSet(testing.allocator, (maxInt(Limb) + 1) | 0x1234_5678_9ABC_DEF0); defer a.deinit(); try a.truncate(a.toConst(), .unsigned, 27); try testing.expect((try a.to(u27)) == 0x2BC_DEF0); } test "big.int truncate multi to single signed" { var a = try Managed.initSet(testing.allocator, maxInt(Limb) << 10); defer a.deinit(); try a.truncate(a.toConst(), .signed, @bitSizeOf(i11)); try testing.expect((try a.to(i11)) == minInt(i11)); } test "big.int truncate multi to multi unsigned" { const bits = @typeInfo(SignedDoubleLimb).Int.bits; const Int = std.meta.Int(.unsigned, bits - 1); var a = try Managed.initSet(testing.allocator, maxInt(SignedDoubleLimb)); defer a.deinit(); try a.truncate(a.toConst(), .unsigned, bits - 1); try testing.expect((try a.to(Int)) == maxInt(Int)); } test "big.int truncate multi to multi signed" { var a = try Managed.initSet(testing.allocator, 3 << @bitSizeOf(Limb)); defer a.deinit(); try a.truncate(a.toConst(), .signed, @bitSizeOf(Limb) + 1); try testing.expect((try a.to(std.meta.Int(.signed, @bitSizeOf(Limb) + 1))) == -1 << @bitSizeOf(Limb)); } test "big.int truncate negative multi to single" { var a = try Managed.initSet(testing.allocator, -@as(SignedDoubleLimb, maxInt(Limb) + 1)); defer a.deinit(); try a.truncate(a.toConst(), .signed, @bitSizeOf(i17)); try testing.expect((try a.to(i17)) == 0); } test "big.int truncate multi unsigned many" { var a = try Managed.initSet(testing.allocator, 1); defer a.deinit(); try a.shiftLeft(a, 1023); var b = try Managed.init(testing.allocator); defer b.deinit(); try b.truncate(a.toConst(), .signed, @bitSizeOf(i1)); try testing.expect((try b.to(i1)) == 0); } test "big.int saturate single signed positive" { var a = try Managed.initSet(testing.allocator, 0xBBBB_BBBB); defer a.deinit(); try a.saturate(a.toConst(), .signed, 17); try testing.expect((try a.to(i17)) == maxInt(i17)); } test "big.int saturate single signed negative" { var a = try Managed.initSet(testing.allocator, -1_234_567); defer a.deinit(); try a.saturate(a.toConst(), .signed, 17); try testing.expect((try a.to(i17)) == minInt(i17)); } test "big.int saturate single signed" { var a = try Managed.initSet(testing.allocator, maxInt(i17) - 1); defer a.deinit(); try a.saturate(a.toConst(), .signed, 17); try testing.expect((try a.to(i17)) == maxInt(i17) - 1); } test "big.int saturate multi signed" { var a = try Managed.initSet(testing.allocator, maxInt(Limb) << @bitSizeOf(SignedDoubleLimb)); defer a.deinit(); try a.saturate(a.toConst(), .signed, @bitSizeOf(SignedDoubleLimb)); try testing.expect((try a.to(SignedDoubleLimb)) == maxInt(SignedDoubleLimb)); } test "big.int saturate single unsigned" { var a = try Managed.initSet(testing.allocator, 0xFEFE_FEFE); defer a.deinit(); try a.saturate(a.toConst(), .unsigned, 23); try testing.expect((try a.to(u23)) == maxInt(u23)); } test "big.int saturate multi unsigned zero" { var a = try Managed.initSet(testing.allocator, -1); defer a.deinit(); try a.saturate(a.toConst(), .unsigned, @bitSizeOf(DoubleLimb)); try testing.expect(a.eqZero()); } test "big.int saturate multi unsigned" { var a = try Managed.initSet(testing.allocator, maxInt(Limb) << @bitSizeOf(DoubleLimb)); defer a.deinit(); try a.saturate(a.toConst(), .unsigned, @bitSizeOf(DoubleLimb)); try testing.expect((try a.to(DoubleLimb)) == maxInt(DoubleLimb)); } test "big.int shift-right single" { var a = try Managed.initSet(testing.allocator, 0xffff0000); defer a.deinit(); try a.shiftRight(a, 16); try testing.expect((try a.to(u32)) == 0xffff); } test "big.int shift-right multi" { var a = try Managed.initSet(testing.allocator, 0xffff0000eeee1111dddd2222cccc3333); defer a.deinit(); try a.shiftRight(a, 67); try testing.expect((try a.to(u64)) == 0x1fffe0001dddc222); try a.set(0xffff0000eeee1111dddd2222cccc3333); try a.shiftRight(a, 63); try a.shiftRight(a, 63); try a.shiftRight(a, 2); try testing.expect(a.eqZero()); } test "big.int shift-left single" { var a = try Managed.initSet(testing.allocator, 0xffff); defer a.deinit(); try a.shiftLeft(a, 16); try testing.expect((try a.to(u64)) == 0xffff0000); } test "big.int shift-left multi" { var a = try Managed.initSet(testing.allocator, 0x1fffe0001dddc222); defer a.deinit(); try a.shiftLeft(a, 67); try testing.expect((try a.to(u128)) == 0xffff0000eeee11100000000000000000); } test "big.int shift-right negative" { var a = try Managed.init(testing.allocator); defer a.deinit(); var arg = try Managed.initSet(testing.allocator, -20); defer arg.deinit(); try a.shiftRight(arg, 2); try testing.expect((try a.to(i32)) == -20 >> 2); var arg2 = try Managed.initSet(testing.allocator, -5); defer arg2.deinit(); try a.shiftRight(arg2, 10); try testing.expect((try a.to(i32)) == -5 >> 10); } test "big.int shift-left negative" { var a = try Managed.init(testing.allocator); defer a.deinit(); var arg = try Managed.initSet(testing.allocator, -10); defer arg.deinit(); try a.shiftRight(arg, 1232); try testing.expect((try a.to(i32)) == -10 >> 1232); } test "big.int sat shift-left simple unsigned" { var a = try Managed.initSet(testing.allocator, 0xffff); defer a.deinit(); try a.shiftLeftSat(a, 16, .unsigned, 21); try testing.expect((try a.to(u64)) == 0x1fffff); } test "big.int sat shift-left simple unsigned no sat" { var a = try Managed.initSet(testing.allocator, 1); defer a.deinit(); try a.shiftLeftSat(a, 16, .unsigned, 21); try testing.expect((try a.to(u64)) == 0x10000); } test "big.int sat shift-left multi unsigned" { var a = try Managed.initSet(testing.allocator, 16); defer a.deinit(); try a.shiftLeftSat(a, @bitSizeOf(DoubleLimb) - 3, .unsigned, @bitSizeOf(DoubleLimb) - 1); try testing.expect((try a.to(DoubleLimb)) == maxInt(DoubleLimb) >> 1); } test "big.int sat shift-left unsigned shift > bitcount" { var a = try Managed.initSet(testing.allocator, 1); defer a.deinit(); try a.shiftLeftSat(a, 10, .unsigned, 10); try testing.expect((try a.to(u10)) == maxInt(u10)); } test "big.int sat shift-left unsigned zero" { var a = try Managed.initSet(testing.allocator, 0); defer a.deinit(); try a.shiftLeftSat(a, 1, .unsigned, 0); try testing.expect((try a.to(u64)) == 0); } test "big.int sat shift-left unsigned negative" { var a = try Managed.initSet(testing.allocator, -100); defer a.deinit(); try a.shiftLeftSat(a, 0, .unsigned, 0); try testing.expect((try a.to(u64)) == 0); } test "big.int sat shift-left signed simple negative" { var a = try Managed.initSet(testing.allocator, -100); defer a.deinit(); try a.shiftLeftSat(a, 3, .signed, 10); try testing.expect((try a.to(i10)) == minInt(i10)); } test "big.int sat shift-left signed simple positive" { var a = try Managed.initSet(testing.allocator, 100); defer a.deinit(); try a.shiftLeftSat(a, 3, .signed, 10); try testing.expect((try a.to(i10)) == maxInt(i10)); } test "big.int sat shift-left signed multi positive" { const x = 1; const shift = @bitSizeOf(SignedDoubleLimb) - 1; var a = try Managed.initSet(testing.allocator, x); defer a.deinit(); try a.shiftLeftSat(a, shift, .signed, @bitSizeOf(SignedDoubleLimb)); try testing.expect((try a.to(SignedDoubleLimb)) == @as(SignedDoubleLimb, x) <<| shift); } test "big.int sat shift-left signed multi negative" { const x = -1; const shift = @bitSizeOf(SignedDoubleLimb) - 1; var a = try Managed.initSet(testing.allocator, x); defer a.deinit(); try a.shiftLeftSat(a, shift, .signed, @bitSizeOf(SignedDoubleLimb)); try testing.expect((try a.to(SignedDoubleLimb)) == @as(SignedDoubleLimb, x) <<| shift); } test "big.int bitNotWrap unsigned simple" { var a = try Managed.initSet(testing.allocator, 123); defer a.deinit(); try a.bitNotWrap(a, .unsigned, 10); try testing.expect((try a.to(u10)) == ~@as(u10, 123)); } test "big.int bitNotWrap unsigned multi" { var a = try Managed.initSet(testing.allocator, 0); defer a.deinit(); try a.bitNotWrap(a, .unsigned, @bitSizeOf(DoubleLimb)); try testing.expect((try a.to(DoubleLimb)) == maxInt(DoubleLimb)); } test "big.int bitNotWrap signed simple" { var a = try Managed.initSet(testing.allocator, -456); defer a.deinit(); try a.bitNotWrap(a, .signed, 11); try testing.expect((try a.to(i11)) == ~@as(i11, -456)); } test "big.int bitNotWrap signed multi" { var a = try Managed.initSet(testing.allocator, 0); defer a.deinit(); try a.bitNotWrap(a, .signed, @bitSizeOf(SignedDoubleLimb)); try testing.expect((try a.to(SignedDoubleLimb)) == -1); } test "big.int bitwise and simple" { var a = try Managed.initSet(testing.allocator, 0xffffffff11111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0xeeeeeeee22222222); defer b.deinit(); try a.bitAnd(a, b); try testing.expect((try a.to(u64)) == 0xeeeeeeee00000000); } test "big.int bitwise and multi-limb" { var a = try Managed.initSet(testing.allocator, maxInt(Limb) + 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(Limb)); defer b.deinit(); try a.bitAnd(a, b); try testing.expect((try a.to(u128)) == 0); } test "big.int bitwise and negative-positive simple" { var a = try Managed.initSet(testing.allocator, -0xffffffff11111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0xeeeeeeee22222222); defer b.deinit(); try a.bitAnd(a, b); try testing.expect((try a.to(u64)) == 0x22222222); } test "big.int bitwise and negative-positive multi-limb" { var a = try Managed.initSet(testing.allocator, -maxInt(Limb) - 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(Limb)); defer b.deinit(); try a.bitAnd(a, b); try testing.expect(a.eqZero()); } test "big.int bitwise and positive-negative simple" { var a = try Managed.initSet(testing.allocator, 0xffffffff11111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -0xeeeeeeee22222222); defer b.deinit(); try a.bitAnd(a, b); try testing.expect((try a.to(u64)) == 0x1111111111111110); } test "big.int bitwise and positive-negative multi-limb" { var a = try Managed.initSet(testing.allocator, maxInt(Limb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -maxInt(Limb) - 1); defer b.deinit(); try a.bitAnd(a, b); try testing.expect(a.eqZero()); } test "big.int bitwise and negative-negative simple" { var a = try Managed.initSet(testing.allocator, -0xffffffff11111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -0xeeeeeeee22222222); defer b.deinit(); try a.bitAnd(a, b); try testing.expect((try a.to(i128)) == -0xffffffff33333332); } test "big.int bitwise and negative-negative multi-limb" { var a = try Managed.initSet(testing.allocator, -maxInt(Limb) - 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -maxInt(Limb) - 2); defer b.deinit(); try a.bitAnd(a, b); try testing.expect((try a.to(i128)) == -maxInt(Limb) * 2 - 2); } test "big.int bitwise and negative overflow" { var a = try Managed.initSet(testing.allocator, -maxInt(Limb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -2); defer b.deinit(); try a.bitAnd(a, b); try testing.expect((try a.to(SignedDoubleLimb)) == -maxInt(Limb) - 1); } test "big.int bitwise xor simple" { var a = try Managed.initSet(testing.allocator, 0xffffffff11111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0xeeeeeeee22222222); defer b.deinit(); try a.bitXor(a, b); try testing.expect((try a.to(u64)) == 0x1111111133333333); } test "big.int bitwise xor multi-limb" { var a = try Managed.initSet(testing.allocator, maxInt(Limb) + 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(Limb)); defer b.deinit(); try a.bitXor(a, b); try testing.expect((try a.to(DoubleLimb)) == (maxInt(Limb) + 1) ^ maxInt(Limb)); } test "big.int bitwise xor single negative simple" { var a = try Managed.initSet(testing.allocator, 0x6b03e381328a3154); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -0x45fd3acef9191fad); defer b.deinit(); try a.bitXor(a, b); try testing.expect((try a.to(i64)) == -0x2efed94fcb932ef9); } test "big.int bitwise xor single negative zero" { var a = try Managed.initSet(testing.allocator, 0); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -0); defer b.deinit(); try a.bitXor(a, b); try testing.expect(a.eqZero()); } test "big.int bitwise xor single negative multi-limb" { var a = try Managed.initSet(testing.allocator, -0x9849c6e7a10d66d0e4260d4846254c32); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0xf2194e7d1c855272a997fcde16f6d5a8); defer b.deinit(); try a.bitXor(a, b); try testing.expect((try a.to(i128)) == -0x6a50889abd8834a24db1f19650d3999a); } test "big.int bitwise xor single negative overflow" { var a = try Managed.initSet(testing.allocator, maxInt(Limb)); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -1); defer b.deinit(); try a.bitXor(a, b); try testing.expect((try a.to(SignedDoubleLimb)) == -(maxInt(Limb) + 1)); } test "big.int bitwise xor double negative simple" { var a = try Managed.initSet(testing.allocator, -0x8e48bd5f755ef1f3); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -0x4dd4fa576f3046ac); defer b.deinit(); try a.bitXor(a, b); try testing.expect((try a.to(u64)) == 0xc39c47081a6eb759); } test "big.int bitwise xor double negative multi-limb" { var a = try Managed.initSet(testing.allocator, -0x684e5da8f500ec8ca7204c33ccc51c9c); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -0xcb07736a7b62289c78d967c3985eebeb); defer b.deinit(); try a.bitXor(a, b); try testing.expect((try a.to(u128)) == 0xa3492ec28e62c410dff92bf0549bf771); } test "big.int bitwise or simple" { var a = try Managed.initSet(testing.allocator, 0xffffffff11111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0xeeeeeeee22222222); defer b.deinit(); try a.bitOr(a, b); try testing.expect((try a.to(u64)) == 0xffffffff33333333); } test "big.int bitwise or multi-limb" { var a = try Managed.initSet(testing.allocator, maxInt(Limb) + 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, maxInt(Limb)); defer b.deinit(); try a.bitOr(a, b); // TODO: big.int.cpp or is wrong on multi-limb. try testing.expect((try a.to(DoubleLimb)) == (maxInt(Limb) + 1) + maxInt(Limb)); } test "big.int bitwise or negative-positive simple" { var a = try Managed.initSet(testing.allocator, -0xffffffff11111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0xeeeeeeee22222222); defer b.deinit(); try a.bitOr(a, b); try testing.expect((try a.to(i64)) == -0x1111111111111111); } test "big.int bitwise or negative-positive multi-limb" { var a = try Managed.initSet(testing.allocator, -maxInt(Limb) - 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 1); defer b.deinit(); try a.bitOr(a, b); try testing.expect((try a.to(SignedDoubleLimb)) == -maxInt(Limb)); } test "big.int bitwise or positive-negative simple" { var a = try Managed.initSet(testing.allocator, 0xffffffff11111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -0xeeeeeeee22222222); defer b.deinit(); try a.bitOr(a, b); try testing.expect((try a.to(i64)) == -0x22222221); } test "big.int bitwise or positive-negative multi-limb" { var a = try Managed.initSet(testing.allocator, maxInt(Limb) + 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -1); defer b.deinit(); try a.bitOr(a, b); try testing.expect((try a.to(SignedDoubleLimb)) == -1); } test "big.int bitwise or negative-negative simple" { var a = try Managed.initSet(testing.allocator, -0xffffffff11111111); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -0xeeeeeeee22222222); defer b.deinit(); try a.bitOr(a, b); try testing.expect((try a.to(i128)) == -0xeeeeeeee00000001); } test "big.int bitwise or negative-negative multi-limb" { var a = try Managed.initSet(testing.allocator, -maxInt(Limb) - 1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -maxInt(Limb)); defer b.deinit(); try a.bitOr(a, b); try testing.expect((try a.to(SignedDoubleLimb)) == -maxInt(Limb)); } test "big.int var args" { var a = try Managed.initSet(testing.allocator, 5); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 6); defer b.deinit(); try a.add(a.toConst(), b.toConst()); try testing.expect((try a.to(u64)) == 11); var c = try Managed.initSet(testing.allocator, 11); defer c.deinit(); try testing.expect(a.order(c) == .eq); var d = try Managed.initSet(testing.allocator, 14); defer d.deinit(); try testing.expect(a.order(d) != .gt); } test "big.int gcd non-one small" { var a = try Managed.initSet(testing.allocator, 17); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 97); defer b.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try r.gcd(a, b); try testing.expect((try r.to(u32)) == 1); } test "big.int gcd non-one small" { var a = try Managed.initSet(testing.allocator, 4864); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 3458); defer b.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try r.gcd(a, b); try testing.expect((try r.to(u32)) == 38); } test "big.int gcd non-one large" { var a = try Managed.initSet(testing.allocator, 0xffffffffffffffff); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0xffffffffffffffff7777); defer b.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try r.gcd(a, b); try testing.expect((try r.to(u32)) == 4369); } test "big.int gcd large multi-limb result" { var a = try Managed.initSet(testing.allocator, 0x12345678123456781234567812345678123456781234567812345678); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 0x12345671234567123456712345671234567123456712345671234567); defer b.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try r.gcd(a, b); const answer = (try r.to(u256)); try testing.expect(answer == 0xf000000ff00000fff0000ffff000fffff00ffffff1); } test "big.int gcd one large" { var a = try Managed.initSet(testing.allocator, 1897056385327307); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 2251799813685248); defer b.deinit(); var r = try Managed.init(testing.allocator); defer r.deinit(); try r.gcd(a, b); try testing.expect((try r.to(u64)) == 1); } test "big.int mutable to managed" { const allocator = testing.allocator; var limbs_buf = try allocator.alloc(Limb, 8); defer allocator.free(limbs_buf); var a = Mutable.init(limbs_buf, 0xdeadbeef); var a_managed = a.toManaged(allocator); try testing.expect(a.toConst().eq(a_managed.toConst())); } test "big.int const to managed" { var a = try Managed.initSet(testing.allocator, 123423453456); defer a.deinit(); var b = try a.toConst().toManaged(testing.allocator); defer b.deinit(); try testing.expect(a.toConst().eq(b.toConst())); } test "big.int pow" { { var a = try Managed.initSet(testing.allocator, -3); defer a.deinit(); try a.pow(a.toConst(), 3); try testing.expectEqual(@as(i32, -27), try a.to(i32)); try a.pow(a.toConst(), 4); try testing.expectEqual(@as(i32, 531441), try a.to(i32)); } { var a = try Managed.initSet(testing.allocator, 10); defer a.deinit(); var y = try Managed.init(testing.allocator); defer y.deinit(); // y and a are not aliased try y.pow(a.toConst(), 123); // y and a are aliased try a.pow(a.toConst(), 123); try testing.expect(a.eq(y)); const ys = try y.toString(testing.allocator, 16, .lower); defer testing.allocator.free(ys); try testing.expectEqualSlices( u8, "183425a5f872f126e00a5ad62c839075cd6846c6fb0230887c7ad7a9dc530fcb" ++ "4933f60e8000000000000000000000000000000", ys, ); } // Special cases { var a = try Managed.initSet(testing.allocator, 0); defer a.deinit(); try a.pow(a.toConst(), 100); try testing.expectEqual(@as(i32, 0), try a.to(i32)); try a.set(1); try a.pow(a.toConst(), 0); try testing.expectEqual(@as(i32, 1), try a.to(i32)); try a.pow(a.toConst(), 100); try testing.expectEqual(@as(i32, 1), try a.to(i32)); try a.set(-1); try a.pow(a.toConst(), 15); try testing.expectEqual(@as(i32, -1), try a.to(i32)); try a.pow(a.toConst(), 16); try testing.expectEqual(@as(i32, 1), try a.to(i32)); } } test "big.int regression test for 1 limb overflow with alias" { // Note these happen to be two consecutive Fibonacci sequence numbers, the // first two whose sum exceeds 2**64. var a = try Managed.initSet(testing.allocator, 7540113804746346429); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 12200160415121876738); defer b.deinit(); try a.ensureAddCapacity(a.toConst(), b.toConst()); try a.add(a.toConst(), b.toConst()); try testing.expect(a.toConst().orderAgainstScalar(19740274219868223167) == .eq); } test "big.int regression test for realloc with alias" { // Note these happen to be two consecutive Fibonacci sequence numbers, the // second of which is the first such number to exceed 2**192. var a = try Managed.initSet(testing.allocator, 5611500259351924431073312796924978741056961814867751431689); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 9079598147510263717870894449029933369491131786514446266146); defer b.deinit(); try a.ensureAddCapacity(a.toConst(), b.toConst()); try a.add(a.toConst(), b.toConst()); try testing.expect(a.toConst().orderAgainstScalar(14691098406862188148944207245954912110548093601382197697835) == .eq); } test "big int popcount" { var a = try Managed.initSet(testing.allocator, -1); defer a.deinit(); var b = try Managed.initSet(testing.allocator, -1); defer b.deinit(); try a.popCount(b.toConst(), 16); try testing.expect(a.toConst().orderAgainstScalar(16) == .eq); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/heap/general_purpose_allocator.zig
//! # General Purpose Allocator //! //! ## Design Priorities //! //! ### `OptimizationMode.debug` and `OptimizationMode.release_safe`: //! //! * Detect double free, and emit stack trace of: //! - Where it was first allocated //! - Where it was freed the first time //! - Where it was freed the second time //! //! * Detect leaks and emit stack trace of: //! - Where it was allocated //! //! * When a page of memory is no longer needed, give it back to resident memory //! as soon as possible, so that it causes page faults when used. //! //! * Do not re-use memory slots, so that memory safety is upheld. For small //! allocations, this is handled here; for larger ones it is handled in the //! backing allocator (by default `std.heap.page_allocator`). //! //! * Make pointer math errors unlikely to harm memory from //! unrelated allocations. //! //! * It's OK for these mechanisms to cost some extra overhead bytes. //! //! * It's OK for performance cost for these mechanisms. //! //! * Rogue memory writes should not harm the allocator's state. //! //! * Cross platform. Operates based on a backing allocator which makes it work //! everywhere, even freestanding. //! //! * Compile-time configuration. //! //! ### `OptimizationMode.release_fast` (note: not much work has gone into this use case yet): //! //! * Low fragmentation is primary concern //! * Performance of worst-case latency is secondary concern //! * Performance of average-case latency is next //! * Finally, having freed memory unmapped, and pointer math errors unlikely to //! harm memory from unrelated allocations are nice-to-haves. //! //! ### `OptimizationMode.release_small` (note: not much work has gone into this use case yet): //! //! * Small binary code size of the executable is the primary concern. //! * Next, defer to the `.release_fast` priority list. //! //! ## Basic Design: //! //! Small allocations are divided into buckets: //! //! ``` //! index obj_size //! 0 1 //! 1 2 //! 2 4 //! 3 8 //! 4 16 //! 5 32 //! 6 64 //! 7 128 //! 8 256 //! 9 512 //! 10 1024 //! 11 2048 //! ``` //! //! The main allocator state has an array of all the "current" buckets for each //! size class. Each slot in the array can be null, meaning the bucket for that //! size class is not allocated. When the first object is allocated for a given //! size class, it allocates 1 page of memory from the OS. This page is //! divided into "slots" - one per allocated object. Along with the page of memory //! for object slots, as many pages as necessary are allocated to store the //! BucketHeader, followed by "used bits", and two stack traces for each slot //! (allocation trace and free trace). //! //! The "used bits" are 1 bit per slot representing whether the slot is used. //! Allocations use the data to iterate to find a free slot. Frees assert that the //! corresponding bit is 1 and set it to 0. //! //! Buckets have prev and next pointers. When there is only one bucket for a given //! size class, both prev and next point to itself. When all slots of a bucket are //! used, a new bucket is allocated, and enters the doubly linked list. The main //! allocator state tracks the "current" bucket for each size class. Leak detection //! currently only checks the current bucket. //! //! Resizing detects if the size class is unchanged or smaller, in which case the same //! pointer is returned unmodified. If a larger size class is required, //! `error.OutOfMemory` is returned. //! //! Large objects are allocated directly using the backing allocator and their metadata is stored //! in a `std.HashMap` using the backing allocator. const std = @import("std"); const builtin = @import("builtin"); const log = std.log.scoped(.gpa); const math = std.math; const assert = std.debug.assert; const mem = std.mem; const Allocator = std.mem.Allocator; const page_size = std.mem.page_size; const StackTrace = std.builtin.StackTrace; /// Integer type for pointing to slots in a small allocation const SlotIndex = std.meta.Int(.unsigned, math.log2(page_size) + 1); const sys_can_stack_trace = switch (builtin.cpu.arch) { // Observed to go into an infinite loop. // TODO: Make this work. .mips, .mipsel, => false, // `@returnAddress()` in LLVM 10 gives // "Non-Emscripten WebAssembly hasn't implemented __builtin_return_address". .wasm32, .wasm64, => builtin.os.tag == .emscripten, else => true, }; const default_test_stack_trace_frames: usize = if (builtin.is_test) 8 else 4; const default_sys_stack_trace_frames: usize = if (sys_can_stack_trace) default_test_stack_trace_frames else 0; const default_stack_trace_frames: usize = switch (builtin.mode) { .Debug => default_sys_stack_trace_frames, else => 0, }; pub const Config = struct { /// Number of stack frames to capture. stack_trace_frames: usize = default_stack_trace_frames, /// If true, the allocator will have two fields: /// * `total_requested_bytes` which tracks the total allocated bytes of memory requested. /// * `requested_memory_limit` which causes allocations to return `error.OutOfMemory` /// when the `total_requested_bytes` exceeds this limit. /// If false, these fields will be `void`. enable_memory_limit: bool = false, /// Whether to enable safety checks. safety: bool = std.debug.runtime_safety, /// Whether the allocator may be used simultaneously from multiple threads. thread_safe: bool = !builtin.single_threaded, /// What type of mutex you'd like to use, for thread safety. /// when specfied, the mutex type must have the same shape as `std.Thread.Mutex` and /// `std.Thread.Mutex.Dummy`, and have no required fields. Specifying this field causes /// the `thread_safe` field to be ignored. /// /// when null (default): /// * the mutex type defaults to `std.Thread.Mutex` when thread_safe is enabled. /// * the mutex type defaults to `std.Thread.Mutex.Dummy` otherwise. MutexType: ?type = null, /// This is a temporary debugging trick you can use to turn segfaults into more helpful /// logged error messages with stack trace details. The downside is that every allocation /// will be leaked, unless used with retain_metadata! never_unmap: bool = false, /// This is a temporary debugging aid that retains metadata about allocations indefinitely. /// This allows a greater range of double frees to be reported. All metadata is freed when /// deinit is called. When used with never_unmap, deliberately leaked memory is also freed /// during deinit. Currently should be used with never_unmap to avoid segfaults. /// TODO https://github.com/ziglang/zig/issues/4298 will allow use without never_unmap retain_metadata: bool = false, /// Enables emitting info messages with the size and address of every allocation. verbose_log: bool = false, }; pub fn GeneralPurposeAllocator(comptime config: Config) type { return struct { allocator: Allocator = Allocator{ .allocFn = alloc, .resizeFn = resize, }, backing_allocator: *Allocator = std.heap.page_allocator, buckets: [small_bucket_count]?*BucketHeader = [1]?*BucketHeader{null} ** small_bucket_count, large_allocations: LargeAllocTable = .{}, empty_buckets: if (config.retain_metadata) ?*BucketHeader else void = if (config.retain_metadata) null else {}, total_requested_bytes: @TypeOf(total_requested_bytes_init) = total_requested_bytes_init, requested_memory_limit: @TypeOf(requested_memory_limit_init) = requested_memory_limit_init, mutex: @TypeOf(mutex_init) = mutex_init, const Self = @This(); const total_requested_bytes_init = if (config.enable_memory_limit) @as(usize, 0) else {}; const requested_memory_limit_init = if (config.enable_memory_limit) @as(usize, math.maxInt(usize)) else {}; const mutex_init = if (config.MutexType) |T| T{} else if (config.thread_safe) std.Thread.Mutex{} else std.Thread.Mutex.Dummy{}; const stack_n = config.stack_trace_frames; const one_trace_size = @sizeOf(usize) * stack_n; const traces_per_slot = 2; pub const Error = mem.Allocator.Error; const small_bucket_count = math.log2(page_size); const largest_bucket_object_size = 1 << (small_bucket_count - 1); const LargeAlloc = struct { bytes: []u8, requested_size: if (config.enable_memory_limit) usize else void, stack_addresses: [trace_n][stack_n]usize, freed: if (config.retain_metadata) bool else void, ptr_align: if (config.never_unmap and config.retain_metadata) u29 else void, const trace_n = if (config.retain_metadata) traces_per_slot else 1; fn dumpStackTrace(self: *LargeAlloc, trace_kind: TraceKind) void { std.debug.dumpStackTrace(self.getStackTrace(trace_kind)); } fn getStackTrace(self: *LargeAlloc, trace_kind: TraceKind) std.builtin.StackTrace { assert(@intFromEnum(trace_kind) < trace_n); const stack_addresses = &self.stack_addresses[@intFromEnum(trace_kind)]; var len: usize = 0; while (len < stack_n and stack_addresses[len] != 0) { len += 1; } return .{ .instruction_addresses = stack_addresses, .index = len, }; } fn captureStackTrace(self: *LargeAlloc, ret_addr: usize, trace_kind: TraceKind) void { assert(@intFromEnum(trace_kind) < trace_n); const stack_addresses = &self.stack_addresses[@intFromEnum(trace_kind)]; collectStackTrace(ret_addr, stack_addresses); } }; const LargeAllocTable = std.AutoHashMapUnmanaged(usize, LargeAlloc); // Bucket: In memory, in order: // * BucketHeader // * bucket_used_bits: [N]u8, // 1 bit for every slot; 1 byte for every 8 slots // * stack_trace_addresses: [N]usize, // traces_per_slot for every allocation const BucketHeader = struct { prev: *BucketHeader, next: *BucketHeader, page: [*]align(page_size) u8, alloc_cursor: SlotIndex, used_count: SlotIndex, fn usedBits(bucket: *BucketHeader, index: usize) *u8 { return @as(*u8, @ptrFromInt(@intFromPtr(bucket) + @sizeOf(BucketHeader) + index)); } fn stackTracePtr( bucket: *BucketHeader, size_class: usize, slot_index: SlotIndex, trace_kind: TraceKind, ) *[stack_n]usize { const start_ptr = @as([*]u8, @ptrCast(bucket)) + bucketStackFramesStart(size_class); const addr = start_ptr + one_trace_size * traces_per_slot * slot_index + @intFromEnum(trace_kind) * @as(usize, one_trace_size); return @as(*[stack_n]usize, @ptrCast(@alignCast(addr))); } fn captureStackTrace( bucket: *BucketHeader, ret_addr: usize, size_class: usize, slot_index: SlotIndex, trace_kind: TraceKind, ) void { // Initialize them to 0. When determining the count we must look // for non zero addresses. const stack_addresses = bucket.stackTracePtr(size_class, slot_index, trace_kind); collectStackTrace(ret_addr, stack_addresses); } }; fn bucketStackTrace( bucket: *BucketHeader, size_class: usize, slot_index: SlotIndex, trace_kind: TraceKind, ) StackTrace { const stack_addresses = bucket.stackTracePtr(size_class, slot_index, trace_kind); var len: usize = 0; while (len < stack_n and stack_addresses[len] != 0) { len += 1; } return StackTrace{ .instruction_addresses = stack_addresses, .index = len, }; } fn bucketStackFramesStart(size_class: usize) usize { return mem.alignForward( @sizeOf(BucketHeader) + usedBitsCount(size_class), @alignOf(usize), ); } fn bucketSize(size_class: usize) usize { const slot_count = @divExact(page_size, size_class); return bucketStackFramesStart(size_class) + one_trace_size * traces_per_slot * slot_count; } fn usedBitsCount(size_class: usize) usize { const slot_count = @divExact(page_size, size_class); if (slot_count < 8) return 1; return @divExact(slot_count, 8); } fn detectLeaksInBucket( bucket: *BucketHeader, size_class: usize, used_bits_count: usize, ) bool { var leaks = false; var used_bits_byte: usize = 0; while (used_bits_byte < used_bits_count) : (used_bits_byte += 1) { const used_byte = bucket.usedBits(used_bits_byte).*; if (used_byte != 0) { var bit_index: u3 = 0; while (true) : (bit_index += 1) { const is_used = @as(u1, @truncate(used_byte >> bit_index)) != 0; if (is_used) { const slot_index = @as(SlotIndex, @intCast(used_bits_byte * 8 + bit_index)); const stack_trace = bucketStackTrace(bucket, size_class, slot_index, .alloc); const addr = bucket.page + slot_index * size_class; log.err("memory address 0x{x} leaked: {s}", .{ @intFromPtr(addr), stack_trace, }); leaks = true; } if (bit_index == math.maxInt(u3)) break; } } } return leaks; } /// Emits log messages for leaks and then returns whether there were any leaks. pub fn detectLeaks(self: *Self) bool { var leaks = false; for (self.buckets, 0..) |optional_bucket, bucket_i| { const first_bucket = optional_bucket orelse continue; const size_class = @as(usize, 1) << @as(math.Log2Int(usize), @intCast(bucket_i)); const used_bits_count = usedBitsCount(size_class); var bucket = first_bucket; while (true) { leaks = detectLeaksInBucket(bucket, size_class, used_bits_count) or leaks; bucket = bucket.next; if (bucket == first_bucket) break; } } var it = self.large_allocations.valueIterator(); while (it.next()) |large_alloc| { if (config.retain_metadata and large_alloc.freed) continue; log.err("memory address 0x{x} leaked: {s}", .{ @intFromPtr(large_alloc.bytes.ptr), large_alloc.getStackTrace(.alloc), }); leaks = true; } return leaks; } fn freeBucket(self: *Self, bucket: *BucketHeader, size_class: usize) void { const bucket_size = bucketSize(size_class); const bucket_slice = @as([*]align(@alignOf(BucketHeader)) u8, @ptrCast(bucket))[0..bucket_size]; self.backing_allocator.free(bucket_slice); } fn freeRetainedMetadata(self: *Self) void { if (config.retain_metadata) { if (config.never_unmap) { // free large allocations that were intentionally leaked by never_unmap var it = self.large_allocations.iterator(); while (it.next()) |large| { if (large.value_ptr.freed) { _ = self.backing_allocator.resizeFn(self.backing_allocator, large.value_ptr.bytes, large.value_ptr.ptr_align, 0, 0, @returnAddress()) catch unreachable; } } } // free retained metadata for small allocations if (self.empty_buckets) |first_bucket| { var bucket = first_bucket; while (true) { const prev = bucket.prev; if (config.never_unmap) { // free page that was intentionally leaked by never_unmap self.backing_allocator.free(bucket.page[0..page_size]); } // alloc_cursor was set to slot count when bucket added to empty_buckets self.freeBucket(bucket, @divExact(page_size, bucket.alloc_cursor)); bucket = prev; if (bucket == first_bucket) break; } self.empty_buckets = null; } } } pub usingnamespace if (config.retain_metadata) struct { pub fn flushRetainedMetadata(self: *Self) void { self.freeRetainedMetadata(); // also remove entries from large_allocations var it = self.large_allocations.iterator(); while (it.next()) |large| { if (large.value_ptr.freed) { _ = self.large_allocations.remove(@intFromPtr(large.value_ptr.bytes.ptr)); } } } } else struct {}; pub fn deinit(self: *Self) bool { const leaks = if (config.safety) self.detectLeaks() else false; if (config.retain_metadata) { self.freeRetainedMetadata(); } self.large_allocations.deinit(self.backing_allocator); self.* = undefined; return leaks; } fn collectStackTrace(first_trace_addr: usize, addresses: *[stack_n]usize) void { if (stack_n == 0) return; mem.set(usize, addresses, 0); var stack_trace = StackTrace{ .instruction_addresses = addresses, .index = 0, }; std.debug.captureStackTrace(first_trace_addr, &stack_trace); } fn reportDoubleFree(ret_addr: usize, alloc_stack_trace: StackTrace, free_stack_trace: StackTrace) void { var addresses: [stack_n]usize = [1]usize{0} ** stack_n; var second_free_stack_trace = StackTrace{ .instruction_addresses = &addresses, .index = 0, }; std.debug.captureStackTrace(ret_addr, &second_free_stack_trace); log.err("Double free detected. Allocation: {s} First free: {s} Second free: {s}", .{ alloc_stack_trace, free_stack_trace, second_free_stack_trace, }); } fn allocSlot(self: *Self, size_class: usize, trace_addr: usize) Error![*]u8 { const bucket_index = math.log2(size_class); const first_bucket = self.buckets[bucket_index] orelse try self.createBucket( size_class, bucket_index, ); var bucket = first_bucket; const slot_count = @divExact(page_size, size_class); while (bucket.alloc_cursor == slot_count) { const prev_bucket = bucket; bucket = prev_bucket.next; if (bucket == first_bucket) { // make a new one bucket = try self.createBucket(size_class, bucket_index); bucket.prev = prev_bucket; bucket.next = prev_bucket.next; prev_bucket.next = bucket; bucket.next.prev = bucket; } } // change the allocator's current bucket to be this one self.buckets[bucket_index] = bucket; const slot_index = bucket.alloc_cursor; bucket.alloc_cursor += 1; var used_bits_byte = bucket.usedBits(slot_index / 8); const used_bit_index: u3 = @as(u3, @intCast(slot_index % 8)); // TODO cast should be unnecessary used_bits_byte.* |= (@as(u8, 1) << used_bit_index); bucket.used_count += 1; bucket.captureStackTrace(trace_addr, size_class, slot_index, .alloc); return bucket.page + slot_index * size_class; } fn searchBucket( bucket_list: ?*BucketHeader, addr: usize, ) ?*BucketHeader { const first_bucket = bucket_list orelse return null; var bucket = first_bucket; while (true) { const in_bucket_range = (addr >= @intFromPtr(bucket.page) and addr < @intFromPtr(bucket.page) + page_size); if (in_bucket_range) return bucket; bucket = bucket.prev; if (bucket == first_bucket) { return null; } } } /// This function assumes the object is in the large object storage regardless /// of the parameters. fn resizeLarge( self: *Self, old_mem: []u8, old_align: u29, new_size: usize, len_align: u29, ret_addr: usize, ) Error!usize { const entry = self.large_allocations.getEntry(@intFromPtr(old_mem.ptr)) orelse { if (config.safety) { @panic("Invalid free"); } else { unreachable; } }; if (config.retain_metadata and entry.value_ptr.freed) { if (config.safety) { reportDoubleFree(ret_addr, entry.value_ptr.getStackTrace(.alloc), entry.value_ptr.getStackTrace(.free)); // Recoverable if this is a free. if (new_size == 0) return @as(usize, 0); @panic("Unrecoverable double free"); } else { unreachable; } } if (config.safety and old_mem.len != entry.value_ptr.bytes.len) { var addresses: [stack_n]usize = [1]usize{0} ** stack_n; var free_stack_trace = StackTrace{ .instruction_addresses = &addresses, .index = 0, }; std.debug.captureStackTrace(ret_addr, &free_stack_trace); log.err("Allocation size {d} bytes does not match free size {d}. Allocation: {s} Free: {s}", .{ entry.value_ptr.bytes.len, old_mem.len, entry.value_ptr.getStackTrace(.alloc), free_stack_trace, }); } // Do memory limit accounting with requested sizes rather than what backing_allocator returns // because if we want to return error.OutOfMemory, we have to leave allocation untouched, and // that is impossible to guarantee after calling backing_allocator.resizeFn. const prev_req_bytes = self.total_requested_bytes; if (config.enable_memory_limit) { const new_req_bytes = prev_req_bytes + new_size - entry.value_ptr.requested_size; if (new_req_bytes > prev_req_bytes and new_req_bytes > self.requested_memory_limit) { return error.OutOfMemory; } self.total_requested_bytes = new_req_bytes; } errdefer if (config.enable_memory_limit) { self.total_requested_bytes = prev_req_bytes; }; const result_len = if (config.never_unmap and new_size == 0) 0 else try self.backing_allocator.resizeFn(self.backing_allocator, old_mem, old_align, new_size, len_align, ret_addr); if (config.enable_memory_limit) { entry.value_ptr.requested_size = new_size; } if (result_len == 0) { if (config.verbose_log) { log.info("large free {d} bytes at {*}", .{ old_mem.len, old_mem.ptr }); } if (!config.retain_metadata) { assert(self.large_allocations.remove(@intFromPtr(old_mem.ptr))); } else { entry.value_ptr.freed = true; entry.value_ptr.captureStackTrace(ret_addr, .free); } return 0; } if (config.verbose_log) { log.info("large resize {d} bytes at {*} to {d}", .{ old_mem.len, old_mem.ptr, new_size, }); } entry.value_ptr.bytes = old_mem.ptr[0..result_len]; entry.value_ptr.captureStackTrace(ret_addr, .alloc); return result_len; } pub fn setRequestedMemoryLimit(self: *Self, limit: usize) void { self.requested_memory_limit = limit; } fn resize( allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, len_align: u29, ret_addr: usize, ) Error!usize { const self = @fieldParentPtr(Self, "allocator", allocator); const held = self.mutex.acquire(); defer held.release(); assert(old_mem.len != 0); const aligned_size = math.max(old_mem.len, old_align); if (aligned_size > largest_bucket_object_size) { return self.resizeLarge(old_mem, old_align, new_size, len_align, ret_addr); } const size_class_hint = math.ceilPowerOfTwoAssert(usize, aligned_size); var bucket_index = math.log2(size_class_hint); var size_class: usize = size_class_hint; const bucket = while (bucket_index < small_bucket_count) : (bucket_index += 1) { if (searchBucket(self.buckets[bucket_index], @intFromPtr(old_mem.ptr))) |bucket| { // move bucket to head of list to optimize search for nearby allocations self.buckets[bucket_index] = bucket; break bucket; } size_class *= 2; } else blk: { if (config.retain_metadata) { if (!self.large_allocations.contains(@intFromPtr(old_mem.ptr))) { // object not in active buckets or a large allocation, so search empty buckets if (searchBucket(self.empty_buckets, @intFromPtr(old_mem.ptr))) |bucket| { // bucket is empty so is_used below will always be false and we exit there break :blk bucket; } else { @panic("Invalid free"); } } } return self.resizeLarge(old_mem, old_align, new_size, len_align, ret_addr); }; const byte_offset = @intFromPtr(old_mem.ptr) - @intFromPtr(bucket.page); const slot_index = @as(SlotIndex, @intCast(byte_offset / size_class)); const used_byte_index = slot_index / 8; const used_bit_index = @as(u3, @intCast(slot_index % 8)); const used_byte = bucket.usedBits(used_byte_index); const is_used = @as(u1, @truncate(used_byte.* >> used_bit_index)) != 0; if (!is_used) { if (config.safety) { reportDoubleFree(ret_addr, bucketStackTrace(bucket, size_class, slot_index, .alloc), bucketStackTrace(bucket, size_class, slot_index, .free)); // Recoverable if this is a free. if (new_size == 0) return @as(usize, 0); @panic("Unrecoverable double free"); } else { unreachable; } } // Definitely an in-use small alloc now. const prev_req_bytes = self.total_requested_bytes; if (config.enable_memory_limit) { const new_req_bytes = prev_req_bytes + new_size - old_mem.len; if (new_req_bytes > prev_req_bytes and new_req_bytes > self.requested_memory_limit) { return error.OutOfMemory; } self.total_requested_bytes = new_req_bytes; } errdefer if (config.enable_memory_limit) { self.total_requested_bytes = prev_req_bytes; }; if (new_size == 0) { // Capture stack trace to be the "first free", in case a double free happens. bucket.captureStackTrace(ret_addr, size_class, slot_index, .free); used_byte.* &= ~(@as(u8, 1) << used_bit_index); bucket.used_count -= 1; if (bucket.used_count == 0) { if (bucket.next == bucket) { // it's the only bucket and therefore the current one self.buckets[bucket_index] = null; } else { bucket.next.prev = bucket.prev; bucket.prev.next = bucket.next; self.buckets[bucket_index] = bucket.prev; } if (!config.never_unmap) { self.backing_allocator.free(bucket.page[0..page_size]); } if (!config.retain_metadata) { self.freeBucket(bucket, size_class); } else { // move alloc_cursor to end so we can tell size_class later const slot_count = @divExact(page_size, size_class); bucket.alloc_cursor = @as(SlotIndex, @truncate(slot_count)); if (self.empty_buckets) |prev_bucket| { // empty_buckets is ordered newest to oldest through prev so that if // config.never_unmap is false and backing_allocator reuses freed memory // then searchBuckets will always return the newer, relevant bucket bucket.prev = prev_bucket; bucket.next = prev_bucket.next; prev_bucket.next = bucket; bucket.next.prev = bucket; } else { bucket.prev = bucket; bucket.next = bucket; } self.empty_buckets = bucket; } } else { @memset(old_mem[0..], undefined); } if (config.verbose_log) { log.info("small free {d} bytes at {*}", .{ old_mem.len, old_mem.ptr }); } return @as(usize, 0); } const new_aligned_size = math.max(new_size, old_align); const new_size_class = math.ceilPowerOfTwoAssert(usize, new_aligned_size); if (new_size_class <= size_class) { if (old_mem.len > new_size) { @memset(old_mem[new_size..], undefined); } if (config.verbose_log) { log.info("small resize {d} bytes at {*} to {d}", .{ old_mem.len, old_mem.ptr, new_size, }); } return new_size; } return error.OutOfMemory; } // Returns true if an allocation of `size` bytes is within the specified // limits if enable_memory_limit is true fn isAllocationAllowed(self: *Self, size: usize) bool { if (config.enable_memory_limit) { const new_req_bytes = self.total_requested_bytes + size; if (new_req_bytes > self.requested_memory_limit) return false; self.total_requested_bytes = new_req_bytes; } return true; } fn alloc(allocator: *Allocator, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) Error![]u8 { const self = @fieldParentPtr(Self, "allocator", allocator); const held = self.mutex.acquire(); defer held.release(); if (!self.isAllocationAllowed(len)) { return error.OutOfMemory; } const new_aligned_size = math.max(len, ptr_align); if (new_aligned_size > largest_bucket_object_size) { try self.large_allocations.ensureUnusedCapacity(self.backing_allocator, 1); const slice = try self.backing_allocator.allocFn(self.backing_allocator, len, ptr_align, len_align, ret_addr); const gop = self.large_allocations.getOrPutAssumeCapacity(@intFromPtr(slice.ptr)); if (config.retain_metadata and !config.never_unmap) { // Backing allocator may be reusing memory that we're retaining metadata for assert(!gop.found_existing or gop.value_ptr.freed); } else { assert(!gop.found_existing); // This would mean the kernel double-mapped pages. } gop.value_ptr.bytes = slice; if (config.enable_memory_limit) gop.value_ptr.requested_size = len; gop.value_ptr.captureStackTrace(ret_addr, .alloc); if (config.retain_metadata) { gop.value_ptr.freed = false; if (config.never_unmap) { gop.value_ptr.ptr_align = ptr_align; } } if (config.verbose_log) { log.info("large alloc {d} bytes at {*}", .{ slice.len, slice.ptr }); } return slice; } const new_size_class = math.ceilPowerOfTwoAssert(usize, new_aligned_size); const ptr = try self.allocSlot(new_size_class, ret_addr); if (config.verbose_log) { log.info("small alloc {d} bytes at {*}", .{ len, ptr }); } return ptr[0..len]; } fn createBucket(self: *Self, size_class: usize, bucket_index: usize) Error!*BucketHeader { const page = try self.backing_allocator.allocAdvanced(u8, page_size, page_size, .exact); errdefer self.backing_allocator.free(page); const bucket_size = bucketSize(size_class); const bucket_bytes = try self.backing_allocator.allocAdvanced(u8, @alignOf(BucketHeader), bucket_size, .exact); const ptr = @as(*BucketHeader, @ptrCast(bucket_bytes.ptr)); ptr.* = BucketHeader{ .prev = ptr, .next = ptr, .page = page.ptr, .alloc_cursor = 0, .used_count = 0, }; self.buckets[bucket_index] = ptr; // Set the used bits to all zeroes @memset(@as([*]u8, @as(*[1]u8, ptr.usedBits(0)))[0..usedBitsCount(size_class)], 0); return ptr; } }; } const TraceKind = enum { alloc, free, }; const test_config = Config{}; test "small allocations - free in same order" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var list = std.ArrayList(*u64).init(std.testing.allocator); defer list.deinit(); var i: usize = 0; while (i < 513) : (i += 1) { const ptr = try allocator.create(u64); try list.append(ptr); } for (list.items) |ptr| { allocator.destroy(ptr); } } test "small allocations - free in reverse order" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var list = std.ArrayList(*u64).init(std.testing.allocator); defer list.deinit(); var i: usize = 0; while (i < 513) : (i += 1) { const ptr = try allocator.create(u64); try list.append(ptr); } while (list.popOrNull()) |ptr| { allocator.destroy(ptr); } } test "large allocations" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; const ptr1 = try allocator.alloc(u64, 42768); const ptr2 = try allocator.alloc(u64, 52768); allocator.free(ptr1); const ptr3 = try allocator.alloc(u64, 62768); allocator.free(ptr3); allocator.free(ptr2); } test "realloc" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var slice = try allocator.alignedAlloc(u8, @alignOf(u32), 1); defer allocator.free(slice); slice[0] = 0x12; // This reallocation should keep its pointer address. const old_slice = slice; slice = try allocator.realloc(slice, 2); try std.testing.expect(old_slice.ptr == slice.ptr); try std.testing.expect(slice[0] == 0x12); slice[1] = 0x34; // This requires upgrading to a larger size class slice = try allocator.realloc(slice, 17); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[1] == 0x34); } test "shrink" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var slice = try allocator.alloc(u8, 20); defer allocator.free(slice); mem.set(u8, slice, 0x11); slice = allocator.shrink(slice, 17); for (slice) |b| { try std.testing.expect(b == 0x11); } slice = allocator.shrink(slice, 16); for (slice) |b| { try std.testing.expect(b == 0x11); } } test "large object - grow" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var slice1 = try allocator.alloc(u8, page_size * 2 - 20); defer allocator.free(slice1); const old = slice1; slice1 = try allocator.realloc(slice1, page_size * 2 - 10); try std.testing.expect(slice1.ptr == old.ptr); slice1 = try allocator.realloc(slice1, page_size * 2); try std.testing.expect(slice1.ptr == old.ptr); slice1 = try allocator.realloc(slice1, page_size * 2 + 1); } test "realloc small object to large object" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var slice = try allocator.alloc(u8, 70); defer allocator.free(slice); slice[0] = 0x12; slice[60] = 0x34; // This requires upgrading to a large object const large_object_size = page_size * 2 + 50; slice = try allocator.realloc(slice, large_object_size); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[60] == 0x34); } test "shrink large object to large object" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var slice = try allocator.alloc(u8, page_size * 2 + 50); defer allocator.free(slice); slice[0] = 0x12; slice[60] = 0x34; slice = try allocator.resize(slice, page_size * 2 + 1); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[60] == 0x34); slice = allocator.shrink(slice, page_size * 2 + 1); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[60] == 0x34); slice = try allocator.realloc(slice, page_size * 2); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[60] == 0x34); } test "shrink large object to large object with larger alignment" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var debug_buffer: [1000]u8 = undefined; const debug_allocator = &std.heap.FixedBufferAllocator.init(&debug_buffer).allocator; const alloc_size = page_size * 2 + 50; var slice = try allocator.alignedAlloc(u8, 16, alloc_size); defer allocator.free(slice); const big_alignment: usize = switch (builtin.os.tag) { .windows => page_size * 32, // Windows aligns to 64K. else => page_size * 2, }; // This loop allocates until we find a page that is not aligned to the big // alignment. Then we shrink the allocation after the loop, but increase the // alignment to the higher one, that we know will force it to realloc. var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator); while (mem.isAligned(@intFromPtr(slice.ptr), big_alignment)) { try stuff_to_free.append(slice); slice = try allocator.alignedAlloc(u8, 16, alloc_size); } while (stuff_to_free.popOrNull()) |item| { allocator.free(item); } slice[0] = 0x12; slice[60] = 0x34; slice = try allocator.reallocAdvanced(slice, big_alignment, alloc_size / 2, .exact); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[60] == 0x34); } test "realloc large object to small object" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var slice = try allocator.alloc(u8, page_size * 2 + 50); defer allocator.free(slice); slice[0] = 0x12; slice[16] = 0x34; slice = try allocator.realloc(slice, 19); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[16] == 0x34); } test "overrideable mutexes" { var gpa = GeneralPurposeAllocator(.{ .MutexType = std.Thread.Mutex }){ .backing_allocator = std.testing.allocator, .mutex = std.Thread.Mutex{}, }; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; const ptr = try allocator.create(i32); defer allocator.destroy(ptr); } test "non-page-allocator backing allocator" { var gpa = GeneralPurposeAllocator(.{}){ .backing_allocator = std.testing.allocator }; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; const ptr = try allocator.create(i32); defer allocator.destroy(ptr); } test "realloc large object to larger alignment" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var debug_buffer: [1000]u8 = undefined; const debug_allocator = &std.heap.FixedBufferAllocator.init(&debug_buffer).allocator; var slice = try allocator.alignedAlloc(u8, 16, page_size * 2 + 50); defer allocator.free(slice); const big_alignment: usize = switch (builtin.os.tag) { .windows => page_size * 32, // Windows aligns to 64K. else => page_size * 2, }; // This loop allocates until we find a page that is not aligned to the big alignment. var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator); while (mem.isAligned(@intFromPtr(slice.ptr), big_alignment)) { try stuff_to_free.append(slice); slice = try allocator.alignedAlloc(u8, 16, page_size * 2 + 50); } while (stuff_to_free.popOrNull()) |item| { allocator.free(item); } slice[0] = 0x12; slice[16] = 0x34; slice = try allocator.reallocAdvanced(slice, 32, page_size * 2 + 100, .exact); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[16] == 0x34); slice = try allocator.reallocAdvanced(slice, 32, page_size * 2 + 25, .exact); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[16] == 0x34); slice = try allocator.reallocAdvanced(slice, big_alignment, page_size * 2 + 100, .exact); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[16] == 0x34); } test "large object shrinks to small but allocation fails during shrink" { var failing_allocator = std.testing.FailingAllocator.init(std.heap.page_allocator, 3); var gpa = GeneralPurposeAllocator(.{}){ .backing_allocator = &failing_allocator.allocator }; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; var slice = try allocator.alloc(u8, page_size * 2 + 50); defer allocator.free(slice); slice[0] = 0x12; slice[3] = 0x34; // Next allocation will fail in the backing allocator of the GeneralPurposeAllocator slice = allocator.shrink(slice, 4); try std.testing.expect(slice[0] == 0x12); try std.testing.expect(slice[3] == 0x34); } test "objects of size 1024 and 2048" { var gpa = GeneralPurposeAllocator(test_config){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; const slice = try allocator.alloc(u8, 1025); const slice2 = try allocator.alloc(u8, 3000); allocator.free(slice); allocator.free(slice2); } test "setting a memory cap" { var gpa = GeneralPurposeAllocator(.{ .enable_memory_limit = true }){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; gpa.setRequestedMemoryLimit(1010); const small = try allocator.create(i32); try std.testing.expect(gpa.total_requested_bytes == 4); const big = try allocator.alloc(u8, 1000); try std.testing.expect(gpa.total_requested_bytes == 1004); try std.testing.expectError(error.OutOfMemory, allocator.create(u64)); allocator.destroy(small); try std.testing.expect(gpa.total_requested_bytes == 1000); allocator.free(big); try std.testing.expect(gpa.total_requested_bytes == 0); const exact = try allocator.alloc(u8, 1010); try std.testing.expect(gpa.total_requested_bytes == 1010); allocator.free(exact); } test "double frees" { // use a GPA to back a GPA to check for leaks of the latter's metadata var backing_gpa = GeneralPurposeAllocator(.{ .safety = true }){}; defer std.testing.expect(!backing_gpa.deinit()) catch @panic("leak"); const GPA = GeneralPurposeAllocator(.{ .safety = true, .never_unmap = true, .retain_metadata = true }); var gpa = GPA{ .backing_allocator = &backing_gpa.allocator }; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); const allocator = &gpa.allocator; // detect a small allocation double free, even though bucket is emptied const index: usize = 6; const size_class: usize = @as(usize, 1) << 6; const small = try allocator.alloc(u8, size_class); try std.testing.expect(GPA.searchBucket(gpa.buckets[index], @intFromPtr(small.ptr)) != null); allocator.free(small); try std.testing.expect(GPA.searchBucket(gpa.buckets[index], @intFromPtr(small.ptr)) == null); try std.testing.expect(GPA.searchBucket(gpa.empty_buckets, @intFromPtr(small.ptr)) != null); // detect a large allocation double free const large = try allocator.alloc(u8, 2 * page_size); try std.testing.expect(gpa.large_allocations.contains(@intFromPtr(large.ptr))); try std.testing.expectEqual(gpa.large_allocations.getEntry(@intFromPtr(large.ptr)).?.value_ptr.bytes, large); allocator.free(large); try std.testing.expect(gpa.large_allocations.contains(@intFromPtr(large.ptr))); try std.testing.expect(gpa.large_allocations.getEntry(@intFromPtr(large.ptr)).?.value_ptr.freed); const normal_small = try allocator.alloc(u8, size_class); defer allocator.free(normal_small); const normal_large = try allocator.alloc(u8, 2 * page_size); defer allocator.free(normal_large); // check that flushing retained metadata doesn't disturb live allocations gpa.flushRetainedMetadata(); try std.testing.expect(gpa.empty_buckets == null); try std.testing.expect(GPA.searchBucket(gpa.buckets[index], @intFromPtr(normal_small.ptr)) != null); try std.testing.expect(gpa.large_allocations.contains(@intFromPtr(normal_large.ptr))); try std.testing.expect(!gpa.large_allocations.contains(@intFromPtr(large.ptr))); } test "bug 9995 fix, large allocs count requested size not backing size" { // with AtLeast, buffer likely to be larger than requested, especially when shrinking var gpa = GeneralPurposeAllocator(.{ .enable_memory_limit = true }){}; var buf = try gpa.allocator.allocAdvanced(u8, 1, page_size + 1, .at_least); try std.testing.expect(gpa.total_requested_bytes == page_size + 1); buf = try gpa.allocator.reallocAtLeast(buf, 1); try std.testing.expect(gpa.total_requested_bytes == 1); buf = try gpa.allocator.reallocAtLeast(buf, 2); try std.testing.expect(gpa.total_requested_bytes == 2); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/heap/arena_allocator.zig
const std = @import("../std.zig"); const assert = std.debug.assert; const mem = std.mem; const Allocator = std.mem.Allocator; /// This allocator takes an existing allocator, wraps it, and provides an interface /// where you can allocate without freeing, and then free it all together. pub const ArenaAllocator = struct { allocator: Allocator, child_allocator: *Allocator, state: State, /// Inner state of ArenaAllocator. Can be stored rather than the entire ArenaAllocator /// as a memory-saving optimization. pub const State = struct { buffer_list: std.SinglyLinkedList([]u8) = @as(std.SinglyLinkedList([]u8), .{}), end_index: usize = 0, pub fn promote(self: State, child_allocator: *Allocator) ArenaAllocator { return .{ .allocator = Allocator{ .allocFn = alloc, .resizeFn = resize, }, .child_allocator = child_allocator, .state = self, }; } }; const BufNode = std.SinglyLinkedList([]u8).Node; pub fn init(child_allocator: *Allocator) ArenaAllocator { return (State{}).promote(child_allocator); } pub fn deinit(self: ArenaAllocator) void { var it = self.state.buffer_list.first; while (it) |node| { // this has to occur before the free because the free frees node const next_it = node.next; self.child_allocator.free(node.data); it = next_it; } } fn createNode(self: *ArenaAllocator, prev_len: usize, minimum_size: usize) !*BufNode { const actual_min_size = minimum_size + (@sizeOf(BufNode) + 16); const big_enough_len = prev_len + actual_min_size; const len = big_enough_len + big_enough_len / 2; const buf = try self.child_allocator.allocFn(self.child_allocator, len, @alignOf(BufNode), 1, @returnAddress()); const buf_node: *BufNode = @ptrCast(@alignCast(buf.ptr)); buf_node.* = BufNode{ .data = buf, .next = null, }; self.state.buffer_list.prepend(buf_node); self.state.end_index = 0; return buf_node; } fn alloc(allocator: *Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 { _ = len_align; _ = ra; const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator); var cur_node = if (self.state.buffer_list.first) |first_node| first_node else try self.createNode(0, n + ptr_align); while (true) { const cur_buf = cur_node.data[@sizeOf(BufNode)..]; const addr = @intFromPtr(cur_buf.ptr) + self.state.end_index; const adjusted_addr = mem.alignForward(addr, ptr_align); const adjusted_index = self.state.end_index + (adjusted_addr - addr); const new_end_index = adjusted_index + n; if (new_end_index <= cur_buf.len) { const result = cur_buf[adjusted_index..new_end_index]; self.state.end_index = new_end_index; return result; } const bigger_buf_size = @sizeOf(BufNode) + new_end_index; // Try to grow the buffer in-place cur_node.data = self.child_allocator.resize(cur_node.data, bigger_buf_size) catch |err| switch (err) { error.OutOfMemory => { // Allocate a new node if that's not possible cur_node = try self.createNode(cur_buf.len, n + ptr_align); continue; }, }; } } fn resize(allocator: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) Allocator.Error!usize { _ = buf_align; _ = len_align; _ = ret_addr; const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator); const cur_node = self.state.buffer_list.first orelse return error.OutOfMemory; const cur_buf = cur_node.data[@sizeOf(BufNode)..]; if (@intFromPtr(cur_buf.ptr) + self.state.end_index != @intFromPtr(buf.ptr) + buf.len) { if (new_len > buf.len) return error.OutOfMemory; return new_len; } if (buf.len >= new_len) { self.state.end_index -= buf.len - new_len; return new_len; } else if (cur_buf.len - self.state.end_index >= new_len - buf.len) { self.state.end_index += new_len - buf.len; return new_len; } else { return error.OutOfMemory; } } };
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/heap/log_to_writer_allocator.zig
const std = @import("../std.zig"); const Allocator = std.mem.Allocator; /// This allocator is used in front of another allocator and logs to the provided writer /// on every call to the allocator. Writer errors are ignored. pub fn LogToWriterAllocator(comptime Writer: type) type { return struct { allocator: Allocator, parent_allocator: *Allocator, writer: Writer, const Self = @This(); pub fn init(parent_allocator: *Allocator, writer: Writer) Self { return Self{ .allocator = Allocator{ .allocFn = alloc, .resizeFn = resize, }, .parent_allocator = parent_allocator, .writer = writer, }; } fn alloc( allocator: *Allocator, len: usize, ptr_align: u29, len_align: u29, ra: usize, ) error{OutOfMemory}![]u8 { const self = @fieldParentPtr(Self, "allocator", allocator); self.writer.print("alloc : {}", .{len}) catch {}; const result = self.parent_allocator.allocFn(self.parent_allocator, len, ptr_align, len_align, ra); if (result) |_| { self.writer.print(" success!\n", .{}) catch {}; } else |_| { self.writer.print(" failure!\n", .{}) catch {}; } return result; } fn resize( allocator: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ra: usize, ) error{OutOfMemory}!usize { const self = @fieldParentPtr(Self, "allocator", allocator); if (new_len == 0) { self.writer.print("free : {}\n", .{buf.len}) catch {}; } else if (new_len <= buf.len) { self.writer.print("shrink: {} to {}\n", .{ buf.len, new_len }) catch {}; } else { self.writer.print("expand: {} to {}", .{ buf.len, new_len }) catch {}; } if (self.parent_allocator.resizeFn(self.parent_allocator, buf, buf_align, new_len, len_align, ra)) |resized_len| { if (new_len > buf.len) { self.writer.print(" success!\n", .{}) catch {}; } return resized_len; } else |e| { std.debug.assert(new_len > buf.len); self.writer.print(" failure!\n", .{}) catch {}; return e; } } }; } /// This allocator is used in front of another allocator and logs to the provided writer /// on every call to the allocator. Writer errors are ignored. pub fn logToWriterAllocator( parent_allocator: *Allocator, writer: anytype, ) LogToWriterAllocator(@TypeOf(writer)) { return LogToWriterAllocator(@TypeOf(writer)).init(parent_allocator, writer); } test "LogToWriterAllocator" { var log_buf: [255]u8 = undefined; var fbs = std.io.fixedBufferStream(&log_buf); var allocator_buf: [10]u8 = undefined; var fixedBufferAllocator = std.mem.validationWrap(std.heap.FixedBufferAllocator.init(&allocator_buf)); const allocator = &logToWriterAllocator(&fixedBufferAllocator.allocator, fbs.writer()).allocator; var a = try allocator.alloc(u8, 10); a = allocator.shrink(a, 5); try std.testing.expect(a.len == 5); try std.testing.expectError(error.OutOfMemory, allocator.resize(a, 20)); allocator.free(a); try std.testing.expectEqualSlices(u8, \\alloc : 10 success! \\shrink: 10 to 5 \\expand: 5 to 20 failure! \\free : 5 \\ , fbs.getWritten()); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/heap/logging_allocator.zig
const std = @import("../std.zig"); const Allocator = std.mem.Allocator; /// This allocator is used in front of another allocator and logs to `std.log` /// on every call to the allocator. /// For logging to a `std.io.Writer` see `std.heap.LogToWriterAllocator` pub fn LoggingAllocator( comptime success_log_level: std.log.Level, comptime failure_log_level: std.log.Level, ) type { return ScopedLoggingAllocator(.default, success_log_level, failure_log_level); } /// This allocator is used in front of another allocator and logs to `std.log` /// with the given scope on every call to the allocator. /// For logging to a `std.io.Writer` see `std.heap.LogToWriterAllocator` pub fn ScopedLoggingAllocator( comptime scope: @Type(.EnumLiteral), comptime success_log_level: std.log.Level, comptime failure_log_level: std.log.Level, ) type { const log = std.log.scoped(scope); return struct { allocator: Allocator, parent_allocator: *Allocator, const Self = @This(); pub fn init(parent_allocator: *Allocator) Self { return .{ .allocator = Allocator{ .allocFn = alloc, .resizeFn = resize, }, .parent_allocator = parent_allocator, }; } // This function is required as the `std.log.log` function is not public inline fn logHelper(comptime log_level: std.log.Level, comptime format: []const u8, args: anytype) void { switch (log_level) { .err => log.err(format, args), .warn => log.warn(format, args), .info => log.info(format, args), .debug => log.debug(format, args), } } fn alloc( allocator: *Allocator, len: usize, ptr_align: u29, len_align: u29, ra: usize, ) error{OutOfMemory}![]u8 { const self = @fieldParentPtr(Self, "allocator", allocator); const result = self.parent_allocator.allocFn(self.parent_allocator, len, ptr_align, len_align, ra); if (result) |_| { logHelper( success_log_level, "alloc - success - len: {}, ptr_align: {}, len_align: {}", .{ len, ptr_align, len_align }, ); } else |err| { logHelper( failure_log_level, "alloc - failure: {s} - len: {}, ptr_align: {}, len_align: {}", .{ @errorName(err), len, ptr_align, len_align }, ); } return result; } fn resize( allocator: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ra: usize, ) error{OutOfMemory}!usize { const self = @fieldParentPtr(Self, "allocator", allocator); if (self.parent_allocator.resizeFn(self.parent_allocator, buf, buf_align, new_len, len_align, ra)) |resized_len| { if (new_len == 0) { logHelper(success_log_level, "free - success - len: {}", .{buf.len}); } else if (new_len <= buf.len) { logHelper( success_log_level, "shrink - success - {} to {}, len_align: {}, buf_align: {}", .{ buf.len, new_len, len_align, buf_align }, ); } else { logHelper( success_log_level, "expand - success - {} to {}, len_align: {}, buf_align: {}", .{ buf.len, new_len, len_align, buf_align }, ); } return resized_len; } else |err| { std.debug.assert(new_len > buf.len); logHelper( failure_log_level, "expand - failure: {s} - {} to {}, len_align: {}, buf_align: {}", .{ @errorName(err), buf.len, new_len, len_align, buf_align }, ); return err; } } }; } /// This allocator is used in front of another allocator and logs to `std.log` /// on every call to the allocator. /// For logging to a `std.io.Writer` see `std.heap.LogToWriterAllocator` pub fn loggingAllocator(parent_allocator: *Allocator) LoggingAllocator(.debug, .err) { return LoggingAllocator(.debug, .err).init(parent_allocator); }
0
repos/gotta-go-fast/src/self-hosted-parser/input_dir
repos/gotta-go-fast/src/self-hosted-parser/input_dir/io/change_detection_stream.zig
const std = @import("../std.zig"); const io = std.io; const mem = std.mem; const assert = std.debug.assert; /// Used to detect if the data written to a stream differs from a source buffer pub fn ChangeDetectionStream(comptime WriterType: type) type { return struct { const Self = @This(); pub const Error = WriterType.Error; pub const Writer = io.Writer(*Self, Error, write); anything_changed: bool, underlying_writer: WriterType, source_index: usize, source: []const u8, pub fn writer(self: *Self) Writer { return .{ .context = self }; } fn write(self: *Self, bytes: []const u8) Error!usize { if (!self.anything_changed) { const end = self.source_index + bytes.len; if (end > self.source.len) { self.anything_changed = true; } else { const src_slice = self.source[self.source_index..end]; self.source_index += bytes.len; if (!mem.eql(u8, bytes, src_slice)) { self.anything_changed = true; } } } return self.underlying_writer.write(bytes); } pub fn changeDetected(self: *Self) bool { return self.anything_changed or (self.source_index != self.source.len); } }; } pub fn changeDetectionStream( source: []const u8, underlying_writer: anytype, ) ChangeDetectionStream(@TypeOf(underlying_writer)) { return ChangeDetectionStream(@TypeOf(underlying_writer)){ .anything_changed = false, .underlying_writer = underlying_writer, .source_index = 0, .source = source, }; }