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
// Copyright © 2016–2019 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 <https://www.gnu.org/licenses/>.

use crate::complex::big::{self, Format};
use crate::ext::xmpc::{ordering2, raw_round2, Ordering2, Round2};
use crate::float::big::ExpFormat;
use crate::float::{Round, Special};
use crate::ops::AssignRound;
use crate::{Assign, Complex, Float};
use gmp_mpfr_sys::mpc;
use std::cmp::Ordering;
use std::fmt::{
    Alignment, Binary, Debug, Display, Formatter, LowerExp, LowerHex, Octal, Result as FmtResult,
    UpperExp, UpperHex,
};
use std::mem;

impl Clone for Complex {
    #[inline]
    fn clone(&self) -> Complex {
        let prec = self.prec();
        let mut ret = Complex::new(prec);
        ret.assign(self);
        ret
    }

    #[inline]
    fn clone_from(&mut self, source: &Complex) {
        self.assign(source);
    }
}

impl Drop for Complex {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            mpc::clear(self.as_raw_mut());
        }
    }
}

impl<Re> From<Re> for Complex
where
    Float: From<Re>,
{
    #[inline]
    fn from(re: Re) -> Self {
        unsafe {
            let_uninit_ptr!(dst: Complex, dst_ptr);
            let inner_ptr = cast_ptr_mut!(dst_ptr, mpc::mpc_t);
            let real = cast_ptr_mut!(mpc::realref(inner_ptr), Float);
            real.write(Float::from(re));
            let imag = cast_ptr_mut!(mpc::imagref(inner_ptr), Float);
            imag.write(Float::new((*real).prec()));
            assume_init!(dst)
        }
    }
}

impl<Re, Im> From<(Re, Im)> for Complex
where
    Float: From<Re> + From<Im>,
{
    #[inline]
    fn from((re, im): (Re, Im)) -> Self {
        unsafe {
            let_uninit_ptr!(dst: Complex, dst_ptr);
            let inner_ptr = cast_ptr_mut!(dst_ptr, mpc::mpc_t);
            let real = cast_ptr_mut!(mpc::realref(inner_ptr), Float);
            real.write(Float::from(re));
            let imag = cast_ptr_mut!(mpc::imagref(inner_ptr), Float);
            imag.write(Float::from(im));
            assume_init!(dst)
        }
    }
}

impl Display for Complex {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let format = Format {
            exp: ExpFormat::Point,
            ..Format::default()
        };
        fmt_radix(self, f, format)
    }
}

impl Debug for Complex {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let format = Format {
            exp: ExpFormat::Point,
            ..Format::default()
        };
        fmt_radix(self, f, format)
    }
}

impl LowerExp for Complex {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let format = Format {
            exp: ExpFormat::Exp,
            ..Format::default()
        };
        fmt_radix(self, f, format)
    }
}

impl UpperExp for Complex {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let format = Format {
            to_upper: true,
            exp: ExpFormat::Point,
            ..Format::default()
        };
        fmt_radix(self, f, format)
    }
}

impl Binary for Complex {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let format = Format {
            radix: 2,
            prefix: "0b",
            exp: ExpFormat::Exp,
            ..Format::default()
        };
        fmt_radix(self, f, format)
    }
}

impl Octal for Complex {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let format = Format {
            radix: 8,
            prefix: "0o",
            exp: ExpFormat::Point,
            ..Format::default()
        };
        fmt_radix(self, f, format)
    }
}

impl LowerHex for Complex {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let format = Format {
            radix: 16,
            prefix: "0x",
            exp: ExpFormat::Point,
            ..Format::default()
        };
        fmt_radix(self, f, format)
    }
}

impl UpperHex for Complex {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let format = Format {
            radix: 16,
            to_upper: true,
            prefix: "0x",
            exp: ExpFormat::Point,
            ..Format::default()
        };
        fmt_radix(self, f, format)
    }
}

impl<T> Assign<T> for Complex
where
    Self: AssignRound<T, Round = Round2, Ordering = Ordering2>,
{
    #[inline]
    fn assign(&mut self, src: T) {
        self.assign_round(src, Default::default());
    }
}

impl AssignRound for Complex {
    type Round = Round2;
    type Ordering = Ordering2;
    #[inline]
    fn assign_round(&mut self, src: Complex, round: Round2) -> Ordering2 {
        let (dst_real, dst_imag) = self.as_mut_real_imag();
        let (src_real, src_imag) = src.into_real_imag();
        let real_ord = if dst_real.prec() == src_real.prec() {
            mem::drop(mem::replace(dst_real, src_real));
            Ordering::Equal
        } else {
            dst_real.assign_round(src_real, round.0)
        };
        let imag_ord = if dst_imag.prec() == src_imag.prec() {
            mem::drop(mem::replace(dst_imag, src_imag));
            Ordering::Equal
        } else {
            dst_imag.assign_round(src_imag, round.1)
        };
        (real_ord, imag_ord)
    }
}

impl AssignRound<&Complex> for Complex {
    type Round = Round2;
    type Ordering = Ordering2;
    #[inline]
    fn assign_round(&mut self, src: &Complex, round: Round2) -> Ordering2 {
        let ret = unsafe { mpc::set(self.as_raw_mut(), src.as_raw(), raw_round2(round)) };
        ordering2(ret)
    }
}

impl<Re> AssignRound<Re> for Complex
where
    Float: AssignRound<Re, Round = Round, Ordering = Ordering>,
{
    type Round = Round2;
    type Ordering = Ordering2;
    #[inline]
    fn assign_round(&mut self, src: Re, round: Round2) -> Ordering2 {
        let real_ord = self.mut_real().assign_round(src, round.0);
        <Float as Assign<Special>>::assign(self.mut_imag(), Special::Zero);
        (real_ord, Ordering::Equal)
    }
}

impl<Re, Im> AssignRound<(Re, Im)> for Complex
where
    Float: AssignRound<Re, Round = Round, Ordering = Ordering>
        + AssignRound<Im, Round = Round, Ordering = Ordering>,
{
    type Round = Round2;
    type Ordering = Ordering2;
    #[inline]
    fn assign_round(&mut self, src: (Re, Im), round: Round2) -> Ordering2 {
        let real_ord = self.mut_real().assign_round(src.0, round.0);
        let imag_ord = self.mut_imag().assign_round(src.1, round.1);
        (real_ord, imag_ord)
    }
}

impl<'a, Re, Im> AssignRound<&'a (Re, Im)> for Complex
where
    Float: AssignRound<&'a Re, Round = Round, Ordering = Ordering>
        + AssignRound<&'a Im, Round = Round, Ordering = Ordering>,
{
    type Round = Round2;
    type Ordering = Ordering2;
    #[inline]
    fn assign_round(&mut self, src: &'a (Re, Im), round: Round2) -> Ordering2 {
        let real_ord = self.mut_real().assign_round(&src.0, round.0);
        let imag_ord = self.mut_imag().assign_round(&src.1, round.1);
        (real_ord, imag_ord)
    }
}

// * overwrites format.precision with fmt.precision()
// * overwrites format.sign_plus with fmt.sign_plus()
// * overwrites prefix with "" if not fmt.alternate()
fn fmt_radix(c: &Complex, fmt: &mut Formatter<'_>, format: Format) -> FmtResult {
    let format = Format {
        precision: fmt.precision(),
        sign_plus: fmt.sign_plus(),
        prefix: if fmt.alternate() { format.prefix } else { "" },
        ..format
    };
    let mut s = String::new();
    big::append_to_string(&mut s, c, format);
    // s is ascii only, so just take len for character count
    let count = s.len();
    let padding = match fmt.width() {
        Some(width) if width > count => width - count,
        _ => return fmt.write_str(&s),
    };
    let (padding_left, padding_right) = match fmt.align() {
        Some(Alignment::Left) => (0, padding),
        Some(Alignment::Right) | None => (padding, 0),
        Some(Alignment::Center) => (padding / 2, padding - padding / 2),
    };
    let mut fill_buf = String::with_capacity(4);
    fill_buf.push(fmt.fill());
    for _ in 0..padding_left {
        fmt.write_str(&fill_buf)?;
    }
    fmt.write_str(&s)?;
    for _ in 0..padding_right {
        fmt.write_str(&fill_buf)?;
    }
    Ok(())
}

unsafe impl Send for Complex {}
unsafe impl Sync for Complex {}

#[cfg(test)]
mod tests {
    use crate::float::Round;
    use crate::ops::AssignRound;
    use crate::{Assign, Complex};
    use std::cmp::Ordering;

    #[test]
    fn check_assign() {
        let nearest = (Round::Nearest, Round::Nearest);
        let mut c = Complex::with_val(4, (1.0, 2.0));
        assert_eq!(c, (1.0, 2.0));

        let other = Complex::with_val(53, (14.75, 15.25));
        let mut dir = c.assign_round(&other, nearest);
        assert_eq!(c, (15.0, 15.0));
        assert_eq!(dir, (Ordering::Greater, Ordering::Less));

        dir = c.assign_round(3.0, nearest);
        assert_eq!(c, (3.0, 0.0));
        assert_eq!(dir, (Ordering::Equal, Ordering::Equal));

        c.assign(other);
        assert_eq!(c, (15.0, 15.0));
    }
}