Skip to content

Commit

Permalink
std::math::big: add << and <<= operator overloading to Int
Browse files Browse the repository at this point in the history
  • Loading branch information
mertcandav committed Mar 2, 2024
1 parent db84686 commit b252afc
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
12 changes: 12 additions & 0 deletions std/math/big/int.jule
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions std/math/big/nat.jule
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions std/math/big/nat_test.jule
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit b252afc

Please sign in to comment.