Skip to content
Open
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
45 changes: 45 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,43 @@ impl<T> Complex<T> {
pub const fn new(re: T, im: T) -> Self {
Complex { re, im }
}

/// Returns `self` converted to an array.
#[inline]
pub fn to_array(self) -> [T; 2] {
[self.re, self.im]
}

/// Returns `self` as a borrowed array.
#[inline]
pub const fn as_array_ref(&self) -> &[T; 2] {
unsafe {
// SAFETY: `Self` is guaranteed to have the same memory layout as `[T; 2]`.
std::mem::transmute::<&Self, &[T; 2]>(self)
}
}

/// Returns `self` as a mutably borrowed array.
#[inline]
pub const fn as_array_mut(&mut self) -> &mut [T; 2] {
unsafe {
// SAFETY: `Self` is guaranteed to have the same memory layout as `[T; 2]`.
std::mem::transmute::<&mut Self, &mut [T; 2]>(self)
}
}

/// Returns a new `Complex` value, with function `f` applied to the real and imaginary
/// components.
#[inline]
pub fn map<F, U>(self, mut f: F) -> Complex<U>
where
F: FnMut(T) -> U,
{
Complex {
re: f(self.re),
im: f(self.im),
}
}
}

impl<T: Clone + Num> Complex<T> {
Expand Down Expand Up @@ -701,6 +738,14 @@ impl<'a, T: Clone + Num> From<&'a T> for Complex<T> {
}
}

impl<T> From<[T; 2]> for Complex<T> {
#[inline]
fn from(array: [T; 2]) -> Self {
let [re, im] = array;
Self { re, im }
}
}

macro_rules! forward_ref_ref_binop {
(impl $imp:ident, $method:ident) => {
impl<'a, 'b, T: Clone + Num> $imp<&'b Complex<T>> for &'a Complex<T> {
Expand Down