math.unsigned: fix rsh() for Uint128, add tests (#24841)

This commit is contained in:
Mike 2025-07-03 13:51:48 +03:00 committed by GitHub
parent 2a5398aff6
commit 3b791be3aa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 21 additions and 2 deletions

View file

@ -323,9 +323,18 @@ pub fn (u Uint128) lsh(n u32) Uint128 {
// rsh returns u >> n
pub fn (u Uint128) rsh(n u32) Uint128 {
mut s := Uint128{}
if n > 64 {
if n == 0 {
s.lo = u.lo
s.hi = u.hi
} else if n >= 128 {
s.lo = 0
s.hi = 0
s.lo = u.hi << (n - 64)
} else if n == 64 {
s.hi = 0
s.lo = u.hi
} else if n > 64 {
s.hi = 0
s.lo = u.hi >> (n - 64)
} else {
s.lo = u.lo >> n | u.hi << (64 - n)
s.hi = u.hi >> n

View file

@ -183,3 +183,13 @@ fn test_lsh() {
assert '302984417681386893975453667670529933312' == a.lsh(100).str()
assert unsigned.uint128_zero == a.lsh(200)
}
fn test_rsh() {
a := unsigned.uint128_from_dec_str('279625844435276397900870454226348864638')!
assert a.str() == a.rsh(0).str()
assert '139812922217638198950435227113174432319' == a.rsh(1).str()
assert '15158547400991018568' == a.rsh(64).str()
assert '220585896' == a.rsh(100).str()
assert '1' == a.rsh(127).str()
assert unsigned.uint128_zero == a.rsh(200)
}