1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
// Copyright © 2016–2017 University of Malta

// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// this program. If not, see <http://www.gnu.org/licenses/>.

use {Assign, Integer};
use gmp_mpfr_sys::gmp::{self, mpz_t};
use std::mem;
use std::ops::Deref;
use std::os::raw::c_int;
use std::sync::atomic::{AtomicPtr, Ordering};

#[repr(C)]
/// A small integer that does not require any memory allocation.
///
/// This can be useful when you have a `u64`, `i64`, `u32` or `i32`
/// but need a reference to an `Integer`.
///
/// If there are functions that take a `u32` or `i32` directly instead
/// of an `Integer` reference, using them can still be faster than
/// using a `SmallInteger`; the functions would still need to check
/// for the size of an `Integer` obtained using `SmallInteger`.
///
/// The `SmallInteger` type can be coerced to an `Integer`, as it
/// implements `Deref` with an `Integer` target.
///
/// # Examples
///
/// ```rust
/// use rug::Integer;
/// use rug::integer::SmallInteger;
/// // `a` requires a heap allocation
/// let mut a = Integer::from(250);
/// // `b` can reside on the stack
/// let b = SmallInteger::from(-100);
/// a.lcm(&b);
/// assert_eq!(a, 500);
/// // another computation:
/// a.lcm(&SmallInteger::from(30));
/// assert_eq!(a, 1500);
/// ```
pub struct SmallInteger {
    inner: Mpz,
    limbs: [gmp::limb_t; LIMBS_IN_SMALL_INTEGER],
}

const LIMBS_IN_SMALL_INTEGER: usize = 64 / gmp::LIMB_BITS as usize;

#[repr(C)]
pub struct Mpz {
    alloc: c_int,
    size: c_int,
    d: AtomicPtr<gmp::limb_t>,
}

impl Default for SmallInteger {
    fn default() -> SmallInteger {
        SmallInteger::new()
    }
}

impl SmallInteger {
    /// Creates a `SmallInteger` with value 0.
    pub fn new() -> SmallInteger {
        SmallInteger {
            inner: Mpz {
                size: 0,
                alloc: LIMBS_IN_SMALL_INTEGER as c_int,
                d: Default::default(),
            },
            limbs: [0; LIMBS_IN_SMALL_INTEGER],
        }
    }

    fn update_d(&self) {
        // sanity check
        assert_eq!(mem::size_of::<Mpz>(), mem::size_of::<mpz_t>());
        // Since this is borrowed, the limbs won't move around, and we
        // can set the d field.
        let d = &self.limbs[0] as *const _ as *mut _;
        self.inner.d.store(d, Ordering::Relaxed);
    }
}

impl Deref for SmallInteger {
    type Target = Integer;
    fn deref(&self) -> &Integer {
        self.update_d();
        let ptr = (&self.inner) as *const _ as *const _;
        unsafe { &*ptr }
    }
}

impl<T> From<T> for SmallInteger
where
    SmallInteger: Assign<T>,
{
    fn from(val: T) -> SmallInteger {
        let mut ret = SmallInteger::new();
        ret.assign(val);
        ret
    }
}

impl Assign<i32> for SmallInteger {
    fn assign(&mut self, val: i32) {
        self.assign(val.wrapping_abs() as u32);
        if val < 0 {
            self.inner.size = -self.inner.size;
        }
    }
}

impl Assign<i64> for SmallInteger {
    fn assign(&mut self, val: i64) {
        self.assign(val.wrapping_abs() as u64);
        if val < 0 {
            self.inner.size = -self.inner.size;
        }
    }
}

impl Assign<u32> for SmallInteger {
    fn assign(&mut self, val: u32) {
        if val == 0 {
            self.inner.size = 0;
        } else {
            self.inner.size = 1;
            self.limbs[0] = val as gmp::limb_t;
        }
    }
}

impl Assign<u64> for SmallInteger {
    fn assign(&mut self, val: u64) {
        match gmp::LIMB_BITS {
            64 => {
                if val == 0 {
                    self.inner.size = 0;
                } else {
                    self.inner.size = 1;
                    self.limbs[0] = val as gmp::limb_t;
                }
            }
            32 => {
                if val == 0 {
                    self.inner.size = 0;
                } else if val <= 0xffff_ffff {
                    self.inner.size = 1;
                    self.limbs[0] = val as u32 as gmp::limb_t;
                } else {
                    self.inner.size = 2;
                    self.limbs[0] = val as u32 as gmp::limb_t;
                    self.limbs[1 + 0] = (val >> 32) as u32 as gmp::limb_t;
                }
            }
            _ => {
                unimplemented!();
            }
        }
    }
}