Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Moving internals from Vec to Cow (Starting point for discussion) #286

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 56 additions & 21 deletions src/biguint.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::big_digit::{self, BigDigit};
use crate::std_alloc::{String, Vec};
use crate::std_alloc::{Cow, String, Vec};

use core::cmp;
use core::cmp::Ordering;
Expand Down Expand Up @@ -36,7 +36,7 @@ pub use self::iter::{U32Digits, U64Digits};

/// A big unsigned integer type.
pub struct BigUint {
data: Vec<BigDigit>,
data: Cow<'static, [BigDigit]>,
}

// Note: derived `Clone` doesn't specialize `clone_from`,
Expand Down Expand Up @@ -146,12 +146,19 @@ impl fmt::Octal for BigUint {
impl Zero for BigUint {
#[inline]
fn zero() -> BigUint {
BigUint { data: Vec::new() }
BigUint {
data: Cow::Borrowed(&[]),
}
}

#[inline]
fn set_zero(&mut self) {
self.data.clear();
match &mut self.data {
Cow::Borrowed(s) => {
*s = &[];
}
Cow::Owned(v) => v.clear(),
}
}

#[inline]
Expand All @@ -163,13 +170,22 @@ impl Zero for BigUint {
impl One for BigUint {
#[inline]
fn one() -> BigUint {
BigUint { data: vec![1] }
BigUint {
data: Cow::Borrowed(&[1]),
}
}

#[inline]
fn set_one(&mut self) {
self.data.clear();
self.data.push(1);
match &mut self.data {
Cow::Borrowed(s) => {
*s = &[1];
}
Cow::Owned(v) => {
v.clear();
v.push(1);
}
}
}

#[inline]
Expand Down Expand Up @@ -515,7 +531,10 @@ pub trait ToBigUint {
/// The digits are in little-endian base matching `BigDigit`.
#[inline]
pub(crate) fn biguint_from_vec(digits: Vec<BigDigit>) -> BigUint {
BigUint { data: digits }.normalized()
BigUint {
data: Cow::Owned(digits),
}
.normalized()
}

impl BigUint {
Expand Down Expand Up @@ -553,13 +572,15 @@ impl BigUint {
/// The base 2<sup>32</sup> digits are ordered least significant digit first.
#[inline]
pub fn assign_from_slice(&mut self, slice: &[u32]) {
self.data.clear();
let mut data = Vec::new();

#[cfg(not(u64_digit))]
self.data.extend_from_slice(slice);
data.extend_from_slice(slice);

#[cfg(u64_digit)]
self.data.extend(slice.chunks(2).map(u32_chunk_to_u64));
data.extend(slice.chunks(2).map(u32_chunk_to_u64));

self.data = Cow::Owned(data);

self.normalize();
}
Expand Down Expand Up @@ -755,7 +776,10 @@ impl BigUint {
/// ```
#[inline]
pub fn iter_u32_digits(&self) -> U32Digits<'_> {
U32Digits::new(self.data.as_slice())
U32Digits::new(match &self.data {
Cow::Borrowed(v) => v,
Cow::Owned(v) => v.as_slice(),
})
}

/// Returns an iterator of `u64` digits representation of the [`BigUint`] ordered least
Expand All @@ -774,7 +798,10 @@ impl BigUint {
/// ```
#[inline]
pub fn iter_u64_digits(&self) -> U64Digits<'_> {
U64Digits::new(self.data.as_slice())
U64Digits::new(match &self.data {
Cow::Borrowed(v) => v,
Cow::Owned(v) => v.as_slice(),
})
}

/// Returns the integer formatted as a string in the given radix.
Expand Down Expand Up @@ -851,10 +878,15 @@ impl BigUint {
fn normalize(&mut self) {
if let Some(&0) = self.data.last() {
let len = self.data.iter().rposition(|&d| d != 0).map_or(0, |i| i + 1);
self.data.truncate(len);
self.data.to_mut().truncate(len);
}
if self.data.len() < self.data.capacity() / 4 {
self.data.shrink_to_fit();
match &mut self.data {
Cow::Owned(v) => {
if v.len() < v.capacity() / 4 {
v.shrink_to_fit();
}
}
_ => {}
}
}

Expand Down Expand Up @@ -948,11 +980,11 @@ impl BigUint {
if value {
if digit_index >= self.data.len() {
let new_len = digit_index.saturating_add(1);
self.data.resize(new_len, 0);
self.data.to_mut().resize(new_len, 0);
}
self.data[digit_index] |= bit_mask;
self.data.to_mut()[digit_index] |= bit_mask;
} else if digit_index < self.data.len() {
self.data[digit_index] &= !bit_mask;
self.data.to_mut()[digit_index] &= !bit_mask;
// the top bit may have been cleared, so normalize
self.normalize();
}
Expand Down Expand Up @@ -998,15 +1030,18 @@ impl IntDigits for BigUint {
}
#[inline]
fn digits_mut(&mut self) -> &mut Vec<BigDigit> {
&mut self.data
self.data.to_mut()
}
#[inline]
fn normalize(&mut self) {
self.normalize();
}
#[inline]
fn capacity(&self) -> usize {
self.data.capacity()
match &self.data {
Cow::Borrowed(v) => v.len(),
Cow::Owned(v) => v.capacity(),
}
}
#[inline]
fn len(&self) -> usize {
Expand Down
30 changes: 16 additions & 14 deletions src/biguint/addition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,16 @@ impl AddAssign<&BigUint> for BigUint {
fn add_assign(&mut self, other: &BigUint) {
let self_len = self.data.len();
let carry = if self_len < other.data.len() {
let lo_carry = __add2(&mut self.data[..], &other.data[..self_len]);
self.data.extend_from_slice(&other.data[self_len..]);
__add2(&mut self.data[self_len..], &[lo_carry])
let lo_carry = __add2(&mut self.data.to_mut()[..], &other.data[..self_len]);
self.data
.to_mut()
.extend_from_slice(&other.data[self_len..]);
__add2(&mut self.data.to_mut()[self_len..], &[lo_carry])
} else {
__add2(&mut self.data[..], &other.data[..])
__add2(&mut self.data.to_mut()[..], &other.data[..])
};
if carry != 0 {
self.data.push(carry);
self.data.to_mut().push(carry);
}
}
}
Expand All @@ -132,12 +134,12 @@ impl AddAssign<u32> for BigUint {
fn add_assign(&mut self, other: u32) {
if other != 0 {
if self.data.is_empty() {
self.data.push(0);
self.data.to_mut().push(0);
}

let carry = __add2(&mut self.data, &[other as BigDigit]);
let carry = __add2(&mut self.data.to_mut(), &[other as BigDigit]);
if carry != 0 {
self.data.push(carry);
self.data.to_mut().push(carry);
}
}
}
Expand Down Expand Up @@ -177,12 +179,12 @@ impl AddAssign<u64> for BigUint {
fn add_assign(&mut self, other: u64) {
if other != 0 {
if self.data.is_empty() {
self.data.push(0);
self.data.to_mut().push(0);
}

let carry = __add2(&mut self.data, &[other as BigDigit]);
let carry = __add2(&mut self.data.to_mut(), &[other as BigDigit]);
if carry != 0 {
self.data.push(carry);
self.data.to_mut().push(carry);
}
}
}
Expand Down Expand Up @@ -233,12 +235,12 @@ impl AddAssign<u128> for BigUint {
*self += lo;
} else {
while self.data.len() < 2 {
self.data.push(0);
self.data.to_mut().push(0);
}

let carry = __add2(&mut self.data, &[lo, hi]);
let carry = __add2(&mut self.data.to_mut(), &[lo, hi]);
if carry != 0 {
self.data.push(carry);
self.data.to_mut().push(carry);
}
}
}
Expand Down
12 changes: 9 additions & 3 deletions src/biguint/arbitrary.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use super::{biguint_from_vec, BigUint};

use crate::big_digit::BigDigit;
#[cfg(feature = "quickcheck")]
use crate::std_alloc::Box;
use crate::std_alloc::Vec;
#[cfg(feature = "quickcheck")]
use crate::std_alloc::{Box, Cow};

#[cfg(feature = "quickcheck")]
impl quickcheck::Arbitrary for BigUint {
Expand All @@ -14,7 +14,13 @@ impl quickcheck::Arbitrary for BigUint {

fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
// Use shrinker from Vec
Box::new(self.data.shrink().map(biguint_from_vec))
Box::new(
match &self.data {
Cow::Owned(v) => v.shrink(),
Cow::Borrowed(v) => v.to_vec().shrink(),
}
.map(biguint_from_vec),
)
}
}

Expand Down
12 changes: 6 additions & 6 deletions src/biguint/bits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ impl BitAnd<&BigUint> for BigUint {
impl BitAndAssign<&BigUint> for BigUint {
#[inline]
fn bitand_assign(&mut self, other: &BigUint) {
for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) {
for (ai, &bi) in self.data.to_mut().iter_mut().zip(other.data.iter()) {
*ai &= bi;
}
self.data.truncate(other.data.len());
self.data.to_mut().truncate(other.data.len());
self.normalize();
}
}
Expand All @@ -57,12 +57,12 @@ impl BitOr<&BigUint> for BigUint {
impl BitOrAssign<&BigUint> for BigUint {
#[inline]
fn bitor_assign(&mut self, other: &BigUint) {
for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) {
for (ai, &bi) in self.data.to_mut().iter_mut().zip(other.data.iter()) {
*ai |= bi;
}
if other.data.len() > self.data.len() {
let extra = &other.data[self.data.len()..];
self.data.extend(extra.iter().cloned());
self.data.to_mut().extend(extra.iter().cloned());
}
}
}
Expand All @@ -81,12 +81,12 @@ impl BitXor<&BigUint> for BigUint {
impl BitXorAssign<&BigUint> for BigUint {
#[inline]
fn bitxor_assign(&mut self, other: &BigUint) {
for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) {
for (ai, &bi) in self.data.to_mut().iter_mut().zip(other.data.iter()) {
*ai ^= bi;
}
if other.data.len() > self.data.len() {
let extra = &other.data[self.data.len()..];
self.data.extend(extra.iter().cloned());
self.data.to_mut().extend(extra.iter().cloned());
}
self.normalize();
}
Expand Down
6 changes: 3 additions & 3 deletions src/biguint/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ impl From<u64> for BigUint {
let mut ret: BigUint = Zero::zero();

while n != 0 {
ret.data.push(n as BigDigit);
ret.data.to_mut().push(n as BigDigit);
// don't overflow if BITS is 64:
n = (n >> 1) >> (big_digit::BITS - 1);
}
Expand All @@ -513,7 +513,7 @@ impl From<u128> for BigUint {
let mut ret: BigUint = Zero::zero();

while n != 0 {
ret.data.push(n as BigDigit);
ret.data.to_mut().push(n as BigDigit);
n >>= big_digit::BITS;
}

Expand Down Expand Up @@ -644,7 +644,7 @@ fn to_inexact_bitwise_digits_le(u: &BigUint, bits: u8) -> Vec<u8> {
let mut r = 0;
let mut rbits = 0;

for c in &u.data {
for c in u.data.iter() {
r |= *c << rbits;
rbits += big_digit::BITS;

Expand Down
Loading