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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright © 2016–2018 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 cast::cast;
use ext::mpfr as xmpfr;
use float::big::raw_round;
use gmp_mpfr_sys::gmp;
use gmp_mpfr_sys::mpfr::{self, mpfr_t};
use misc::NegAbs;
use std::mem;
use std::ops::Deref;
use std::os::raw::c_int;
use std::sync::atomic::{AtomicPtr, Ordering};
use std::{i32, u32};
use {Assign, Float};

/**
A small float that does not require any memory allocation.

This can be useful when you have a primitive number type but need a
reference to a [`Float`]. The `SmallFloat` will have a precision
according to the type of the primitive used to set its value.

* [`i8`], [`u8`]: the `SmallFloat` will have eight bits of precision.
* [`i16`], [`u16`]: the `SmallFloat` will have 16 bits of precision.
* [`i32`], [`u32`]: the `SmallFloat` will have 32 bits of precision.
* [`i64`], [`u64`]: the `SmallFloat` will have 64 bits of precision.
* [`i128`], [`u128`]: (if supported by the compiler) the `SmallFloat`
  will have 128 bits of precision.
* [`isize`], [`usize`]: the `SmallFloat` will have 32 or 64 bits of
  precision, depending on the platform.
* [`f32`]: the `SmallFloat` will have 24 bits of precision.
* [`f64`]: the `SmallFloat` will have 53 bits of precision.

The `SmallFloat` type can be coerced to a [`Float`], as it implements
[`Deref<Target = Float>`][`Deref`].

# Examples

```rust
use rug::float::SmallFloat;
use rug::Float;
// `a` requires a heap allocation, has 53-bit precision
let mut a = Float::with_val(53, 250);
// `b` can reside on the stack
let b = SmallFloat::from(-100f64);
a += &*b;
assert_eq!(a, 150);
// another computation:
a *= &*b;
assert_eq!(a, -15000);
```

[`Deref`]: https://doc.rust-lang.org/nightly/std/ops/trait.Deref.html
[`Float`]: ../struct.Float.html
[`f32`]: https://doc.rust-lang.org/nightly/std/primitive.f32.html
[`f64`]: https://doc.rust-lang.org/nightly/std/primitive.f64.html
[`i128`]: https://doc.rust-lang.org/nightly/std/primitive.i128.html
[`i16`]: https://doc.rust-lang.org/nightly/std/primitive.i16.html
[`i32`]: https://doc.rust-lang.org/nightly/std/primitive.i32.html
[`i64`]: https://doc.rust-lang.org/nightly/std/primitive.i64.html
[`i8`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html
[`isize`]: https://doc.rust-lang.org/nightly/std/primitive.isize.html
[`u128`]: https://doc.rust-lang.org/nightly/std/primitive.u128.html
[`u16`]: https://doc.rust-lang.org/nightly/std/primitive.u16.html
[`u32`]: https://doc.rust-lang.org/nightly/std/primitive.u32.html
[`u64`]: https://doc.rust-lang.org/nightly/std/primitive.u64.html
[`u8`]: https://doc.rust-lang.org/nightly/std/primitive.u8.html
[`usize`]: https://doc.rust-lang.org/nightly/std/primitive.usize.html
*/
#[derive(Clone)]
#[repr(C)]
pub struct SmallFloat {
    pub(crate) inner: Mpfr,
    pub(crate) limbs: Limbs,
}

#[cfg(not(int_128))]
pub(crate) const LIMBS_IN_SMALL_FLOAT: usize = (64 / gmp::LIMB_BITS) as usize;
#[cfg(int_128)]
pub(crate) const LIMBS_IN_SMALL_FLOAT: usize = (128 / gmp::LIMB_BITS) as usize;
pub(crate) type Limbs = [gmp::limb_t; LIMBS_IN_SMALL_FLOAT];

#[repr(C)]
pub(crate) struct Mpfr {
    pub prec: mpfr::prec_t,
    pub sign: c_int,
    pub exp: mpfr::exp_t,
    pub d: AtomicPtr<gmp::limb_t>,
}

fn _static_assertions() {
    #[cfg(not(int_128))]
    static_assert_size!(Limbs: 8);
    #[cfg(int_128)]
    static_assert_size!(Limbs: 16);
    static_assert_size!(Mpfr, mpfr_t);
}

// Mpfr is only used inside SmallFloat and SmallComplex. The d field
// does not need to be copied from self. SmallComplex::clone is
// responsible to keep real and imag parts ordered.
impl Clone for Mpfr {
    #[inline]
    fn clone(&self) -> Mpfr {
        Mpfr {
            prec: self.prec,
            sign: self.sign,
            exp: self.exp,
            d: Default::default(),
        }
    }
}

impl SmallFloat {
    /// Returns a mutable reference to a [`Float`] for simple
    /// operations that do not need to change the precision of the
    /// number.
    ///
    /// # Safety
    ///
    /// It is undefined behaviour to modify the precision of the
    /// referenced [`Float`] or to swap it with
    /// another number.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rug::float::SmallFloat;
    /// let mut f = SmallFloat::from(1.0f32);
    /// // addition does not change the precision
    /// unsafe {
    ///     *f.as_nonreallocating_float() += 2.0;
    /// }
    /// assert_eq!(*f, 3.0);
    /// ```
    ///
    /// [`Float`]: ../struct.Float.html
    #[inline]
    pub unsafe fn as_nonreallocating_float(&mut self) -> &mut Float {
        self.update_d();
        let ptr = cast_ptr_mut!(&mut self.inner, Float);
        &mut *ptr
    }

    #[inline]
    fn update_d(&self) {
        // Since this is borrowed, the limb won't move around, and we
        // can set the d field.
        let d = &self.limbs[0] as *const gmp::limb_t as *mut gmp::limb_t;
        self.inner.d.store(d, Ordering::Relaxed);
    }
}

impl Deref for SmallFloat {
    type Target = Float;
    #[inline]
    fn deref(&self) -> &Float {
        self.update_d();
        let ptr = cast_ptr!(&self.inner, Float);
        unsafe { &*ptr }
    }
}

pub(crate) trait CopyToSmall: Copy {
    fn copy(self, inner: &mut Mpfr, limbs: &mut Limbs);
}

macro_rules! signed {
    ($($I:ty)*) => { $(
        impl CopyToSmall for $I {
            #[inline]
            fn copy(self, inner: &mut Mpfr, limbs: &mut Limbs) {
                let (neg, abs) = self.neg_abs();
                abs.copy(inner, limbs);
                if neg {
                    inner.sign = -1;
                }
            }
        }
    )* };
}

macro_rules! unsigned_32 {
    ($U:ty, $bits:expr) => {
        impl CopyToSmall for $U {
            #[inline]
            fn copy(self, inner: &mut Mpfr, limbs: &mut Limbs) {
                let ptr = cast_ptr_mut!(inner, mpfr_t);
                let limbs_ptr: *mut gmp::limb_t = &mut limbs[0];
                unsafe {
                    if self == 0 {
                        xmpfr::custom_zero(ptr, limbs_ptr, $bits);
                    } else {
                        let leading = self.leading_zeros();
                        let limb_leading =
                            leading + cast::<_, u32>(gmp::LIMB_BITS) - $bits;
                        limbs[0] = gmp::limb_t::from(self) << limb_leading;
                        let exp = $bits - leading;
                        xmpfr::custom_regular(ptr, limbs_ptr, cast(exp), $bits);
                    }
                }
            }
        }
    };
}

signed! { i8 i16 i32 i64 }
#[cfg(int_128)]
signed! { i128 }
signed! { isize }

unsigned_32! { u8, 8 }
unsigned_32! { u16, 16 }
unsigned_32! { u32, 32 }

impl CopyToSmall for u64 {
    #[inline]
    fn copy(self, inner: &mut Mpfr, limbs: &mut Limbs) {
        let ptr = cast_ptr_mut!(inner, mpfr_t);
        let limbs_ptr: *mut gmp::limb_t = &mut limbs[0];
        unsafe {
            if self == 0 {
                xmpfr::custom_zero(ptr, limbs_ptr, 64);
            } else {
                let leading = self.leading_zeros();
                let sval = self << leading;
                #[cfg(gmp_limb_bits_64)]
                {
                    limbs[0] = sval;
                }
                #[cfg(gmp_limb_bits_32)]
                {
                    limbs[0] = sval as u32;
                    limbs[1] = (sval >> 32) as u32;
                }
                xmpfr::custom_regular(ptr, limbs_ptr, cast(64 - leading), 64);
            }
        }
    }
}

#[cfg(int_128)]
impl CopyToSmall for u128 {
    #[inline]
    fn copy(self, inner: &mut Mpfr, limbs: &mut Limbs) {
        let ptr = cast_ptr_mut!(inner, mpfr_t);
        let limbs_ptr: *mut gmp::limb_t = &mut limbs[0];
        unsafe {
            if self == 0 {
                xmpfr::custom_zero(ptr, limbs_ptr, 128);
            } else {
                let leading = self.leading_zeros();
                let sval = self << leading;
                #[cfg(gmp_limb_bits_64)]
                {
                    limbs[0] = sval as u64;
                    limbs[1] = (sval >> 64) as u64;
                }
                #[cfg(gmp_limb_bits_32)]
                {
                    limbs[0] = sval as u32;
                    limbs[1] = (sval >> 32) as u32;
                    limbs[2] = (sval >> 64) as u32;
                    limbs[3] = (sval >> 96) as u32;
                }
                xmpfr::custom_regular(ptr, limbs_ptr, cast(128 - leading), 128);
            }
        }
    }
}

impl CopyToSmall for usize {
    #[inline]
    fn copy(self, inner: &mut Mpfr, limbs: &mut Limbs) {
        #[cfg(target_pointer_width = "32")]
        {
            (self as u32).copy(inner, limbs);
        }
        #[cfg(target_pointer_width = "64")]
        {
            (self as u64).copy(inner, limbs);
        }
    }
}

impl CopyToSmall for f32 {
    #[inline]
    fn copy(self, inner: &mut Mpfr, limbs: &mut Limbs) {
        let ptr = cast_ptr_mut!(inner, mpfr_t);
        let limbs_ptr: *mut gmp::limb_t = &mut limbs[0];
        unsafe {
            xmpfr::custom_zero(ptr, limbs_ptr, 24);
            mpfr::set_d(ptr, self.into(), raw_round(Default::default()));
        }
        // retain sign in case of NaN
        if self.is_sign_negative() {
            inner.sign = -1;
        }
    }
}

impl CopyToSmall for f64 {
    #[inline]
    fn copy(self, inner: &mut Mpfr, limbs: &mut Limbs) {
        let ptr = cast_ptr_mut!(inner, mpfr_t);
        let limbs_ptr: *mut gmp::limb_t = &mut limbs[0];
        unsafe {
            xmpfr::custom_zero(ptr, limbs_ptr, 53);
            mpfr::set_d(ptr, self, raw_round(Default::default()));
        }
        // retain sign in case of NaN
        if self.is_sign_negative() {
            inner.sign = -1;
        }
    }
}

macro_rules! impl_assign_from {
    ($($T:ty)*) => { $(
        impl Assign<$T> for SmallFloat {
            #[inline]
            fn assign(&mut self, src: $T) {
                src.copy(&mut self.inner, &mut self.limbs);
            }
        }

        impl From<$T> for SmallFloat {
            #[inline]
            fn from(src: $T) -> Self {
                let mut dst = SmallFloat {
                    inner: unsafe { mem::uninitialized() },
                    limbs: [0; LIMBS_IN_SMALL_FLOAT],
                };
                src.copy(&mut dst.inner, &mut dst.limbs);
                dst
            }
        }
    )* };
}

impl_assign_from! { i8 i16 i32 i64 }
#[cfg(int_128)]
impl_assign_from! { i128 }
impl_assign_from! { isize }
impl_assign_from! { u8 u16 u32 u64 }
#[cfg(int_128)]
impl_assign_from! { u128 }
impl_assign_from! { usize }
impl_assign_from! { f32 f64 }

impl<'a> Assign<&'a Self> for SmallFloat {
    #[inline]
    fn assign(&mut self, other: &Self) {
        self.clone_from(other);
    }
}

impl Assign for SmallFloat {
    #[inline]
    fn assign(&mut self, other: Self) {
        mem::drop(mem::replace(self, other));
    }
}

#[cfg(test)]
mod tests {
    use float::SmallFloat;
    use Assign;

    #[test]
    fn check_assign() {
        let mut f = SmallFloat::from(-1.0f32);
        assert_eq!(*f, -1.0);
        f.assign(-2.0f64);
        assert_eq!(*f, -2.0);
        let other = SmallFloat::from(4u8);
        f.assign(&other);
        assert_eq!(*f, 4);
        f.assign(5i8);
        assert_eq!(*f, 5);
        f.assign(other);
        assert_eq!(*f, 4);
        f.assign(6u16);
        assert_eq!(*f, 6);
        f.assign(-6i16);
        assert_eq!(*f, -6);
        f.assign(6u32);
        assert_eq!(*f, 6);
        f.assign(-6i32);
        assert_eq!(*f, -6);
        f.assign(6u64);
        assert_eq!(*f, 6);
        f.assign(-6i64);
        assert_eq!(*f, -6);
        #[cfg(int_128)]
        {
            f.assign(6u128);
            assert_eq!(*f, 6);
            f.assign(-6i128);
            assert_eq!(*f, -6);
        }
        f.assign(6usize);
        assert_eq!(*f, 6);
        f.assign(-6isize);
        assert_eq!(*f, -6);
        f.assign(0u32);
        assert_eq!(*f, 0);
    }
}