<commit_before>// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(append)]
#![feature(exit_status)]
#![feature(fs_walk)]
#![feature(path_ext)]
#![feature(slice_extras)]
#![feature(slice_patterns)]
#![feature(test)]

#[macro_use] extern crate bitflags;
extern crate png;
extern crate test;
extern crate url;
extern crate util;

use std::env;
use std::ffi::OsStr;
use std::fs::{PathExt, File, walk_dir};
use std::io::{self, Read, Result};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use test::{AutoColor, DynTestName, DynTestFn, TestDesc, TestOpts, TestDescAndFn, ShouldPanic};
use test::run_tests_console;
use url::Url;

bitflags!(
    flags RenderMode: u32 {
        const CPU_RENDERING  = 0x00000001,
        const GPU_RENDERING  = 0x00000010,
        const LINUX_TARGET   = 0x00000100,
        const MACOS_TARGET   = 0x00001000,
        const ANDROID_TARGET = 0x00010000
    }
);

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut parts = args.tail().split(|e| &**e == "--");

    let harness_args = parts.next().unwrap();  // .split() is never empty
    let servo_args = parts.next().unwrap_or(&[]);

    let (render_mode_string, base_path, testname) = match harness_args {
        [] | [_] => panic!("USAGE: cpu|gpu base_path [testname regex]"),
        [ref render_mode_string, ref base_path] => (render_mode_string, base_path, None),
        [ref render_mode_string, ref base_path, ref testname, ..] =>
            (render_mode_string, base_path, Some(testname.clone())),
    };

    let mut render_mode = match &**render_mode_string {
        "cpu" => CPU_RENDERING,
        "gpu" => GPU_RENDERING,
        _ => panic!("First argument must specify cpu or gpu as rendering mode")
    };
    if cfg!(target_os = "linux") {
        render_mode.insert(LINUX_TARGET);
    }
    if cfg!(target_os = "macos") {
        render_mode.insert(MACOS_TARGET);
    }
    if cfg!(target_os = "android") {
        render_mode.insert(ANDROID_TARGET);
    }

    let mut all_tests = vec!();
    println!("Scanning {} for manifests\n", base_path);

    for file in walk_dir(base_path).unwrap() {
        let file = file.unwrap().path();
        let maybe_extension = file.extension();
        match maybe_extension {
            Some(extension) => {
                if extension == OsStr::new("list") && file.is_file() {
                    let mut tests = parse_lists(&file, servo_args, render_mode, all_tests.len());
                    println!("\t{} [{} tests]", file.display(), tests.len());
                    all_tests.append(&mut tests);
                }
            }
            _ => {}
        }
    }

    let test_opts = TestOpts {
        filter: testname,
        run_ignored: false,
        logfile: None,
        run_tests: true,
        bench_benchmarks: false,
        nocapture: false,
        color: AutoColor,
    };

    match run(test_opts,
              all_tests,
              servo_args.iter().map(|x| x.clone()).collect()) {
        Ok(false) => env::set_exit_status(1), // tests failed
        Err(_) => env::set_exit_status(2),    // I/O-related failure
        _ => (),
    }
}

fn run(test_opts: TestOpts, all_tests: Vec<TestDescAndFn>,
       servo_args: Vec<String>) -> io::Result<bool> {
    // Verify that we're passing in valid servo arguments. Otherwise, servo
    // will exit before we've run any tests, and it will appear to us as if
    // all the tests are failing.
    let output = match Command::new(&servo_path()).args(&servo_args).output() {
        Ok(p) => p,
        Err(e) => panic!("failed to execute process: {}", e),
    };
    let stderr = String::from_utf8(output.stderr).unwrap();

    if stderr.contains("Unrecognized") {
        println!("Servo: {}", stderr);
        return Ok(false);
    }

    run_tests_console(&test_opts, all_tests)
}

#[derive(PartialEq)]
enum ReftestKind {
    Same,
    Different,
}

struct Reftest {
    name: String,
    kind: ReftestKind,
    files: [PathBuf; 2],
    id: usize,
    servo_args: Vec<String>,
    render_mode: RenderMode,
    is_flaky: bool,
    experimental: bool,
    fragment_identifier: Option<String>,
    resolution: Option<String>,
}

struct TestLine<'a> {
    conditions: &'a str,
    kind: &'a str,
    file_left: &'a str,
    file_right: &'a str,
}

fn parse_lists(file: &Path, servo_args: &[String], render_mode: RenderMode, id_offset: usize) -> Vec<TestDescAndFn> {
    let mut tests = Vec::new();
    let contents = {
        let mut f = File::open(file).unwrap();
        let mut contents = String::new();
        f.read_to_string(&mut contents).unwrap();
        contents
    };

    for line in contents.lines() {
        // ignore comments or empty lines
        if line.starts_with("#") || line.is_empty() {
            continue;
        }

        let parts: Vec<&str> = line.split(' ').filter(|p| !p.is_empty()).collect();

        let test_line = match parts.len() {
            3 => TestLine {
                conditions: "",
                kind: parts[0],
                file_left: parts[1],
                file_right: parts[2],
            },
            4 => TestLine {
                conditions: parts[0],
                kind: parts[1],
                file_left: parts[2],
                file_right: parts[3],
            },
            _ => panic!("reftest line: '{}' doesn't match '[CONDITIONS] KIND LEFT RIGHT'", line),
        };

        let kind = match test_line.kind {
            "==" => ReftestKind::Same,
            "!=" => ReftestKind::Different,
            part => panic!("reftest line: '{}' has invalid kind '{}'", line, part)
        };

        let base = env::current_dir().unwrap().join(file.parent().unwrap());

        let file_left =  base.join(test_line.file_left);
        let file_right = base.join(test_line.file_right);

        let conditions_list = test_line.conditions.split(',');
        let mut flakiness = RenderMode::empty();
        let mut experimental = false;
        let mut fragment_identifier = None;
        let mut resolution = None;
        for condition in conditions_list {
            match condition {
                "flaky_cpu" => flakiness.insert(CPU_RENDERING),
                "flaky_gpu" => flakiness.insert(GPU_RENDERING),
                "flaky_linux" => flakiness.insert(LINUX_TARGET),
                "flaky_macos" => flakiness.insert(MACOS_TARGET),
                "experimental" => experimental = true,
                _ => (),
            }
            if condition.starts_with("fragment=") {
                fragment_identifier = Some(condition["fragment=".len()..].to_string());
            }
            if condition.starts_with("resolution=") {
                resolution = Some(condition["resolution=".len() ..].to_string());
            }
        }

        let reftest = Reftest {
            name: format!("{} {} {}", test_line.file_left, test_line.kind, test_line.file_right),
            kind: kind,
            files: [file_left, file_right],
            id: id_offset + tests.len(),
            render_mode: render_mode,
            servo_args: servo_args.to_vec(),
            is_flaky: render_mode.intersects(flakiness),
            experimental: experimental,
            fragment_identifier: fragment_identifier,
            resolution: resolution,
        };

        tests.push(make_test(reftest));
    }
    tests
}

fn make_test(reftest: Reftest) -> TestDescAndFn {
    let name = reftest.name.clone();
    TestDescAndFn {
        desc: TestDesc {
            name: DynTestName(name),
            ignore: false,
            should_panic: ShouldPanic::No,
        },
        testfn: DynTestFn(Box::new(move || {
            check_reftest(reftest);
        })),
    }
}

fn capture(reftest: &Reftest, side: usize) -> (u32, u32, Vec<u8>) {
    let png_filename = format!("/tmp/servo-reftest-{:06}-{}.png", reftest.id, side);
    let mut command = Command::new(&servo_path());
    command
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .args(&reftest.servo_args[..])
        .arg("--user-stylesheet").arg(util::resource_files::resources_dir_path().join("ahem.css"))
        // Allows pixel perfect rendering of Ahem font and the HTML canvas for reftests.
        .arg("-Z")
        .arg("disable-text-aa,disable-canvas-aa")
        .args(&["-f", "-o"])
        .arg(&png_filename)
        .arg(&{
            let mut url = Url::from_file_path(&*reftest.files[side]).unwrap();
            url.fragment = reftest.fragment_identifier.clone();
            url.to_string()
        });
    // CPU rendering is the default
    if reftest.render_mode.contains(CPU_RENDERING) {
        command.arg("-c");
    }
    if reftest.render_mode.contains(GPU_RENDERING) {
        command.arg("-g");
    }
    if reftest.experimental {
        command.arg("--experimental");
    }
    if let Some(ref resolution) = reftest.resolution {
        command.arg("--resolution");
        command.arg(resolution);
    }
    let retval = match command.status() {
        Ok(status) => status,
        Err(e) => panic!("failed to execute process: {}", e),
    };
    assert!(retval.success());

    let image = png::load_png(&png_filename).unwrap();
    let rgba8_bytes = match image.pixels {
        png::PixelsByColorType::RGBA8(pixels) => pixels,
        _ => panic!(),
    };
    (image.width, image.height, rgba8_bytes)
}

fn servo_path() -> PathBuf {
    let current_exe = env::current_exe().ok().expect("Could not locate current executable");
    current_exe.parent().unwrap().join("servo")
}

fn check_reftest(reftest: Reftest) {
    let (left_width, left_height, left_bytes) = capture(&reftest, 0);
    let (right_width, right_height, right_bytes) = capture(&reftest, 1);

    assert_eq!(left_width, right_width);
    assert_eq!(left_height, right_height);

    let left_all_white = left_bytes.iter().all(|&p| p == 255);
    let right_all_white = right_bytes.iter().all(|&p| p == 255);

    if left_all_white && right_all_white {
        panic!("Both renderings are empty")
    }

    let pixels = left_bytes.iter().zip(right_bytes.iter()).map(|(&a, &b)| {
        if a == b {
            // White for correct
            0xFF
        } else {
            // "1100" in the RGBA channel with an error for an incorrect value
            // This results in some number of C0 and FFs, which is much more
            // readable (and distinguishable) than the previous difference-wise
            // scaling but does not require reconstructing the actual RGBA pixel.
            0xC0
        }
    }).collect::<Vec<u8>>();

    if pixels.iter().any(|&a| a < 255) {
        let output = format!("/tmp/servo-reftest-{:06}-diff.png", reftest.id);

        let mut img = png::Image {
            width: left_width,
            height: left_height,
            pixels: png::PixelsByColorType::RGBA8(pixels),
        };
        let res = png::store_png(&mut img, &output);
        assert!(res.is_ok());

        match (reftest.kind, reftest.is_flaky) {
            (ReftestKind::Same, true) => println!("flaky test - rendering difference: {}", output),
            (ReftestKind::Same, false) => panic!("rendering difference: {}", output),
            (ReftestKind::Different, _) => {}   // Result was different and that's what was expected
        }
    } else {
        assert!(reftest.is_flaky || reftest.kind == ReftestKind::Same);
    }
}
<commit_msg>Auto merge of #7240 - Ms2ger:slice_extras, r=nox<commit_after>// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(append)]
#![feature(exit_status)]
#![feature(fs_walk)]
#![feature(path_ext)]
#![feature(slice_patterns)]
#![feature(test)]

#[macro_use] extern crate bitflags;
extern crate png;
extern crate test;
extern crate url;
extern crate util;

use std::env;
use std::ffi::OsStr;
use std::fs::{PathExt, File, walk_dir};
use std::io::{self, Read, Result};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use test::{AutoColor, DynTestName, DynTestFn, TestDesc, TestOpts, TestDescAndFn, ShouldPanic};
use test::run_tests_console;
use url::Url;

bitflags!(
    flags RenderMode: u32 {
        const CPU_RENDERING  = 0x00000001,
        const GPU_RENDERING  = 0x00000010,
        const LINUX_TARGET   = 0x00000100,
        const MACOS_TARGET   = 0x00001000,
        const ANDROID_TARGET = 0x00010000
    }
);

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut parts = args[1..].split(|e| &**e == "--");

    let harness_args = parts.next().unwrap();  // .split() is never empty
    let servo_args = parts.next().unwrap_or(&[]);

    let (render_mode_string, base_path, testname) = match harness_args {
        [] | [_] => panic!("USAGE: cpu|gpu base_path [testname regex]"),
        [ref render_mode_string, ref base_path] => (render_mode_string, base_path, None),
        [ref render_mode_string, ref base_path, ref testname, ..] =>
            (render_mode_string, base_path, Some(testname.clone())),
    };

    let mut render_mode = match &**render_mode_string {
        "cpu" => CPU_RENDERING,
        "gpu" => GPU_RENDERING,
        _ => panic!("First argument must specify cpu or gpu as rendering mode")
    };
    if cfg!(target_os = "linux") {
        render_mode.insert(LINUX_TARGET);
    }
    if cfg!(target_os = "macos") {
        render_mode.insert(MACOS_TARGET);
    }
    if cfg!(target_os = "android") {
        render_mode.insert(ANDROID_TARGET);
    }

    let mut all_tests = vec!();
    println!("Scanning {} for manifests\n", base_path);

    for file in walk_dir(base_path).unwrap() {
        let file = file.unwrap().path();
        let maybe_extension = file.extension();
        match maybe_extension {
            Some(extension) => {
                if extension == OsStr::new("list") && file.is_file() {
                    let mut tests = parse_lists(&file, servo_args, render_mode, all_tests.len());
                    println!("\t{} [{} tests]", file.display(), tests.len());
                    all_tests.append(&mut tests);
                }
            }
            _ => {}
        }
    }

    let test_opts = TestOpts {
        filter: testname,
        run_ignored: false,
        logfile: None,
        run_tests: true,
        bench_benchmarks: false,
        nocapture: false,
        color: AutoColor,
    };

    match run(test_opts,
              all_tests,
              servo_args.iter().map(|x| x.clone()).collect()) {
        Ok(false) => env::set_exit_status(1), // tests failed
        Err(_) => env::set_exit_status(2),    // I/O-related failure
        _ => (),
    }
}

fn run(test_opts: TestOpts, all_tests: Vec<TestDescAndFn>,
       servo_args: Vec<String>) -> io::Result<bool> {
    // Verify that we're passing in valid servo arguments. Otherwise, servo
    // will exit before we've run any tests, and it will appear to us as if
    // all the tests are failing.
    let output = match Command::new(&servo_path()).args(&servo_args).output() {
        Ok(p) => p,
        Err(e) => panic!("failed to execute process: {}", e),
    };
    let stderr = String::from_utf8(output.stderr).unwrap();

    if stderr.contains("Unrecognized") {
        println!("Servo: {}", stderr);
        return Ok(false);
    }

    run_tests_console(&test_opts, all_tests)
}

#[derive(PartialEq)]
enum ReftestKind {
    Same,
    Different,
}

struct Reftest {
    name: String,
    kind: ReftestKind,
    files: [PathBuf; 2],
    id: usize,
    servo_args: Vec<String>,
    render_mode: RenderMode,
    is_flaky: bool,
    experimental: bool,
    fragment_identifier: Option<String>,
    resolution: Option<String>,
}

struct TestLine<'a> {
    conditions: &'a str,
    kind: &'a str,
    file_left: &'a str,
    file_right: &'a str,
}

fn parse_lists(file: &Path, servo_args: &[String], render_mode: RenderMode, id_offset: usize) -> Vec<TestDescAndFn> {
    let mut tests = Vec::new();
    let contents = {
        let mut f = File::open(file).unwrap();
        let mut contents = String::new();
        f.read_to_string(&mut contents).unwrap();
        contents
    };

    for line in contents.lines() {
        // ignore comments or empty lines
        if line.starts_with("#") || line.is_empty() {
            continue;
        }

        let parts: Vec<&str> = line.split(' ').filter(|p| !p.is_empty()).collect();

        let test_line = match parts.len() {
            3 => TestLine {
                conditions: "",
                kind: parts[0],
                file_left: parts[1],
                file_right: parts[2],
            },
            4 => TestLine {
                conditions: parts[0],
                kind: parts[1],
                file_left: parts[2],
                file_right: parts[3],
            },
            _ => panic!("reftest line: '{}' doesn't match '[CONDITIONS] KIND LEFT RIGHT'", line),
        };

        let kind = match test_line.kind {
            "==" => ReftestKind::Same,
            "!=" => ReftestKind::Different,
            part => panic!("reftest line: '{}' has invalid kind '{}'", line, part)
        };

        let base = env::current_dir().unwrap().join(file.parent().unwrap());

        let file_left =  base.join(test_line.file_left);
        let file_right = base.join(test_line.file_right);

        let conditions_list = test_line.conditions.split(',');
        let mut flakiness = RenderMode::empty();
        let mut experimental = false;
        let mut fragment_identifier = None;
        let mut resolution = None;
        for condition in conditions_list {
            match condition {
                "flaky_cpu" => flakiness.insert(CPU_RENDERING),
                "flaky_gpu" => flakiness.insert(GPU_RENDERING),
                "flaky_linux" => flakiness.insert(LINUX_TARGET),
                "flaky_macos" => flakiness.insert(MACOS_TARGET),
                "experimental" => experimental = true,
                _ => (),
            }
            if condition.starts_with("fragment=") {
                fragment_identifier = Some(condition["fragment=".len()..].to_string());
            }
            if condition.starts_with("resolution=") {
                resolution = Some(condition["resolution=".len() ..].to_string());
            }
        }

        let reftest = Reftest {
            name: format!("{} {} {}", test_line.file_left, test_line.kind, test_line.file_right),
            kind: kind,
            files: [file_left, file_right],
            id: id_offset + tests.len(),
            render_mode: render_mode,
            servo_args: servo_args.to_vec(),
            is_flaky: render_mode.intersects(flakiness),
            experimental: experimental,
            fragment_identifier: fragment_identifier,
            resolution: resolution,
        };

        tests.push(make_test(reftest));
    }
    tests
}

fn make_test(reftest: Reftest) -> TestDescAndFn {
    let name = reftest.name.clone();
    TestDescAndFn {
        desc: TestDesc {
            name: DynTestName(name),
            ignore: false,
            should_panic: ShouldPanic::No,
        },
        testfn: DynTestFn(Box::new(move || {
            check_reftest(reftest);
        })),
    }
}

fn capture(reftest: &Reftest, side: usize) -> (u32, u32, Vec<u8>) {
    let png_filename = format!("/tmp/servo-reftest-{:06}-{}.png", reftest.id, side);
    let mut command = Command::new(&servo_path());
    command
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .args(&reftest.servo_args[..])
        .arg("--user-stylesheet").arg(util::resource_files::resources_dir_path().join("ahem.css"))
        // Allows pixel perfect rendering of Ahem font and the HTML canvas for reftests.
        .arg("-Z")
        .arg("disable-text-aa,disable-canvas-aa")
        .args(&["-f", "-o"])
        .arg(&png_filename)
        .arg(&{
            let mut url = Url::from_file_path(&*reftest.files[side]).unwrap();
            url.fragment = reftest.fragment_identifier.clone();
            url.to_string()
        });
    // CPU rendering is the default
    if reftest.render_mode.contains(CPU_RENDERING) {
        command.arg("-c");
    }
    if reftest.render_mode.contains(GPU_RENDERING) {
        command.arg("-g");
    }
    if reftest.experimental {
        command.arg("--experimental");
    }
    if let Some(ref resolution) = reftest.resolution {
        command.arg("--resolution");
        command.arg(resolution);
    }
    let retval = match command.status() {
        Ok(status) => status,
        Err(e) => panic!("failed to execute process: {}", e),
    };
    assert!(retval.success());

    let image = png::load_png(&png_filename).unwrap();
    let rgba8_bytes = match image.pixels {
        png::PixelsByColorType::RGBA8(pixels) => pixels,
        _ => panic!(),
    };
    (image.width, image.height, rgba8_bytes)
}

fn servo_path() -> PathBuf {
    let current_exe = env::current_exe().ok().expect("Could not locate current executable");
    current_exe.parent().unwrap().join("servo")
}

fn check_reftest(reftest: Reftest) {
    let (left_width, left_height, left_bytes) = capture(&reftest, 0);
    let (right_width, right_height, right_bytes) = capture(&reftest, 1);

    assert_eq!(left_width, right_width);
    assert_eq!(left_height, right_height);

    let left_all_white = left_bytes.iter().all(|&p| p == 255);
    let right_all_white = right_bytes.iter().all(|&p| p == 255);

    if left_all_white && right_all_white {
        panic!("Both renderings are empty")
    }

    let pixels = left_bytes.iter().zip(right_bytes.iter()).map(|(&a, &b)| {
        if a == b {
            // White for correct
            0xFF
        } else {
            // "1100" in the RGBA channel with an error for an incorrect value
            // This results in some number of C0 and FFs, which is much more
            // readable (and distinguishable) than the previous difference-wise
            // scaling but does not require reconstructing the actual RGBA pixel.
            0xC0
        }
    }).collect::<Vec<u8>>();

    if pixels.iter().any(|&a| a < 255) {
        let output = format!("/tmp/servo-reftest-{:06}-diff.png", reftest.id);

        let mut img = png::Image {
            width: left_width,
            height: left_height,
            pixels: png::PixelsByColorType::RGBA8(pixels),
        };
        let res = png::store_png(&mut img, &output);
        assert!(res.is_ok());

        match (reftest.kind, reftest.is_flaky) {
            (ReftestKind::Same, true) => println!("flaky test - rendering difference: {}", output),
            (ReftestKind::Same, false) => panic!("rendering difference: {}", output),
            (ReftestKind::Different, _) => {}   // Result was different and that's what was expected
        }
    } else {
        assert!(reftest.is_flaky || reftest.kind == ReftestKind::Same);
    }
}
<|endoftext|>


<commit_before>#[warn(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]
#[allow(clippy::no_effect, clippy::unnecessary_operation)]
fn main() {
    // Test clippy::cast_precision_loss
    let x0 = 1i32;
    x0 as f32;
    let x1 = 1i64;
    x1 as f32;
    x1 as f64;
    let x2 = 1u32;
    x2 as f32;
    let x3 = 1u64;
    x3 as f32;
    x3 as f64;
    // Test clippy::cast_possible_truncation
    1f32 as i32;
    1f32 as u32;
    1f64 as f32;
    1i32 as i8;
    1i32 as u8;
    1f64 as isize;
    1f64 as usize;
    // Test clippy::cast_possible_wrap
    1u8 as i8;
    1u16 as i16;
    1u32 as i32;
    1u64 as i64;
    1usize as isize;
    // Test clippy::cast_sign_loss
    1i32 as u32;
    -1i32 as u32;
    1isize as usize;
    -1isize as usize;
    0i8 as u8;
    i8::max_value() as u8;
    i16::max_value() as u16;
    i32::max_value() as u32;
    i64::max_value() as u64;
    i128::max_value() as u128;
    (-1i8).abs() as u8;
    (-1i16).abs() as u16;
    (-1i32).abs() as u32;
    (-1i64).abs() as u64;
    (-1isize).abs() as usize;
    (-1i8).checked_abs().unwrap() as u8;
    (-1i16).checked_abs().unwrap() as u16;
    (-1i32).checked_abs().unwrap() as u32;
    (-1i64).checked_abs().unwrap() as u64;
    (-1isize).checked_abs().unwrap() as usize;
    (-1i8).rem_euclid(1i8) as u8;
    (-1i16).rem_euclid(1i16) as u16;
    (-1i32).rem_euclid(1i32) as u32;
    (-1i64).rem_euclid(1i64) as u64;
    (-1isize).rem_euclid(1isize) as usize;
    (1i8).rem_euclid(-1i8) as u8;
    (1i16).rem_euclid(-1i16) as u16;
    (1i32).rem_euclid(-1i32) as u32;
    (1i64).rem_euclid(-1i64) as u64;
    (1isize).rem_euclid(-1isize) as usize;
    (-1i8).checked_rem_euclid(1i8).unwrap() as u8;
    (-1i16).checked_rem_euclid(1i16).unwrap() as u16;
    (-1i32).checked_rem_euclid(1i32).unwrap() as u32;
    (-1i64).checked_rem_euclid(1i64).unwrap() as u64;
    (-1isize).checked_rem_euclid(1isize).unwrap() as usize;
    (1i8).checked_rem_euclid(-1i8).unwrap() as u8;
    (1i16).checked_rem_euclid(-1i16).unwrap() as u16;
    (1i32).checked_rem_euclid(-1i32).unwrap() as u32;
    (1i64).checked_rem_euclid(-1i64).unwrap() as u64;
    (1isize).checked_rem_euclid(-1isize).unwrap() as usize;
}
<commit_msg>Add widening tests for `cast_sign_loss` lint<commit_after>#[warn(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_possible_wrap
)]
#[allow(clippy::no_effect, clippy::unnecessary_operation)]
fn main() {
    // Test clippy::cast_precision_loss
    let x0 = 1i32;
    x0 as f32;
    let x1 = 1i64;
    x1 as f32;
    x1 as f64;
    let x2 = 1u32;
    x2 as f32;
    let x3 = 1u64;
    x3 as f32;
    x3 as f64;
    // Test clippy::cast_possible_truncation
    1f32 as i32;
    1f32 as u32;
    1f64 as f32;
    1i32 as i8;
    1i32 as u8;
    1f64 as isize;
    1f64 as usize;
    // Test clippy::cast_possible_wrap
    1u8 as i8;
    1u16 as i16;
    1u32 as i32;
    1u64 as i64;
    1usize as isize;
    // Test clippy::cast_sign_loss
    1i32 as u32;
    -1i32 as u32;
    1isize as usize;
    -1isize as usize;
    0i8 as u8;
    i8::max_value() as u8;
    i16::max_value() as u16;
    i32::max_value() as u32;
    i64::max_value() as u64;
    i128::max_value() as u128;

    (-1i8).abs() as u8;
    (-1i16).abs() as u16;
    (-1i32).abs() as u32;
    (-1i64).abs() as u64;
    (-1isize).abs() as usize;

    (-1i8).checked_abs().unwrap() as u8;
    (-1i16).checked_abs().unwrap() as u16;
    (-1i32).checked_abs().unwrap() as u32;
    (-1i64).checked_abs().unwrap() as u64;
    (-1isize).checked_abs().unwrap() as usize;

    (-1i8).rem_euclid(1i8) as u8;
    (-1i8).rem_euclid(1i8) as u16;
    (-1i16).rem_euclid(1i16) as u16;
    (-1i16).rem_euclid(1i16) as u32;
    (-1i32).rem_euclid(1i32) as u32;
    (-1i32).rem_euclid(1i32) as u64;
    (-1i64).rem_euclid(1i64) as u64;
    (-1i64).rem_euclid(1i64) as u128;
    (-1isize).rem_euclid(1isize) as usize;
    (1i8).rem_euclid(-1i8) as u8;
    (1i8).rem_euclid(-1i8) as u16;
    (1i16).rem_euclid(-1i16) as u16;
    (1i16).rem_euclid(-1i16) as u32;
    (1i32).rem_euclid(-1i32) as u32;
    (1i32).rem_euclid(-1i32) as u64;
    (1i64).rem_euclid(-1i64) as u64;
    (1i64).rem_euclid(-1i64) as u128;
    (1isize).rem_euclid(-1isize) as usize;

    (-1i8).checked_rem_euclid(1i8).unwrap() as u8;
    (-1i8).checked_rem_euclid(1i8).unwrap() as u16;
    (-1i16).checked_rem_euclid(1i16).unwrap() as u16;
    (-1i16).checked_rem_euclid(1i16).unwrap() as u32;
    (-1i32).checked_rem_euclid(1i32).unwrap() as u32;
    (-1i32).checked_rem_euclid(1i32).unwrap() as u64;
    (-1i64).checked_rem_euclid(1i64).unwrap() as u64;
    (-1i64).checked_rem_euclid(1i64).unwrap() as u128;
    (-1isize).checked_rem_euclid(1isize).unwrap() as usize;
    (1i8).checked_rem_euclid(-1i8).unwrap() as u8;
    (1i8).checked_rem_euclid(-1i8).unwrap() as u16;
    (1i16).checked_rem_euclid(-1i16).unwrap() as u16;
    (1i16).checked_rem_euclid(-1i16).unwrap() as u32;
    (1i32).checked_rem_euclid(-1i32).unwrap() as u32;
    (1i32).checked_rem_euclid(-1i32).unwrap() as u64;
    (1i64).checked_rem_euclid(-1i64).unwrap() as u64;
    (1i64).checked_rem_euclid(-1i64).unwrap() as u128;
    (1isize).checked_rem_euclid(-1isize).unwrap() as usize;
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate cfg_if;
#[cfg_attr(not(target_os = "redox"), macro_use)]
extern crate nix;
#[macro_use]
extern crate lazy_static;

macro_rules! skip {
    ($($reason: expr),+) => {
        use ::std::io::{self, Write};

        let stderr = io::stderr();
        let mut handle = stderr.lock();
        writeln!(handle, $($reason),+).unwrap();
        return;
    }
}

cfg_if! {
    if #[cfg(any(target_os = "android", target_os = "linux"))] {
        macro_rules! require_capability {
            ($capname:ident) => {
                use ::caps::{Capability, CapSet, has_cap};

                if !has_cap(None, CapSet::Effective, Capability::$capname)
                    .unwrap()
                {
                    skip!("Insufficient capabilities. Skipping test.");
                }
            }
        }
    } else if #[cfg(not(target_os = "redox"))] {
        macro_rules! require_capability {
            ($capname:ident) => {}
        }
    }
}

#[cfg(target_os = "freebsd")]
macro_rules! skip_if_jailed {
    ($name:expr) => {
        use ::sysctl::CtlValue;

        if let CtlValue::Int(1) = ::sysctl::value("security.jail.jailed")
            .unwrap()
        {
            skip!("{} cannot run in a jail. Skipping test.", $name);
        }
    }
}

#[cfg(not(target_os = "redox"))]
macro_rules! skip_if_not_root {
    ($name:expr) => {
        use nix::unistd::Uid;

        if !Uid::current().is_root() {
            skip!("{} requires root privileges. Skipping test.", $name);
        }
    };
}

cfg_if! {
    if #[cfg(any(target_os = "android", target_os = "linux"))] {
        macro_rules! skip_if_seccomp {
            ($name:expr) => {
                if let Ok(s) = std::fs::read_to_string("/proc/self/status") {
                    for l in s.lines() {
                        let mut fields = l.split_whitespace();
                        if fields.next() == Some("Seccomp:") &&
                            fields.next() != Some("0")
                        {
                            skip!("{} cannot be run in Seccomp mode.  Skipping test.",
                                stringify!($name));
                        }
                    }
                }
            }
        }
    } else if #[cfg(not(target_os = "redox"))] {
        macro_rules! skip_if_seccomp {
            ($name:expr) => {}
        }
    }
}

cfg_if! {
    if #[cfg(target_os = "linux")] {
        macro_rules! require_kernel_version {
            ($name:expr, $version_requirement:expr) => {
                use semver::{Version, VersionReq};

                let version_requirement = VersionReq::parse($version_requirement)
                        .expect("Bad match_version provided");

                let uname = nix::sys::utsname::uname();

                let mut version = Version::parse(uname.release()).unwrap();

                //Keep only numeric parts
                version.pre.clear();
                version.build.clear();

                if !version_requirement.matches(&version) {
                    skip!("Skip {} because kernel version `{}` doesn't match the requirement `{}`",
                        stringify!($name), version, version_requirement);
                }
            }
        }
    }
}

mod sys;
#[cfg(not(target_os = "redox"))]
mod test_dir;
mod test_fcntl;
#[cfg(any(target_os = "android",
          target_os = "linux"))]
mod test_kmod;
#[cfg(any(target_os = "dragonfly",
          target_os = "freebsd",
          target_os = "fushsia",
          target_os = "linux",
          target_os = "netbsd"))]
mod test_mq;
#[cfg(not(target_os = "redox"))]
mod test_net;
mod test_nix_path;
mod test_poll;
#[cfg(not(target_os = "redox"))]
mod test_pty;
#[cfg(any(target_os = "android",
          target_os = "linux"))]
mod test_sched;
#[cfg(any(target_os = "android",
          target_os = "freebsd",
          target_os = "ios",
          target_os = "linux",
          target_os = "macos"))]
mod test_sendfile;
mod test_stat;
mod test_time;
mod test_unistd;

use std::os::unix::io::RawFd;
use std::path::PathBuf;
use std::sync::{Mutex, RwLock, RwLockWriteGuard};
use nix::unistd::{chdir, getcwd, read};

/// Helper function analogous to `std::io::Read::read_exact`, but for `RawFD`s
fn read_exact(f: RawFd, buf: &mut  [u8]) {
    let mut len = 0;
    while len < buf.len() {
        // get_mut would be better than split_at_mut, but it requires nightly
        let (_, remaining) = buf.split_at_mut(len);
        len += read(f, remaining).unwrap();
    }
}

lazy_static! {
    /// Any test that changes the process's current working directory must grab
    /// the RwLock exclusively.  Any process that cares about the current
    /// working directory must grab it shared.
    pub static ref CWD_LOCK: RwLock<()> = RwLock::new(());
    /// Any test that creates child processes must grab this mutex, regardless
    /// of what it does with those children.
    pub static ref FORK_MTX: Mutex<()> = Mutex::new(());
    /// Any test that changes the process's supplementary groups must grab this
    /// mutex
    pub static ref GROUPS_MTX: Mutex<()> = Mutex::new(());
    /// Any tests that loads or unloads kernel modules must grab this mutex
    pub static ref KMOD_MTX: Mutex<()> = Mutex::new(());
    /// Any test that calls ptsname(3) must grab this mutex.
    pub static ref PTSNAME_MTX: Mutex<()> = Mutex::new(());
    /// Any test that alters signal handling must grab this mutex.
    pub static ref SIGNAL_MTX: Mutex<()> = Mutex::new(());
}

/// RAII object that restores a test's original directory on drop
struct DirRestore<'a> {
    d: PathBuf,
    _g: RwLockWriteGuard<'a, ()>
}

impl<'a> DirRestore<'a> {
    fn new() -> Self {
        let guard = crate::CWD_LOCK.write()
            .expect("Lock got poisoned by another test");
        DirRestore{
            _g: guard,
            d: getcwd().unwrap(),
        }
    }
}

impl<'a> Drop for DirRestore<'a> {
    fn drop(&mut self) {
        let r = chdir(&self.d);
        if std::thread::panicking() {
            r.unwrap();
        }
    }
}
<commit_msg>update require_kernel_version to handle "_" in version string<commit_after>#[macro_use]
extern crate cfg_if;
#[cfg_attr(not(target_os = "redox"), macro_use)]
extern crate nix;
#[macro_use]
extern crate lazy_static;

macro_rules! skip {
    ($($reason: expr),+) => {
        use ::std::io::{self, Write};

        let stderr = io::stderr();
        let mut handle = stderr.lock();
        writeln!(handle, $($reason),+).unwrap();
        return;
    }
}

cfg_if! {
    if #[cfg(any(target_os = "android", target_os = "linux"))] {
        macro_rules! require_capability {
            ($capname:ident) => {
                use ::caps::{Capability, CapSet, has_cap};

                if !has_cap(None, CapSet::Effective, Capability::$capname)
                    .unwrap()
                {
                    skip!("Insufficient capabilities. Skipping test.");
                }
            }
        }
    } else if #[cfg(not(target_os = "redox"))] {
        macro_rules! require_capability {
            ($capname:ident) => {}
        }
    }
}

#[cfg(target_os = "freebsd")]
macro_rules! skip_if_jailed {
    ($name:expr) => {
        use ::sysctl::CtlValue;

        if let CtlValue::Int(1) = ::sysctl::value("security.jail.jailed")
            .unwrap()
        {
            skip!("{} cannot run in a jail. Skipping test.", $name);
        }
    }
}

#[cfg(not(target_os = "redox"))]
macro_rules! skip_if_not_root {
    ($name:expr) => {
        use nix::unistd::Uid;

        if !Uid::current().is_root() {
            skip!("{} requires root privileges. Skipping test.", $name);
        }
    };
}

cfg_if! {
    if #[cfg(any(target_os = "android", target_os = "linux"))] {
        macro_rules! skip_if_seccomp {
            ($name:expr) => {
                if let Ok(s) = std::fs::read_to_string("/proc/self/status") {
                    for l in s.lines() {
                        let mut fields = l.split_whitespace();
                        if fields.next() == Some("Seccomp:") &&
                            fields.next() != Some("0")
                        {
                            skip!("{} cannot be run in Seccomp mode.  Skipping test.",
                                stringify!($name));
                        }
                    }
                }
            }
        }
    } else if #[cfg(not(target_os = "redox"))] {
        macro_rules! skip_if_seccomp {
            ($name:expr) => {}
        }
    }
}

cfg_if! {
    if #[cfg(target_os = "linux")] {
        macro_rules! require_kernel_version {
            ($name:expr, $version_requirement:expr) => {
                use semver::{Version, VersionReq};

                let version_requirement = VersionReq::parse($version_requirement)
                        .expect("Bad match_version provided");

                let uname = nix::sys::utsname::uname();

                // Linux may report version as 4.18.el8_2.x86_64 or 5.18.200-fc33.x86_64
                // semver sematics does not support underscore. Replace this with hypen.
                let mut version = Version::parse(
                    &uname.release().to_string().replace("_", "-")
                ).unwrap();

                //Keep only numeric parts
                version.pre.clear();
                version.build.clear();

                if !version_requirement.matches(&version) {
                    skip!("Skip {} because kernel version `{}` doesn't match the requirement `{}`",
                        stringify!($name), version, version_requirement);
                }
            }
        }
    }
}

mod sys;
#[cfg(not(target_os = "redox"))]
mod test_dir;
mod test_fcntl;
#[cfg(any(target_os = "android",
          target_os = "linux"))]
mod test_kmod;
#[cfg(any(target_os = "dragonfly",
          target_os = "freebsd",
          target_os = "fushsia",
          target_os = "linux",
          target_os = "netbsd"))]
mod test_mq;
#[cfg(not(target_os = "redox"))]
mod test_net;
mod test_nix_path;
mod test_poll;
#[cfg(not(target_os = "redox"))]
mod test_pty;
#[cfg(any(target_os = "android",
          target_os = "linux"))]
mod test_sched;
#[cfg(any(target_os = "android",
          target_os = "freebsd",
          target_os = "ios",
          target_os = "linux",
          target_os = "macos"))]
mod test_sendfile;
mod test_stat;
mod test_time;
mod test_unistd;

use std::os::unix::io::RawFd;
use std::path::PathBuf;
use std::sync::{Mutex, RwLock, RwLockWriteGuard};
use nix::unistd::{chdir, getcwd, read};

/// Helper function analogous to `std::io::Read::read_exact`, but for `RawFD`s
fn read_exact(f: RawFd, buf: &mut  [u8]) {
    let mut len = 0;
    while len < buf.len() {
        // get_mut would be better than split_at_mut, but it requires nightly
        let (_, remaining) = buf.split_at_mut(len);
        len += read(f, remaining).unwrap();
    }
}

lazy_static! {
    /// Any test that changes the process's current working directory must grab
    /// the RwLock exclusively.  Any process that cares about the current
    /// working directory must grab it shared.
    pub static ref CWD_LOCK: RwLock<()> = RwLock::new(());
    /// Any test that creates child processes must grab this mutex, regardless
    /// of what it does with those children.
    pub static ref FORK_MTX: Mutex<()> = Mutex::new(());
    /// Any test that changes the process's supplementary groups must grab this
    /// mutex
    pub static ref GROUPS_MTX: Mutex<()> = Mutex::new(());
    /// Any tests that loads or unloads kernel modules must grab this mutex
    pub static ref KMOD_MTX: Mutex<()> = Mutex::new(());
    /// Any test that calls ptsname(3) must grab this mutex.
    pub static ref PTSNAME_MTX: Mutex<()> = Mutex::new(());
    /// Any test that alters signal handling must grab this mutex.
    pub static ref SIGNAL_MTX: Mutex<()> = Mutex::new(());
}

/// RAII object that restores a test's original directory on drop
struct DirRestore<'a> {
    d: PathBuf,
    _g: RwLockWriteGuard<'a, ()>
}

impl<'a> DirRestore<'a> {
    fn new() -> Self {
        let guard = crate::CWD_LOCK.write()
            .expect("Lock got poisoned by another test");
        DirRestore{
            _g: guard,
            d: getcwd().unwrap(),
        }
    }
}

impl<'a> Drop for DirRestore<'a> {
    fn drop(&mut self) {
        let r = chdir(&self.d);
        if std::thread::panicking() {
            r.unwrap();
        }
    }
}
<|endoftext|>


<commit_before>use atoms::*;
use molecule::*;

pub const WATER: &'static Molecule = &Molecule {
    compounds: &[
        MoleculeCompound { atom: HYDROGEN, amount: 2 },
        MoleculeCompound { atom: OXYGEN, amount: 1 }
    ]
};

pub const TABLE_SALT: &'static Molecule = &Molecule {
    compounds: &[
        MoleculeCompound { atom: SODIUM, amount: 1 },
        MoleculeCompound { atom: CHLORINE, amount: 1 }
    ]
};
<commit_msg>Fix build error on stable branch<commit_after>use atoms::*;
use molecule::*;

pub const WATER: &'static Molecule<'static> = &Molecule {
    compounds: &[
        MoleculeCompound { atom: HYDROGEN, amount: 2 },
        MoleculeCompound { atom: OXYGEN, amount: 1 }
    ]
};

pub const TABLE_SALT: &'static Molecule<'static> = &Molecule {
    compounds: &[
        MoleculeCompound { atom: SODIUM, amount: 1 },
        MoleculeCompound { atom: CHLORINE, amount: 1 }
    ]
};
<|endoftext|>


<commit_before>// cargo run --example just_udp_socket
// echo -n "hello" > /dev/udp/0.0.0.0/5546 // this isn't working version

// this one requires socat, but works like a breeze
// echo -e "\xff" | socat - UDP-DATAGRAM:0.0.0.0:5546,broadcast

use std::net::UdpSocket;
use std::time::{Duration, Instant};
use std::io::ErrorKind;
use std::str;
use std::thread;

fn main() {
    let sock = UdpSocket::bind("0.0.0.0:5546").expect("Failed to bind socket");
    sock.set_nonblocking(true) .expect("Failed to enter non-blocking mode");

    // Poll for data every 5 milliseconds for 5 seconds.
    let start = Instant::now();
    let mut buf = [0u8; 1024];

    // for 50 seconds...
    while start.elapsed().as_secs() < 50 {
        let result = sock.recv(&mut buf);
        match result {
            // If `recv` was successfull, print the number of bytes received.
            // The received data is stored in `buf`.
            Ok(num_bytes) => {
                println!("I received {} bytes! Message is {}", num_bytes, String::from_utf8_lossy(&buf[0..num_bytes]));
            }
            // If we get an error other than "would block", print the error.
            Err(ref err) if err.kind() != ErrorKind::WouldBlock => {
            // Do nothing otherwise.
                println!("Something went wrong: {}", err)
            }
            _ => {}
        }

        thread::sleep(Duration::from_millis(5));
    }

    println!("Done");
}
<commit_msg>remove dead dependencie from file<commit_after>// cargo run --example just_udp_socket
// echo -n "hello" > /dev/udp/0.0.0.0/5546 // this isn't working version

// this one requires socat, but works like a breeze
// echo -e "\xff" | socat - UDP-DATAGRAM:0.0.0.0:5546,broadcast

use std::net::UdpSocket;
use std::time::{Duration, Instant};
use std::io::ErrorKind;
use std::thread;

fn main() {
    let sock = UdpSocket::bind("0.0.0.0:5546").expect("Failed to bind socket");
    sock.set_nonblocking(true) .expect("Failed to enter non-blocking mode");

    // Poll for data every 5 milliseconds for 5 seconds.
    let start = Instant::now();
    let mut buf = [0u8; 1024];

    // for 50 seconds...
    while start.elapsed().as_secs() < 50 {
        let result = sock.recv(&mut buf);
        match result {
            // If `recv` was successfull, print the number of bytes received.
            // The received data is stored in `buf`.
            Ok(num_bytes) => {
                println!("I received {} bytes! Message is {}", num_bytes, String::from_utf8_lossy(&buf[0..num_bytes]));
            }
            // If we get an error other than "would block", print the error.
            Err(ref err) if err.kind() != ErrorKind::WouldBlock => {
            // Do nothing otherwise.
                println!("Something went wrong: {}", err)
            }
            _ => {}
        }

        thread::sleep(Duration::from_millis(5));
    }

    println!("Done");
}
<|endoftext|>


<commit_before>// cargo run --example just_udp_socket
// echo -n "hello" > /dev/udp/0.0.0.0/5546 // this isn't working version

// this one requires socat, but works like a breeze
// echo -e "\xff" | socat - UDP-DATAGRAM:0.0.0.0:5546,broadcast

use std::net::UdpSocket;
use std::time::{Duration, Instant};
use std::io::ErrorKind;
use std::thread;

fn main() {
    let sock = UdpSocket::bind("0.0.0.0:5546").expect("Failed to bind socket");
    sock.set_nonblocking(true) .expect("Failed to enter non-blocking mode");

    // Poll for data every 5 milliseconds for 5 seconds.
    let start = Instant::now();
    let mut buf = [0u8; 1024];

    // for 50 seconds...
    while start.elapsed().as_secs() < 50 {
        let result = sock.recv(&mut buf);
        match result {
            // If `recv` was successfull, print the number of bytes received.
            // The received data is stored in `buf`.
            Ok(num_bytes) => println!("I received {} bytes!", num_bytes),
            // If we get an error other than "would block", print the error.
            Err(ref err) if err.kind() != ErrorKind::WouldBlock => {
            // Do nothing otherwise.
                println!("Something went wrong: {}", err)
            }
            _ => {}
        }

        thread::sleep(Duration::from_millis(5));
    }

    println!("Done");
}
<commit_msg>build string from udp content<commit_after>// cargo run --example just_udp_socket
// echo -n "hello" > /dev/udp/0.0.0.0/5546 // this isn't working version

// this one requires socat, but works like a breeze
// echo -e "\xff" | socat - UDP-DATAGRAM:0.0.0.0:5546,broadcast

use std::net::UdpSocket;
use std::time::{Duration, Instant};
use std::io::ErrorKind;
use std::str;
use std::thread;

fn main() {
    let sock = UdpSocket::bind("0.0.0.0:5546").expect("Failed to bind socket");
    sock.set_nonblocking(true) .expect("Failed to enter non-blocking mode");

    // Poll for data every 5 milliseconds for 5 seconds.
    let start = Instant::now();
    let mut buf = [0u8; 1024];

    // for 50 seconds...
    while start.elapsed().as_secs() < 50 {
        let result = sock.recv(&mut buf);
        match result {
            // If `recv` was successfull, print the number of bytes received.
            // The received data is stored in `buf`.
            Ok(num_bytes) => {
                println!("I received {} bytes! Message is {}", num_bytes, String::from_utf8_lossy(&buf[0..num_bytes]));
            }
            // If we get an error other than "would block", print the error.
            Err(ref err) if err.kind() != ErrorKind::WouldBlock => {
            // Do nothing otherwise.
                println!("Something went wrong: {}", err)
            }
            _ => {}
        }

        thread::sleep(Duration::from_millis(5));
    }

    println!("Done");
}
<|endoftext|>


<commit_before>extern crate rand;

use std::cmp::Ordering;

#[derive(Debug, Clone)]
pub struct Gene {
    in_neuron_id: usize,
    out_neuron_id: usize,
    weight: f64,
    enabled: bool,
    innovation: u64,
}

impl Eq for Gene {}

impl PartialEq for Gene {
    fn eq(&self, other: &Gene) -> bool {
        self.in_neuron_id == other.in_neuron_id && self.out_neuron_id == other.out_neuron_id
    }
}

impl Ord for Gene {
    fn cmp(&self, other: &Gene) -> Ordering {
        if self == other {
            Ordering::Equal
        } else if self.in_neuron_id == other.in_neuron_id {
            if self.out_neuron_id > other.out_neuron_id {
                Ordering::Greater
            } else {
                Ordering::Less
            }
        } else if self.in_neuron_id > other.in_neuron_id {
            Ordering::Greater
        } else {
            Ordering::Less
        }
    }
}

impl PartialOrd for Gene {
    fn partial_cmp(&self, other: &Gene) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Gene {
    pub fn generate_weight() -> f64 {
        rand::random::<f64>() * 2f64 - 1f64
    }
}

impl Default for Gene {
    fn default() -> Gene {
        Gene {
            in_neuron_id: 1,
            out_neuron_id: 1,
            weight: Gene::generate_weight(),
            enabled: true,
        }
    }
}

#[cfg(test)]
mod tests {
    use neat::*;

    fn g(n_in: usize, n_out: usize) -> Gene {
        Gene {
            in_neuron_id: n_in,
            out_neuron_id: n_out,
            ..Gene::default()
        }
    }

    #[test]
    fn should_be_able_to_binary_search_for_a_gene() {
        let mut genome = vec![g(0, 1), g(0, 2), g(3, 2), g(2, 3), g(1, 5)];
        genome.sort();
        genome.binary_search(&g(0, 1)).unwrap();
        genome.binary_search(&g(0, 2)).unwrap();
        genome.binary_search(&g(1, 5)).unwrap();
        genome.binary_search(&g(2, 3)).unwrap();
        genome.binary_search(&g(3, 2)).unwrap();
    }
}
<commit_msg>fix/gene Redo earler edit. This PR shoudl eb rustfmt only<commit_after>extern crate rand;

use std::cmp::Ordering;

#[derive(Debug, Clone)]
pub struct Gene {
    pub in_neuron_id: usize,
    pub out_neuron_id: usize,
    pub weight: f64,
    pub enabled: bool,
}

impl Eq for Gene {}

impl PartialEq for Gene {
    fn eq(&self, other: &Gene) -> bool {
        self.in_neuron_id == other.in_neuron_id && self.out_neuron_id == other.out_neuron_id
    }
}

impl Ord for Gene {
    fn cmp(&self, other: &Gene) -> Ordering {
        if self == other {
            Ordering::Equal
        } else if self.in_neuron_id == other.in_neuron_id {
            if self.out_neuron_id > other.out_neuron_id {
                Ordering::Greater
            } else {
                Ordering::Less
            }
        } else if self.in_neuron_id > other.in_neuron_id {
            Ordering::Greater
        } else {
            Ordering::Less
        }
    }
}

impl PartialOrd for Gene {
    fn partial_cmp(&self, other: &Gene) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Gene {
    pub fn generate_weight() -> f64 {
        rand::random::<f64>() * 2f64 - 1f64
    }
}

impl Default for Gene {
    fn default() -> Gene {
        Gene {
            in_neuron_id: 1,
            out_neuron_id: 1,
            weight: Gene::generate_weight(),
            enabled: true,
        }
    }
}

#[cfg(test)]
mod tests {
    use neat::*;

    fn g(n_in: usize, n_out: usize) -> Gene {
        Gene {
            in_neuron_id: n_in,
            out_neuron_id: n_out,
            ..Gene::default()
        }
    }

    #[test]
    fn should_be_able_to_binary_search_for_a_gene() {
        let mut genome = vec![g(0, 1), g(0, 2), g(3, 2), g(2, 3), g(1, 5)];
        genome.sort();
        genome.binary_search(&g(0, 1)).unwrap();
        genome.binary_search(&g(0, 2)).unwrap();
        genome.binary_search(&g(1, 5)).unwrap();
        genome.binary_search(&g(2, 3)).unwrap();
        genome.binary_search(&g(3, 2)).unwrap();
    }
}
<|endoftext|>


<commit_before>use super::command::{Command, Query};
use super::command::Command::Normalize;
use std::collections::HashMap;
use types::normalizer_type::NormalizerType;
use command_query::CommandQuery;
use queryable::Queryable;
use command_line::CommandLine;
use commandable::Commandable;
use request_cancellable::RequestCancellable;
use request_timeoutable::RequestTimeoutable;
use std::fmt;
use std::str::FromStr;
use std::convert::AsRef;
use self::FlagType::{None, RemoveBlank, WithTypes, WithChecks, RemoveTokenizedDelimiter,
                     ExtFlagType};
use util;

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct NormalizeCommand {
    command: Command,
    normalizer: NormalizerType,
    string: String,
    arguments: HashMap<String, String>,
}

#[derive (Debug)]
pub enum FlagTypeError {
    Empty,
}

#[derive (Clone, PartialEq, Eq, Debug)]
pub enum FlagType {
    None,
    RemoveBlank,
    WithTypes,
    WithChecks,
    RemoveTokenizedDelimiter,
    /// For future extensibility.
    ExtFlagType(String),
}

impl AsRef<str> for FlagType {
    fn as_ref(&self) -> &str {
        match *self {
            None => "NONE",
            RemoveBlank => "REMOVE_BLANK",
            WithTypes => "WITH_TYPES",
            WithChecks => "WITH_CHECKS",
            RemoveTokenizedDelimiter => "REMOVE_TOKENIZED_DELIMITER",
            ExtFlagType(ref s) => s.as_ref(),
        }
    }
}

impl fmt::Display for FlagType {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str(match *self {
            None => "NONE",
            RemoveBlank => "REMOVE_BLANK",
            WithTypes => "WITH_TYPES",
            WithChecks => "WITH_CHECKS",
            RemoveTokenizedDelimiter => "REMOVE_TOKENIZED_DELIMITER",
            ExtFlagType(ref s) => s.as_ref(),
        })
    }
}

impl FromStr for FlagType {
    type Err = FlagTypeError;
    fn from_str(s: &str) -> Result<FlagType, FlagTypeError> {
        if s == "" {
            Err(FlagTypeError::Empty)
        } else {
            Ok(match s {
                "None" | "NONE" => None,
                "RemoveBlank" | "REMOVE_BLANK" => RemoveBlank,
                "WithTypes" | "WITH_TYPES" => WithTypes,
                "WithChecks" | "WITH_CHECKS" => WithChecks,
                "RemoveTokenizedDelimiter" | "REMOVE_TOKENIZED_DELIMITER" => {
                    RemoveTokenizedDelimiter
                }
                _ => ExtFlagType(s.to_owned()),
            })
        }
    }
}

impl Default for NormalizeCommand {
    fn default() -> NormalizeCommand {
        NormalizeCommand {
            command: Normalize,
            normalizer: NormalizerType::Auto,
            string: "".to_string(),
            arguments: HashMap::new(),
        }
    }
}

impl NormalizeCommand {
    pub fn new(normalizer: NormalizerType, string: String) -> NormalizeCommand {
        let default: NormalizeCommand = Default::default();
        NormalizeCommand {
            command: default.command,
            normalizer: normalizer,
            string: format!("\"{}\"", string),
            arguments: default.arguments,
        }
    }

    pub fn flags(mut self, flags: Vec<FlagType>) -> NormalizeCommand {
        let string = util::split_flags_vec(flags);
        self.arguments.insert("flags".to_string(), string.to_owned());
        self
    }

    pub fn build(self) -> (Command, Query) {
        let mut query: Query = vec![("normalizer".to_string(), format!("{}", self.normalizer)),
                                    ("string".to_string(), self.string)];
        for (key, value) in &self.arguments {
            query.push((key.to_owned(), value.to_owned()));
        }
        (self.command, query)
    }
}

impl Queryable for NormalizeCommand {
    fn to_query(self) -> String {
        let (command, query) = self.build();
        let mut command = CommandQuery::new(command, query);
        command.encode()
    }
}

impl Commandable for NormalizeCommand {
    fn to_command(self) -> String {
        let (command, query) = self.build();
        let mut command = CommandLine::new(command, query);
        command.encode()
    }
}

request_cancellable!(NormalizeCommand);
request_timeoutable!(NormalizeCommand);

#[cfg(test)]
mod test {
    use super::*;
    use std::collections::HashMap;
    use std::str::FromStr;
    use types::normalizer_type::NormalizerType;
    use command::Command::Normalize;
    use queryable::Queryable;
    use commandable::Commandable;

    #[test]
    fn test_from_str() {
        assert_eq!(FlagType::None, FromStr::from_str("None").unwrap());
        assert_eq!(FlagType::ExtFlagType("added-type".to_owned()),
                   FromStr::from_str("added-type").unwrap());
        let x: Result<FlagType, _> = FromStr::from_str("");
        if let Err(FlagTypeError::Empty) = x {
        } else {
            panic!("An empty input type is invalid!")
        }
    }

    #[test]
    fn test_fmt() {
        assert_eq!("NONE".to_owned(), format!("{}", FlagType::None));
        assert_eq!("REMOVE_BLANK".to_owned(),
                   format!("{}", FlagType::RemoveBlank));
        assert_eq!("WITH_TYPES".to_owned(), format!("{}", FlagType::WithTypes));
        assert_eq!("WITH_CHECKS".to_owned(),
                   format!("{}", FlagType::WithChecks));
        assert_eq!("REMOVE_TOKENIZED_DELIMITER".to_owned(),
                   format!("{}", FlagType::RemoveTokenizedDelimiter));
        assert_eq!("added-type".to_owned(),
                   format!("{}", FlagType::ExtFlagType("added-type".to_owned())));
    }

    #[test]
    fn test_as_str() {
        assert_eq!(FlagType::None.as_ref(), "NONE");
        assert_eq!(FlagType::RemoveBlank.as_ref(), "REMOVE_BLANK");
        assert_eq!(FlagType::WithTypes.as_ref(), "WITH_TYPES");
        assert_eq!(FlagType::WithChecks.as_ref(), "WITH_CHECKS");
        assert_eq!(FlagType::RemoveTokenizedDelimiter.as_ref(),
                   "REMOVE_TOKENIZED_DELIMITER");
        assert_eq!(FlagType::ExtFlagType("added-type".to_owned()).as_ref(),
                   "added-type");
    }

    #[test]
    fn test_new() {
        let normalize = NormalizeCommand::new(NormalizerType::Auto, "element".to_string());
        let expected = NormalizeCommand {
            command: Normalize,
            normalizer: NormalizerType::Auto,
            string: "\"element\"".to_string(),
            arguments: HashMap::new(),
        };
        assert_eq!(expected, normalize);
    }

    #[test]
    fn test_flags() {
        let normalize = NormalizeCommand::new(NormalizerType::Auto, "element".to_string())
                            .flags(vec![(FlagType::RemoveBlank), (FlagType::WithTypes)]);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("flags".to_string(), "REMOVE_BLANK|WITH_TYPES".to_string());
        let expected = NormalizeCommand {
            command: Normalize,
            normalizer: NormalizerType::Auto,
            string: "\"element\"".to_string(),
            arguments: arg.to_owned(),
        };
        assert_eq!(expected, normalize);
    }

    #[test]
    fn test_build() {
        let actual = NormalizeCommand::new(NormalizerType::Auto, "element".to_string()).build();
        let expected = (Normalize,
                        vec![("normalizer".to_string(),
                              format!("{}", format!("{}", NormalizerType::Auto))),
                             ("string".to_string(), "\"element\"".to_string())]);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_queryable() {
        let query = NormalizeCommand::new(NormalizerType::Auto, "element".to_string()).to_query();
        let url_encoded = "/d/normalize?normalizer=NormalizerAuto&string=%22element%22";
        assert_eq!(url_encoded.to_string(), query);
    }

    #[test]
    fn test_commandable() {
        let query = NormalizeCommand::new(NormalizerType::Auto, "element".to_string()).to_command();
        let cli_encoded = "normalize --normalizer NormalizerAuto --string \"element\"";
        assert_eq!(cli_encoded.to_string(), query);
    }
}
<commit_msg>Suppress clippy lint warnings<commit_after>use super::command::{Command, Query};
use super::command::Command::Normalize;
use std::collections::HashMap;
use types::normalizer_type::NormalizerType;
use command_query::CommandQuery;
use queryable::Queryable;
use command_line::CommandLine;
use commandable::Commandable;
use request_cancellable::RequestCancellable;
use request_timeoutable::RequestTimeoutable;
use std::fmt;
use std::str::FromStr;
use std::convert::AsRef;
use self::FlagType::{None, RemoveBlank, WithTypes, WithChecks, RemoveTokenizedDelimiter,
                     ExtFlagType};
use util;

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct NormalizeCommand {
    command: Command,
    normalizer: NormalizerType,
    string: String,
    arguments: HashMap<String, String>,
}

#[derive (Debug)]
pub enum FlagTypeError {
    Empty,
}

#[derive (Clone, PartialEq, Eq, Debug)]
pub enum FlagType {
    None,
    RemoveBlank,
    WithTypes,
    WithChecks,
    RemoveTokenizedDelimiter,
    /// For future extensibility.
    ExtFlagType(String),
}

impl AsRef<str> for FlagType {
    fn as_ref(&self) -> &str {
        match *self {
            None => "NONE",
            RemoveBlank => "REMOVE_BLANK",
            WithTypes => "WITH_TYPES",
            WithChecks => "WITH_CHECKS",
            RemoveTokenizedDelimiter => "REMOVE_TOKENIZED_DELIMITER",
            ExtFlagType(ref s) => s.as_ref(),
        }
    }
}

impl fmt::Display for FlagType {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str(match *self {
            None => "NONE",
            RemoveBlank => "REMOVE_BLANK",
            WithTypes => "WITH_TYPES",
            WithChecks => "WITH_CHECKS",
            RemoveTokenizedDelimiter => "REMOVE_TOKENIZED_DELIMITER",
            ExtFlagType(ref s) => s.as_ref(),
        })
    }
}

impl FromStr for FlagType {
    type Err = FlagTypeError;
    fn from_str(s: &str) -> Result<FlagType, FlagTypeError> {
        if s == "" {
            Err(FlagTypeError::Empty)
        } else {
            Ok(match s {
                "None" | "NONE" => None,
                "RemoveBlank" | "REMOVE_BLANK" => RemoveBlank,
                "WithTypes" | "WITH_TYPES" => WithTypes,
                "WithChecks" | "WITH_CHECKS" => WithChecks,
                "RemoveTokenizedDelimiter" | "REMOVE_TOKENIZED_DELIMITER" => {
                    RemoveTokenizedDelimiter
                }
                _ => ExtFlagType(s.to_owned()),
            })
        }
    }
}

impl Default for NormalizeCommand {
    fn default() -> NormalizeCommand {
        NormalizeCommand {
            command: Normalize,
            normalizer: NormalizerType::Auto,
            string: "".to_string(),
            arguments: HashMap::new(),
        }
    }
}

impl NormalizeCommand {
    pub fn new(normalizer: NormalizerType, string: String) -> NormalizeCommand {
        let default: NormalizeCommand = Default::default();
        NormalizeCommand {
            command: default.command,
            normalizer: normalizer,
            string: format!("\"{}\"", string),
            arguments: default.arguments,
        }
    }

    pub fn flags(mut self, flags: Vec<FlagType>) -> NormalizeCommand {
        let string = util::split_flags_vec(flags);
        self.arguments.insert("flags".to_string(), string.to_owned());
        self
    }

    pub fn build(self) -> (Command, Query) {
        let mut query: Query = vec![("normalizer".to_string(), format!("{}", self.normalizer)),
                                    ("string".to_string(), self.string)];
        for (key, value) in &self.arguments {
            query.push((key.to_owned(), value.to_owned()));
        }
        (self.command, query)
    }
}

impl Queryable for NormalizeCommand {
    fn to_query(self) -> String {
        let (command, query) = self.build();
        let mut command = CommandQuery::new(command, query);
        command.encode()
    }
}

impl Commandable for NormalizeCommand {
    fn to_command(self) -> String {
        let (command, query) = self.build();
        let mut command = CommandLine::new(command, query);
        command.encode()
    }
}

request_cancellable!(NormalizeCommand);
request_timeoutable!(NormalizeCommand);

#[cfg(test)]
mod test {
    use super::*;
    use std::collections::HashMap;
    use std::str::FromStr;
    use types::normalizer_type::NormalizerType;
    use command::Command::Normalize;
    use queryable::Queryable;
    use commandable::Commandable;

    #[test]
    fn test_from_str() {
        assert_eq!(FlagType::None, FromStr::from_str("None").unwrap());
        assert_eq!(FlagType::ExtFlagType("added-type".to_owned()),
                   FromStr::from_str("added-type").unwrap());
        let x: Result<FlagType, _> = FromStr::from_str("");
        if let Err(FlagTypeError::Empty) = x {
        } else {
            panic!("An empty input type is invalid!")
        }
    }

    #[test]
    fn test_fmt() {
        assert_eq!("NONE".to_owned(), format!("{}", FlagType::None));
        assert_eq!("REMOVE_BLANK".to_owned(),
                   format!("{}", FlagType::RemoveBlank));
        assert_eq!("WITH_TYPES".to_owned(), format!("{}", FlagType::WithTypes));
        assert_eq!("WITH_CHECKS".to_owned(),
                   format!("{}", FlagType::WithChecks));
        assert_eq!("REMOVE_TOKENIZED_DELIMITER".to_owned(),
                   format!("{}", FlagType::RemoveTokenizedDelimiter));
        assert_eq!("added-type".to_owned(),
                   format!("{}", FlagType::ExtFlagType("added-type".to_owned())));
    }

    #[test]
    fn test_as_str() {
        assert_eq!(FlagType::None.as_ref(), "NONE");
        assert_eq!(FlagType::RemoveBlank.as_ref(), "REMOVE_BLANK");
        assert_eq!(FlagType::WithTypes.as_ref(), "WITH_TYPES");
        assert_eq!(FlagType::WithChecks.as_ref(), "WITH_CHECKS");
        assert_eq!(FlagType::RemoveTokenizedDelimiter.as_ref(),
                   "REMOVE_TOKENIZED_DELIMITER");
        assert_eq!(FlagType::ExtFlagType("added-type".to_owned()).as_ref(),
                   "added-type");
    }

    #[test]
    fn test_new() {
        let normalize = NormalizeCommand::new(NormalizerType::Auto, "element".to_string());
        let expected = NormalizeCommand {
            command: Normalize,
            normalizer: NormalizerType::Auto,
            string: "\"element\"".to_string(),
            arguments: HashMap::new(),
        };
        assert_eq!(expected, normalize);
    }

    #[test]
    fn test_flags() {
        let normalize = NormalizeCommand::new(NormalizerType::Auto, "element".to_string())
                            .flags(vec![(FlagType::RemoveBlank), (FlagType::WithTypes)]);
        let mut arg: HashMap<String, String> = HashMap::new();
        arg.insert("flags".to_string(), "REMOVE_BLANK|WITH_TYPES".to_string());
        let expected = NormalizeCommand {
            command: Normalize,
            normalizer: NormalizerType::Auto,
            string: "\"element\"".to_string(),
            arguments: arg.to_owned(),
        };
        assert_eq!(expected, normalize);
    }

    #[test]
    fn test_build() {
        let actual = NormalizeCommand::new(NormalizerType::Auto, "element".to_string()).build();
        let expected = (Normalize,
                        vec![("normalizer".to_string(),
                              format!("{}", NormalizerType::Auto)),
                             ("string".to_string(), "\"element\"".to_string())]);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_queryable() {
        let query = NormalizeCommand::new(NormalizerType::Auto, "element".to_string()).to_query();
        let url_encoded = "/d/normalize?normalizer=NormalizerAuto&string=%22element%22";
        assert_eq!(url_encoded.to_string(), query);
    }

    #[test]
    fn test_commandable() {
        let query = NormalizeCommand::new(NormalizerType::Auto, "element".to_string()).to_command();
        let cli_encoded = "normalize --normalizer NormalizerAuto --string \"element\"";
        assert_eq!(cli_encoded.to_string(), query);
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2017 Gilad Naaman
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

/// Macro to create a local `base_ptr` raw pointer of the given type, avoiding UB as
/// much as is possible currently.
#[cfg(maybe_uninit)]
#[macro_export]
#[doc(hidden)]
macro_rules! _memoffset__let_base_ptr {
    ($name:ident, $type:path) => {
        // No UB here, and the pointer does not dangle, either.
        // But we have to make sure that `uninit` lives long enough,
        // so it has to be in the same scope as `$name`. That's why
        // `let_base_ptr` declares a variable (several, actually)
        // instead of returning one.
        let uninit = $crate::mem::MaybeUninit::<$type>::uninit();
        // Transmuting for const-compatibility.
        #[allow(unused_unsafe)] // for when the macro is used in an unsafe block
        let $name: *const $type = unsafe { $crate::mem::transmute(&uninit) };
    };
}
#[cfg(not(maybe_uninit))]
#[macro_export]
#[doc(hidden)]
macro_rules! _memoffset__let_base_ptr {
    ($name:ident, $type:path) => {
        // No UB right here, but we will later dereference this pointer to
        // offset into a field, and that is UB when the pointer is dangling.
        let $name = $crate::mem::align_of::<$type>() as *const $type;
    };
}

/// Calculates the offset of the specified field from the start of the struct.
///
/// ## Examples
/// ```
/// #[macro_use]
/// extern crate memoffset;
///
/// #[repr(C, packed)]
/// struct Foo {
///     a: u32,
///     b: u64,
///     c: [u8; 5]
/// }
///
/// fn main() {
///     assert_eq!(offset_of!(Foo, a), 0);
///     assert_eq!(offset_of!(Foo, b), 4);
/// }
/// ```
#[cfg(not(feature = "unstable_const"))]
#[macro_export(local_inner_macros)]
macro_rules! offset_of {
    ($parent:path, $field:tt) => {{
        // Get a base pointer.
        _memoffset__let_base_ptr!(base_ptr, $parent);
        // Get field pointer.
        let field_ptr = raw_field!(base_ptr, $parent, $field);
        // Compute offset, as integers to make the fewest assumptions.
        (field_ptr as usize) - (base_ptr as usize)
    }};
}

#[cfg(feature = "unstable_const")]
#[macro_export(local_inner_macros)]
macro_rules! offset_of {
    ($parent:path, $field:tt) => {{
        // Get a base pointer.
        _memoffset__let_base_ptr!(base_ptr, $parent);
        // Get field pointer.
        let field_ptr = raw_field!(base_ptr, $parent, $field);
        // Compute offset, with unstable `offset_from` for const-compatibility.
        // (Requires the pointers to not dangle, but we already need that for `raw_field!` anyway.)
        unsafe { (field_ptr as *const u8).offset_from(base_ptr as *const u8) as usize }
    }};
}

#[cfg(test)]
mod tests {
    #[test]
    fn offset_simple() {
        #[repr(C)]
        struct Foo {
            a: u32,
            b: [u8; 2],
            c: i64,
        }

        assert_eq!(offset_of!(Foo, a), 0);
        assert_eq!(offset_of!(Foo, b), 4);
        assert_eq!(offset_of!(Foo, c), 8);
    }

    #[test]
    #[cfg_attr(miri, ignore)] // this creates unaligned references
    fn offset_simple_packed() {
        #[repr(C, packed)]
        struct Foo {
            a: u32,
            b: [u8; 2],
            c: i64,
        }

        assert_eq!(offset_of!(Foo, a), 0);
        assert_eq!(offset_of!(Foo, b), 4);
        assert_eq!(offset_of!(Foo, c), 6);
    }

    #[test]
    fn tuple_struct() {
        #[repr(C)]
        struct Tup(i32, i32);

        assert_eq!(offset_of!(Tup, 0), 0);
        assert_eq!(offset_of!(Tup, 1), 4);
    }

    #[test]
    fn path() {
        mod sub {
            #[repr(C)]
            pub struct Foo {
                pub x: u32,
            }
        }

        assert_eq!(offset_of!(sub::Foo, x), 0);
    }

    #[test]
    fn inside_generic_method() {
        struct Pair<T, U>(T, U);

        fn foo<T, U>(_: Pair<T, U>) -> usize {
            offset_of!(Pair<T, U>, 1)
        }

        assert_eq!(foo(Pair(0, 0)), 4);
    }

    #[test]
    fn test_raw_field() {
        #[repr(C)]
        struct Foo {
            a: u32,
            b: [u8; 2],
            c: i64,
        }

        let f: Foo = Foo {
            a: 0,
            b: [0, 0],
            c: 0,
        };
        let f_ptr = &f as *const _;
        assert_eq!(f_ptr as usize + 0, raw_field!(f_ptr, Foo, a) as usize);
        assert_eq!(f_ptr as usize + 4, raw_field!(f_ptr, Foo, b) as usize);
        assert_eq!(f_ptr as usize + 8, raw_field!(f_ptr, Foo, c) as usize);
    }

    #[cfg(feature = "unstable_const")]
    #[test]
    fn const_offset() {
        #[repr(C)]
        struct Foo {
            a: u32,
            b: [u8; 2],
            c: i64,
        }

        assert_eq!([0; offset_of!(Foo, b)].len(), 4);
    }
}
<commit_msg>factor difference between const and non-const into sub-macro<commit_after>// Copyright (c) 2017 Gilad Naaman
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

/// Macro to create a local `base_ptr` raw pointer of the given type, avoiding UB as
/// much as is possible currently.
#[cfg(maybe_uninit)]
#[macro_export]
#[doc(hidden)]
macro_rules! _memoffset__let_base_ptr {
    ($name:ident, $type:path) => {
        // No UB here, and the pointer does not dangle, either.
        // But we have to make sure that `uninit` lives long enough,
        // so it has to be in the same scope as `$name`. That's why
        // `let_base_ptr` declares a variable (several, actually)
        // instead of returning one.
        let uninit = $crate::mem::MaybeUninit::<$type>::uninit();
        // Transmuting for const-compatibility.
        #[allow(unused_unsafe)] // for when the macro is used in an unsafe block
        let $name: *const $type = unsafe { $crate::mem::transmute(&uninit) };
    };
}
#[cfg(not(maybe_uninit))]
#[macro_export]
#[doc(hidden)]
macro_rules! _memoffset__let_base_ptr {
    ($name:ident, $type:path) => {
        // No UB right here, but we will later dereference this pointer to
        // offset into a field, and that is UB because the pointer is dangling.
        let $name = $crate::mem::align_of::<$type>() as *const $type;
    };
}

/// Macro to compute the distance between two pointers.
#[cfg(feature = "unstable_const")]
#[macro_export]
#[doc(hidden)]
macro_rules! _memoffset_offset_from {
    ($field:expr, $base:expr) => {
        // Compute offset, with unstable `offset_from` for const-compatibility.
        // (Requires the pointers to not dangle, but we already need that for `raw_field!` anyway.)
        unsafe { ($field as *const u8).offset_from($base as *const u8) as usize }
    }
}
#[cfg(not(feature = "unstable_const"))]
#[macro_export]
#[doc(hidden)]
macro_rules! _memoffset_offset_from {
    ($field:expr, $base:expr) => {
        // Compute offset.
        ($field as usize) - ($base as usize)
    }
}

/// Calculates the offset of the specified field from the start of the struct.
///
/// ## Examples
/// ```
/// #[macro_use]
/// extern crate memoffset;
///
/// #[repr(C, packed)]
/// struct Foo {
///     a: u32,
///     b: u64,
///     c: [u8; 5]
/// }
///
/// fn main() {
///     assert_eq!(offset_of!(Foo, a), 0);
///     assert_eq!(offset_of!(Foo, b), 4);
/// }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! offset_of {
    ($parent:path, $field:tt) => {{
        // Get a base pointer (non-dangling if rustc supports `MaybeUninit`).
        _memoffset__let_base_ptr!(base_ptr, $parent);
        // Get field pointer.
        let field_ptr = raw_field!(base_ptr, $parent, $field);
        // Compute offset.
        _memoffset_offset_from!(field_ptr, base_ptr)
    }};
}

#[cfg(test)]
mod tests {
    #[test]
    fn offset_simple() {
        #[repr(C)]
        struct Foo {
            a: u32,
            b: [u8; 2],
            c: i64,
        }

        assert_eq!(offset_of!(Foo, a), 0);
        assert_eq!(offset_of!(Foo, b), 4);
        assert_eq!(offset_of!(Foo, c), 8);
    }

    #[test]
    #[cfg_attr(miri, ignore)] // this creates unaligned references
    fn offset_simple_packed() {
        #[repr(C, packed)]
        struct Foo {
            a: u32,
            b: [u8; 2],
            c: i64,
        }

        assert_eq!(offset_of!(Foo, a), 0);
        assert_eq!(offset_of!(Foo, b), 4);
        assert_eq!(offset_of!(Foo, c), 6);
    }

    #[test]
    fn tuple_struct() {
        #[repr(C)]
        struct Tup(i32, i32);

        assert_eq!(offset_of!(Tup, 0), 0);
        assert_eq!(offset_of!(Tup, 1), 4);
    }

    #[test]
    fn path() {
        mod sub {
            #[repr(C)]
            pub struct Foo {
                pub x: u32,
            }
        }

        assert_eq!(offset_of!(sub::Foo, x), 0);
    }

    #[test]
    fn inside_generic_method() {
        struct Pair<T, U>(T, U);

        fn foo<T, U>(_: Pair<T, U>) -> usize {
            offset_of!(Pair<T, U>, 1)
        }

        assert_eq!(foo(Pair(0, 0)), 4);
    }

    #[test]
    fn test_raw_field() {
        #[repr(C)]
        struct Foo {
            a: u32,
            b: [u8; 2],
            c: i64,
        }

        let f: Foo = Foo {
            a: 0,
            b: [0, 0],
            c: 0,
        };
        let f_ptr = &f as *const _;
        assert_eq!(f_ptr as usize + 0, raw_field!(f_ptr, Foo, a) as usize);
        assert_eq!(f_ptr as usize + 4, raw_field!(f_ptr, Foo, b) as usize);
        assert_eq!(f_ptr as usize + 8, raw_field!(f_ptr, Foo, c) as usize);
    }

    #[cfg(feature = "unstable_const")]
    #[test]
    fn const_offset() {
        #[repr(C)]
        struct Foo {
            a: u32,
            b: [u8; 2],
            c: i64,
        }

        assert_eq!([0; offset_of!(Foo, b)].len(), 4);
    }
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate lazy_static;
extern crate quickcheck;

use std::path::PathBuf;
use quickcheck::{quickcheck};

extern crate hyphenation;
use hyphenation::{load, Language, Corpus, Hyphenation, Standard};

fn fiat_io(lang: Language) -> Corpus {
    let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    path.push("patterns");

    hyphenation::set_pattern_folder(path.as_path());
    load::language(lang).unwrap()
}

lazy_static! {
    static ref EN_US: Corpus = fiat_io(Language::English_US);
}

#[test]
fn collected_equals_original() {
    fn property(original: String) -> bool {
        let collected: String = original.hyphenate(&EN_US).collect();

        collected == original
    }

    quickcheck(property as fn(String) -> bool);
}

#[test]
fn opportunities_within_bounds() {
    fn property(s: String) -> bool {
        let os = s.opportunities(&EN_US);
        let l = s.len();

        os.iter().all(|&i| i < l)
    }

    quickcheck(property as fn(String) -> bool);
}

#[test]
fn punctuated_count() {
    fn property(s: String) -> bool {
        let l = s.chars().count();
        let os = s.opportunities(&EN_US);
        let h: String = s.hyphenate(&EN_US).punctuate().collect();

        h.chars().count() == l + os.len()
    }

    quickcheck(property as fn(String) -> bool);
}

#[test]
fn basics() {
    let h1: Standard = "hyphenation".hyphenate(&EN_US);
    let h2: Standard = "project".hyphenate(&EN_US);
    let h3: Standard = "hypha".hyphenate(&EN_US);

    let v1: Vec<&str> = h1.clone().collect();
    let v2: Vec<&str> = h2.clone().collect();
    let v3: Vec<&str> = h3.clone().collect();
    assert_eq!(v1, vec!["hy", "phen", "ation"]);
    assert_eq!(v2, vec!["project"]);
    assert_eq!(v3, vec!["hy", "pha"]);

    let s1: String = h1.punctuate().collect();
    assert_eq!(s1, "hy\u{ad}phen\u{ad}ation".to_owned());
}
<commit_msg>Add quickcheck test for hyphenation boundaries<commit_after>#[macro_use]
extern crate lazy_static;
extern crate quickcheck;

use std::path::PathBuf;
use quickcheck::{quickcheck, TestResult};

extern crate hyphenation;
use hyphenation::{load, Language, Corpus, Hyphenation, Standard};

fn fiat_io(lang: Language) -> Corpus {
    let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    path.push("patterns");

    hyphenation::set_pattern_folder(path.as_path());
    load::language(lang).unwrap()
}

lazy_static! {
    static ref EN_US: Corpus = fiat_io(Language::English_US);
}

#[test]
fn collected_equals_original() {
    fn property(original: String) -> bool {
        let collected: String = original.hyphenate(&EN_US).collect();

        collected == original
    }

    quickcheck(property as fn(String) -> bool);
}

#[test]
fn opportunities_within_bounds() {
    fn property(s: String) -> bool {
        let os = s.opportunities(&EN_US);
        let l = s.len();

        os.iter().all(|&i| i < l)
    }

    quickcheck(property as fn(String) -> bool);
}

#[test]
fn punctuated_count() {
    fn property(s: String) -> bool {
        let l = s.chars().count();
        let os = s.opportunities(&EN_US);
        let h: String = s.hyphenate(&EN_US).punctuate().collect();

        h.chars().count() == l + os.len()
    }

    quickcheck(property as fn(String) -> bool);
}

#[test]
fn hyphenation_bounds() {
    fn property(s: String) -> TestResult {
        let ci: Vec<_> = s.char_indices().collect();
        let (l_min, r_min) = (&EN_US.left_min, &EN_US.right_min);
        let s_len = ci.len();
        if s_len < l_min + r_min {
            return TestResult::discard();
        }

        let os = s.opportunities(&EN_US);
        let ((l, _), (r, _)) = (ci[l_min - 1], ci[s_len - r_min]);
        let within_bounds = |&i| i > l && i <= r;

        TestResult::from_bool(os.iter().all(within_bounds))
    }

    quickcheck(property as fn(String) -> TestResult);
}

#[test]
fn basics() {
    let h1: Standard = "hyphenation".hyphenate(&EN_US);
    let h2: Standard = "project".hyphenate(&EN_US);
    let h3: Standard = "hypha".hyphenate(&EN_US);

    let v1: Vec<&str> = h1.clone().collect();
    let v2: Vec<&str> = h2.clone().collect();
    let v3: Vec<&str> = h3.clone().collect();
    assert_eq!(v1, vec!["hy", "phen", "ation"]);
    assert_eq!(v2, vec!["project"]);
    assert_eq!(v3, vec!["hy", "pha"]);

    let s1: String = h1.punctuate().collect();
    assert_eq!(s1, "hy\u{ad}phen\u{ad}ation".to_owned());
}
<|endoftext|>


<commit_before>extern crate codespawn;

#[test]
fn check_from_xml() {
    let raw_code = codespawn::from_xml("examples/sample.xml").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.to_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    let _ = raw_code.to_rust().to_file("tests/sample.rst");
    let _ = raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
fn check_from_json() {
    let raw_code = codespawn::from_json("examples/sample.json").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.to_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    let _ = raw_code.to_rust().to_file("tests/sample.rst");
    let _ = raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
#[should_panic]
fn check_from_xml_fail() {
    let _ = codespawn::from_xml("foobar").unwrap(); }

#[test]
#[should_panic]
fn check_from_json_fail() {
    let _ = codespawn::from_json("foobar").unwrap(); }

#[test]
#[should_panic]
fn check_from_xml_fail_cfg() {
    let _ = codespawn::from_xml_str("<config file=\"foobar\"/><var name=\"x\" type=\"int\"/>").unwrap(); }

#[test]
#[should_panic]
fn check_from_json_fail_cfg() {
    let _ = codespawn::from_json_str("{\"config\": { \"file\": \"foobar\" }, \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap(); }

#[test]
#[should_panic]
fn check_from_xml_fail_malformed() {
    let _ = codespawn::from_xml_str("<config file=\"foobar\"/>var name=\"x\" type=\"int\"/>").unwrap(); }

#[test]
#[should_panic]
fn check_from_json_fail_malformed() {
    let _ = codespawn::from_json_str("{\"config\": { \"file\": \"examples/rust.json\" } \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap(); }

#[test]
#[should_panic]
fn check_from_xml_fail_enum() {
    let rc = codespawn::from_xml_str("<enum name=\"Foo\"><func name=\"x\" type=\"int\"/></enum>").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_enum() {
    let rc = codespawn::from_json_str("{\"enum\":{ \"name\":\"Foo\",\"func\": { \"name\":\"x\",\"type\":\"int\"}}}").unwrap();
    rc.to_cpp().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_func() {
    let rc = codespawn::from_xml_str("<func name=\"x\" type=\"int\"><enum name=\"Foo\"></enum></func>").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_func() {
    let rc = codespawn::from_json_str("{\"func\": {\"name\":\"x\",\"type\":\"int\",\"enum\": {\"name\":\"Foo\"}}}").unwrap();
    rc.to_cpp().to_string(); }

#[test]

fn check_from_xml_fail_bitflags() {
    let rc = codespawn::from_xml_str("<struct name=\"Foo\"><bitflags name=\"x\" type=\"int\"><enum></enum></bitflags></struct>").unwrap();
    rc.to_rust().to_string(); }

#[test]

fn check_from_json_fail_bitflags() {
    let rc = codespawn::from_json_str("{\"struct\":{ \"name\":\"Foo\",\"bitflags\": { \"name\":\"x\",\"type\":\"int\", \"enum\": { \"name\": \"foonum\" }}}}").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_malformed_cfg() {
    let _ = codespawn::from_xml_str("<config file=\"tests/malformed_cfg.xml\"/><var name=\"x\" type=\"int\"/>").unwrap(); }

#[test]
#[should_panic]
fn check_write_file() {
    let raw_code = codespawn::from_xml("examples/sample.xml").unwrap();
    raw_code.to_cpp().to_file("").unwrap(); }
<commit_msg>fixed broken tests<commit_after>extern crate codespawn;

#[test]
fn check_from_xml() {
    let raw_code = codespawn::from_xml("examples/sample.xml").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.to_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    let _ = raw_code.to_rust().to_file("tests/sample.rst");
    let _ = raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
fn check_from_json() {
    let raw_code = codespawn::from_json("examples/sample.json").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.to_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    let _ = raw_code.to_rust().to_file("tests/sample.rst");
    let _ = raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
#[should_panic]
fn check_from_xml_fail() {
    let _ = codespawn::from_xml("foobar").unwrap(); }

#[test]
#[should_panic]
fn check_from_json_fail() {
    let _ = codespawn::from_json("foobar").unwrap(); }

#[test]
#[should_panic]
fn check_from_xml_fail_cfg() {
    let _ = codespawn::from_xml_str("<config file=\"foobar\"/><var name=\"x\" type=\"int\"/>").unwrap(); }

#[test]
#[should_panic]
fn check_from_json_fail_cfg() {
    let _ = codespawn::from_json_str("{\"config\": { \"file\": \"foobar\" }, \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap(); }

#[test]
#[should_panic]
fn check_from_xml_fail_malformed() {
    let _ = codespawn::from_xml_str("<config file=\"foobar\"/>var name=\"x\" type=\"int\"/>").unwrap(); }

#[test]
#[should_panic]
fn check_from_json_fail_malformed() {
    let _ = codespawn::from_json_str("{\"config\": { \"file\": \"examples/rust.json\" } \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap(); }

#[test]
#[should_panic]
fn check_from_xml_fail_enum() {
    let rc = codespawn::from_xml_str("<enum name=\"Foo\"><func name=\"x\" type=\"int\"/></enum>").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_enum() {
    let rc = codespawn::from_json_str("{\"enum\":{ \"name\":\"Foo\",\"func\": { \"name\":\"x\",\"type\":\"int\"}}}").unwrap();
    rc.to_cpp().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_func() {
    let rc = codespawn::from_xml_str("<func name=\"x\" type=\"int\"><enum name=\"Foo\"></enum></func>").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_func() {
    let rc = codespawn::from_json_str("{\"func\": {\"name\":\"x\",\"type\":\"int\",\"enum\": {\"name\":\"Foo\"}}}").unwrap();
    rc.to_cpp().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_bitflags() {
    let rc = codespawn::from_xml_str("<struct name=\"Foo\"><bitflags name=\"x\" type=\"int\"><enum></enum></bitflags></struct>").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_bitflags() {
    let rc = codespawn::from_json_str("{\"struct\":{ \"name\":\"Foo\",\"bitflags\": { \"name\":\"x\",\"type\":\"int\", \"enum\": { \"name\": \"foonum\" }}}}").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_malformed_cfg() {
    let _ = codespawn::from_xml_str("<config file=\"tests/malformed_cfg.xml\"/><var name=\"x\" type=\"int\"/>").unwrap(); }

#[test]
#[should_panic]
fn check_write_file() {
    let raw_code = codespawn::from_xml("examples/sample.xml").unwrap();
    raw_code.to_cpp().to_file("").unwrap(); }
<|endoftext|>


<commit_before>extern crate pihex;
use pihex::*;

const TEST_CASES: &[(u32, &str)] = &[(0, "243f"),
                                     (1, "43f6"),
                                     (2, "3f6a"),
                                     (3, "f6a8"),
                                     (4, "6a88"),
                                     (8, "85a3"),
                                     (12, "08d3"),
                                     (96, "c0ac"),
                                     (128, "9216"),
                                     (1024, "25d4"),
                                     (3704, "34c6"),
                                     (4096, "5a04"),
                                     (4527, "e4f3"),
                                     (8192, "77af"),
                                     (2090, "e674"),
                                     (2944, "5094"),
                                     (11027, "e70f"),
                                     (11742, "41fb"),
                                     (15367, "0c67")];

#[test]
fn pihex_test() {
    for &(d, hex) in TEST_CASES {
        assert_eq!(bbp::pihex(d), hex);
    }
}

#[test]
fn pihex_bellard_test() {
    for &(d, hex) in TEST_CASES {
        assert_eq!(bellard::pihex(d), hex);
    }
}

#[test]
fn pihex_bellard_pihex_test() {
    for i in 0..1000 {
        assert_eq!((i, bbp::pihex(i)), (i, bellard::pihex(i)));
    }
}
<commit_msg>rename test functions<commit_after>extern crate pihex;
use pihex::*;

const TEST_CASES: &[(u32, &str)] = &[(0, "243f"),
                                     (1, "43f6"),
                                     (2, "3f6a"),
                                     (3, "f6a8"),
                                     (4, "6a88"),
                                     (8, "85a3"),
                                     (12, "08d3"),
                                     (96, "c0ac"),
                                     (128, "9216"),
                                     (1024, "25d4"),
                                     (3704, "34c6"),
                                     (4096, "5a04"),
                                     (4527, "e4f3"),
                                     (8192, "77af"),
                                     (2090, "e674"),
                                     (2944, "5094"),
                                     (11027, "e70f"),
                                     (11742, "41fb"),
                                     (15367, "0c67")];

#[test]
fn bbp_pihex_test() {
    for &(d, hex) in TEST_CASES {
        assert_eq!(bbp::pihex(d), hex);
    }
}

#[test]
fn pihex_bellard_test() {
    for &(d, hex) in TEST_CASES {
        assert_eq!(bellard::pihex(d), hex);
    }
}

#[test]
fn bbp_pihex_bellard_pihex_test() {
    for i in 0..1000 {
        assert_eq!((i, bbp::pihex(i)), (i, bellard::pihex(i)));
    }
}
<|endoftext|>


<commit_before>
extern crate ndarray;
#[macro_use]
extern crate ndarray_linalg;
extern crate num_traits;

use std::cmp::min;
use ndarray::*;
use ndarray_linalg::*;
use num_traits::Float;

fn test(a: Array2<f64>, n: usize, m: usize) {
    let answer = a.clone();
    println!("a = \n{:?}", &a);
    let (u, s, vt): (_, Array1<_>, _) = a.svd(true, true).unwrap();
    let u: Array2<_> = u.unwrap();
    let vt: Array2<_> = vt.unwrap();
    println!("u = \n{:?}", &u);
    println!("s = \n{:?}", &s);
    println!("v = \n{:?}", &vt);
    let mut sm = Array::zeros((n, m));
    for i in 0..min(n, m) {
        sm[(i, i)] = s[i];
    }
    assert_close_l2!(&u.dot(&sm).dot(&vt), &answer, 1e-7);
}

#[test]
fn svd_square() {
    let a = random((3, 3));
    test(a, 3, 3);
}

#[test]
fn svd_square_t() {
    let a = random((3, 3).f());
    test(a, 3, 3);
}

#[test]
fn svd_3x4() {
    let a = random((3, 4));
    test(a, 3, 4);
}

#[test]
fn svd_3x4_t() {
    let a = random((3, 4).f());
    test(a, 3, 4);
}

#[test]
fn svd_4x3() {
    let a = random((4, 3));
    test(a, 4, 3);
}

#[test]
fn svd_4x3_t() {
    let a = random((4, 3).f());
    test(a, 4, 3);
}
<commit_msg>Fix tests<commit_after>
extern crate ndarray;
#[macro_use]
extern crate ndarray_linalg;

use std::cmp::min;
use ndarray::*;
use ndarray_linalg::*;

fn test(a: Array2<f64>, n: usize, m: usize) {
    let answer = a.clone();
    println!("a = \n{:?}", &a);
    let (u, s, vt): (_, Array1<_>, _) = a.svd(true, true).unwrap();
    let u: Array2<_> = u.unwrap();
    let vt: Array2<_> = vt.unwrap();
    println!("u = \n{:?}", &u);
    println!("s = \n{:?}", &s);
    println!("v = \n{:?}", &vt);
    let mut sm = Array::zeros((n, m));
    for i in 0..min(n, m) {
        sm[(i, i)] = s[i];
    }
    assert_close_l2!(&u.dot(&sm).dot(&vt), &answer, 1e-7);
}

#[test]
fn svd_square() {
    let a = random((3, 3));
    test(a, 3, 3);
}

#[test]
fn svd_square_t() {
    let a = random((3, 3).f());
    test(a, 3, 3);
}

#[test]
fn svd_3x4() {
    let a = random((3, 4));
    test(a, 3, 4);
}

#[test]
fn svd_3x4_t() {
    let a = random((3, 4).f());
    test(a, 3, 4);
}

#[test]
fn svd_4x3() {
    let a = random((4, 3));
    test(a, 4, 3);
}

#[test]
fn svd_4x3_t() {
    let a = random((4, 3).f());
    test(a, 4, 3);
}
<|endoftext|>