Skip to content

Commit b359fc7

Browse files
bors[bot]burrbull
andcommitted
63: const new r=cuviper a=burrbull Co-authored-by: Andrey Zgarbul <zgarbul.andrey@gmail.com>
2 parents dc2157f + a20e33d commit b359fc7

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

build.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,17 @@ use std::env;
44

55
fn main() {
66
let ac = autocfg::new();
7+
78
if ac.probe_type("i128") {
89
println!("cargo:rustc-cfg=has_i128");
910
} else if env::var_os("CARGO_FEATURE_I128").is_some() {
1011
panic!("i128 support was not detected!");
1112
}
1213

14+
// autocfg doesn't have a direct way to probe for `const fn` yet.
15+
if ac.probe_rustc_version(1, 31) {
16+
autocfg::emit("has_const_fn");
17+
}
18+
1319
autocfg::rerun_path(file!());
1420
}

src/lib.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,13 +92,23 @@ pub struct Complex<T> {
9292
pub type Complex32 = Complex<f32>;
9393
pub type Complex64 = Complex<f64>;
9494

95-
impl<T: Clone + Num> Complex<T> {
95+
impl<T> Complex<T> {
96+
#[cfg(has_const_fn)]
97+
/// Create a new Complex
98+
#[inline]
99+
pub const fn new(re: T, im: T) -> Self {
100+
Complex { re: re, im: im }
101+
}
102+
103+
#[cfg(not(has_const_fn))]
96104
/// Create a new Complex
97105
#[inline]
98106
pub fn new(re: T, im: T) -> Self {
99107
Complex { re: re, im: im }
100108
}
109+
}
101110

111+
impl<T: Clone + Num> Complex<T> {
102112
/// Returns imaginary unit
103113
#[inline]
104114
pub fn i() -> Self {
@@ -2639,4 +2649,15 @@ mod test {
26392649
c.set_one();
26402650
assert!(c.is_one());
26412651
}
2652+
2653+
#[cfg(has_const_fn)]
2654+
#[test]
2655+
fn test_const() {
2656+
const R: f64 = 12.3;
2657+
const I: f64 = -4.5;
2658+
const C: Complex64 = Complex::new(R, I);
2659+
2660+
assert_eq!(C.re, 12.3);
2661+
assert_eq!(C.im, -4.5);
2662+
}
26422663
}

0 commit comments

Comments
 (0)