math.big: improve the performance of left_shift_digits_in_place and right_shift_digits_in_place (#22450)

This commit is contained in:
kbkpbot 2024-10-09 02:48:26 +08:00 committed by GitHub
parent ef72f97b96
commit 0224581bc6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -256,31 +256,24 @@ fn pow2(k int) Integer {
} }
// optimized left shift in place. amount must be positive // optimized left shift in place. amount must be positive
@[direct_array_access]
fn left_shift_digits_in_place(mut a []u32, amount int) { fn left_shift_digits_in_place(mut a []u32, amount int) {
a_len := a.len // this is actual in builtin/array.v, prepend_many (private fn)
// control or allocate capacity // x := []u32{ len : amount }
for _ in a_len .. a_len + amount { // a.prepend_many(&x[0], amount)
a << u32(0) old_len := a.len
} elem_size := a.element_size
for index := a_len - 1; index >= 0; index-- { unsafe {
a[index + amount] = a[index] a.grow_len(amount)
} sptr := &u8(a.data)
for index in 0 .. amount { dptr := &u8(a.data) + u64(amount) * u64(elem_size)
a[index] = u32(0) vmemmove(dptr, sptr, u64(old_len) * u64(elem_size))
vmemset(sptr, 0, u64(amount) * u64(elem_size))
} }
} }
// optimized right shift in place. amount must be positive // optimized right shift in place. amount must be positive
@[direct_array_access]
fn right_shift_digits_in_place(mut a []u32, amount int) { fn right_shift_digits_in_place(mut a []u32, amount int) {
for index := 0; index < a.len - amount; index++ { a.drop(amount)
a[index] = a[index + amount]
}
for index := a.len - amount; index < a.len; index++ {
a[index] = u32(0)
}
shrink_tail_zeros(mut a)
} }
// operand b can be greater than operand a // operand b can be greater than operand a