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
// Copyright © 2016–2023 Trevor Spiteri
// 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
// <https://www.gnu.org/licenses/>.
use crate::ext::xmpfr;
use crate::float;
use crate::float::ToSmall;
use crate::{Assign, Complex};
use core::cell::UnsafeCell;
use core::mem;
use core::mem::MaybeUninit;
use core::ops::Deref;
use core::ptr::NonNull;
use gmp_mpfr_sys::gmp;
use gmp_mpfr_sys::gmp::limb_t;
use gmp_mpfr_sys::mpc::mpc_t;
use gmp_mpfr_sys::mpfr::{mpfr_t, prec_t};
const LIMBS_IN_SMALL: usize = (128 / gmp::LIMB_BITS) as usize;
type Limbs = [MaybeUninit<limb_t>; LIMBS_IN_SMALL];
/**
A small complex number that does not require any memory allocation.
This can be useful when you have real and imaginary numbers that are primitive
integers or floats and you need a reference to a [`Complex`].
The `SmallComplex` will have a precision according to the types of the
primitives used to set its real and imaginary parts. Note that if different
types are used to set the parts, the parts can have different precisions.
* [`i8`], [`u8`]: the part will have eight bits of precision.
* [`i16`], [`u16`]: the part will have 16 bits of precision.
* [`i32`], [`u32`]: the part will have 32 bits of precision.
* [`i64`], [`u64`]: the part will have 64 bits of precision.
* [`i128`], [`u128`]: the part will have 128 bits of precision.
* [`isize`], [`usize`]: the part will have 32 or 64 bits of precision,
depending on the platform.
* [`f32`]: the part will have 24 bits of precision.
* [`f64`]: the part will have 53 bits of precision.
* [`Special`][crate::float::Special]: the part will have the [minimum possible
precision][crate::float::prec_min].
The `SmallComplex` type can be coerced to a [`Complex`], as it implements
<code>[Deref]\<[Target][Deref::Target] = [Complex]></code>.
# Examples
```rust
use rug::complex::SmallComplex;
use rug::Complex;
// `a` requires a heap allocation
let mut a = Complex::with_val(53, (1, 2));
// `b` can reside on the stack
let b = SmallComplex::from((-10f64, -20.5f64));
a += &*b;
assert_eq!(*a.real(), -9);
assert_eq!(*a.imag(), -18.5);
```
*/
pub struct SmallComplex {
inner: UnsafeCell<mpc_t>,
// real part is first in limbs if inner.re.d <= inner.im.d
first_limbs: Limbs,
last_limbs: Limbs,
}
impl Clone for SmallComplex {
fn clone(&self) -> SmallComplex {
SmallComplex {
inner: UnsafeCell::new(unsafe { *self.inner.get().cast_const() }),
first_limbs: self.first_limbs,
last_limbs: self.last_limbs,
}
}
}
// Safety: SmallComplex cannot be Sync because it contains an
// UnsafeCell which is written to then read without further
// protection, so it could lead to data races. But SmallComplex can be
// Send because if it is owned, no other reference can be used to
// modify the UnsafeCell.
unsafe impl Send for SmallComplex {}
impl Default for SmallComplex {
#[inline]
fn default() -> Self {
SmallComplex::new()
}
}
impl SmallComplex {
/// Creates a [`SmallComplex`] with value 0 and the [minimum possible
/// precision][crate::float::prec_min].
///
/// # Examples
///
/// ```rust
/// use rug::complex::SmallComplex;
/// let c = SmallComplex::new();
/// // Borrow c as if it were Complex.
/// assert_eq!(*c, 0);
/// ```
#[inline]
pub const fn new() -> Self {
SmallComplex {
inner: UnsafeCell::new(mpc_t {
re: mpfr_t {
prec: float::prec_min() as prec_t,
sign: 1,
exp: xmpfr::EXP_ZERO,
d: NonNull::dangling(),
},
im: mpfr_t {
prec: float::prec_min() as prec_t,
sign: 1,
exp: xmpfr::EXP_ZERO,
d: NonNull::dangling(),
},
}),
first_limbs: small_limbs![],
last_limbs: small_limbs![],
}
}
/// Returns a mutable reference to a [`Complex`] number for simple
/// operations that do not need to change the precision of the real or
/// imaginary part.
///
/// # Safety
///
/// It is undefined behavior to modify the precision of the referenced
/// [`Complex`] number or to swap it with another number.
///
/// # Examples
///
/// ```rust
/// use rug::complex::SmallComplex;
/// let mut c = SmallComplex::from((1.0f32, 3.0f32));
/// // rotation does not change the precision
/// unsafe {
/// c.as_nonreallocating_complex().mul_i_mut(false);
/// }
/// assert_eq!(*c, (-3.0, 1.0));
/// ```
#[inline]
// Safety: after calling update_d(), self.inner.d points to the
// limbs so it is in a consistent state.
pub unsafe fn as_nonreallocating_complex(&mut self) -> &mut Complex {
self.update_d();
let ptr = cast_ptr_mut!(&mut self.inner, Complex);
unsafe { &mut *ptr }
}
#[inline]
// Safety: self is not Sync, so reading d does not cause a data race.
fn re_is_first(&self) -> bool {
let ptr = self.inner.get().cast_const();
unsafe { (*ptr).re.d <= (*ptr).im.d }
}
// To be used when offsetting re and im in case the struct has
// been displaced in memory; if currently re.d <= im.d then re.d
// points to first_limbs and im.d points to last_limbs, otherwise
// re.d points to last_limbs and im.d points to first_limbs.
#[inline]
fn update_d(&self) {
// Since this is borrowed, the limbs won't move around, and we can set
// the d fields.
//
// However, if there already exists a reference created with Deref, we
// must not set the d fields as that reference contains its d fields
// without the UnsafeCell wrapping. So we first check whether the d
// fields are already set correctly. If not, then there is no existing
// reference created with Deref yet, so we can set the d fields.
let first = NonNull::<[MaybeUninit<limb_t>]>::from(&self.first_limbs[..]).cast();
let last = NonNull::<[MaybeUninit<limb_t>]>::from(&self.last_limbs[..]).cast();
let (re_d, im_d) = if self.re_is_first() {
(first, last)
} else {
(last, first)
};
// Safety: self is not Sync, so we can write to d without causing a data race.
let ptr = self.inner.get().cast_const();
unsafe {
if (*ptr).re.d != re_d || (*ptr).im.d != im_d {
let ptr = self.inner.get();
(*ptr).re.d = re_d;
(*ptr).im.d = im_d;
}
}
}
}
impl Deref for SmallComplex {
type Target = Complex;
#[inline]
fn deref(&self) -> &Complex {
self.update_d();
let ptr = cast_ptr!(&self.inner, Complex);
// Safety: since we called update_d, the inner pointer is
// pointing to the limbs and the complex number is in a
// consistent state.
unsafe { &*ptr }
}
}
impl<Re: ToSmall> Assign<Re> for SmallComplex {
fn assign(&mut self, src: Re) {
unsafe {
src.copy(&mut self.inner.get_mut().re, &mut self.first_limbs);
xmpfr::custom_zero(
&mut self.inner.get_mut().im,
cast_ptr_mut!(self.last_limbs.as_mut_ptr(), limb_t),
self.inner.get_mut().re.prec,
);
}
}
}
impl<Re: ToSmall> From<Re> for SmallComplex {
fn from(src: Re) -> Self {
let mut inner = mpc_t {
re: mpfr_t {
prec: 0,
sign: 0,
exp: 0,
d: NonNull::dangling(),
},
im: mpfr_t {
prec: 0,
sign: 0,
exp: 0,
d: NonNull::dangling(),
},
};
let mut re_limbs = small_limbs![];
let mut im_limbs = small_limbs![];
unsafe {
src.copy(&mut inner.re, &mut re_limbs);
xmpfr::custom_zero(
&mut inner.im,
cast_ptr_mut!(im_limbs.as_mut_ptr(), limb_t),
inner.re.prec,
);
}
// order of limbs is important as inner.num.d != inner.den.d
if re_limbs.as_ptr() <= im_limbs.as_ptr() {
SmallComplex {
inner: UnsafeCell::new(inner),
first_limbs: re_limbs,
last_limbs: im_limbs,
}
} else {
SmallComplex {
inner: UnsafeCell::new(inner),
first_limbs: im_limbs,
last_limbs: re_limbs,
}
}
}
}
impl<Re: ToSmall, Im: ToSmall> Assign<(Re, Im)> for SmallComplex {
fn assign(&mut self, src: (Re, Im)) {
unsafe {
src.0
.copy(&mut self.inner.get_mut().re, &mut self.first_limbs);
src.1
.copy(&mut self.inner.get_mut().im, &mut self.last_limbs);
}
}
}
impl<Re: ToSmall, Im: ToSmall> From<(Re, Im)> for SmallComplex {
fn from(src: (Re, Im)) -> Self {
let mut inner = mpc_t {
re: mpfr_t {
prec: 0,
sign: 0,
exp: 0,
d: NonNull::dangling(),
},
im: mpfr_t {
prec: 0,
sign: 0,
exp: 0,
d: NonNull::dangling(),
},
};
let mut re_limbs = small_limbs![];
let mut im_limbs = small_limbs![];
unsafe {
src.0.copy(&mut inner.re, &mut re_limbs);
src.1.copy(&mut inner.im, &mut im_limbs);
}
// order of limbs is important as inner.num.d != inner.den.d
if re_limbs.as_ptr() <= im_limbs.as_ptr() {
SmallComplex {
inner: UnsafeCell::new(inner),
first_limbs: re_limbs,
last_limbs: im_limbs,
}
} else {
SmallComplex {
inner: UnsafeCell::new(inner),
first_limbs: im_limbs,
last_limbs: re_limbs,
}
}
}
}
impl Assign<&Self> for SmallComplex {
#[inline]
fn assign(&mut self, other: &Self) {
self.clone_from(other);
}
}
impl Assign for SmallComplex {
#[inline]
fn assign(&mut self, other: Self) {
drop(mem::replace(self, other));
}
}
#[cfg(test)]
mod tests {
use crate::complex::SmallComplex;
use crate::float;
use crate::float::FreeCache;
use crate::Assign;
#[test]
fn check_assign() {
let mut c = SmallComplex::from((1.0, 2.0));
assert_eq!(*c, (1.0, 2.0));
c.assign(3.0);
assert_eq!(*c, (3.0, 0.0));
let other = SmallComplex::from((4.0, 5.0));
c.assign(&other);
assert_eq!(*c, (4.0, 5.0));
c.assign((6.0, 7.0));
assert_eq!(*c, (6.0, 7.0));
c.assign(other);
assert_eq!(*c, (4.0, 5.0));
float::free_cache(FreeCache::All);
}
fn swapped_parts(small: &SmallComplex) -> bool {
unsafe {
let re = (*small.real().as_raw()).d;
let im = (*small.imag().as_raw()).d;
re > im
}
}
#[test]
fn check_swapped_parts() {
let mut c = SmallComplex::from((1, 2));
assert_eq!(*c, (1, 2));
assert_eq!(*c.clone(), *c);
let mut orig_swapped_parts = swapped_parts(&c);
unsafe {
c.as_nonreallocating_complex().mul_i_mut(false);
}
assert_eq!(*c, (-2, 1));
assert_eq!(*c.clone(), *c);
assert!(swapped_parts(&c) != orig_swapped_parts);
c.assign(12);
assert_eq!(*c, 12);
assert_eq!(*c.clone(), *c);
orig_swapped_parts = swapped_parts(&c);
unsafe {
c.as_nonreallocating_complex().mul_i_mut(false);
}
assert_eq!(*c, (0, 12));
assert_eq!(*c.clone(), *c);
assert!(swapped_parts(&c) != orig_swapped_parts);
c.assign((4, 5));
assert_eq!(*c, (4, 5));
assert_eq!(*c.clone(), *c);
orig_swapped_parts = swapped_parts(&c);
unsafe {
c.as_nonreallocating_complex().mul_i_mut(false);
}
assert_eq!(*c, (-5, 4));
assert_eq!(*c.clone(), *c);
assert!(swapped_parts(&c) != orig_swapped_parts);
}
}