Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

const new #63

Merged
merged 2 commits into from Jul 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions build.rs
Expand Up @@ -4,11 +4,17 @@ use std::env;

fn main() {
let ac = autocfg::new();

if ac.probe_type("i128") {
println!("cargo:rustc-cfg=has_i128");
} else if env::var_os("CARGO_FEATURE_I128").is_some() {
panic!("i128 support was not detected!");
}

// autocfg doesn't have a direct way to probe for `const fn` yet.
if ac.probe_rustc_version(1, 31) {
autocfg::emit("has_const_fn");
}

autocfg::rerun_path(file!());
}
23 changes: 22 additions & 1 deletion src/lib.rs
Expand Up @@ -92,13 +92,23 @@ pub struct Complex<T> {
pub type Complex32 = Complex<f32>;
pub type Complex64 = Complex<f64>;

impl<T: Clone + Num> Complex<T> {
impl<T> Complex<T> {
#[cfg(has_const_fn)]
/// Create a new Complex
#[inline]
pub const fn new(re: T, im: T) -> Self {
Complex { re: re, im: im }
}

#[cfg(not(has_const_fn))]
/// Create a new Complex
#[inline]
pub fn new(re: T, im: T) -> Self {
Complex { re: re, im: im }
}
}

impl<T: Clone + Num> Complex<T> {
/// Returns imaginary unit
#[inline]
pub fn i() -> Self {
Expand Down Expand Up @@ -2639,4 +2649,15 @@ mod test {
c.set_one();
assert!(c.is_one());
}

#[cfg(has_const_fn)]
#[test]
fn test_const() {
const R: f64 = 12.3;
const I: f64 = -4.5;
const C: Complex64 = Complex::new(R, I);

assert_eq!(C.re, 12.3);
assert_eq!(C.im, -4.5);
}
}