<commit_before>extern crate cargotest;
extern crate hamcrest;

use std::fs;
use std::env;

use cargotest::{is_nightly, rustc_host};
use cargotest::support::{project, execs};
use hamcrest::assert_that;

#[test]
fn plugin_to_the_max() {
    if !is_nightly() { return }

    let foo = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [lib]
            name = "foo_lib"

            [dependencies.bar]
            path = "../bar"
        "#)
        .file("src/main.rs", r#"
            #![feature(plugin)]
            #![plugin(bar)]
            extern crate foo_lib;

            fn main() { foo_lib::foo(); }
        "#)
        .file("src/foo_lib.rs", r#"
            #![feature(plugin)]
            #![plugin(bar)]

            pub fn foo() {}
        "#)
        .build();
    let _bar = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [lib]
            name = "bar"
            plugin = true

            [dependencies.baz]
            path = "../baz"
        "#)
        .file("src/lib.rs", r#"
            #![feature(plugin_registrar, rustc_private)]

            extern crate rustc_plugin;
            extern crate baz;

            use rustc_plugin::Registry;

            #[plugin_registrar]
            pub fn foo(_reg: &mut Registry) {
                println!("{}", baz::baz());
            }
        "#)
        .build();
    let _baz = project("baz")
        .file("Cargo.toml", r#"
            [package]
            name = "baz"
            version = "0.0.1"
            authors = []

            [lib]
            name = "baz"
            crate_type = ["dylib"]
        "#)
        .file("src/lib.rs", "pub fn baz() -> i32 { 1 }")
        .build();

    assert_that(foo.cargo("build"),
                execs().with_status(0));
    assert_that(foo.cargo("doc"),
                execs().with_status(0));
}

#[test]
fn plugin_with_dynamic_native_dependency() {
    if !is_nightly() { return }

    let workspace = project("ws")
        .file("Cargo.toml", r#"
            [workspace]
            members = ["builder", "foo"]
        "#)
        .build();

    let build = project("ws/builder")
        .file("Cargo.toml", r#"
            [package]
            name = "builder"
            version = "0.0.1"
            authors = []

            [lib]
            name = "builder"
            crate-type = ["dylib"]
        "#)
        .file("src/lib.rs", r#"
            #[no_mangle]
            pub extern fn foo() {}
        "#)
        .build();

    let foo = project("ws/foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies.bar]
            path = "bar"
        "#)
        .file("src/main.rs", r#"
            #![feature(plugin)]
            #![plugin(bar)]

            fn main() {}
        "#)
        .file("bar/Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []
            build = 'build.rs'

            [lib]
            name = "bar"
            plugin = true
        "#)
        .file("bar/build.rs", r#"
            use std::path::PathBuf;
            use std::env;

            fn main() {
                let src = PathBuf::from(env::var("SRC").unwrap());
                println!("cargo:rustc-flags=-L {}/deps", src.parent().unwrap().display());
            }
        "#)
        .file("bar/src/lib.rs", r#"
            #![feature(plugin_registrar, rustc_private)]
            extern crate rustc_plugin;

            use rustc_plugin::Registry;

            #[cfg_attr(not(target_env = "msvc"), link(name = "builder"))]
            #[cfg_attr(target_env = "msvc", link(name = "builder.dll"))]
            extern { fn foo(); }

            #[plugin_registrar]
            pub fn bar(_reg: &mut Registry) {
                unsafe { foo() }
            }
        "#)
        .build();

    assert_that(build.cargo("build"),
                execs().with_status(0));

    let src = workspace.root().join("target/debug");
    let lib = fs::read_dir(&src).unwrap().map(|s| s.unwrap().path()).find(|lib| {
        let lib = lib.file_name().unwrap().to_str().unwrap();
        lib.starts_with(env::consts::DLL_PREFIX) &&
            lib.ends_with(env::consts::DLL_SUFFIX)
    }).unwrap();

    assert_that(foo.cargo("build").env("SRC", &lib).arg("-v"),
                execs().with_status(0));
}

#[test]
fn plugin_integration() {
    let p = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []
            build = "build.rs"

            [lib]
            name = "foo"
            plugin = true
            doctest = false
        "#)
        .file("build.rs", "fn main() {}")
        .file("src/lib.rs", "")
        .file("tests/it_works.rs", "")
        .build();

    assert_that(p.cargo("test").arg("-v"),
                execs().with_status(0));
}

#[test]
fn doctest_a_plugin() {
    let p = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies]
            bar = { path = "bar" }
        "#)
        .file("src/lib.rs", r#"
            #[macro_use]
            extern crate bar;
        "#)
        .file("bar/Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [lib]
            name = "bar"
            plugin = true
        "#)
        .file("bar/src/lib.rs", r#"
            pub fn bar() {}
        "#)
        .build();

    assert_that(p.cargo("test").arg("-v"),
                execs().with_status(0));
}

// See #1515
#[test]
fn native_plugin_dependency_with_custom_ar_linker() {
    let target = rustc_host();

    let _foo = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [lib]
            plugin = true
        "#)
        .file("src/lib.rs", "")
        .build();

    let bar = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [dependencies.foo]
            path = "../foo"
        "#)
        .file("src/lib.rs", "")
        .file(".cargo/config", &format!(r#"
            [target.{}]
            ar = "nonexistent-ar"
            linker = "nonexistent-linker"
        "#, target))
        .build();

    assert_that(bar.cargo("build").arg("--verbose"),
                execs().with_stderr_contains("\
[COMPILING] foo v0.0.1 ([..])
[RUNNING] `rustc [..] -C ar=nonexistent-ar -C linker=nonexistent-linker [..]`
[ERROR] could not exec the linker [..]
"));
}

#[test]
fn panic_abort_plugins() {
    if !is_nightly() {
        return
    }

    let p = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [profile.dev]
            panic = 'abort'

            [dependencies]
            foo = { path = "foo" }
        "#)
        .file("src/lib.rs", "")
        .file("foo/Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [lib]
            plugin = true
        "#)
        .file("foo/src/lib.rs", r#"
            #![feature(rustc_private)]
            extern crate syntax;
        "#)
        .build();

    assert_that(p.cargo("build"),
                execs().with_status(0));
}

#[test]
fn shared_panic_abort_plugins() {
    if !is_nightly() {
        return
    }

    let p = project("top")
        .file("Cargo.toml", r#"
            [package]
            name = "top"
            version = "0.0.1"
            authors = []

            [profile.dev]
            panic = 'abort'

            [dependencies]
            foo = { path = "foo" }
            bar = { path = "bar" }
        "#)
        .file("src/lib.rs", "
            extern crate bar;
        ")
        .file("foo/Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [lib]
            plugin = true

            [dependencies]
            bar = { path = "../bar" }
        "#)
        .file("foo/src/lib.rs", r#"
            #![feature(rustc_private)]
            extern crate syntax;
            extern crate bar;
        "#)
        .file("bar/Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []
        "#)
        .file("bar/src/lib.rs", "")
        .build();

    assert_that(p.cargo("build"),
                execs().with_status(0));
}
<commit_msg>Auto merge of #4871 - fschutt:master, r=matklad<commit_after>extern crate cargotest;
extern crate hamcrest;

use std::fs;
use std::env;

use cargotest::{is_nightly, rustc_host};
use cargotest::support::{project, execs};
use hamcrest::assert_that;

#[test]
fn plugin_to_the_max() {
    if !is_nightly() { return }

    let foo = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [lib]
            name = "foo_lib"

            [dependencies.bar]
            path = "../bar"
        "#)
        .file("src/main.rs", r#"
            #![feature(plugin)]
            #![plugin(bar)]
            extern crate foo_lib;

            fn main() { foo_lib::foo(); }
        "#)
        .file("src/foo_lib.rs", r#"
            #![feature(plugin)]
            #![plugin(bar)]

            pub fn foo() {}
        "#)
        .build();
    let _bar = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [lib]
            name = "bar"
            plugin = true

            [dependencies.baz]
            path = "../baz"
        "#)
        .file("src/lib.rs", r#"
            #![feature(plugin_registrar, rustc_private)]

            extern crate rustc_plugin;
            extern crate baz;

            use rustc_plugin::Registry;

            #[plugin_registrar]
            pub fn foo(_reg: &mut Registry) {
                println!("{}", baz::baz());
            }
        "#)
        .build();
    let _baz = project("baz")
        .file("Cargo.toml", r#"
            [package]
            name = "baz"
            version = "0.0.1"
            authors = []

            [lib]
            name = "baz"
            crate_type = ["dylib"]
        "#)
        .file("src/lib.rs", "pub fn baz() -> i32 { 1 }")
        .build();

    assert_that(foo.cargo("build"),
                execs().with_status(0));
    assert_that(foo.cargo("doc"),
                execs().with_status(0));
}

#[test]
fn plugin_with_dynamic_native_dependency() {
    if !is_nightly() { return }

    let workspace = project("ws")
        .file("Cargo.toml", r#"
            [workspace]
            members = ["builder", "foo"]
        "#)
        .build();

    let build = project("ws/builder")
        .file("Cargo.toml", r#"
            [package]
            name = "builder"
            version = "0.0.1"
            authors = []

            [lib]
            name = "builder"
            crate-type = ["dylib"]
        "#)
        .file("src/lib.rs", r#"
            #[no_mangle]
            pub extern fn foo() {}
        "#)
        .build();

    let foo = project("ws/foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies.bar]
            path = "bar"
        "#)
        .file("src/main.rs", r#"
            #![feature(plugin)]
            #![plugin(bar)]

            fn main() {}
        "#)
        .file("bar/Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []
            build = 'build.rs'

            [lib]
            name = "bar"
            plugin = true
        "#)
        .file("bar/build.rs", r#"
            use std::path::PathBuf;
            use std::env;

            fn main() {
                let src = PathBuf::from(env::var("SRC").unwrap());
                println!("cargo:rustc-flags=-L {}/deps", src.parent().unwrap().display());
            }
        "#)
        .file("bar/src/lib.rs", r#"
            #![feature(plugin_registrar, rustc_private)]
            extern crate rustc_plugin;

            use rustc_plugin::Registry;

            #[cfg_attr(not(target_env = "msvc"), link(name = "builder"))]
            #[cfg_attr(target_env = "msvc", link(name = "builder.dll"))]
            extern { fn foo(); }

            #[plugin_registrar]
            pub fn bar(_reg: &mut Registry) {
                unsafe { foo() }
            }
        "#)
        .build();

    assert_that(build.cargo("build"),
                execs().with_status(0));

    let src = workspace.root().join("target/debug");
    let lib = fs::read_dir(&src).unwrap().map(|s| s.unwrap().path()).find(|lib| {
        let lib = lib.file_name().unwrap().to_str().unwrap();
        lib.starts_with(env::consts::DLL_PREFIX) &&
            lib.ends_with(env::consts::DLL_SUFFIX)
    }).unwrap();

    assert_that(foo.cargo("build").env("SRC", &lib).arg("-v"),
                execs().with_status(0));
}

#[test]
fn plugin_integration() {
    let p = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []
            build = "build.rs"

            [lib]
            name = "foo"
            plugin = true
            doctest = false
        "#)
        .file("build.rs", "fn main() {}")
        .file("src/lib.rs", "")
        .file("tests/it_works.rs", "")
        .build();

    assert_that(p.cargo("test").arg("-v"),
                execs().with_status(0));
}

#[test]
fn doctest_a_plugin() {
    let p = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [dependencies]
            bar = { path = "bar" }
        "#)
        .file("src/lib.rs", r#"
            #[macro_use]
            extern crate bar;
        "#)
        .file("bar/Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [lib]
            name = "bar"
            plugin = true
        "#)
        .file("bar/src/lib.rs", r#"
            pub fn bar() {}
        "#)
        .build();

    assert_that(p.cargo("test").arg("-v"),
                execs().with_status(0));
}

// See #1515
#[test]
fn native_plugin_dependency_with_custom_ar_linker() {
    let target = rustc_host();

    let _foo = project("foo")
        .file("Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [lib]
            plugin = true
        "#)
        .file("src/lib.rs", "")
        .build();

    let bar = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [dependencies.foo]
            path = "../foo"
        "#)
        .file("src/lib.rs", "")
        .file(".cargo/config", &format!(r#"
            [target.{}]
            ar = "nonexistent-ar"
            linker = "nonexistent-linker"
        "#, target))
        .build();

    assert_that(bar.cargo("build").arg("--verbose"),
                execs().with_stderr_contains("\
[COMPILING] foo v0.0.1 ([..])
[RUNNING] `rustc [..] -C ar=nonexistent-ar -C linker=nonexistent-linker [..]`
[ERROR] [..]linker[..]
"));
}

#[test]
fn panic_abort_plugins() {
    if !is_nightly() {
        return
    }

    let p = project("bar")
        .file("Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []

            [profile.dev]
            panic = 'abort'

            [dependencies]
            foo = { path = "foo" }
        "#)
        .file("src/lib.rs", "")
        .file("foo/Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [lib]
            plugin = true
        "#)
        .file("foo/src/lib.rs", r#"
            #![feature(rustc_private)]
            extern crate syntax;
        "#)
        .build();

    assert_that(p.cargo("build"),
                execs().with_status(0));
}

#[test]
fn shared_panic_abort_plugins() {
    if !is_nightly() {
        return
    }

    let p = project("top")
        .file("Cargo.toml", r#"
            [package]
            name = "top"
            version = "0.0.1"
            authors = []

            [profile.dev]
            panic = 'abort'

            [dependencies]
            foo = { path = "foo" }
            bar = { path = "bar" }
        "#)
        .file("src/lib.rs", "
            extern crate bar;
        ")
        .file("foo/Cargo.toml", r#"
            [package]
            name = "foo"
            version = "0.0.1"
            authors = []

            [lib]
            plugin = true

            [dependencies]
            bar = { path = "../bar" }
        "#)
        .file("foo/src/lib.rs", r#"
            #![feature(rustc_private)]
            extern crate syntax;
            extern crate bar;
        "#)
        .file("bar/Cargo.toml", r#"
            [package]
            name = "bar"
            version = "0.0.1"
            authors = []
        "#)
        .file("bar/src/lib.rs", "")
        .build();

    assert_that(p.cargo("build"),
                execs().with_status(0));
}
<|endoftext|>


<commit_before>// Take a look at the license at the top of the repository in the LICENSE file.

use sysinfo::ProcessExt;
use sysinfo::SystemExt;

#[test]
fn test_process() {
    let mut s = sysinfo::System::new();
    assert_eq!(s.processes().len(), 0);
    s.refresh_processes();
    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }
    assert!(!s.processes().is_empty());
    #[cfg(not(windows))]
    assert!(s
        .processes()
        .values()
        .any(|p| !p.exe().to_str().unwrap_or("").is_empty()));
}

#[test]
fn test_cwd() {
    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }
    let mut p = if cfg!(target_os = "windows") {
        std::process::Command::new("waitfor")
            .arg("/t")
            .arg("3")
            .arg("CwdSignal")
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap()
    } else {
        std::process::Command::new("sleep")
            .arg("3")
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap()
    };

    let pid = p.id() as sysinfo::Pid;
    std::thread::sleep(std::time::Duration::from_millis(250));
    let mut s = sysinfo::System::new();
    s.refresh_processes();
    p.kill().expect("Unable to kill process.");

    let processes = s.processes();
    let p = processes.get(&pid);

    if let Some(p) = p {
        assert_eq!(p.pid(), pid);
        assert_eq!(p.cwd(), std::env::current_dir().unwrap());
    } else {
        panic!("Process not found!");
    }
}

#[test]
fn test_cmd() {
    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }
    let mut p = if cfg!(target_os = "windows") {
        std::process::Command::new("waitfor")
            .arg("/t")
            .arg("3")
            .arg("CmdSignal")
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap()
    } else {
        std::process::Command::new("sleep")
            .arg("3")
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap()
    };
    std::thread::sleep(std::time::Duration::from_millis(250));
    let mut s = sysinfo::System::new();
    assert!(s.processes().is_empty());
    s.refresh_processes();
    p.kill().expect("Unable to kill process.");
    assert!(!s.processes().is_empty());
    if let Some(process) = s.process(p.id() as sysinfo::Pid) {
        if cfg!(target_os = "windows") {
            assert_eq!(process.cmd(), &["waitfor", "/t", "3", "CmdSignal"]);
        } else {
            assert_eq!(process.cmd(), &["sleep", "3"]);
        }
    } else {
        panic!("Process not found!");
    }
}

#[test]
fn test_environ() {
    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }
    let mut p = if cfg!(target_os = "windows") {
        std::process::Command::new("waitfor")
            .arg("/t")
            .arg("3")
            .arg("EnvironSignal")
            .stdout(std::process::Stdio::null())
            .env("FOO", "BAR")
            .env("OTHER", "VALUE")
            .spawn()
            .unwrap()
    } else {
        std::process::Command::new("sleep")
            .arg("3")
            .stdout(std::process::Stdio::null())
            .env("FOO", "BAR")
            .env("OTHER", "VALUE")
            .spawn()
            .unwrap()
    };

    let pid = p.id() as sysinfo::Pid;
    std::thread::sleep(std::time::Duration::from_millis(250));
    let mut s = sysinfo::System::new();
    s.refresh_processes();
    p.kill().expect("Unable to kill process.");

    let processes = s.processes();
    let p = processes.get(&pid);

    if let Some(p) = p {
        assert_eq!(p.pid(), pid);
        // FIXME: instead of ignoring the test on CI, try to find out what's wrong...
        if std::env::var("APPLE_CI").is_err() {
            assert!(p.environ().iter().any(|e| e == "FOO=BAR"));
            assert!(p.environ().iter().any(|e| e == "OTHER=VALUE"));
        }
    } else {
        panic!("Process not found!");
    }
}

#[test]
fn test_process_refresh() {
    let mut s = sysinfo::System::new();
    assert_eq!(s.processes().len(), 0);

    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }
    s.refresh_process(sysinfo::get_current_pid().expect("failed to get current pid"));
    assert!(s
        .process(sysinfo::get_current_pid().expect("failed to get current pid"))
        .is_some(),);
}

#[test]
fn test_process_disk_usage() {
    use std::fs;
    use std::fs::File;
    use std::io::prelude::*;
    use sysinfo::{get_current_pid, ProcessExt, SystemExt};

    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }

    fn inner() -> sysinfo::System {
        {
            let mut file = File::create("test.txt").expect("failed to create file");
            file.write_all(b"This is a test file\nwith test data.\n")
                .expect("failed to write to file");
        }
        fs::remove_file("test.txt").expect("failed to remove file");
        let mut system = sysinfo::System::new();
        assert!(system.processes().is_empty());
        system.refresh_processes();
        assert!(!system.processes().is_empty());
        system
    }

    let mut system = inner();
    let mut p = system
        .process(get_current_pid().expect("Failed retrieving current pid."))
        .expect("failed to get process");

    if cfg!(any(target_os = "macos", target_os = "ios")) && p.disk_usage().total_written_bytes == 0
    {
        // For whatever reason, sometimes, mac doesn't work on the first time when running
        // `cargo test`. Two solutions, either run with "cargo test -- --test-threads 1", or
        // check twice...
        system = inner();
        p = system
            .process(get_current_pid().expect("Failed retrieving current pid."))
            .expect("failed to get process");
    }

    assert!(
        p.disk_usage().total_written_bytes > 0,
        "found {} total written bytes...",
        p.disk_usage().total_written_bytes
    );
    assert!(
        p.disk_usage().written_bytes > 0,
        "found {} written bytes...",
        p.disk_usage().written_bytes
    );
}

#[test]
fn cpu_usage_is_not_nan() {
    let mut system = sysinfo::System::new();
    system.refresh_processes();

    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }

    let first_pids = system
        .processes()
        .iter()
        .take(10)
        .map(|(&pid, _)| pid)
        .collect::<Vec<_>>();
    let mut checked = 0;

    first_pids.into_iter().for_each(|pid| {
        system.refresh_process(pid);
        if let Some(p) = system.process(pid) {
            assert!(!p.cpu_usage().is_nan());
            checked += 1;
        }
    });
    assert!(checked > 0);
}
<commit_msg>Fix failing windows test<commit_after>// Take a look at the license at the top of the repository in the LICENSE file.

use sysinfo::ProcessExt;
use sysinfo::SystemExt;

#[test]
fn test_process() {
    let mut s = sysinfo::System::new();
    assert_eq!(s.processes().len(), 0);
    s.refresh_processes();
    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }
    assert!(!s.processes().is_empty());
    #[cfg(not(windows))]
    assert!(s
        .processes()
        .values()
        .any(|p| !p.exe().to_str().unwrap_or("").is_empty()));
}

#[test]
fn test_cwd() {
    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }
    let mut p = if cfg!(target_os = "windows") {
        std::process::Command::new("waitfor")
            .arg("/t")
            .arg("3")
            .arg("CwdSignal")
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap()
    } else {
        std::process::Command::new("sleep")
            .arg("3")
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap()
    };

    let pid = p.id() as sysinfo::Pid;
    std::thread::sleep(std::time::Duration::from_millis(250));
    let mut s = sysinfo::System::new();
    s.refresh_processes();
    p.kill().expect("Unable to kill process.");

    let processes = s.processes();
    let p = processes.get(&pid);

    if let Some(p) = p {
        assert_eq!(p.pid(), pid);
        assert_eq!(p.cwd(), std::env::current_dir().unwrap());
    } else {
        panic!("Process not found!");
    }
}

#[test]
fn test_cmd() {
    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }
    let mut p = if cfg!(target_os = "windows") {
        std::process::Command::new("waitfor")
            .arg("/t")
            .arg("3")
            .arg("CmdSignal")
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap()
    } else {
        std::process::Command::new("sleep")
            .arg("3")
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap()
    };
    std::thread::sleep(std::time::Duration::from_millis(250));
    let mut s = sysinfo::System::new();
    assert!(s.processes().is_empty());
    s.refresh_processes();
    p.kill().expect("Unable to kill process.");
    assert!(!s.processes().is_empty());
    if let Some(process) = s.process(p.id() as sysinfo::Pid) {
        if cfg!(target_os = "windows") {
            // Sometimes, we get the full path instead for some reasons... So just in case,
            // we check for the command independently that from the arguments.
            assert!(process.cmd()[0].contains("waitfor"));
            assert_eq!(&process.cmd()[1..], &["/t", "3", "CmdSignal"]);
        } else {
            assert_eq!(process.cmd(), &["sleep", "3"]);
        }
    } else {
        panic!("Process not found!");
    }
}

#[test]
fn test_environ() {
    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }
    let mut p = if cfg!(target_os = "windows") {
        std::process::Command::new("waitfor")
            .arg("/t")
            .arg("3")
            .arg("EnvironSignal")
            .stdout(std::process::Stdio::null())
            .env("FOO", "BAR")
            .env("OTHER", "VALUE")
            .spawn()
            .unwrap()
    } else {
        std::process::Command::new("sleep")
            .arg("3")
            .stdout(std::process::Stdio::null())
            .env("FOO", "BAR")
            .env("OTHER", "VALUE")
            .spawn()
            .unwrap()
    };

    let pid = p.id() as sysinfo::Pid;
    std::thread::sleep(std::time::Duration::from_millis(250));
    let mut s = sysinfo::System::new();
    s.refresh_processes();
    p.kill().expect("Unable to kill process.");

    let processes = s.processes();
    let p = processes.get(&pid);

    if let Some(p) = p {
        assert_eq!(p.pid(), pid);
        // FIXME: instead of ignoring the test on CI, try to find out what's wrong...
        if std::env::var("APPLE_CI").is_err() {
            assert!(p.environ().iter().any(|e| e == "FOO=BAR"));
            assert!(p.environ().iter().any(|e| e == "OTHER=VALUE"));
        }
    } else {
        panic!("Process not found!");
    }
}

#[test]
fn test_process_refresh() {
    let mut s = sysinfo::System::new();
    assert_eq!(s.processes().len(), 0);

    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }
    s.refresh_process(sysinfo::get_current_pid().expect("failed to get current pid"));
    assert!(s
        .process(sysinfo::get_current_pid().expect("failed to get current pid"))
        .is_some(),);
}

#[test]
fn test_process_disk_usage() {
    use std::fs;
    use std::fs::File;
    use std::io::prelude::*;
    use sysinfo::{get_current_pid, ProcessExt, SystemExt};

    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }

    fn inner() -> sysinfo::System {
        {
            let mut file = File::create("test.txt").expect("failed to create file");
            file.write_all(b"This is a test file\nwith test data.\n")
                .expect("failed to write to file");
        }
        fs::remove_file("test.txt").expect("failed to remove file");
        let mut system = sysinfo::System::new();
        assert!(system.processes().is_empty());
        system.refresh_processes();
        assert!(!system.processes().is_empty());
        system
    }

    let mut system = inner();
    let mut p = system
        .process(get_current_pid().expect("Failed retrieving current pid."))
        .expect("failed to get process");

    if cfg!(any(target_os = "macos", target_os = "ios")) && p.disk_usage().total_written_bytes == 0
    {
        // For whatever reason, sometimes, mac doesn't work on the first time when running
        // `cargo test`. Two solutions, either run with "cargo test -- --test-threads 1", or
        // check twice...
        system = inner();
        p = system
            .process(get_current_pid().expect("Failed retrieving current pid."))
            .expect("failed to get process");
    }

    assert!(
        p.disk_usage().total_written_bytes > 0,
        "found {} total written bytes...",
        p.disk_usage().total_written_bytes
    );
    assert!(
        p.disk_usage().written_bytes > 0,
        "found {} written bytes...",
        p.disk_usage().written_bytes
    );
}

#[test]
fn cpu_usage_is_not_nan() {
    let mut system = sysinfo::System::new();
    system.refresh_processes();

    if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
        return;
    }

    let first_pids = system
        .processes()
        .iter()
        .take(10)
        .map(|(&pid, _)| pid)
        .collect::<Vec<_>>();
    let mut checked = 0;

    first_pids.into_iter().for_each(|pid| {
        system.refresh_process(pid);
        if let Some(p) = system.process(pid) {
            assert!(!p.cpu_usage().is_nan());
            checked += 1;
        }
    });
    assert!(checked > 0);
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

///! Utilities for the implementation of JSAPI proxy handlers.

use dom::bindings::conversions::is_dom_proxy;
use dom::bindings::utils::delete_property_by_id;
use js::jsapi::{JSContext, jsid, JSPropertyDescriptor, JSObject, JSString};
use js::jsapi::{JS_GetPropertyDescriptorById, JS_NewStringCopyN};
use js::jsapi::{JS_DefinePropertyById, JS_NewObjectWithGivenProto};
use js::jsapi::{JS_ReportErrorFlagsAndNumber, JS_StrictPropertyStub};
use js::jsapi::{JSREPORT_WARNING, JSREPORT_STRICT, JSREPORT_STRICT_MODE_ERROR};
use js::jsval::ObjectValue;
use js::glue::GetProxyExtra;
use js::glue::{GetObjectProto, GetObjectParent, SetProxyExtra, GetProxyHandler};
use js::glue::InvokeGetOwnPropertyDescriptor;
use js::glue::RUST_js_GetErrorMessage;
use js::glue::AutoIdVector;
use js::{JSPROP_GETTER, JSPROP_ENUMERATE, JSPROP_READONLY, JSRESOLVE_QUALIFIED};

use libc;
use std::mem;
use std::ptr;

static JSPROXYSLOT_EXPANDO: u32 = 0;

pub unsafe extern fn getPropertyDescriptor(cx: *mut JSContext, proxy: *mut JSObject,
                                           id: jsid, set: bool,
                                           desc: *mut JSPropertyDescriptor)
                                           -> bool {
    let handler = GetProxyHandler(proxy);
    if !InvokeGetOwnPropertyDescriptor(handler, cx, proxy, id, set, desc) {
        return false;
    }
    if !(*desc).obj.is_null() {
        return true;
    }

    //let proto = JS_GetPrototype(proxy);
    let proto = GetObjectProto(proxy);
    if proto.is_null() {
        (*desc).obj = ptr::null_mut();
        return true;
    }

    JS_GetPropertyDescriptorById(cx, proto, id, JSRESOLVE_QUALIFIED, desc) != 0
}

pub unsafe extern fn defineProperty_(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
                              desc: *mut JSPropertyDescriptor) -> bool {
    static JSMSG_GETTER_ONLY: libc::c_uint = 160;

    //FIXME: Workaround for https://github.com/mozilla/rust/issues/13385
    let setter: *const libc::c_void = mem::transmute((*desc).setter);
    let setter_stub: *const libc::c_void = mem::transmute(JS_StrictPropertyStub);
    if ((*desc).attrs & JSPROP_GETTER) != 0 && setter == setter_stub {
        return JS_ReportErrorFlagsAndNumber(cx,
                                            JSREPORT_WARNING | JSREPORT_STRICT |
                                            JSREPORT_STRICT_MODE_ERROR,
                                            Some(RUST_js_GetErrorMessage), ptr::null_mut(),
                                            JSMSG_GETTER_ONLY) != 0;
    }

    let expando = EnsureExpandoObject(cx, proxy);
    if expando.is_null() {
        return false;
    }

    return JS_DefinePropertyById(cx, expando, id, (*desc).value, (*desc).getter,
                                 (*desc).setter, (*desc).attrs) != 0;
}

pub unsafe extern fn delete_(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
                             bp: *mut bool) -> bool {
    let expando = EnsureExpandoObject(cx, proxy);
    if expando.is_null() {
        return false;
    }

    return delete_property_by_id(cx, expando, id, &mut *bp);
}

pub fn _obj_toString(cx: *mut JSContext, name: &str) -> *mut JSString {
    unsafe {
        let result = format!("[object {}]", name);

        let chars = result.as_ptr() as *const libc::c_char;
        let length = result.len() as libc::size_t;

        let string = JS_NewStringCopyN(cx, chars, length);
        assert!(!string.is_null());
        return string;
    }
}

pub fn GetExpandoObject(obj: *mut JSObject) -> *mut JSObject {
    unsafe {
        assert!(is_dom_proxy(obj));
        let val = GetProxyExtra(obj, JSPROXYSLOT_EXPANDO);
        if val.is_undefined() {
            ptr::null_mut()
        } else {
            val.to_object()
        }
    }
}

pub fn EnsureExpandoObject(cx: *mut JSContext, obj: *mut JSObject) -> *mut JSObject {
    unsafe {
        assert!(is_dom_proxy(obj));
        let mut expando = GetExpandoObject(obj);
        if expando.is_null() {
            expando = JS_NewObjectWithGivenProto(cx, ptr::null_mut(),
                                                 ptr::null_mut(),
                                                 GetObjectParent(obj));
            if expando.is_null() {
                return ptr::null_mut();
            }

            SetProxyExtra(obj, JSPROXYSLOT_EXPANDO, ObjectValue(&*expando));
        }
        return expando;
    }
}

pub fn FillPropertyDescriptor(desc: &mut JSPropertyDescriptor, obj: *mut JSObject, readonly: bool) {
    desc.obj = obj;
    desc.attrs = if readonly { JSPROP_READONLY } else { 0 } | JSPROP_ENUMERATE;
    desc.getter = None;
    desc.setter = None;
    desc.shortid = 0;
}

pub unsafe extern fn getOwnPropertyNames_(_cx: *mut JSContext,
                                          _obj: *mut JSObject,
                                          _v: *mut AutoIdVector) -> bool {
    true
}

pub unsafe extern fn enumerate_(_cx: *mut JSContext, _obj: *mut JSObject,
                                _v: *mut AutoIdVector) -> bool {
    true
}
<commit_msg>Don't create an expando holder to delete an expando.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

///! Utilities for the implementation of JSAPI proxy handlers.

use dom::bindings::conversions::is_dom_proxy;
use dom::bindings::utils::delete_property_by_id;
use js::jsapi::{JSContext, jsid, JSPropertyDescriptor, JSObject, JSString};
use js::jsapi::{JS_GetPropertyDescriptorById, JS_NewStringCopyN};
use js::jsapi::{JS_DefinePropertyById, JS_NewObjectWithGivenProto};
use js::jsapi::{JS_ReportErrorFlagsAndNumber, JS_StrictPropertyStub};
use js::jsapi::{JSREPORT_WARNING, JSREPORT_STRICT, JSREPORT_STRICT_MODE_ERROR};
use js::jsval::ObjectValue;
use js::glue::GetProxyExtra;
use js::glue::{GetObjectProto, GetObjectParent, SetProxyExtra, GetProxyHandler};
use js::glue::InvokeGetOwnPropertyDescriptor;
use js::glue::RUST_js_GetErrorMessage;
use js::glue::AutoIdVector;
use js::{JSPROP_GETTER, JSPROP_ENUMERATE, JSPROP_READONLY, JSRESOLVE_QUALIFIED};

use libc;
use std::mem;
use std::ptr;

static JSPROXYSLOT_EXPANDO: u32 = 0;

pub unsafe extern fn getPropertyDescriptor(cx: *mut JSContext, proxy: *mut JSObject,
                                           id: jsid, set: bool,
                                           desc: *mut JSPropertyDescriptor)
                                           -> bool {
    let handler = GetProxyHandler(proxy);
    if !InvokeGetOwnPropertyDescriptor(handler, cx, proxy, id, set, desc) {
        return false;
    }
    if !(*desc).obj.is_null() {
        return true;
    }

    //let proto = JS_GetPrototype(proxy);
    let proto = GetObjectProto(proxy);
    if proto.is_null() {
        (*desc).obj = ptr::null_mut();
        return true;
    }

    JS_GetPropertyDescriptorById(cx, proto, id, JSRESOLVE_QUALIFIED, desc) != 0
}

pub unsafe extern fn defineProperty_(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
                              desc: *mut JSPropertyDescriptor) -> bool {
    static JSMSG_GETTER_ONLY: libc::c_uint = 160;

    //FIXME: Workaround for https://github.com/mozilla/rust/issues/13385
    let setter: *const libc::c_void = mem::transmute((*desc).setter);
    let setter_stub: *const libc::c_void = mem::transmute(JS_StrictPropertyStub);
    if ((*desc).attrs & JSPROP_GETTER) != 0 && setter == setter_stub {
        return JS_ReportErrorFlagsAndNumber(cx,
                                            JSREPORT_WARNING | JSREPORT_STRICT |
                                            JSREPORT_STRICT_MODE_ERROR,
                                            Some(RUST_js_GetErrorMessage), ptr::null_mut(),
                                            JSMSG_GETTER_ONLY) != 0;
    }

    let expando = EnsureExpandoObject(cx, proxy);
    if expando.is_null() {
        return false;
    }

    return JS_DefinePropertyById(cx, expando, id, (*desc).value, (*desc).getter,
                                 (*desc).setter, (*desc).attrs) != 0;
}

pub unsafe extern fn delete_(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
                             bp: *mut bool) -> bool {
    let expando = GetExpandoObject(proxy);
    if expando.is_null() {
        *bp = true;
        return true;
    }

    return delete_property_by_id(cx, expando, id, &mut *bp);
}

pub fn _obj_toString(cx: *mut JSContext, name: &str) -> *mut JSString {
    unsafe {
        let result = format!("[object {}]", name);

        let chars = result.as_ptr() as *const libc::c_char;
        let length = result.len() as libc::size_t;

        let string = JS_NewStringCopyN(cx, chars, length);
        assert!(!string.is_null());
        return string;
    }
}

pub fn GetExpandoObject(obj: *mut JSObject) -> *mut JSObject {
    unsafe {
        assert!(is_dom_proxy(obj));
        let val = GetProxyExtra(obj, JSPROXYSLOT_EXPANDO);
        if val.is_undefined() {
            ptr::null_mut()
        } else {
            val.to_object()
        }
    }
}

pub fn EnsureExpandoObject(cx: *mut JSContext, obj: *mut JSObject) -> *mut JSObject {
    unsafe {
        assert!(is_dom_proxy(obj));
        let mut expando = GetExpandoObject(obj);
        if expando.is_null() {
            expando = JS_NewObjectWithGivenProto(cx, ptr::null_mut(),
                                                 ptr::null_mut(),
                                                 GetObjectParent(obj));
            if expando.is_null() {
                return ptr::null_mut();
            }

            SetProxyExtra(obj, JSPROXYSLOT_EXPANDO, ObjectValue(&*expando));
        }
        return expando;
    }
}

pub fn FillPropertyDescriptor(desc: &mut JSPropertyDescriptor, obj: *mut JSObject, readonly: bool) {
    desc.obj = obj;
    desc.attrs = if readonly { JSPROP_READONLY } else { 0 } | JSPROP_ENUMERATE;
    desc.getter = None;
    desc.setter = None;
    desc.shortid = 0;
}

pub unsafe extern fn getOwnPropertyNames_(_cx: *mut JSContext,
                                          _obj: *mut JSObject,
                                          _v: *mut AutoIdVector) -> bool {
    true
}

pub unsafe extern fn enumerate_(_cx: *mut JSContext, _obj: *mut JSObject,
                                _v: *mut AutoIdVector) -> bool {
    true
}
<|endoftext|>


<commit_before>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use clap::{value_t, App, Arg};
use config_builder::swarm_config::SwarmConfigBuilder;
use std::convert::TryInto;

const BASE_ARG: &str = "base";
const NODES_ARG: &str = "nodes";
const OUTPUT_DIR_ARG: &str = "output-dir";
const DISCOVERY_ARG: &str = "discovery";
const KEY_SEED_ARG: &str = "key-seed";
const FAUCET_ACCOUNT_FILE_ARG: &str = "faucet_account_file";

fn main() {
    let args = App::new("Libra Config Tool")
        .version("0.1.0")
        .author("Libra Association <opensource@libra.org>")
        .about("Tool to manage and create Libra Configs")
        .arg(
            Arg::with_name(BASE_ARG)
                .short("b")
                .long(BASE_ARG)
                .takes_value(true)
                .required(true)
                .help("Base config to use"),
        )
        .arg(
            Arg::with_name(NODES_ARG)
                .short("n")
                .long(NODES_ARG)
                .takes_value(true)
                .default_value("1")
                .help("Specify the number of nodes to configure"),
        )
        .arg(
            Arg::with_name(OUTPUT_DIR_ARG)
                .short("o")
                .long(OUTPUT_DIR_ARG)
                .takes_value(true)
                .help("The output directory"),
        )
        .arg(
            Arg::with_name(DISCOVERY_ARG)
                .short("d")
                .long(DISCOVERY_ARG)
                .help("Generate peer config with one peer only (to force discovery)"),
        )
        .arg(
            Arg::with_name(KEY_SEED_ARG)
                .short("s")
                .long(KEY_SEED_ARG)
                .takes_value(true)
                .help("Use the provided seed for generating keys for each of the validators"),
        )
        .arg(
            Arg::with_name(FAUCET_ACCOUNT_FILE_ARG)
                .short("m")
                .long(FAUCET_ACCOUNT_FILE_ARG)
                .help("File location from which to load faucet account generated via generate_keypair tool")
                .takes_value(true),
        )
        .get_matches();
    let base_path = value_t!(args, BASE_ARG, String).expect("Path to base config");
    let nodes_count = value_t!(args, NODES_ARG, usize).unwrap();
    let output_dir = if args.is_present(OUTPUT_DIR_ARG) {
        let dir = value_t!(args, OUTPUT_DIR_ARG, String).unwrap();
        dir.into()
    } else {
        ::std::env::current_dir().unwrap()
    };
    let faucet_account_file_path = value_t!(args, FAUCET_ACCOUNT_FILE_ARG, String)
        .expect("Must provide faucet account file path");
    let (faucet_account_keypair, _faucet_key_file_path, _temp_dir) =
        generate_keypair::load_faucet_key_or_create_default(Some(faucet_account_file_path));

    let mut config_builder = SwarmConfigBuilder::new();
    config_builder
        .with_nodes(nodes_count)
        .with_base(base_path)
        .with_output_dir(output_dir)
        .with_faucet_keypair(faucet_account_keypair);
    if args.is_present(DISCOVERY_ARG) {
        config_builder.force_discovery();
    }
    if args.is_present(KEY_SEED_ARG) {
        let seed_hex = value_t!(args, KEY_SEED_ARG, String).expect("Missing Seed");
        let seed = hex::decode(seed_hex).unwrap();
        config_builder.with_key_seed(seed[..32].try_into().unwrap());
    }
    let generated_configs = config_builder.build().expect("Unable to generate configs");

    println!(
        "Trusted Peers Config: {:?}",
        generated_configs.get_trusted_peers_config().0
    );

    println!(
        "Seed Peers Config: {:?}",
        generated_configs.get_seed_peers_config().0
    );

    for (path, node_config) in generated_configs.get_configs() {
        println!(
            "Node Config for PeerId({}): {:?}",
            node_config.base.peer_id, path
        );
        println!(
            "Node Keys for PeerId({}): {:?}",
            node_config.base.peer_id, node_config.base.peer_keypairs_file
        );
    }
}
<commit_msg>[ConfigBuilder] Replace unwrap with expect and better error message<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use clap::{value_t, App, Arg};
use config_builder::swarm_config::SwarmConfigBuilder;
use std::convert::TryInto;

const BASE_ARG: &str = "base";
const NODES_ARG: &str = "nodes";
const OUTPUT_DIR_ARG: &str = "output-dir";
const DISCOVERY_ARG: &str = "discovery";
const KEY_SEED_ARG: &str = "key-seed";
const FAUCET_ACCOUNT_FILE_ARG: &str = "faucet_account_file";

fn main() {
    let args = App::new("Libra Config Tool")
        .version("0.1.0")
        .author("Libra Association <opensource@libra.org>")
        .about("Tool to manage and create Libra Configs")
        .arg(
            Arg::with_name(BASE_ARG)
                .short("b")
                .long(BASE_ARG)
                .takes_value(true)
                .required(true)
                .help("Base config to use"),
        )
        .arg(
            Arg::with_name(NODES_ARG)
                .short("n")
                .long(NODES_ARG)
                .takes_value(true)
                .default_value("1")
                .help("Specify the number of nodes to configure"),
        )
        .arg(
            Arg::with_name(OUTPUT_DIR_ARG)
                .short("o")
                .long(OUTPUT_DIR_ARG)
                .takes_value(true)
                .help("The output directory"),
        )
        .arg(
            Arg::with_name(DISCOVERY_ARG)
                .short("d")
                .long(DISCOVERY_ARG)
                .help("Generate peer config with one peer only (to force discovery)"),
        )
        .arg(
            Arg::with_name(KEY_SEED_ARG)
                .short("s")
                .long(KEY_SEED_ARG)
                .takes_value(true)
                .help("Use the provided seed for generating keys for each of the validators"),
        )
        .arg(
            Arg::with_name(FAUCET_ACCOUNT_FILE_ARG)
                .short("m")
                .long(FAUCET_ACCOUNT_FILE_ARG)
                .help("File location from which to load faucet account generated via generate_keypair tool")
                .takes_value(true),
        )
        .get_matches();
    let base_path = value_t!(args, BASE_ARG, String).expect("Missing path to base config.");
    let nodes_count = value_t!(args, NODES_ARG, usize).expect("Missing node count.");
    let output_dir = if args.is_present(OUTPUT_DIR_ARG) {
        let dir = value_t!(args, OUTPUT_DIR_ARG, String).expect("Missing output directory.");
        dir.into()
    } else {
        ::std::env::current_dir().expect("Failed to access current directory.")
    };
    let faucet_account_file_path = value_t!(args, FAUCET_ACCOUNT_FILE_ARG, String)
        .expect("Must provide faucet account file path");
    let (faucet_account_keypair, _faucet_key_file_path, _temp_dir) =
        generate_keypair::load_faucet_key_or_create_default(Some(faucet_account_file_path));

    let mut config_builder = SwarmConfigBuilder::new();
    config_builder
        .with_nodes(nodes_count)
        .with_base(base_path)
        .with_output_dir(output_dir)
        .with_faucet_keypair(faucet_account_keypair);
    if args.is_present(DISCOVERY_ARG) {
        config_builder.force_discovery();
    }
    if args.is_present(KEY_SEED_ARG) {
        let seed_hex = value_t!(args, KEY_SEED_ARG, String).expect("Missing Seed");
        let seed = hex::decode(seed_hex).expect("Invalid hex in seed.");
        config_builder.with_key_seed(
            seed[..32]
                .try_into()
                .expect("Seed should be 32 bytes long."),
        );
    }
    let generated_configs = config_builder.build().expect("Unable to generate configs");

    println!(
        "Trusted Peers Config: {:?}",
        generated_configs.get_trusted_peers_config().0
    );

    println!(
        "Seed Peers Config: {:?}",
        generated_configs.get_seed_peers_config().0
    );

    for (path, node_config) in generated_configs.get_configs() {
        println!(
            "Node Config for PeerId({}): {:?}",
            node_config.base.peer_id, path
        );
        println!(
            "Node Keys for PeerId({}): {:?}",
            node_config.base.peer_id, node_config.base.peer_keypairs_file
        );
    }
}
<|endoftext|>


<commit_before>#![allow(
    clippy::no_effect_underscore_binding,
    clippy::too_many_lines,
    clippy::used_underscore_binding
)]

#[rustfmt::skip]
mod gen;

use proc_macro2::{Ident, Literal, TokenStream};
use ref_cast::RefCast;
use std::fmt::{self, Debug};
use std::ops::Deref;
use syn::punctuated::Punctuated;

#[derive(RefCast)]
#[repr(transparent)]
pub struct Lite<T: ?Sized> {
    value: T,
}

#[allow(non_snake_case)]
pub fn Lite<T: ?Sized>(value: &T) -> &Lite<T> {
    Lite::ref_cast(value)
}

impl<T: ?Sized> Deref for Lite<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl Debug for Lite<bool> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", self.value)
    }
}

impl Debug for Lite<u32> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", self.value)
    }
}

impl Debug for Lite<usize> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", self.value)
    }
}

impl Debug for Lite<String> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{:?}", self.value)
    }
}

impl Debug for Lite<Ident> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{:?}", self.value.to_string())
    }
}

impl Debug for Lite<Literal> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", self.value)
    }
}

impl Debug for Lite<TokenStream> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        let string = self.value.to_string();
        if string.len() <= 80 {
            write!(formatter, "TokenStream(`{}`)", self.value)
        } else {
            formatter
                .debug_tuple("TokenStream")
                .field(&format_args!("`{}`", string))
                .finish()
        }
    }
}

impl<'a, T> Debug for Lite<&'a T>
where
    Lite<T>: Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(Lite(&*self.value), formatter)
    }
}

impl<T> Debug for Lite<Box<T>>
where
    Lite<T>: Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(Lite(&*self.value), formatter)
    }
}

impl<T> Debug for Lite<Vec<T>>
where
    Lite<T>: Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter
            .debug_list()
            .entries(self.value.iter().map(Lite))
            .finish()
    }
}

impl<T, P> Debug for Lite<Punctuated<T, P>>
where
    Lite<T>: Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter
            .debug_list()
            .entries(self.value.iter().map(Lite))
            .finish()
    }
}
<commit_msg>Resolve borrow_deref_ref clippy lint<commit_after>#![allow(
    clippy::no_effect_underscore_binding,
    clippy::too_many_lines,
    clippy::used_underscore_binding
)]

#[rustfmt::skip]
mod gen;

use proc_macro2::{Ident, Literal, TokenStream};
use ref_cast::RefCast;
use std::fmt::{self, Debug};
use std::ops::Deref;
use syn::punctuated::Punctuated;

#[derive(RefCast)]
#[repr(transparent)]
pub struct Lite<T: ?Sized> {
    value: T,
}

#[allow(non_snake_case)]
pub fn Lite<T: ?Sized>(value: &T) -> &Lite<T> {
    Lite::ref_cast(value)
}

impl<T: ?Sized> Deref for Lite<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl Debug for Lite<bool> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", self.value)
    }
}

impl Debug for Lite<u32> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", self.value)
    }
}

impl Debug for Lite<usize> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", self.value)
    }
}

impl Debug for Lite<String> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{:?}", self.value)
    }
}

impl Debug for Lite<Ident> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{:?}", self.value.to_string())
    }
}

impl Debug for Lite<Literal> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", self.value)
    }
}

impl Debug for Lite<TokenStream> {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        let string = self.value.to_string();
        if string.len() <= 80 {
            write!(formatter, "TokenStream(`{}`)", self.value)
        } else {
            formatter
                .debug_tuple("TokenStream")
                .field(&format_args!("`{}`", string))
                .finish()
        }
    }
}

impl<'a, T> Debug for Lite<&'a T>
where
    Lite<T>: Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(Lite(self.value), formatter)
    }
}

impl<T> Debug for Lite<Box<T>>
where
    Lite<T>: Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        Debug::fmt(Lite(&*self.value), formatter)
    }
}

impl<T> Debug for Lite<Vec<T>>
where
    Lite<T>: Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter
            .debug_list()
            .entries(self.value.iter().map(Lite))
            .finish()
    }
}

impl<T, P> Debug for Lite<Punctuated<T, P>>
where
    Lite<T>: Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter
            .debug_list()
            .entries(self.value.iter().map(Lite))
            .finish()
    }
}
<|endoftext|>


<commit_before>
extern crate gltf;

#[test]
fn import_v2() {
    let assets = [
        // These are currently the only available 2.0 compliant sample assets
        "glTF-Sample-Models/2.0/Corset/glTF/Corset.gltf",
        "glTF-Sample-Models/2.0/BoomBox/glTF/BoomBox.gltf",
        "glTF-Sample-Models/2.0/Lantern/glTF/Lantern.gltf",
    ];
    for asset in &assets {
        match gltf::v2::import(asset) {
            Ok(_) => {}
            Err(err) => {
                println!("{}: {:?}", asset, err);
                panic!()
            }
        }
    }
}
<commit_msg>add Box sample to test<commit_after>
extern crate gltf;

#[test]
fn import_v2() {
    let assets = [
        // These are currently the only available 2.0 compliant sample assets
        "glTF-Sample-Models/2.0/Corset/glTF/Corset.gltf",
        "glTF-Sample-Models/2.0/BoomBox/glTF/BoomBox.gltf",
        "glTF-Sample-Models/2.0/Lantern/glTF/Lantern.gltf",
        "glTF-Sample-Models/2.0/Box/glTF/Box.gltf",
    ];
    for asset in &assets {
        match gltf::v2::import(asset) {
            Ok(_) => {}
            Err(err) => {
                println!("{}: {:?}", asset, err);
                panic!()
            }
        }
    }
}
<|endoftext|>


<commit_before>use focus_char::FocusChar;
use fragments::Fragment;
use location::Location;
use location::Direction::{Bottom, BottomLeft, BottomRight, Left, Right, Top, TopLeft, TopRight};
use block::Block::{A, C, E, F, J, K, M, O, P, S, U, W, Y};
use point_block::PointBlock;
use fragments::{line, arc, arrow_line};

pub trait Enhance {
    fn enhance(&self) -> (Vec<Fragment>, Vec<Location>);
}

impl<'g> Enhance for FocusChar<'g> {

    fn enhance(&self) -> (Vec<Fragment>, Vec<Location>) {
        let mut elm = vec![];
        let mut consumed = vec![];
        let a = &PointBlock::block(A);
        //let _b = &PointBlock::block(B);
        let c = &PointBlock::block(C);
        //let _d = &PointBlock::block(D);
        let e = &PointBlock::block(E);
        let f = &PointBlock::block(F);
        //let _g = &PointBlock::block(G);
        //let _h = &PointBlock::block(H);
        //let _i = &PointBlock::block(I);
        let j = &PointBlock::block(J);
        let k = &PointBlock::block(K);
        //let _l = &PointBlock::block(L);
        let m = &PointBlock::block(M);
        //let _n = &PointBlock::block(N);
        let o = &PointBlock::block(O);
        let p = &PointBlock::block(P);
        //let _q = &PointBlock::block(Q);
        //let _r = &PointBlock::block(R);
        let s = &PointBlock::block(S);
        //let _t = &PointBlock::block(T);
        let u = &PointBlock::block(U);
        //let _v = &PointBlock::block(V);
        let w = &PointBlock::block(W);
        //let _x = &PointBlock::block(X);
        let y = &PointBlock::block(Y);

        let this = || Location::this();
        let top = || Location::go(Top);
        let bottom = || Location::go(Bottom);
        let left = || Location::go(Left);
        let right = || Location::go(Right);
        let top_left = || Location::go(TopLeft);
        let top_right = || Location::go(TopRight);
        let bottom_left = || Location::go(BottomLeft);
        let bottom_right = || Location::go(BottomRight);

        let top_left2 = || top().go_left(2);
        let top_right2 = || top().go_right(2);
        let bottom_right2 = || bottom().go_right(2);
        let bottom_left2 = || bottom().go_left(2);

        // _ underscore
        if self.is('_') {
            //   _|
            if self.right().any("|[") {
                elm.push(line(u, &right().w()));
            }
            //    |_
            if self.left().any("|]") {
                elm.push(line(y, &left().w()));
            }
        }
        if self.any("`'") {
            // for circuitries
            //  +     +    \
            //   `>    '>   `>
            if self.top_left().any("+\\") && self.right().is('>') {
                elm.push(arrow_line(&top_left().m(), &right().f()));
                consumed.extend(vec![this(), right()]);
            }
            // for circuitries
            //     +    /
            //   <'   <'
            if self.top_right().any("+/") && self.left().is('<') {
                elm.push(arrow_line(&top_right().m(), &left().j()));
                consumed.extend(vec![this(), left()]);
            }
            // For diamond rectangle
            //     .
            //    '
            if self.top_right().any(".,") {
                elm.push(line(c, &top_right().m()));
                consumed.extend(vec![this(), top_right()]);
            }
            //   .
            //    '
            if self.top_left().any(".,") {
                elm.push(line(c, &top_left().m()));
                consumed.extend(vec![this(), top_left()]);
            }
            //   .'
            if self.left().any(".,") {
                elm.push(line(c, &left().m()));
                consumed.extend(vec![this(),left()]);
            }
            //   '.
            if self.right().any(".,") {
                elm.push(line(c, &right().m()));
                consumed.extend(vec![this(),right()]);
            }
        }
        if self.any(".,") {
            // for circuitries
            //   <.    <,   <.
            //     +     \    \
            if self.bottom_right().any("+\\") && self.left().is('<') {
                elm.push(arrow_line(&bottom_right().m(), &left().t()));
                consumed.extend(vec![this(),left()]);
            }
            // for circuitries
            //   .>    ,>   ,>
            //  +     +    /
            if self.bottom_left().any("+/") && self.right().is('>') {
                elm.push(arrow_line(&bottom_left().m(), &right().p()));
                consumed.extend(vec![this(),right()]);
            }
        }
        // transistor complimentary enhancement
        if self.is('|') {
            //    |    |
            //    <    >
            if self.bottom().any("><") {
                elm.push(line(c, &bottom().m()));
                consumed.push(this());
            }
            //    <    >
            //    |    |
            if self.top().any("><") {
                elm.push(line(w, &top().m()));
                consumed.push(this());
            }
            //    _
            //   |
            if self.top_right().is('_') {
                elm.extend(vec![line(c,w),line(c, e)]);
                consumed.push(this());
            }
            //    _
            //     |
            if self.top_left().is('_') {
                elm.extend(vec![line(c,w),line(a,c)]);
                consumed.push(this());
            }
        }
        if self.is('/') {
            //      >
            //     /
            if self.top_right().is('>') {
                elm.push(line(u, &top_right().m()));
                consumed.push(this());
            }
            //    /
            //   <
            if self.bottom_left().is('<') {
                elm.push(line(e, &bottom_left().m()));
                consumed.push(this());
            }
        }
        if self.is('\\') {
            //      \
            //       >
            if self.bottom_right().is('>') {
                elm.push(line(a, &bottom_right().m()));
                consumed.push(this());
            }
            //    <
            //     \
            if self.top_left().is('<') {
                elm.push(line(y, &top_left().m()));
                consumed.push(this());
            }
        }

        if self.any("vV"){
            //     `.
            //       V
            if self.top_left().is('.') && self.top().in_left(2).is('`'){
                elm.push(arrow_line(&top_left2().c(), j));
                consumed.push(this())
            }
            //    .'
            //   V
            if self.top_right().is('.') && self.top().in_right(2).is('\''){
                elm.push(arrow_line(&top_right2().c(), f));
                consumed.push(this())
            }
        }
        if self.is('^'){
            //  ^
            //   `.
            if self.bottom_right().is('`') && self.bottom().in_right(2).is('.'){
                elm.push(arrow_line(&bottom_right2().t(), m));
                consumed.push(this());
            }
            //    ^
            //  .'
            if self.bottom_left().is('\'') && self.bottom().in_left(2).is('.') {
                elm.push(arrow_line(&bottom_left2().p(), m));
                consumed.push(this());
            }
        }
        // circuitries jump
        //    |
        //   -(-
        //    |
        //
       if self.is('(') && self.top().can_strongly_connect(&W)
            && self.bottom().can_strongly_connect(&C)
            && self.left().can_strongly_connect(&O)
            && self.right().can_strongly_connect(&K)
        {
            elm.extend(vec![arc(c, w, 5), line(k, o)]);
            consumed.push(this());
        }
        // circuitries jump
        //    |
        //   -)-
        //    |
        //
        if self.is(')') && self.top().can_strongly_connect(&W)
            && self.bottom().can_strongly_connect(&C)
            && self.left().can_strongly_connect(&O)
            && self.right().can_strongly_connect(&K)
        {
            elm.extend(vec![arc(w, c, 5), line(k, o)]);
            consumed.push(this());
        }

        (elm, consumed)
    }
}
<commit_msg>minor enhancement on circuitries<commit_after>use focus_char::FocusChar;
use fragments::Fragment;
use location::Location;
use location::Direction::{Bottom, BottomLeft, BottomRight, Left, Right, Top, TopLeft, TopRight};
use block::Block::{A, C, E, F, J, K, M, O, P, S, U, W, Y};
use point_block::PointBlock;
use fragments::{line, arc, arrow_line};

pub trait Enhance {
    fn enhance(&self) -> (Vec<Fragment>, Vec<Location>);
}

impl<'g> Enhance for FocusChar<'g> {

    fn enhance(&self) -> (Vec<Fragment>, Vec<Location>) {
        let mut elm = vec![];
        let mut consumed = vec![];
        let a = &PointBlock::block(A);
        //let _b = &PointBlock::block(B);
        let c = &PointBlock::block(C);
        //let _d = &PointBlock::block(D);
        let e = &PointBlock::block(E);
        let f = &PointBlock::block(F);
        //let _g = &PointBlock::block(G);
        //let _h = &PointBlock::block(H);
        //let _i = &PointBlock::block(I);
        let j = &PointBlock::block(J);
        let k = &PointBlock::block(K);
        //let _l = &PointBlock::block(L);
        let m = &PointBlock::block(M);
        //let _n = &PointBlock::block(N);
        let o = &PointBlock::block(O);
        let p = &PointBlock::block(P);
        //let _q = &PointBlock::block(Q);
        //let _r = &PointBlock::block(R);
        let s = &PointBlock::block(S);
        //let _t = &PointBlock::block(T);
        let u = &PointBlock::block(U);
        //let _v = &PointBlock::block(V);
        let w = &PointBlock::block(W);
        //let _x = &PointBlock::block(X);
        let y = &PointBlock::block(Y);

        let this = || Location::this();
        let top = || Location::go(Top);
        let bottom = || Location::go(Bottom);
        let left = || Location::go(Left);
        let right = || Location::go(Right);
        let top_left = || Location::go(TopLeft);
        let top_right = || Location::go(TopRight);
        let bottom_left = || Location::go(BottomLeft);
        let bottom_right = || Location::go(BottomRight);
        let top2 = || Location::jump(Top,2);

        let top_left2 = || top().go_left(2);
        let top_right2 = || top().go_right(2);
        let bottom_right2 = || bottom().go_right(2);
        let bottom_left2 = || bottom().go_left(2);
        let top2_right = || top2().right();

        // _ underscore
        if self.is('_') {
            //   _|
            if self.right().any("|[") {
                elm.push(line(u, &right().w()));
            }
            //    |_
            if self.left().any("|]") {
                elm.push(line(y, &left().w()));
            }
        }
        if self.any("`'") {
            // for circuitries
            //  +     +
            //   `>    '>
            if self.top_left().is('+') && self.right().is('>') {
                elm.push(arrow_line(&top_left().m(), &right().f()));
                consumed.extend(vec![this(), right()]);
            }
            //      \
            //       `>
            if self.top_left().is('\\') && self.right().is('>') {
                elm.push(arrow_line(&top_left().c(), &right().f()));
                consumed.extend(vec![this(), right(), top_left()]);
            }
            //
            //        +
            //      <'
            if self.top_right().is('+') && self.left().is('<') {
                elm.push(arrow_line(&top_right().m(), &left().j()));
                consumed.extend(vec![this(), left()]);
            }
            //
            //        /
            //      <'
            if self.top_right().is('/') && self.left().is('<') {
                elm.push(arrow_line(&top_right().c(), &left().j()));
                consumed.extend(vec![this(), left(),top_right()]);
            }
            // For diamond rectangle
            //     .
            //    '
            if self.top_right().any(".,") {
                elm.push(line(c, &top_right().m()));
                consumed.extend(vec![this(), top_right()]);
            }
            //   .
            //    '
            if self.top_left().any(".,") {
                elm.push(line(c, &top_left().m()));
                consumed.extend(vec![this(), top_left()]);
            }
            //   .'
            if self.left().any(".,") {
                elm.push(line(c, &left().m()));
                consumed.extend(vec![this(),left()]);
            }
            //   '.
            if self.right().any(".,") {
                elm.push(line(c, &right().m()));
                consumed.extend(vec![this(),right()]);
            }
        }
        if self.any(".,") {
            // for circuitries
            //   <.  <,
            //     +   +
            if self.bottom_right().is('+') && self.left().is('<') {
                elm.push(arrow_line(&bottom_right().m(), &left().t()));
                consumed.extend(vec![this(),left()]);
            }
            //       <,   <.
            //         \    \
            if self.bottom_right().is('\\') && self.left().is('<') {
                elm.push(arrow_line(&bottom_right().w(), &left().t()));
                consumed.extend(vec![this(),left(), bottom_right()]);
            }
            //
            //   .>    ,>
            //  +     +
            if self.bottom_left().is('+') && self.right().is('>') {
                elm.push(arrow_line(&bottom_left().m(), &right().p()));
                consumed.extend(vec![this(),right()]);
            }
            //
            //       ,>
            //      /
            if self.bottom_left().is('/') && self.right().is('>') {
                elm.push(arrow_line(&bottom_left().w(), &right().p()));
                consumed.extend(vec![this(),right(), bottom_left()]);
            }
        }
        // transistor complimentary enhancement
        if self.is('|') {
            //    |    |
            //    <    >
            if self.bottom().any("><") {
                elm.push(line(c, &bottom().m()));
                consumed.push(this());
            }
            //    <    >
            //    |    |
            if self.top().any("><") {
                elm.push(line(w, &top().m()));
                consumed.push(this());
            }
            //    _
            //   |
            if self.top_right().is('_') {
                elm.extend(vec![line(c,w),line(c, e)]);
                consumed.push(this());
            }
            //    _
            //     |
            if self.top_left().is('_') {
                elm.extend(vec![line(c,w),line(a,c)]);
                consumed.push(this());
            }
        }
        if self.is('/') {
            //      >
            //     /
            if self.top_right().is('>') {
                elm.push(line(u, &top_right().m()));
                consumed.push(this());
            }
            //    /
            //   <
            if self.bottom_left().is('<') {
                elm.push(line(e, &bottom_left().m()));
                consumed.push(this());
            }
        }
        if self.is('\\') {
            //      \
            //       >
            if self.bottom_right().is('>') {
                elm.push(line(a, &bottom_right().m()));
                consumed.push(this());
            }
            //    <
            //     \
            if self.top_left().is('<') {
                elm.push(line(y, &top_left().m()));
                consumed.push(this());
            }
        }

        if self.any("vV"){
            //     `.
            //       V
            if self.top_left().is('.') && self.top().in_left(2).is('`'){
                elm.push(arrow_line(&top_left2().c(), j));
                consumed.push(this())
            }
            //    .'
            //   V
            if self.top_right().is('.') && self.top().in_right(2).is('\''){
                elm.push(arrow_line(&top_right2().c(), f));
                consumed.push(this())
            }
        }
        if self.is('^'){
            //  ^
            //   `.
            if self.bottom_right().is('`') && self.bottom().in_right(2).is('.'){
                elm.push(arrow_line(&bottom_right2().t(), m));
                consumed.push(this());
            }
            //    ^
            //  .'
            if self.bottom_left().is('\'') && self.bottom().in_left(2).is('.') {
                elm.push(arrow_line(&bottom_left2().p(), m));
                consumed.push(this());
            }
        }
        // circuitries jump
        //    |
        //   -(-
        //    |
        //
       if self.is('(') && self.top().can_strongly_connect(&W)
            && self.bottom().can_strongly_connect(&C)
            && self.left().can_strongly_connect(&O)
            && self.right().can_strongly_connect(&K)
        {
            elm.extend(vec![arc(c, w, 5), line(k, o)]);
            consumed.push(this());
        }
        // circuitries jump
        //    |
        //   -)-
        //    |
        //
        if self.is(')') && self.top().can_strongly_connect(&W)
            && self.bottom().can_strongly_connect(&C)
            && self.left().can_strongly_connect(&O)
            && self.right().can_strongly_connect(&K)
        {
            elm.extend(vec![arc(w, c, 5), line(k, o)]);
            consumed.push(this());
        }

        (elm, consumed)
    }
}
<|endoftext|>


<commit_before>// Copyright 2019 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![doc(
    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
    html_favicon_url = "https://www.rust-lang.org/favicon.ico",
    html_root_url = "https://rust-random.github.io/rand/"
)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![allow(
    clippy::excessive_precision,
    clippy::float_cmp,
    clippy::unreadable_literal
)]
#![allow(clippy::neg_cmp_op_on_partial_ord)] // suggested fix too verbose
#![no_std]
#![cfg_attr(doc_cfg, feature(doc_cfg))]

//! Generating random samples from probability distributions.
//!
//! ## Re-exports
//!
//! This crate is a super-set of the [`rand::distributions`] module. See the
//! [`rand::distributions`] module documentation for an overview of the core
//! [`Distribution`] trait and implementations.
//!
//! The following are re-exported:
//!
//! - The [`Distribution`] trait and [`DistIter`] helper type
//! - The [`Standard`], [`Alphanumeric`], [`Uniform`], [`OpenClosed01`],
//! [`Open01`], [`Bernoulli`], and [`WeightedIndex`] distributions
//!
//! ## Distributions
//!
//! This crate provides the following probability distributions:
//!
//! - Related to real-valued quantities that grow linearly
//!   (e.g. errors, offsets):
//!   - [`Normal`] distribution, and [`StandardNormal`] as a primitive
//!   - [`Cauchy`] distribution
//! - Related to Bernoulli trials (yes/no events, with a given probability):
//!   - [`Binomial`] distribution
//! - Related to positive real-valued quantities that grow exponentially
//!   (e.g. prices, incomes, populations):
//!   - [`LogNormal`] distribution
//! - Related to the occurrence of independent events at a given rate:
//!   - [`Pareto`] distribution
//!   - [`Poisson`] distribution
//!   - [`Exp`]onential distribution, and [`Exp1`] as a primitive
//!   - [`Weibull`] distribution
//! - Gamma and derived distributions:
//!   - [`Gamma`] distribution
//!   - [`ChiSquared`] distribution
//!   - [`StudentT`] distribution
//!   - [`FisherF`] distribution
//! - Triangular distribution:
//!   - [`Beta`] distribution
//!   - [`Triangular`] distribution
//! - Multivariate probability distributions
//!   - [`Dirichlet`] distribution
//!   - [`UnitSphere`] distribution
//!   - [`UnitBall`] distribution
//!   - [`UnitCircle`] distribution
//!   - [`UnitDisc`] distribution
//! - Misc. distributions
//!   - [`InverseGaussian`] distribution
//!   - [`NormalInverseGaussian`] distribution

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

pub use rand::distributions::{
    uniform, Alphanumeric, Bernoulli, BernoulliError, DistIter, Distribution, Open01, OpenClosed01,
    Standard, Uniform,
};

pub use self::binomial::{Binomial, Error as BinomialError};
pub use self::cauchy::{Cauchy, Error as CauchyError};
#[cfg(feature = "alloc")]
pub use self::dirichlet::{Dirichlet, Error as DirichletError};
pub use self::exponential::{Error as ExpError, Exp, Exp1};
pub use self::gamma::{
    Beta, BetaError, ChiSquared, ChiSquaredError, Error as GammaError, FisherF, FisherFError,
    Gamma, StudentT,
};
pub use self::inverse_gaussian::{InverseGaussian, Error as InverseGaussianError};
pub use self::normal::{Error as NormalError, LogNormal, Normal, StandardNormal};
pub use self::normal_inverse_gaussian::{NormalInverseGaussian, Error as NormalInverseGaussianError};
pub use self::pareto::{Error as ParetoError, Pareto};
pub use self::pert::{Pert, PertError};
pub use self::poisson::{Error as PoissonError, Poisson};
pub use self::triangular::{Triangular, TriangularError};
pub use self::unit_ball::UnitBall;
pub use self::unit_circle::UnitCircle;
pub use self::unit_disc::UnitDisc;
pub use self::unit_sphere::UnitSphere;
pub use self::weibull::{Error as WeibullError, Weibull};
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
pub use rand::distributions::weighted::{WeightedError, WeightedIndex};
#[cfg(feature = "alloc")]
pub use weighted_alias::WeightedAliasIndex;

pub use num_traits;

#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
pub mod weighted_alias;

mod binomial;
mod cauchy;
mod dirichlet;
mod exponential;
mod gamma;
mod inverse_gaussian;
mod normal;
mod normal_inverse_gaussian;
mod pareto;
mod pert;
mod poisson;
mod triangular;
mod unit_ball;
mod unit_circle;
mod unit_disc;
mod unit_sphere;
mod utils;
mod weibull;
mod ziggurat_tables;

#[cfg(test)]
mod test {
    // Notes on testing
    //
    // Testing random number distributions correctly is hard. The following
    // testing is desired:
    //
    // - Construction: test initialisation with a few valid parameter sets.
    // - Erroneous usage: test that incorrect usage generates an error.
    // - Vector: test that usage with fixed inputs (including RNG) generates a
    //   fixed output sequence on all platforms.
    // - Correctness at fixed points (optional): using a specific mock RNG,
    //   check that specific values are sampled (e.g. end-points and median of
    //   distribution).
    // - Correctness of PDF (extra): generate a histogram of samples within a
    //   certain range, and check this approximates the PDF. These tests are
    //   expected to be expensive, and should be behind a feature-gate.
    //
    // TODO: Vector and correctness tests are largely absent so far.
    // NOTE: Some distributions have tests checking only that samples can be
    // generated. This is redundant with vector and correctness tests.

    /// Construct a deterministic RNG with the given seed
    pub fn rng(seed: u64) -> impl rand::RngCore {
        // For tests, we want a statistically good, fast, reproducible RNG.
        // PCG32 will do fine, and will be easy to embed if we ever need to.
        const INC: u64 = 11634580027462260723;
        rand_pcg::Pcg32::new(seed, INC)
    }
}
<commit_msg>Don't use deprecated import path<commit_after>// Copyright 2019 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![doc(
    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
    html_favicon_url = "https://www.rust-lang.org/favicon.ico",
    html_root_url = "https://rust-random.github.io/rand/"
)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![allow(
    clippy::excessive_precision,
    clippy::float_cmp,
    clippy::unreadable_literal
)]
#![allow(clippy::neg_cmp_op_on_partial_ord)] // suggested fix too verbose
#![no_std]
#![cfg_attr(doc_cfg, feature(doc_cfg))]

//! Generating random samples from probability distributions.
//!
//! ## Re-exports
//!
//! This crate is a super-set of the [`rand::distributions`] module. See the
//! [`rand::distributions`] module documentation for an overview of the core
//! [`Distribution`] trait and implementations.
//!
//! The following are re-exported:
//!
//! - The [`Distribution`] trait and [`DistIter`] helper type
//! - The [`Standard`], [`Alphanumeric`], [`Uniform`], [`OpenClosed01`],
//! [`Open01`], [`Bernoulli`], and [`WeightedIndex`] distributions
//!
//! ## Distributions
//!
//! This crate provides the following probability distributions:
//!
//! - Related to real-valued quantities that grow linearly
//!   (e.g. errors, offsets):
//!   - [`Normal`] distribution, and [`StandardNormal`] as a primitive
//!   - [`Cauchy`] distribution
//! - Related to Bernoulli trials (yes/no events, with a given probability):
//!   - [`Binomial`] distribution
//! - Related to positive real-valued quantities that grow exponentially
//!   (e.g. prices, incomes, populations):
//!   - [`LogNormal`] distribution
//! - Related to the occurrence of independent events at a given rate:
//!   - [`Pareto`] distribution
//!   - [`Poisson`] distribution
//!   - [`Exp`]onential distribution, and [`Exp1`] as a primitive
//!   - [`Weibull`] distribution
//! - Gamma and derived distributions:
//!   - [`Gamma`] distribution
//!   - [`ChiSquared`] distribution
//!   - [`StudentT`] distribution
//!   - [`FisherF`] distribution
//! - Triangular distribution:
//!   - [`Beta`] distribution
//!   - [`Triangular`] distribution
//! - Multivariate probability distributions
//!   - [`Dirichlet`] distribution
//!   - [`UnitSphere`] distribution
//!   - [`UnitBall`] distribution
//!   - [`UnitCircle`] distribution
//!   - [`UnitDisc`] distribution
//! - Misc. distributions
//!   - [`InverseGaussian`] distribution
//!   - [`NormalInverseGaussian`] distribution

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

pub use rand::distributions::{
    uniform, Alphanumeric, Bernoulli, BernoulliError, DistIter, Distribution, Open01, OpenClosed01,
    Standard, Uniform,
};

pub use self::binomial::{Binomial, Error as BinomialError};
pub use self::cauchy::{Cauchy, Error as CauchyError};
#[cfg(feature = "alloc")]
pub use self::dirichlet::{Dirichlet, Error as DirichletError};
pub use self::exponential::{Error as ExpError, Exp, Exp1};
pub use self::gamma::{
    Beta, BetaError, ChiSquared, ChiSquaredError, Error as GammaError, FisherF, FisherFError,
    Gamma, StudentT,
};
pub use self::inverse_gaussian::{InverseGaussian, Error as InverseGaussianError};
pub use self::normal::{Error as NormalError, LogNormal, Normal, StandardNormal};
pub use self::normal_inverse_gaussian::{NormalInverseGaussian, Error as NormalInverseGaussianError};
pub use self::pareto::{Error as ParetoError, Pareto};
pub use self::pert::{Pert, PertError};
pub use self::poisson::{Error as PoissonError, Poisson};
pub use self::triangular::{Triangular, TriangularError};
pub use self::unit_ball::UnitBall;
pub use self::unit_circle::UnitCircle;
pub use self::unit_disc::UnitDisc;
pub use self::unit_sphere::UnitSphere;
pub use self::weibull::{Error as WeibullError, Weibull};
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
pub use rand::distributions::{WeightedError, WeightedIndex};
#[cfg(feature = "alloc")]
pub use weighted_alias::WeightedAliasIndex;

pub use num_traits;

#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
pub mod weighted_alias;

mod binomial;
mod cauchy;
mod dirichlet;
mod exponential;
mod gamma;
mod inverse_gaussian;
mod normal;
mod normal_inverse_gaussian;
mod pareto;
mod pert;
mod poisson;
mod triangular;
mod unit_ball;
mod unit_circle;
mod unit_disc;
mod unit_sphere;
mod utils;
mod weibull;
mod ziggurat_tables;

#[cfg(test)]
mod test {
    // Notes on testing
    //
    // Testing random number distributions correctly is hard. The following
    // testing is desired:
    //
    // - Construction: test initialisation with a few valid parameter sets.
    // - Erroneous usage: test that incorrect usage generates an error.
    // - Vector: test that usage with fixed inputs (including RNG) generates a
    //   fixed output sequence on all platforms.
    // - Correctness at fixed points (optional): using a specific mock RNG,
    //   check that specific values are sampled (e.g. end-points and median of
    //   distribution).
    // - Correctness of PDF (extra): generate a histogram of samples within a
    //   certain range, and check this approximates the PDF. These tests are
    //   expected to be expensive, and should be behind a feature-gate.
    //
    // TODO: Vector and correctness tests are largely absent so far.
    // NOTE: Some distributions have tests checking only that samples can be
    // generated. This is redundant with vector and correctness tests.

    /// Construct a deterministic RNG with the given seed
    pub fn rng(seed: u64) -> impl rand::RngCore {
        // For tests, we want a statistically good, fast, reproducible RNG.
        // PCG32 will do fine, and will be easy to embed if we ever need to.
        const INC: u64 = 11634580027462260723;
        rand_pcg::Pcg32::new(seed, INC)
    }
}
<|endoftext|>


<commit_before>use std::sync::Arc;

use futures;
use futures::{Future, Stream, Poll};
use futures::future::{result};
use hyper;
use hyper::{Body, Method};
use hyper::client::Client;
use hyper::header::ContentType;
use hyper_tls::HttpsConnector;
use serde_json;
use tokio_core::reactor::Handle;
use url::Url;

use telegram_bot_raw::{Request, Response};

use errors::{Error, Result, ErrorKind};

use stream::UpdatesStream;

const TELEGRAM_URL: &'static str = "https://api.telegram.org/";

#[must_use = "futures do nothing unless polled"]
pub struct TelegramFuture<T> {
    inner: Box<Future<Item=T, Error=Error>>
}

impl<T> Future for TelegramFuture<T> {
    type Item = T;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        self.inner.poll()
    }
}

#[derive(Clone)]
pub struct Api {
    inner: Arc<ApiInner>,
}

#[derive(Clone)]
struct ApiInner {
    token: String,
    client: Client<HttpsConnector>,
    handle: Handle,
}

impl Api {
    pub fn from_token(handle: &Handle, token: &str) -> Result<Self> {
        let connector = HttpsConnector::new(1, handle);
        let config = Client::configure().connector(connector);

        Ok(Api {
            inner: Arc::new(ApiInner {
                token: token.to_string(),
                client: config.build(handle),
                handle: handle.clone(),
            }),
        })
    }

    pub fn stream(&self) -> UpdatesStream {
        UpdatesStream::new(self)
    }

    pub fn spawn<Req>(&self, request: Req)
        where Req: Request + 'static, <Req as Request>::Response: ::std::marker::Send + 'static {

        self.inner.handle.spawn(self.send(request).then(|_| Ok(())))
    }

    pub fn send<Req>(&self, request: Req) -> TelegramFuture<Req::Response>
        where Req: Request + 'static, <Req as Request>::Response: ::std::marker::Send + 'static {

        let url = result(url(&self.inner.token, request.name()));
        let body = futures::lazy(move || {
            serde_json::to_vec(&request).map(Body::from)
        }).map_err(From::from);

        let api = self.clone();
        let response = url.join(body).and_then(move |(url, body)| {
            let mut http_request = hyper::client::Request::new(Method::Post, url);
            http_request.set_body(body);
            http_request.headers_mut().set(ContentType::json());

            api.inner.client.request(http_request).map_err(From::from)
        });

        let bytes = response.and_then(|response| {
            response.body().map_err(From::from)
                .fold(vec![], |mut result, chunk| -> Result<Vec<u8>> {
                    result.extend_from_slice(&chunk);
                    Ok(result)
            })
        });

        let future = bytes.and_then(|bytes| {
            result(serde_json::from_slice(&bytes).map_err(From::from).and_then(|value| {
                match value {
                    Response::Success {result} => Ok(result),
                    Response::Error { description, parameters } => {
                        Err(ErrorKind::TelegramError {
                            description: description,
                            parameters: parameters
                        }.into())
                    },
                }
            }))
        });

        TelegramFuture {
            inner: Box::new(future)
        }
    }
}

fn url(token: &str, method: &str) -> Result<Url> {
    Url::parse(&format!("{}bot{}/{}", TELEGRAM_URL, token, method)).map_err(From::from)
}
<commit_msg>refactor: use Rc instead of Arc in Api<commit_after>use std::rc::Rc;

use futures;
use futures::{Future, Stream, Poll};
use futures::future::{result};
use hyper;
use hyper::{Body, Method};
use hyper::client::Client;
use hyper::header::ContentType;
use hyper_tls::HttpsConnector;
use serde_json;
use tokio_core::reactor::Handle;
use url::Url;

use telegram_bot_raw::{Request, Response};

use errors::{Error, Result, ErrorKind};

use stream::UpdatesStream;

const TELEGRAM_URL: &'static str = "https://api.telegram.org/";

#[must_use = "futures do nothing unless polled"]
pub struct TelegramFuture<T> {
    inner: Box<Future<Item=T, Error=Error>>
}

impl<T> Future for TelegramFuture<T> {
    type Item = T;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        self.inner.poll()
    }
}

#[derive(Clone)]
pub struct Api {
    inner: Rc<ApiInner>,
}

#[derive(Clone)]
struct ApiInner {
    token: String,
    client: Client<HttpsConnector>,
    handle: Handle,
}

impl Api {
    pub fn from_token(handle: &Handle, token: &str) -> Result<Self> {
        let connector = HttpsConnector::new(1, handle);
        let config = Client::configure().connector(connector);

        Ok(Api {
            inner: Rc::new(ApiInner {
                token: token.to_string(),
                client: config.build(handle),
                handle: handle.clone(),
            }),
        })
    }

    pub fn stream(&self) -> UpdatesStream {
        UpdatesStream::new(self)
    }

    pub fn spawn<Req>(&self, request: Req)
        where Req: Request + 'static, <Req as Request>::Response: ::std::marker::Send + 'static {

        self.inner.handle.spawn(self.send(request).then(|_| Ok(())))
    }

    pub fn send<Req>(&self, request: Req) -> TelegramFuture<Req::Response>
        where Req: Request + 'static, <Req as Request>::Response: ::std::marker::Send + 'static {

        let url = result(url(&self.inner.token, request.name()));
        let body = futures::lazy(move || {
            serde_json::to_vec(&request).map(Body::from)
        }).map_err(From::from);

        let api = self.clone();
        let response = url.join(body).and_then(move |(url, body)| {
            let mut http_request = hyper::client::Request::new(Method::Post, url);
            http_request.set_body(body);
            http_request.headers_mut().set(ContentType::json());

            api.inner.client.request(http_request).map_err(From::from)
        });

        let bytes = response.and_then(|response| {
            response.body().map_err(From::from)
                .fold(vec![], |mut result, chunk| -> Result<Vec<u8>> {
                    result.extend_from_slice(&chunk);
                    Ok(result)
            })
        });

        let future = bytes.and_then(|bytes| {
            result(serde_json::from_slice(&bytes).map_err(From::from).and_then(|value| {
                match value {
                    Response::Success {result} => Ok(result),
                    Response::Error { description, parameters } => {
                        Err(ErrorKind::TelegramError {
                            description: description,
                            parameters: parameters
                        }.into())
                    },
                }
            }))
        });

        TelegramFuture {
            inner: Box::new(future)
        }
    }
}

fn url(token: &str, method: &str) -> Result<Url> {
    Url::parse(&format!("{}bot{}/{}", TELEGRAM_URL, token, method)).map_err(From::from)
}
<|endoftext|>