From b252afcdd7493ec37ff00e392a37eb50f842c1bf Mon Sep 17 00:00:00 2001 From: mertcandav Date: Sat, 2 Mar 2024 15:03:06 +0300 Subject: [PATCH] std::math::big: add << and <<= operator overloading to Int --- std/math/big/int.jule | 12 ++++++++++++ std/math/big/nat.jule | 16 ++++++++++++++++ std/math/big/nat_test.jule | 22 ++++++++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/std/math/big/int.jule b/std/math/big/int.jule index 1f1845fc6..642188e53 100644 --- a/std/math/big/int.jule +++ b/std/math/big/int.jule @@ -123,6 +123,18 @@ impl Int { ret } + // Bitwise left shift. + pub fn shl(self, y: uint): Int { + let mut r = self + r <<= y + ret r + } + + // Bitwise left shift for assignment. + pub fn shl_assign(mut self, y: uint) { + self.nat <<= y + } + // Bitwise right shift. pub fn shr(self, y: uint): Int { let mut r = self diff --git a/std/math/big/nat.jule b/std/math/big/nat.jule index 896cf1b10..ce1165038 100644 --- a/std/math/big/nat.jule +++ b/std/math/big/nat.jule @@ -181,6 +181,22 @@ impl Nat { self.fit() } + // Bitwise left shift. + pub fn shl(self, y: uint): Nat { + let mut r = self + r <<= y + ret r + } + + // Bitwise left shift for assignment. + pub fn shl_assign(mut self, y: uint) { + if y > 0 && self.len() > 0 { + let mut xbits = make(bits, self.len() + int(y)) + _ = copy(xbits[y:], self.bits) + self.bits = xbits + } + } + // Bitwise right shift. pub fn shr(self, y: uint): Nat { let mut r = self diff --git a/std/math/big/nat_test.jule b/std/math/big/nat_test.jule index f27a812b6..c8640b4e7 100644 --- a/std/math/big/nat_test.jule +++ b/std/math/big/nat_test.jule @@ -31,6 +31,16 @@ static cases_nat_sub = [ ["101011", "11000", "10011"], ] +static cases_nat_shl: [][]u64 = [ + [1, 8, 256], + [9834, 32, 42236708388864], + [9383, 0, 9383], + [9383, 1, 18766], + [0, 20, 0], + [0, 0, 0], + [123456789, 8, 31604937984], +] + static cases_nat_shr: [][]u64 = [ [64, 2, 16], [256, 8, 1], @@ -118,6 +128,18 @@ fn test_nat_sub(mut t: &T) { } } +#test +fn test_nat_shl(mut t: &T) { + for _, c in cases_nat_shl { + let n = Nat.new(c[0]) + let mut r = n << uint(c[1]) + let u = r.to_u64()! + if u != c[2] { + t.errorf("{} << {} != {}", c[0], c[1], c[2]) + } + } +} + #test fn test_nat_shr(mut t: &T) { for _, c in cases_nat_shr {