<commit_before>use std::env;
use std::path::{Path};
use std::process::{Command};

const SEARCH_LINUX: &'static [&'static str] = &[
    "/usr/lib",
    "/usr/lib/llvm",
    "/usr/lib/llvm-3.8/lib",
    "/usr/lib/llvm-3.7/lib",
    "/usr/lib/llvm-3.6/lib",
    "/usr/lib/llvm-3.5/lib",
    "/usr/lib/llvm-3.4/lib",
    "/usr/lib64/llvm",
    "/usr/lib/x86_64-linux-gnu",
    "/usr/local/lib",
];

const SEARCH_OSX: &'static [&'static str] = &[
    "/usr/local/opt/llvm/lib",
    "/Library/Developer/CommandLineTools/usr/lib",
    "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib",
];

const SEARCH_WINDOWS: &'static [&'static str] = &[
    "C:\\Program Files\\LLVM\\bin",
    "C:\\Program Files\\LLVM\\lib",
];

fn error(prefix: &str) -> ! {
    panic!("{:?}, set the LIBCLANG_PATH environment variable to your system's libclang directory", prefix);
}

fn run(command: &str, arguments: &[&str]) -> Option<String> {
    Command::new(command).args(arguments).output().map(|o| {
        String::from_utf8_lossy(&o.stdout).into_owned()
    }).ok()
}

fn find_libclang() -> Option<(String, String)> {
    let search = if let Ok(directory) = env::var("LIBCLANG_PATH") {
        vec![directory]
    } else if let Some(output) = run("llvm-config", &["--libdir"]) {
        vec![output.lines().map(|s| s.to_string()).next().unwrap()]
    } else {
        if cfg!(any(target_os="freebsd", target_os="linux")) {
            SEARCH_LINUX
        } else if cfg!(target_os="osx") {
            SEARCH_OSX
        } else if cfg!(target_os="windows") {
            SEARCH_WINDOWS
        } else {
            error("unsupported operating system");
        }.into_iter().map(|s| s.to_string()).collect()
    };
    let library = format!("{}clang{}", env::consts::DLL_PREFIX, env::consts::DLL_SUFFIX);
    let directory = search.into_iter().find(|d| Path::new(&d).join(&library).exists());
    directory.map(|d| (d, library))
}

const LIBRARIES: &'static [&'static str] = &[
    "LLVMAnalysis",
    "LLVMBitReader",
    "LLVMCore",
    "LLVMLTO",
    "LLVMLinker",
    "LLVMMC",
    "LLVMMCParser",
    "LLVMObjCARCOpts",
    "LLVMObject",
    "LLVMOption",
    "LLVMScalarOpts",
    "LLVMSupport",
    "LLVMTarget",
    "LLVMTransformUtils",
    "LLVMVectorize",
    "LLVMipa",
    "LLVMipo",
    "clang",
    "clangARCMigrate",
    "clangAST",
    "clangASTMatchers",
    "clangAnalysis",
    "clangBasic",
    "clangDriver",
    "clangEdit",
    "clangFormat",
    "clangFrontend",
    "clangIndex",
    "clangLex",
    "clangParse",
    "clangRewrite",
    "clangRewriteFrontend",
    "clangSema",
    "clangSerialization",
    "clangStaticAnalyzerCheckers",
    "clangStaticAnalyzerCore",
    "clangStaticAnalyzerFrontend",
    "clangTooling",
];

fn get_libraries() -> Vec<String> {
    run("llvm-config", &["--libs"]).map(|o| {
        o.split_whitespace().filter_map(|p| {
            Path::new(p).file_stem().map(|l| l.to_string_lossy()[2..].into())
        }).collect()
    }).unwrap_or_else(|| LIBRARIES.iter().map(|l| (*l).into()).collect())
}

fn main() {
    let (directory, file) = match find_libclang() {
        Some((directory, file)) => (directory, file),
        _ => error("unable to find libclang"),
    };

    if cfg!(feature="static") {
        print!("cargo:rustc-flags=");
        if let Ok(directory) = env::var("LIBCLANG_STATIC_PATH") {
            print!("-L {} ", directory);
        }
        for library in get_libraries() {
            print!("-l static={} ", library)
        }
        println!("-L {} -l ncursesw -l z -l stdc++", directory);
    } else {
        println!("cargo:rustc-link-search={}", directory);
        println!("cargo:rustc-link-lib=dylib=:{}", file);
    }
}
<commit_msg>Fix target_os value for OS X<commit_after>use std::env;
use std::path::{Path};
use std::process::{Command};

const SEARCH_LINUX: &'static [&'static str] = &[
    "/usr/lib",
    "/usr/lib/llvm",
    "/usr/lib/llvm-3.8/lib",
    "/usr/lib/llvm-3.7/lib",
    "/usr/lib/llvm-3.6/lib",
    "/usr/lib/llvm-3.5/lib",
    "/usr/lib/llvm-3.4/lib",
    "/usr/lib64/llvm",
    "/usr/lib/x86_64-linux-gnu",
    "/usr/local/lib",
];

const SEARCH_OSX: &'static [&'static str] = &[
    "/usr/local/opt/llvm/lib",
    "/Library/Developer/CommandLineTools/usr/lib",
    "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib",
];

const SEARCH_WINDOWS: &'static [&'static str] = &[
    "C:\\Program Files\\LLVM\\bin",
    "C:\\Program Files\\LLVM\\lib",
];

fn error(prefix: &str) -> ! {
    panic!("{:?}, set the LIBCLANG_PATH environment variable to your system's libclang directory", prefix);
}

fn run(command: &str, arguments: &[&str]) -> Option<String> {
    Command::new(command).args(arguments).output().map(|o| {
        String::from_utf8_lossy(&o.stdout).into_owned()
    }).ok()
}

fn find_libclang() -> Option<(String, String)> {
    let search = if let Ok(directory) = env::var("LIBCLANG_PATH") {
        vec![directory]
    } else if let Some(output) = run("llvm-config", &["--libdir"]) {
        vec![output.lines().map(|s| s.to_string()).next().unwrap()]
    } else {
        if cfg!(any(target_os="freebsd", target_os="linux")) {
            SEARCH_LINUX
        } else if cfg!(target_os="macos") {
            SEARCH_OSX
        } else if cfg!(target_os="windows") {
            SEARCH_WINDOWS
        } else {
            error("unsupported operating system");
        }.into_iter().map(|s| s.to_string()).collect()
    };
    let library = format!("{}clang{}", env::consts::DLL_PREFIX, env::consts::DLL_SUFFIX);
    let directory = search.into_iter().find(|d| Path::new(&d).join(&library).exists());
    directory.map(|d| (d, library))
}

const LIBRARIES: &'static [&'static str] = &[
    "LLVMAnalysis",
    "LLVMBitReader",
    "LLVMCore",
    "LLVMLTO",
    "LLVMLinker",
    "LLVMMC",
    "LLVMMCParser",
    "LLVMObjCARCOpts",
    "LLVMObject",
    "LLVMOption",
    "LLVMScalarOpts",
    "LLVMSupport",
    "LLVMTarget",
    "LLVMTransformUtils",
    "LLVMVectorize",
    "LLVMipa",
    "LLVMipo",
    "clang",
    "clangARCMigrate",
    "clangAST",
    "clangASTMatchers",
    "clangAnalysis",
    "clangBasic",
    "clangDriver",
    "clangEdit",
    "clangFormat",
    "clangFrontend",
    "clangIndex",
    "clangLex",
    "clangParse",
    "clangRewrite",
    "clangRewriteFrontend",
    "clangSema",
    "clangSerialization",
    "clangStaticAnalyzerCheckers",
    "clangStaticAnalyzerCore",
    "clangStaticAnalyzerFrontend",
    "clangTooling",
];

fn get_libraries() -> Vec<String> {
    run("llvm-config", &["--libs"]).map(|o| {
        o.split_whitespace().filter_map(|p| {
            Path::new(p).file_stem().map(|l| l.to_string_lossy()[2..].into())
        }).collect()
    }).unwrap_or_else(|| LIBRARIES.iter().map(|l| (*l).into()).collect())
}

fn main() {
    let (directory, file) = match find_libclang() {
        Some((directory, file)) => (directory, file),
        _ => error("unable to find libclang"),
    };

    if cfg!(feature="static") {
        print!("cargo:rustc-flags=");
        if let Ok(directory) = env::var("LIBCLANG_STATIC_PATH") {
            print!("-L {} ", directory);
        }
        for library in get_libraries() {
            print!("-l static={} ", library)
        }
        println!("-L {} -l ncursesw -l z -l stdc++", directory);
    } else {
        println!("cargo:rustc-link-search={}", directory);
        println!("cargo:rustc-link-lib=dylib=:{}", file);
    }
}
<|endoftext|>


<commit_before>#[cfg(all(windows, target_env = "msvc"))]
extern crate winreg;

use std::process::Command;
use std::path::{Path, PathBuf};
use std::env;
#[cfg(all(windows, target_env = "msvc"))]
use winreg::enums::*;

#[cfg(not(windows))]
fn main() {}

#[cfg(windows)]
fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    compile_resource(&out_dir);
    println!("cargo:rustc-link-search=native={}", out_dir);
}

#[cfg(all(windows, target_env = "msvc"))]
fn compile_resource(out_dir: &str) {
    // `.res`es are linkable under MSVC as well as normal libraries.
    let rc_path = find_windows_sdk_bin_dir().and_then(|mut x| {
        x.push("rc.exe");
        if x.exists() { Some(x) } else { None }
    });

    Command::new(rc_path.as_ref().map_or(Path::new("rc.exe"), Path::new))
        .args(&["/fo", &format!("{}/cargo-install-update-manifest.lib", out_dir), "cargo-install-update-manifest.rc"])
        .status()
        .expect("Are you sure you have RC.EXE in your $PATH?");
}

#[cfg(all(windows, target_env = "msvc"))]
fn find_windows_sdk_bin_dir() -> Option<PathBuf> {
    #[derive(Clone, Copy)]
    enum Arch {
        X86,
        X64,
    }

    // Windows 8 - 10
    fn find_windows_kits_bin_dir(key: &str, arch: Arch) -> Option<PathBuf> {
        winreg::RegKey::predef(HKEY_LOCAL_MACHINE)
            .open_subkey_with_flags(r"SOFTWARE\Microsoft\Windows Kits\Installed Roots", KEY_QUERY_VALUE)
            .and_then(|reg_key| reg_key.get_value::<String, _>(key))
            .ok()
            .and_then(|root_dir| {
                let mut p = PathBuf::from(root_dir);
                match arch {
                    Arch::X86 => p.push(r"bin\x86"),
                    Arch::X64 => p.push(r"bin\x64"),
                }
                if p.is_dir() { Some(p) } else { None }
            })
    }

    // Windows Vista - 7
    fn find_latest_windows_sdk_bin_dir(arch: Arch) -> Option<PathBuf> {
        winreg::RegKey::predef(HKEY_LOCAL_MACHINE)
            .open_subkey_with_flags(r"SOFTWARE\Microsoft\Microsoft SDKs\Windows", KEY_QUERY_VALUE)
            .and_then(|reg_key| reg_key.get_value::<String, _>("CurrentInstallFolder"))
            .ok()
            .and_then(|root_dir| {
                let mut p = PathBuf::from(root_dir);
                match arch {
                    Arch::X86 => p.push("Bin"),
                    Arch::X64 => p.push(r"Bin\x64"),
                }
                if p.is_dir() { Some(p) } else { None }
            })
    }

    let arch = if env::var("TARGET").unwrap().starts_with("x86_64") {
        Arch::X64
    } else {
        Arch::X86
    };

    find_windows_kits_bin_dir("KitsRoot10", arch)
        .or_else(|| find_windows_kits_bin_dir("KitsRoot81", arch))
        .or_else(|| find_windows_kits_bin_dir("KitsRoot", arch))
        .or_else(|| find_latest_windows_sdk_bin_dir(arch))
}

#[cfg(all(windows, not(target_env = "msvc")))]
fn compile_resource(out_dir: &str) {
    Command::new("windres")
        .args(&["--input", "cargo-install-update-manifest.rc", "--output-format=coff", "--output"])
        .arg(&format!("{}/cargo-install-update-manifest.res", out_dir))
        .status()
        .unwrap();

    Command::new("ar")
        .args(&["crs", "libcargo-install-update-manifest.a", "cargo-install-update-manifest.res"])
        .current_dir(&Path::new(&out_dir))
        .status()
        .unwrap();
}
<commit_msg>Fix build.rs nitpicks<commit_after>#[cfg(all(windows, target_env = "msvc"))]
extern crate winreg;

#[cfg(all(windows, target_env = "msvc"))]
use winreg::enums::*;

use std::path::{Path, PathBuf};
use std::process::Command;
use std::env;

#[cfg(not(windows))]
fn main() {}

#[cfg(windows)]
fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    compile_resource(&out_dir);
    println!("cargo:rustc-link-search=native={}", out_dir);
}

#[cfg(all(windows, target_env = "msvc"))]
fn compile_resource(out_dir: &str) {
    let rc_path = find_windows_sdk_bin_dir().and_then(|mut x| {
        x.push("rc.exe");
        if x.exists() { Some(x) } else { None }
    });

    // `.res`es are linkable under MSVC as well as normal libraries.
    Command::new(rc_path.as_ref().map_or(Path::new("rc.exe"), Path::new))
        .args(&["/fo", &format!("{}/cargo-install-update-manifest.lib", out_dir), "cargo-install-update-manifest.rc"])
        .status()
        .expect("Are you sure you have RC.EXE in your $PATH?");
}

#[cfg(all(windows, target_env = "msvc"))]
fn find_windows_sdk_bin_dir() -> Option<PathBuf> {
    #[derive(Clone, Copy)]
    enum Arch {
        X86,
        X64,
    }

    // Windows 8 - 10
    fn find_windows_kits_bin_dir(key: &str, arch: Arch) -> Option<PathBuf> {
        winreg::RegKey::predef(HKEY_LOCAL_MACHINE)
            .open_subkey_with_flags(r"SOFTWARE\Microsoft\Windows Kits\Installed Roots", KEY_QUERY_VALUE)
            .and_then(|reg_key| reg_key.get_value::<String, _>(key))
            .ok()
            .and_then(|root_dir| try_bin_dir(root_dir, "bin/x86", "bin/x64", arch))
    }

    // Windows Vista - 7
    fn find_latest_windows_sdk_bin_dir(arch: Arch) -> Option<PathBuf> {
        winreg::RegKey::predef(HKEY_LOCAL_MACHINE)
            .open_subkey_with_flags(r"SOFTWARE\Microsoft\Microsoft SDKs\Windows", KEY_QUERY_VALUE)
            .and_then(|reg_key| reg_key.get_value::<String, _>("CurrentInstallFolder"))
            .ok()
            .and_then(|root_dir| try_bin_dir(root_dir, "Bin", "Bin/x64", arch))
    }

    fn try_bin_dir(root_dir: String, x86_bin: &str, x64_bin: &str, arch: Arch) -> Option<PathBuf> {
        let mut p = PathBuf::from(root_dir);
        match arch {
            Arch::X86 => p.push(x86_bin),
            Arch::X64 => p.push(x64_bin),
        }
        if p.is_dir() { Some(p) } else { None }
    }

    let arch = if env::var("TARGET").unwrap().starts_with("x86_64") {
        Arch::X64
    } else {
        Arch::X86
    };

    find_windows_kits_bin_dir("KitsRoot10", arch)
        .or_else(|| find_windows_kits_bin_dir("KitsRoot81", arch))
        .or_else(|| find_windows_kits_bin_dir("KitsRoot", arch))
        .or_else(|| find_latest_windows_sdk_bin_dir(arch))
}

#[cfg(all(windows, not(target_env = "msvc")))]
fn compile_resource(out_dir: &str) {
    Command::new("windres")
        .args(&["--input", "cargo-install-update-manifest.rc", "--output-format=coff", "--output"])
        .arg(&format!("{}/cargo-install-update-manifest.res", out_dir))
        .status()
        .unwrap();

    Command::new("ar")
        .args(&["crs", "libcargo-install-update-manifest.a", "cargo-install-update-manifest.res"])
        .current_dir(&Path::new(&out_dir))
        .status()
        .unwrap();
}
<|endoftext|>


<commit_before>extern crate gcc;

fn main() {
    let mut opencv_config = gcc::Build::new();
    opencv_config
        .cpp(true)
        .file("native/opencv-wrapper.cc")
        .file("native/utils.cc")
        .include("/usr/local/include")
        .include("native")
        .flag("--std=c++11");

    if cfg!(feature = "gpu") {
        opencv_config.file("native/opencv-gpu.cc");
    }

    opencv_config.compile("libopencv-wrapper.a");

    println!("cargo:rustc-link-search=native=/usr/local/lib");
    println!("cargo:rustc-link-lib=opencv_core");
    println!("cargo:rustc-link-lib=opencv_imgcodecs");
    println!("cargo:rustc-link-lib=opencv_imgproc");
    println!("cargo:rustc-link-lib=opencv_highgui");
    println!("cargo:rustc-link-lib=opencv_videoio");
    println!("cargo:rustc-link-lib=opencv_objdetect");
    println!("cargo:rustc-link-lib=opencv_video");

    if cfg!(feature = "gpu") {
        println!("cargo:rustc-link-lib=opencv_cudaobjdetect");
    }
}
<commit_msg>Add "%OPENCV_DIR%/include" to includes<commit_after>extern crate gcc;

fn main() {
    let mut opencv_config = gcc::Build::new();
    opencv_config
        .cpp(true)
        .file("native/opencv-wrapper.cc")
        .file("native/utils.cc")
        .include("/usr/local/include")
        .include("%OPENCV_DIR%/include")
        .include("native")
        .flag("--std=c++11");

    if cfg!(feature = "gpu") {
        opencv_config.file("native/opencv-gpu.cc");
    }

    opencv_config.compile("libopencv-wrapper.a");

    println!("cargo:rustc-link-search=native=/usr/local/lib");
    println!("cargo:rustc-link-lib=opencv_core");
    println!("cargo:rustc-link-lib=opencv_imgcodecs");
    println!("cargo:rustc-link-lib=opencv_imgproc");
    println!("cargo:rustc-link-lib=opencv_highgui");
    println!("cargo:rustc-link-lib=opencv_videoio");
    println!("cargo:rustc-link-lib=opencv_objdetect");
    println!("cargo:rustc-link-lib=opencv_video");

    if cfg!(feature = "gpu") {
        println!("cargo:rustc-link-lib=opencv_cudaobjdetect");
    }
}
<|endoftext|>


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

extern crate "pkg-config" as pkg_config;

use std::path::Path;
use std::fs::PathExt;
use std::env;

#[cfg(all(unix, not(target_os = "linux")))]
use unix_platform as platform;

fn main() {
    if env::var("PORTAUDIO_ONLY_STATIC").is_err() {
        // If pkg-config finds a library on the system, we are done
        if pkg_config::Config::new().atleast_version("19").find("portaudio-2.0").is_ok() {
            return;
        }
    }

    build();
}

fn build() {
    // retrieve cargo deps out dir
    let out_dir_str = env::var("OUT_DIR").unwrap();
    let out_dir = Path::new(&out_dir_str);

    let static_lib = out_dir.join("lib/libportaudio.a");
    if !static_lib.exists() {
        platform::build(out_dir);
    }

    platform::print_libs(out_dir);
}

#[allow(dead_code)]
mod unix_platform {
    use std::old_io::process::Command;
    use std::path::Path;
    use std::old_path::Path as OldPath;

    use std::{env, os};

    pub const PORTAUDIO_URL: &'static str = "http://www.portaudio.com/archives/pa_stable_v19_20140130.tgz";
    pub const PORTAUDIO_TAR: &'static str = "pa_stable_v19_20140130.tgz";
    pub const PORTAUDIO_FOLDER: &'static str = "portaudio";

    pub fn build(out_dir: &Path) {
        // get portaudio library sources
        match Command::new("wget").arg(PORTAUDIO_URL).output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // untar portaudio sources
        match Command::new("tar").arg("xvf").arg(PORTAUDIO_TAR).output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // change dir to the portaudio folder
        match env::set_current_dir(&OldPath::new(PORTAUDIO_FOLDER)) {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // run portaudio autoconf
        Command::new("./configure")
            .args(&["--disable-shared", "--enable-static"]) // Only build static lib
            .args(&["--prefix", out_dir.to_str().unwrap()]) // Install on the outdir
            .arg("--with-pic") // Build position-independent code (required by Rust)
            .output()
            .unwrap();

        // then make
        match Command::new("make").arg(format!("-j{}", os::num_cpus())).output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // "install" on the outdir
        match Command::new("make").arg("install").output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // return to rust-portaudio root
        match env::set_current_dir(&OldPath::new("..")) {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // cleaning portaudio sources
        match Command::new("rm").arg("-rf").args(&[PORTAUDIO_TAR, PORTAUDIO_FOLDER]).output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }
    }

    pub fn print_libs(out_dir: &Path) {
        let out_str = out_dir.to_str().unwrap();
        println!("cargo:rustc-flags=-L native={}/lib -l static=portaudio", out_str);
    }
}

#[cfg(target_os = "linux")]
mod platform {
    use pkg_config;
    use super::unix_platform;
    use std::path::Path;

    pub fn build(out_dir: &Path) {
        unix_platform::build(out_dir);
    }

    pub fn print_libs(out_dir: &Path) {
        let portaudio_pc_file = out_dir.join("lib/pkgconfig/portaudio-2.0.pc");
        let portaudio_pc_file = portaudio_pc_file.to_str().unwrap();

        pkg_config::Config::new().statik(true).find(portaudio_pc_file).unwrap();
    }
}

#[cfg(windows)]
mod platform {
    use std::path::Path;

    pub fn build(_: &Path) {
        panic!("Don't know how to build portaudio on Windows yet!");
    }

    pub fn print_libs(_: &Path) {
        panic!("Don't know how to build portaudio on Windows yet!");
    }
}
<commit_msg>Use curl to download portaudio on non-linux unixes<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2013 Jeremy Letang (letang.jeremy@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#![feature(old_io, old_path, path, fs, os)]

extern crate "pkg-config" as pkg_config;

use std::path::Path;
use std::fs::PathExt;
use std::env;

#[cfg(all(unix, not(target_os = "linux")))]
use unix_platform as platform;

fn main() {
    if env::var("PORTAUDIO_ONLY_STATIC").is_err() {
        // If pkg-config finds a library on the system, we are done
        if pkg_config::Config::new().atleast_version("19").find("portaudio-2.0").is_ok() {
            return;
        }
    }

    build();
}

fn build() {
    // retrieve cargo deps out dir
    let out_dir_str = env::var("OUT_DIR").unwrap();
    let out_dir = Path::new(&out_dir_str);

    let static_lib = out_dir.join("lib/libportaudio.a");
    if !static_lib.exists() {
        platform::download();
        platform::build(out_dir);
    }

    platform::print_libs(out_dir);
}

#[allow(dead_code)]
mod unix_platform {
    use std::old_io::process::Command;
    use std::path::Path;
    use std::old_path::Path as OldPath;

    use std::{env, os};

    pub const PORTAUDIO_URL: &'static str = "http://www.portaudio.com/archives/pa_stable_v19_20140130.tgz";
    pub const PORTAUDIO_TAR: &'static str = "pa_stable_v19_20140130.tgz";
    pub const PORTAUDIO_FOLDER: &'static str = "portaudio";

    pub fn download() {
        match Command::new("curl").arg(PORTAUDIO_URL).arg("-O").output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }
    }

    pub fn build(out_dir: &Path) {
        // untar portaudio sources
        match Command::new("tar").arg("xvf").arg(PORTAUDIO_TAR).output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // change dir to the portaudio folder
        match env::set_current_dir(&OldPath::new(PORTAUDIO_FOLDER)) {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // run portaudio autoconf
        Command::new("./configure")
            .args(&["--disable-shared", "--enable-static"]) // Only build static lib
            .args(&["--prefix", out_dir.to_str().unwrap()]) // Install on the outdir
            .arg("--with-pic") // Build position-independent code (required by Rust)
            .output()
            .unwrap();

        // then make
        match Command::new("make").arg(format!("-j{}", os::num_cpus())).output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // "install" on the outdir
        match Command::new("make").arg("install").output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // return to rust-portaudio root
        match env::set_current_dir(&OldPath::new("..")) {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }

        // cleaning portaudio sources
        match Command::new("rm").arg("-rf").args(&[PORTAUDIO_TAR, PORTAUDIO_FOLDER]).output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }
    }

    pub fn print_libs(out_dir: &Path) {
        let out_str = out_dir.to_str().unwrap();
        println!("cargo:rustc-flags=-L native={}/lib -l static=portaudio", out_str);
    }
}

#[cfg(target_os = "linux")]
mod platform {
    use pkg_config;
    use std::old_io::process::Command;
    use super::unix_platform;
    use std::path::Path;

    pub fn download() {
        match Command::new("wget").arg(unix_platform::PORTAUDIO_URL).output() {
            Ok(_) => {},
            Err(e) => panic!("{}", e)
        }
    }

    pub fn build(out_dir: &Path) {
        unix_platform::build(out_dir);
    }

    pub fn print_libs(out_dir: &Path) {
        let portaudio_pc_file = out_dir.join("lib/pkgconfig/portaudio-2.0.pc");
        let portaudio_pc_file = portaudio_pc_file.to_str().unwrap();

        pkg_config::Config::new().statik(true).find(portaudio_pc_file).unwrap();
    }
}

#[cfg(windows)]
mod platform {
    use std::path::Path;

    pub fn download(_: &Path) {
        panic!("Don't know how to build portaudio on Windows yet!");
    }

    pub fn build(_: &Path) {
        panic!("Don't know how to build portaudio on Windows yet!");
    }

    pub fn print_libs(_: &Path) {
        panic!("Don't know how to build portaudio on Windows yet!");
    }
}
<|endoftext|>


<commit_before>/* -- Lots of reuse from: https://github.com/alexcrichton/git2-rs/blob/master/libgit2-sys/build.rs */
#[macro_use]
extern crate serde_derive;

extern crate rustc_version;
extern crate serde;
extern crate serde_json;

use rustc_version::{version, Version};
use std::convert::AsRef;
use std::env;
use std::fs;
use std::fs::OpenOptions;
use std::io::{ErrorKind, Read};
use std::path::PathBuf;
use std::process::Command;

// Windows specific library file names
static WIN_CUDA_LIB: &'static str = "afcuda";
static WIN_OCL_LIB: &'static str = "afopencl";
static WIN_UNI_LIB: &'static str = "af";
// Linux & OSX specific library file names
static UNIX_CUDA_LIB: &'static str = "libafcuda";
static UNIX_OCL_LIB: &'static str = "libafopencl";
static UNIX_UNI_LIB: &'static str = "libaf";

#[allow(dead_code)]
#[derive(Deserialize, Debug)]
struct Config {
    // Use existing arrayfire installation
    use_lib: bool,

    // Variables used for building arrayfire submodule
    build_type: String,
    build_threads: u8,
    build_cpu: String,
    build_cuda: String,
    build_opencl: String,
    build_nonfree: String,
    build_examples: String,
    build_test: String,

    with_intelmkl: String,
    with_imageio: String,
    with_graphics: String,
    with_opencl_blas_lib: String,

    vcpkg_toolchain_file: String,

    lnx_cuda_sdk: String,
    lnx_opencl_sdk: String,
    lnx_cuda_host_compiler: String,

    win_cuda_sdk: String,
    win_opencl_sdk: String,
    win_cmake_generator: String,
    win_vs_toolset: String,
}

fn fail(s: &str) -> ! {
    panic!("\n{}\n\nbuild script failed, must exit now", s)
}

fn dir_exists(location: &str) -> bool {
    match fs::metadata(location) {
        Ok(f) => f.is_dir(),
        Err(_) => false,
    }
}

fn file_exists(location: &str) -> bool {
    match fs::metadata(location) {
        Ok(f) => f.is_file(),
        Err(_) => false,
    }
}

fn run(cmd: &mut Command, program: &str) {
    println!("running: {:?}", cmd);
    let status = match cmd.status() {
        Ok(status) => status,
        Err(ref e) if e.kind() == ErrorKind::NotFound => {
            fail(&format!(
                "failed to run cmd: {}\nis `{}` not installed?",
                e, program
            ));
        }
        Err(e) => fail(&format!("failed to execute command: {}", e)),
    };
    if !status.success() {
        fail(&format!(
            "command did not execute successfully, got: {}",
            status
        ));
    }
}

fn read_file(file_name: &std::path::PathBuf) -> String {
    let file_path = file_name.to_str().unwrap();
    let options = OpenOptions::new()
        .read(true)
        .write(false)
        .create(false)
        .open(&file_path);

    let mut file = match options {
        Ok(file) => file,
        Err(..) => panic!("error reading file"),
    };

    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Ok(_) => s,
        Err(..) => panic!("Error reading file to a string"),
    }
}

fn read_conf(conf_file: &std::path::PathBuf) -> Config {
    let raw_conf = read_file(conf_file);
    let decoded: Config = serde_json::from_str(&raw_conf).unwrap();
    decoded
}

fn prep_cmake_options(conf: &Config) -> Vec<String> {
    let mut options: Vec<String> = vec![];

    match conf.build_type.as_ref() {
        "Release" | "RelWithDebInfo" | "Debug" => {
            options.push(format!("-DCMAKE_BUILD_TYPE:STRING={}", conf.build_type));
        }
        _ => fail("Invalid value for build_type option"),
    };
    match conf.build_cpu.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_BUILD_CPU:BOOL={}", conf.build_cpu));
        }
        _ => fail("Invalid value for build_cpu option"),
    };
    match conf.build_cuda.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_BUILD_CUDA:BOOL={}", conf.build_cuda));
        }
        _ => fail("Invalid value for build_cuda option"),
    };
    match conf.build_opencl.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_BUILD_OPENCL:BOOL={}", conf.build_opencl));
        }
        _ => fail("Invalid value for build_opencl option"),
    };
    match conf.build_nonfree.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_BUILD_NONFREE:BOOL={}", conf.build_nonfree));
        }
        _ => fail("Invalid value for build_nonfree option"),
    };
    match conf.build_examples.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_BUILD_EXAMPLES:BOOL={}", conf.build_examples));
        }
        _ => fail("Invalid value for build_examples option"),
    };
    match conf.build_test.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DBUILD_TESTING:BOOL={}", conf.build_test));
        }
        _ => fail("Invalid value for build_test option"),
    };
    match conf.with_intelmkl.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DUSE_CPU_MKL:BOOL={0}", conf.with_intelmkl));
            options.push(format!("-DUSE_OPENCL_MKL:BOOL={0}", conf.with_intelmkl));
        }
        _ => fail("Invalid value for with_intelmkl option"),
    };
    match conf.with_imageio.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_WITH_IMAGEIO:BOOL={0}", conf.with_imageio));
        }
        _ => fail("Invalid value for with_imageio option"),
    };
    match conf.with_graphics.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_WITH_GRAPHICS:BOOL={0}", conf.with_graphics));
        }
        _ => fail("Invalid value for with_graphics option"),
    };
    match conf.with_opencl_blas_lib.as_ref() {
        "clblast" => {
            options.push(format!("-DAF_OPENCL_BLAS_LIBRARY:STRING=CLBlast"));
        }
        "clblas" => {
            options.push(format!("-DAF_OPENCL_BLAS_LIBRARY:STRING=clBLAS"));
        }
        _ => fail("Invalid value for with_opencl_blas_lib option"),
    };
    return options;
}

#[cfg(windows)]
fn run_cmake_command(conf: &Config, build_dir: &std::path::PathBuf) {
    let _ = fs::create_dir(&build_dir);

    let options = prep_cmake_options(conf);

    let mut cmake_cmd = Command::new("cmake");
    cmake_cmd.current_dir(&build_dir);

    run(
        cmake_cmd
            .arg("..")
            .arg("-T")
            .arg(format!("{}", conf.win_vs_toolset))
            .arg("-G")
            .arg(format!("{}", conf.win_cmake_generator))
            .args(&options)
            .arg(format!(
                "-DCMAKE_TOOLCHAIN_FILE:FILEPATH={}",
                conf.vcpkg_toolchain_file
            ))
            .arg(format!("-DCMAKE_INSTALL_PREFIX={}", "package")),
        "cmake",
    );

    let mut make_cmd = Command::new("MSBuild.exe");
    make_cmd.current_dir(&build_dir);
    run(
        make_cmd
            .arg(format!("/m:{}", conf.build_threads))
            .arg(format!("/p:Configuration={}", conf.build_type))
            .arg(format!("ArrayFire.sln")),
        "MSBuild",
    );

    let mut install_cmd = Command::new("MSBuild.exe");
    install_cmd.current_dir(&build_dir);
    run(
        install_cmd
            .arg(format!("/p:Configuration={}", conf.build_type))
            .arg(format!("INSTALL.vcxproj")),
        "Install",
    );
}

#[cfg(not(windows))]
fn run_cmake_command(conf: &Config, build_dir: &std::path::PathBuf) {
    let _ = fs::create_dir(&build_dir);

    let options = prep_cmake_options(conf);
    println!("options are {:?}", options);

    let mut cmake_cmd = Command::new("cmake");
    cmake_cmd.current_dir(&build_dir);

    run(
        cmake_cmd
            .arg("..")
            .args(&options)
            .arg(format!("-DCMAKE_INSTALL_PREFIX={}", "package"))
            .arg(format!(
                "-DCUDA_HOST_COMPILER={}",
                conf.lnx_cuda_host_compiler
            )),
        "cmake",
    );

    let mut make_cmd = Command::new("make");
    make_cmd.current_dir(&build_dir);
    run(
        make_cmd
            .arg(format!("-j{}", conf.build_threads))
            .arg(format!("install")),
        "make",
    );
}

fn backend_exists(name: &str) -> bool {
    let win_backend = name.to_string() + ".dll";
    let osx_backend = name.to_string() + ".dylib";
    let linux_backend = name.to_string() + ".so";

    return file_exists(&win_backend) || file_exists(&osx_backend) || file_exists(&linux_backend);
}

fn blob_backends(conf: &Config, build_dir: &std::path::PathBuf) -> (Vec<String>, Vec<String>) {
    let mut backend_dirs: Vec<String> = Vec::new();
    let mut backends: Vec<String> = Vec::new();

    if conf.use_lib {
        let afpath = match env::var("AF_PATH") {
            Ok(af_path) => PathBuf::from(&af_path),
            Err(_) => {
                println!(
                    "WARNING! USE_LIB is defined,
                          but AF_PATH is not found,"
                );
                println!(
                    "Trying to find libraries from
                          known default locations"
                );
                if cfg!(target_os = "windows") {
                    PathBuf::from("C:\\Program Files\\ArrayFire\\v3\\")
                } else {
                    PathBuf::from("/opt/arrayfire/")
                }
            }
        };

        backend_dirs.push(afpath.join("lib").to_str().to_owned().unwrap().to_string());
        backend_dirs.push(
            afpath
                .join("lib64")
                .to_str()
                .to_owned()
                .unwrap()
                .to_string(),
        );

        if !cfg!(target_os = "windows") {
            backend_dirs.push(String::from("/usr/local/lib"));
            backend_dirs.push(String::from("/usr/lib"));
        }
    } else {
        backend_dirs.push(
            build_dir
                .join("package")
                .join("lib")
                .to_str()
                .to_owned()
                .unwrap()
                .to_string(),
        );
    }

    let mut uni_lib_exists = false;
    let mut cud_lib_exists = false;
    let mut ocl_lib_exists = false;

    for backend_dir in backend_dirs.iter() {
        let lib_dir = PathBuf::from(backend_dir);

        let culib_name = if cfg!(windows) {
            WIN_CUDA_LIB
        } else {
            UNIX_CUDA_LIB
        };
        cud_lib_exists =
            cud_lib_exists || backend_exists(&lib_dir.join(culib_name).to_string_lossy());
        let ocllib_name = if cfg!(windows) {
            WIN_OCL_LIB
        } else {
            UNIX_OCL_LIB
        };
        ocl_lib_exists =
            ocl_lib_exists || backend_exists(&lib_dir.join(ocllib_name).to_string_lossy());
        let unilib_name = if cfg!(windows) {
            WIN_UNI_LIB
        } else {
            UNIX_UNI_LIB
        };
        uni_lib_exists =
            uni_lib_exists || backend_exists(&lib_dir.join(unilib_name).to_string_lossy());
    }

    if !conf.use_lib {
        // blob in cuda deps
        if cud_lib_exists {
            if cfg!(windows) {
                backend_dirs.push(format!("{}\\lib\\x64", conf.win_cuda_sdk));
            } else {
                let sdk_dir = format!("{}/{}", conf.lnx_cuda_sdk, "lib64");
                match dir_exists(&sdk_dir) {
                    true => {
                        backend_dirs.push(sdk_dir);
                    }
                    false => {
                        backend_dirs.push(format!("{}/{}", conf.lnx_cuda_sdk, "lib"));
                    }
                };
            }
        }

        //blob in opencl deps
        if ocl_lib_exists {
            if !cfg!(target_os = "macos") {
                backends.push("OpenCL".to_string());
            }
            if cfg!(windows) {
                let sdk_dir = format!("{}\\lib\\x64", conf.win_opencl_sdk);
                if dir_exists(&sdk_dir) {
                    backend_dirs.push(sdk_dir);
                } else {
                    backend_dirs.push(format!("{}\\lib\\x86_64", conf.win_opencl_sdk));
                }
            } else {
                let sdk_dir = format!("{}/{}", conf.lnx_opencl_sdk, "lib64");
                if dir_exists(&sdk_dir) {
                    backend_dirs.push(sdk_dir);
                } else {
                    backend_dirs.push(format!("{}/{}", conf.lnx_opencl_sdk, "lib"));
                }
            }
        }

        if conf.with_graphics == "ON" {
            if !conf.use_lib {
                backend_dirs.push(
                    build_dir
                        .join("third_party")
                        .join("forge")
                        .join("lib")
                        .to_str()
                        .to_owned()
                        .unwrap()
                        .to_string(),
                );
            }
        }
    }

    if uni_lib_exists {
        backends.push("af".to_string());
        if !conf.use_lib && conf.with_graphics == "ON" {
            backends.push("forge".to_string());
        }
    }

    return (backends, backend_dirs);
}

fn main() {
    // Setup pathing
    let src = PathBuf::from(&env::var("CARGO_MANIFEST_DIR").unwrap());
    let conf_file = src.join("build.conf");
    let conf = read_conf(&conf_file);

    let arrayfire_dir = src.join("arrayfire");
    let build_dir = arrayfire_dir.join("build");

    if !conf.use_lib {
        run_cmake_command(&conf, &build_dir);
    }

    let (backends, backend_dirs) = blob_backends(&conf, &build_dir);
    for backend in backends.iter() {
        println!("cargo:rustc-link-lib=dylib={}", backend);
    }
    for backend_dir in backend_dirs.iter() {
        println!("cargo:rustc-link-search=native={}", backend_dir);
    }
    if version().unwrap() >= Version::parse("1.8.0").unwrap() {
        println!("cargo:rustc-cfg=op_assign");
    }
}
<commit_msg>Address clippy warnings in build script<commit_after>/* -- Lots of reuse from: https://github.com/alexcrichton/git2-rs/blob/master/libgit2-sys/build.rs */
#[macro_use]
extern crate serde_derive;

extern crate rustc_version;
extern crate serde;
extern crate serde_json;

use rustc_version::{version, Version};
use std::convert::AsRef;
use std::env;
use std::fs;
use std::fs::OpenOptions;
use std::io::{ErrorKind, Read};
use std::path::PathBuf;
use std::process::Command;

// Windows specific library file names
static WIN_CUDA_LIB: &str = "afcuda";
static WIN_OCL_LIB: &str = "afopencl";
static WIN_UNI_LIB: &str = "af";
// Linux & OSX specific library file names
static UNIX_CUDA_LIB: &str = "libafcuda";
static UNIX_OCL_LIB: &str = "libafopencl";
static UNIX_UNI_LIB: &str = "libaf";

#[allow(dead_code)]
#[derive(Deserialize, Debug)]
struct Config {
    // Use existing arrayfire installation
    use_lib: bool,

    // Variables used for building arrayfire submodule
    build_type: String,
    build_threads: u8,
    build_cpu: String,
    build_cuda: String,
    build_opencl: String,
    build_nonfree: String,
    build_examples: String,
    build_test: String,

    with_intelmkl: String,
    with_imageio: String,
    with_graphics: String,
    with_opencl_blas_lib: String,

    vcpkg_toolchain_file: String,

    lnx_cuda_sdk: String,
    lnx_opencl_sdk: String,
    lnx_cuda_host_compiler: String,

    win_cuda_sdk: String,
    win_opencl_sdk: String,
    win_cmake_generator: String,
    win_vs_toolset: String,
}

fn fail(s: &str) -> ! {
    panic!("\n{}\n\nbuild script failed, must exit now", s)
}

fn dir_exists(location: &str) -> bool {
    match fs::metadata(location) {
        Ok(f) => f.is_dir(),
        Err(_) => false,
    }
}

fn file_exists(location: &str) -> bool {
    match fs::metadata(location) {
        Ok(f) => f.is_file(),
        Err(_) => false,
    }
}

fn run(cmd: &mut Command, program: &str) {
    println!("running: {:?}", cmd);
    let status = match cmd.status() {
        Ok(status) => status,
        Err(ref e) if e.kind() == ErrorKind::NotFound => {
            fail(&format!(
                "failed to run cmd: {}\nis `{}` not installed?",
                e, program
            ));
        }
        Err(e) => fail(&format!("failed to execute command: {}", e)),
    };
    if !status.success() {
        fail(&format!(
            "command did not execute successfully, got: {}",
            status
        ));
    }
}

fn read_file(file_name: &std::path::PathBuf) -> String {
    let file_path = file_name.to_str().unwrap();
    let options = OpenOptions::new()
        .read(true)
        .write(false)
        .create(false)
        .open(&file_path);

    let mut file = match options {
        Ok(file) => file,
        Err(..) => panic!("error reading file"),
    };

    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Ok(_) => s,
        Err(..) => panic!("Error reading file to a string"),
    }
}

fn read_conf(conf_file: &std::path::PathBuf) -> Config {
    let raw_conf = read_file(conf_file);
    let decoded: Config = serde_json::from_str(&raw_conf).unwrap();
    decoded
}

fn prep_cmake_options(conf: &Config) -> Vec<String> {
    let mut options: Vec<String> = vec![];

    match conf.build_type.as_ref() {
        "Release" | "RelWithDebInfo" | "Debug" => {
            options.push(format!("-DCMAKE_BUILD_TYPE:STRING={}", conf.build_type));
        }
        _ => fail("Invalid value for build_type option"),
    };
    match conf.build_cpu.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_BUILD_CPU:BOOL={}", conf.build_cpu));
        }
        _ => fail("Invalid value for build_cpu option"),
    };
    match conf.build_cuda.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_BUILD_CUDA:BOOL={}", conf.build_cuda));
        }
        _ => fail("Invalid value for build_cuda option"),
    };
    match conf.build_opencl.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_BUILD_OPENCL:BOOL={}", conf.build_opencl));
        }
        _ => fail("Invalid value for build_opencl option"),
    };
    match conf.build_nonfree.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_BUILD_NONFREE:BOOL={}", conf.build_nonfree));
        }
        _ => fail("Invalid value for build_nonfree option"),
    };
    match conf.build_examples.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_BUILD_EXAMPLES:BOOL={}", conf.build_examples));
        }
        _ => fail("Invalid value for build_examples option"),
    };
    match conf.build_test.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DBUILD_TESTING:BOOL={}", conf.build_test));
        }
        _ => fail("Invalid value for build_test option"),
    };
    match conf.with_intelmkl.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DUSE_CPU_MKL:BOOL={0}", conf.with_intelmkl));
            options.push(format!("-DUSE_OPENCL_MKL:BOOL={0}", conf.with_intelmkl));
        }
        _ => fail("Invalid value for with_intelmkl option"),
    };
    match conf.with_imageio.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_WITH_IMAGEIO:BOOL={0}", conf.with_imageio));
        }
        _ => fail("Invalid value for with_imageio option"),
    };
    match conf.with_graphics.as_ref() {
        "ON" | "OFF" => {
            options.push(format!("-DAF_WITH_GRAPHICS:BOOL={0}", conf.with_graphics));
        }
        _ => fail("Invalid value for with_graphics option"),
    };
    match conf.with_opencl_blas_lib.as_ref() {
        "clblast" => {
            options.push("-DAF_OPENCL_BLAS_LIBRARY:STRING=CLBlast".to_string());
        }
        "clblas" => {
            options.push("-DAF_OPENCL_BLAS_LIBRARY:STRING=clBLAS".to_string());
        }
        _ => fail("Invalid value for with_opencl_blas_lib option"),
    };
    options
}

#[cfg(windows)]
fn run_cmake_command(conf: &Config, build_dir: &std::path::PathBuf) {
    let _ = fs::create_dir(&build_dir);

    let options = prep_cmake_options(conf);

    let mut cmake_cmd = Command::new("cmake");
    cmake_cmd.current_dir(&build_dir);

    run(
        cmake_cmd
            .arg("..")
            .arg("-T")
            .arg(format!("{}", conf.win_vs_toolset))
            .arg("-G")
            .arg(format!("{}", conf.win_cmake_generator))
            .args(&options)
            .arg(format!(
                "-DCMAKE_TOOLCHAIN_FILE:FILEPATH={}",
                conf.vcpkg_toolchain_file
            ))
            .arg(format!("-DCMAKE_INSTALL_PREFIX={}", "package")),
        "cmake",
    );

    let mut make_cmd = Command::new("MSBuild.exe");
    make_cmd.current_dir(&build_dir);
    run(
        make_cmd
            .arg(format!("/m:{}", conf.build_threads))
            .arg(format!("/p:Configuration={}", conf.build_type))
            .arg(format!("ArrayFire.sln")),
        "MSBuild",
    );

    let mut install_cmd = Command::new("MSBuild.exe");
    install_cmd.current_dir(&build_dir);
    run(
        install_cmd
            .arg(format!("/p:Configuration={}", conf.build_type))
            .arg(format!("INSTALL.vcxproj")),
        "Install",
    );
}

#[cfg(not(windows))]
fn run_cmake_command(conf: &Config, build_dir: &std::path::PathBuf) {
    let _ = fs::create_dir(&build_dir);

    let options = prep_cmake_options(conf);
    println!("options are {:?}", options);

    let mut cmake_cmd = Command::new("cmake");
    cmake_cmd.current_dir(&build_dir);

    run(
        cmake_cmd
            .arg("..")
            .args(&options)
            .arg(format!("-DCMAKE_INSTALL_PREFIX={}", "package"))
            .arg(format!(
                "-DCUDA_HOST_COMPILER={}",
                conf.lnx_cuda_host_compiler
            )),
        "cmake",
    );

    let mut make_cmd = Command::new("make");
    make_cmd.current_dir(&build_dir);
    run(
        make_cmd
            .arg(format!("-j{}", conf.build_threads))
            .arg("install".to_string()),
        "make",
    );
}

fn backend_exists(name: &str) -> bool {
    let win_backend = name.to_string() + ".dll";
    let osx_backend = name.to_string() + ".dylib";
    let linux_backend = name.to_string() + ".so";

    file_exists(&win_backend) || file_exists(&osx_backend) || file_exists(&linux_backend)
}

fn blob_backends(conf: &Config, build_dir: &std::path::PathBuf) -> (Vec<String>, Vec<String>) {
    let mut backend_dirs: Vec<String> = Vec::new();
    let mut backends: Vec<String> = Vec::new();

    if conf.use_lib {
        let afpath = match env::var("AF_PATH") {
            Ok(af_path) => PathBuf::from(&af_path),
            Err(_) => {
                println!(
                    "WARNING! USE_LIB is defined,
                          but AF_PATH is not found,"
                );
                println!(
                    "Trying to find libraries from
                          known default locations"
                );
                if cfg!(target_os = "windows") {
                    PathBuf::from("C:\\Program Files\\ArrayFire\\v3\\")
                } else {
                    PathBuf::from("/opt/arrayfire/")
                }
            }
        };

        backend_dirs.push(afpath.join("lib").to_str().to_owned().unwrap().to_string());
        backend_dirs.push(
            afpath
                .join("lib64")
                .to_str()
                .to_owned()
                .unwrap()
                .to_string(),
        );

        if !cfg!(target_os = "windows") {
            backend_dirs.push(String::from("/usr/local/lib"));
            backend_dirs.push(String::from("/usr/lib"));
        }
    } else {
        backend_dirs.push(
            build_dir
                .join("package")
                .join("lib")
                .to_str()
                .to_owned()
                .unwrap()
                .to_string(),
        );
    }

    let mut uni_lib_exists = false;
    let mut cud_lib_exists = false;
    let mut ocl_lib_exists = false;

    for backend_dir in backend_dirs.iter() {
        let lib_dir = PathBuf::from(backend_dir);

        let culib_name = if cfg!(windows) {
            WIN_CUDA_LIB
        } else {
            UNIX_CUDA_LIB
        };
        cud_lib_exists =
            cud_lib_exists || backend_exists(&lib_dir.join(culib_name).to_string_lossy());
        let ocllib_name = if cfg!(windows) {
            WIN_OCL_LIB
        } else {
            UNIX_OCL_LIB
        };
        ocl_lib_exists =
            ocl_lib_exists || backend_exists(&lib_dir.join(ocllib_name).to_string_lossy());
        let unilib_name = if cfg!(windows) {
            WIN_UNI_LIB
        } else {
            UNIX_UNI_LIB
        };
        uni_lib_exists =
            uni_lib_exists || backend_exists(&lib_dir.join(unilib_name).to_string_lossy());
    }

    if !conf.use_lib {
        // blob in cuda deps
        if cud_lib_exists {
            if cfg!(windows) {
                backend_dirs.push(format!("{}\\lib\\x64", conf.win_cuda_sdk));
            } else {
                let sdk_dir = format!("{}/{}", conf.lnx_cuda_sdk, "lib64");
                match dir_exists(&sdk_dir) {
                    true => {
                        backend_dirs.push(sdk_dir);
                    }
                    false => {
                        backend_dirs.push(format!("{}/{}", conf.lnx_cuda_sdk, "lib"));
                    }
                };
            }
        }

        //blob in opencl deps
        if ocl_lib_exists {
            if !cfg!(target_os = "macos") {
                backends.push("OpenCL".to_string());
            }
            if cfg!(windows) {
                let sdk_dir = format!("{}\\lib\\x64", conf.win_opencl_sdk);
                if dir_exists(&sdk_dir) {
                    backend_dirs.push(sdk_dir);
                } else {
                    backend_dirs.push(format!("{}\\lib\\x86_64", conf.win_opencl_sdk));
                }
            } else {
                let sdk_dir = format!("{}/{}", conf.lnx_opencl_sdk, "lib64");
                if dir_exists(&sdk_dir) {
                    backend_dirs.push(sdk_dir);
                } else {
                    backend_dirs.push(format!("{}/{}", conf.lnx_opencl_sdk, "lib"));
                }
            }
        }

        if conf.with_graphics == "ON" && !conf.use_lib {
            backend_dirs.push(
                build_dir
                    .join("third_party")
                    .join("forge")
                    .join("lib")
                    .to_str()
                    .to_owned()
                    .unwrap()
                    .to_string(),
            );
        }
    }

    if uni_lib_exists {
        backends.push("af".to_string());
        if !conf.use_lib && conf.with_graphics == "ON" {
            backends.push("forge".to_string());
        }
    }

    (backends, backend_dirs)
}

fn main() {
    // Setup pathing
    let src = PathBuf::from(&env::var("CARGO_MANIFEST_DIR").unwrap());
    let conf_file = src.join("build.conf");
    let conf = read_conf(&conf_file);

    let arrayfire_dir = src.join("arrayfire");
    let build_dir = arrayfire_dir.join("build");

    if !conf.use_lib {
        run_cmake_command(&conf, &build_dir);
    }

    let (backends, backend_dirs) = blob_backends(&conf, &build_dir);
    for backend in backends.iter() {
        println!("cargo:rustc-link-lib=dylib={}", backend);
    }
    for backend_dir in backend_dirs.iter() {
        println!("cargo:rustc-link-search=native={}", backend_dir);
    }
    if version().unwrap() >= Version::parse("1.8.0").unwrap() {
        println!("cargo:rustc-cfg=op_assign");
    }
}
<|endoftext|>


<commit_before>//! Finds and links to the required `libclang` libraries.

#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", warn(clippy))]
#![cfg_attr(feature="clippy", allow(if_not_else, similar_names))]

extern crate glob;

use std::env;
use std::path::{Path};
use std::process::{Command};

use glob::{MatchOptions};

// Environment variables:
//
// * LLVM_CONFIG_PATH - provides a path to an `llvm-config` executable
// * LIBCLANG_PATH - provides a path to a directory containing a `libclang` shared library
// * LIBCLANG_STATIC_PATH - provides a path to a directory containing LLVM and Clang static libraries

/// Returns whether the supplied directory contains the supplied file.
fn contains<D: AsRef<Path>>(directory: D, file: &str) -> bool {
    directory.as_ref().join(file).exists()
}

/// Panics with a user friendly error message.
fn error(file: &str, env: &str) -> ! {
    panic!("could not find {0}, set the {1} environment variable to a path where {0} can be found", file, env);
}

/// Runs a console command, returning the output if the command was successfully executed.
fn run(command: &str, arguments: &[&str]) -> Option<String> {
    Command::new(command).args(arguments).output().map(|o| {
        String::from_utf8_lossy(&o.stdout).into_owned()
    }).ok()
}

/// Runs `llvm-config`, returning the output if the command was successfully executed.
fn run_llvm_config(arguments: &[&str]) -> Option<String> {
    run(&env::var("LLVM_CONFIG_PATH").unwrap_or("llvm-config".into()), arguments)
}

/// Backup search directory globs for FreeBSD and Linux.
const SEARCH_LINUX: &'static [&'static str] = &[
    "/usr/*",
    "/usr/*/*",
    "/usr/*/*/*",
];

/// Backup search directory globs for OS X.
const SEARCH_OSX: &'static [&'static str] = &[
    "/usr/local/opt/*/lib",
    "/Library/Developer/CommandLineTools/usr/lib",
    "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib",
    "/usr/local/opt/*/lib/*/lib",
];

/// Backup search directory globs for Windows.
const SEARCH_WINDOWS: &'static [&'static str] = &[
    "C:\\LLVM\\bin",
    "C:\\LLVM\\lib",
    "C:\\Program Files*\\LLVM\\bin",
    "C:\\Program Files*\\LLVM\\lib",
];

/// Searches for a library, returning the directory it can be found in if the search was successful.
fn find(file: &str, env: &str) -> Option<String> {
    // Search the directory provided by the relevant environment variable, if set.
    if let Some(directory) = env::var(env).ok() {
        if contains(&directory, file) {
            return Some(directory);
        }
    }

    // Search the `bin` and `lib` subdirectories in the directory returned by
    // `llvm-config --prefix`, if `llvm-config` is available.
    if let Some(output) = run_llvm_config(&["--prefix"]) {
        let directory = output.lines().map(|s| s.to_string()).next().unwrap();
        let bin = format!("{}/bin", directory);
        if contains(&bin, file) {
            return Some(bin);
        }
        let lib = format!("{}/lib", directory);
        if contains(&lib, file) {
            return Some(lib);
        }
    }

    // Search the backup directories.
    let search = if cfg!(any(target_os="freebsd", target_os="linux")) {
        SEARCH_LINUX
    } else if cfg!(target_os="macos") {
        SEARCH_OSX
    } else if cfg!(target_os="windows") {
        SEARCH_WINDOWS
    } else {
        return None;
    };
    for pattern in search {
        let mut options = MatchOptions::new();
        options.case_sensitive = false;
        options.require_literal_separator = true;
        if let Ok(paths) = glob::glob_with(pattern, &options) {
            for path in paths.filter_map(Result::ok) {
                if contains(&path, file) {
                    return Some(path.to_string_lossy().into_owned());
                }
            }
        }
    }
    None
}

/// Returns the name of an LLVM or Clang library from a path.
fn get_library_name(path: &Path) -> Option<String> {
    path.file_stem().map(|l| l.to_string_lossy()[3..].into())
}

/// Returns the LLVM libraries required to link to `libclang` statically.
fn get_llvm_libraries() -> Vec<String> {
    run_llvm_config(&["--libs"]).expect(
        "could not execute `llvm-config --libs`, set the LLVM_CONFIG_PATH environment variable to \
         a path to an `llvm-config` executable"
    ).split_whitespace().filter_map(|p| {
        // Depending on the version of `llvm-config` in use, listed libraries may be in one of two
        // forms, a full path to the library or simply prefixed with `-l`.
        if p.starts_with("-l") {
            Some(p[2..].into())
        } else {
            get_library_name(Path::new(p))
        }
    }).collect()
}

/// Clang libraries required to link to `libclang` 3.5 and later statically.
const CLANG_LIBRARIES: &'static [&'static str] = &[
    "clang",
    "clangAST",
    "clangAnalysis",
    "clangBasic",
    "clangDriver",
    "clangEdit",
    "clangFrontend",
    "clangIndex",
    "clangLex",
    "clangParse",
    "clangRewrite",
    "clangSema",
    "clangSerialization",
];

/// Returns the Clang libraries required to link to `libclang` statically.
fn get_clang_libraries(directory: &str) -> Vec<String> {
    let pattern = Path::new(directory).join("libclang*.a").to_string_lossy().to_string();
    if let Ok(libraries) = glob::glob(&pattern) {
        libraries.filter_map(|l| l.ok().and_then(|l| get_library_name(&l))).collect()
    } else {
        CLANG_LIBRARIES.iter().map(|l| l.to_string()).collect()
    }
}

fn main() {
    if cfg!(feature="static") {
        // Find LLVM and Clang static libraries.
        let directory = match find("libclang.a", "LIBCLANG_STATIC_PATH") {
            Some(directory) => directory,
            _ => error("libclang.a", "LIBCLANG_STATIC_PATH"),
        };

        print!("cargo:rustc-flags=");

        // Specify required LLVM and Clang static libraries.
        print!("-L {} ", directory);
        for library in get_llvm_libraries() {
            print!("-l static={} ", library);
        }
        for library in get_clang_libraries(&directory) {
            print!("-l static={} ", library);
        }

        // Specify required system libraries.
        if cfg!(any(target_os="freebsd", target_os="linux")) {
            println!("-l ffi -l ncursesw -l stdc++ -l z");
        } else if cfg!(target_os="macos") {
            println!("-l ffi -l ncurses -l stdc++ -l z");
        } else {
            panic!("unsupported operating system for static linking");
        }
    } else {
        let file = if cfg!(target_os="windows") {
            // The filename of the `libclang` shared library on Windows is `libclang.dll` instead of
            // the expected `clang.dll`.
            "libclang.dll".into()
        } else {
            format!("{}clang{}", env::consts::DLL_PREFIX, env::consts::DLL_SUFFIX)
        };

        // Find the `libclang` shared library.
        let directory = match find(&file, "LIBCLANG_PATH") {
            Some(directory) => directory,
            _ => error(&file, "LIBCLANG_PATH")
        };

        println!("cargo:rustc-link-search={}", directory);
        if cfg!(all(target_os="windows", target_env="msvc")) {
            // Find the `libclang` stub static library required for the MSVC toolchain.
            let directory = match find("libclang.lib", "LIBCLANG_PATH") {
                Some(directory) => directory,
                _ => error("libclang.lib", "LIBCLANG_PATH"),
            };

            println!("cargo:rustc-link-search={}", directory);
            println!("cargo:rustc-link-lib=dylib=libclang");
        } else {
            println!("cargo:rustc-link-lib=dylib=clang");
        }
    }
}
<commit_msg>Reduce generality of backup search directory globs<commit_after>//! Finds and links to the required `libclang` libraries.

#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", warn(clippy))]
#![cfg_attr(feature="clippy", allow(if_not_else, similar_names))]

extern crate glob;

use std::env;
use std::path::{Path};
use std::process::{Command};

use glob::{MatchOptions};

// Environment variables:
//
// * LLVM_CONFIG_PATH - provides a path to an `llvm-config` executable
// * LIBCLANG_PATH - provides a path to a directory containing a `libclang` shared library
// * LIBCLANG_STATIC_PATH - provides a path to a directory containing LLVM and Clang static libraries

/// Returns whether the supplied directory contains the supplied file.
fn contains<D: AsRef<Path>>(directory: D, file: &str) -> bool {
    directory.as_ref().join(file).exists()
}

/// Panics with a user friendly error message.
fn error(file: &str, env: &str) -> ! {
    panic!("could not find {0}, set the {1} environment variable to a path where {0} can be found", file, env);
}

/// Runs a console command, returning the output if the command was successfully executed.
fn run(command: &str, arguments: &[&str]) -> Option<String> {
    Command::new(command).args(arguments).output().map(|o| {
        String::from_utf8_lossy(&o.stdout).into_owned()
    }).ok()
}

/// Runs `llvm-config`, returning the output if the command was successfully executed.
fn run_llvm_config(arguments: &[&str]) -> Option<String> {
    run(&env::var("LLVM_CONFIG_PATH").unwrap_or("llvm-config".into()), arguments)
}

/// Backup search directory globs for FreeBSD and Linux.
const SEARCH_LINUX: &'static [&'static str] = &[
    "/usr/lib*",
    "/usr/lib*/*",
    "/usr/lib*/*/*",
    "/usr/local/lib*",
    "/usr/local/lib*/*",
    "/usr/local/lib*/*/*",
    "/usr/local/llvm*/lib",
];

/// Backup search directory globs for OS X.
const SEARCH_OSX: &'static [&'static str] = &[
    "/usr/local/opt/llvm*/lib",
    "/Library/Developer/CommandLineTools/usr/lib",
    "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib",
    "/usr/local/opt/llvm*/lib/llvm*/lib",
];

/// Backup search directory globs for Windows.
const SEARCH_WINDOWS: &'static [&'static str] = &[
    "C:\\LLVM\\bin",
    "C:\\LLVM\\lib",
    "C:\\Program Files*\\LLVM\\bin",
    "C:\\Program Files*\\LLVM\\lib",
];

/// Searches for a library, returning the directory it can be found in if the search was successful.
fn find(file: &str, env: &str) -> Option<String> {
    // Search the directory provided by the relevant environment variable, if set.
    if let Some(directory) = env::var(env).ok() {
        if contains(&directory, file) {
            return Some(directory);
        }
    }

    // Search the `bin` and `lib` subdirectories in the directory returned by
    // `llvm-config --prefix`, if `llvm-config` is available.
    if let Some(output) = run_llvm_config(&["--prefix"]) {
        let directory = output.lines().map(|s| s.to_string()).next().unwrap();
        let bin = format!("{}/bin", directory);
        if contains(&bin, file) {
            return Some(bin);
        }
        let lib = format!("{}/lib", directory);
        if contains(&lib, file) {
            return Some(lib);
        }
    }

    // Search the backup directories.
    let search = if cfg!(any(target_os="freebsd", target_os="linux")) {
        SEARCH_LINUX
    } else if cfg!(target_os="macos") {
        SEARCH_OSX
    } else if cfg!(target_os="windows") {
        SEARCH_WINDOWS
    } else {
        return None;
    };
    for pattern in search {
        let mut options = MatchOptions::new();
        options.case_sensitive = false;
        options.require_literal_separator = true;
        if let Ok(paths) = glob::glob_with(pattern, &options) {
            for path in paths.filter_map(Result::ok).filter(|p| p.is_dir()) {
                if contains(&path, file) {
                    return Some(path.to_string_lossy().into_owned());
                }
            }
        }
    }
    None
}

/// Returns the name of an LLVM or Clang library from a path.
fn get_library_name(path: &Path) -> Option<String> {
    path.file_stem().map(|l| l.to_string_lossy()[3..].into())
}

/// Returns the LLVM libraries required to link to `libclang` statically.
fn get_llvm_libraries() -> Vec<String> {
    run_llvm_config(&["--libs"]).expect(
        "could not execute `llvm-config --libs`, set the LLVM_CONFIG_PATH environment variable to \
         a path to an `llvm-config` executable"
    ).split_whitespace().filter_map(|p| {
        // Depending on the version of `llvm-config` in use, listed libraries may be in one of two
        // forms, a full path to the library or simply prefixed with `-l`.
        if p.starts_with("-l") {
            Some(p[2..].into())
        } else {
            get_library_name(Path::new(p))
        }
    }).collect()
}

/// Clang libraries required to link to `libclang` 3.5 and later statically.
const CLANG_LIBRARIES: &'static [&'static str] = &[
    "clang",
    "clangAST",
    "clangAnalysis",
    "clangBasic",
    "clangDriver",
    "clangEdit",
    "clangFrontend",
    "clangIndex",
    "clangLex",
    "clangParse",
    "clangRewrite",
    "clangSema",
    "clangSerialization",
];

/// Returns the Clang libraries required to link to `libclang` statically.
fn get_clang_libraries(directory: &str) -> Vec<String> {
    let pattern = Path::new(directory).join("libclang*.a").to_string_lossy().to_string();
    if let Ok(libraries) = glob::glob(&pattern) {
        libraries.filter_map(|l| l.ok().and_then(|l| get_library_name(&l))).collect()
    } else {
        CLANG_LIBRARIES.iter().map(|l| l.to_string()).collect()
    }
}

fn main() {
    if cfg!(feature="static") {
        // Find LLVM and Clang static libraries.
        let directory = match find("libclang.a", "LIBCLANG_STATIC_PATH") {
            Some(directory) => directory,
            _ => error("libclang.a", "LIBCLANG_STATIC_PATH"),
        };

        print!("cargo:rustc-flags=");

        // Specify required LLVM and Clang static libraries.
        print!("-L {} ", directory);
        for library in get_llvm_libraries() {
            print!("-l static={} ", library);
        }
        for library in get_clang_libraries(&directory) {
            print!("-l static={} ", library);
        }

        // Specify required system libraries.
        if cfg!(any(target_os="freebsd", target_os="linux")) {
            println!("-l ffi -l ncursesw -l stdc++ -l z");
        } else if cfg!(target_os="macos") {
            println!("-l ffi -l ncurses -l stdc++ -l z");
        } else {
            panic!("unsupported operating system for static linking");
        }
    } else {
        let file = if cfg!(target_os="windows") {
            // The filename of the `libclang` shared library on Windows is `libclang.dll` instead of
            // the expected `clang.dll`.
            "libclang.dll".into()
        } else {
            format!("{}clang{}", env::consts::DLL_PREFIX, env::consts::DLL_SUFFIX)
        };

        // Find the `libclang` shared library.
        let directory = match find(&file, "LIBCLANG_PATH") {
            Some(directory) => directory,
            _ => error(&file, "LIBCLANG_PATH")
        };

        println!("cargo:rustc-link-search={}", directory);
        if cfg!(all(target_os="windows", target_env="msvc")) {
            // Find the `libclang` stub static library required for the MSVC toolchain.
            let directory = match find("libclang.lib", "LIBCLANG_PATH") {
                Some(directory) => directory,
                _ => error("libclang.lib", "LIBCLANG_PATH"),
            };

            println!("cargo:rustc-link-search={}", directory);
            println!("cargo:rustc-link-lib=dylib=libclang");
        } else {
            println!("cargo:rustc-link-lib=dylib=clang");
        }
    }
}
<|endoftext|>


<commit_before>use std::io::File;

struct Color{
	r:u8,
	g:u8,
	b:u8,
}

fn main(){

	let iteration:u64 = 100;
	let magnify:f64 = 0.25;
	let hxres = 500;
	let hyres = 500;

	let total = (hxres)*(hyres);
	println!("total: {}", total);
	let mut pixels:Vec<Color> =Vec::new();// should be 3 * total
	for t in range(0, total){
	    pixels.push(Color{r:0,g:0,b:0});
	}

	let mut palette:Vec<u8> = Vec::new();
	for pa in range (0, iteration){
		palette.push(((pa+100) * (100/iteration)) as u8);
	}
	let index:usize = 1;
	//Here N=2^8 is chosen as a reasonable bailout radius.
	let bailout = (1 << 16);
	for si in range (0, iteration){
		for hy in range(0,hyres) {
			for hx in range(0,hxres) {
				let cx:f64 = (hx as f64 / hxres as f64 - 0.5) / magnify ;
				let cy:f64 = (hy as f64 / hyres as f64 - 0.5) / magnify ;
				let mut x:f64 = 0.0;
				let mut y:f64 = 0.0;
				let mut escaped:bool = false;
				let index = hy*hyres+hx;
				for i in range(0,si) {
					let xx:f64 = x*x - y*y + cx;
					y = 2.0 * x*y + cy;
					x = xx;
					if  x*x + y*y > bailout as f64 {
						escaped = true;
					}
				}
				if ! escaped {
					if si % 2 == 0 {
						pixels[index] = Color{r:0,g:palette[si as usize],b:0};
					}
					else{
						pixels[index] = Color{r:0,g:0,b:palette[si as usize]};
					}
				}
				else{
				    //will be black, but leave it to preserve previous iteration color values
				}
			}
		}
	}

	save_to_file(pixels, hxres, hyres);

}

fn save_to_file(pixels:Vec<Color>, hxres:usize, hyres:usize){

	let mut file = File::create(&Path::new("man.ppm"));
	let header = String::from_str(format!("P6\n# CREATOR: lee\n").as_slice());
	file.write(header.into_bytes().as_slice());

	let size = String::from_str(format!("{} {}\n255\n", hxres, hyres).as_slice());
	file.write(size.into_bytes().as_slice());

	for p in range(0,pixels.len()){
		file.write_u8(pixels[p].r);
		file.write_u8(pixels[p].g);
		file.write_u8(pixels[p].b);
	}
}

<commit_msg>change output image to mandelbrot.ppm<commit_after>use std::io::File;

struct Color{
	r:u8,
	g:u8,
	b:u8,
}

fn main(){

	let iteration:u64 = 100;
	let magnify:f64 = 0.25;
	let hxres = 500;
	let hyres = 500;

	let total = (hxres)*(hyres);
	println!("total: {}", total);
	let mut pixels:Vec<Color> =Vec::new();// should be 3 * total
	for t in range(0, total){
	    pixels.push(Color{r:0,g:0,b:0});
	}

	let mut palette:Vec<u8> = Vec::new();
	for pa in range (0, iteration){
		palette.push(((pa+100) * (100/iteration)) as u8);
	}
	let index:usize = 1;
	//Here N=2^8 is chosen as a reasonable bailout radius.
	let bailout = (1 << 16);
	for si in range (0, iteration){
		for hy in range(0,hyres) {
			for hx in range(0,hxres) {
				let cx:f64 = (hx as f64 / hxres as f64 - 0.5) / magnify ;
				let cy:f64 = (hy as f64 / hyres as f64 - 0.5) / magnify ;
				let mut x:f64 = 0.0;
				let mut y:f64 = 0.0;
				let mut escaped:bool = false;
				let index = hy*hyres+hx;
				for i in range(0,si) {
					let xx:f64 = x*x - y*y + cx;
					y = 2.0 * x*y + cy;
					x = xx;
					if  x*x + y*y > bailout as f64 {
						escaped = true;
					}
				}
				if ! escaped {
					if si % 2 == 0 {
						pixels[index] = Color{r:0,g:palette[si as usize],b:0};
					}
					else{
						pixels[index] = Color{r:0,g:0,b:palette[si as usize]};
					}
				}
				else{
				    //will be black, but leave it to preserve previous iteration color values
				}
			}
		}
	}

	save_to_file(pixels, hxres, hyres);

}

fn save_to_file(pixels:Vec<Color>, hxres:usize, hyres:usize){

	let mut file = File::create(&Path::new("mandelbrot.ppm"));
	let header = String::from_str(format!("P6\n# CREATOR: lee\n").as_slice());
	file.write(header.into_bytes().as_slice());

	let size = String::from_str(format!("{} {}\n255\n", hxres, hyres).as_slice());
	file.write(size.into_bytes().as_slice());

	for p in range(0,pixels.len()){
		file.write_u8(pixels[p].r);
		file.write_u8(pixels[p].g);
		file.write_u8(pixels[p].b);
	}
}

<|endoftext|>


<commit_before>extern crate ktensor as k;
use k::{Arc, Vec2, Tensor, Context, Graph, State, Variable};
use std::path::{Path};
use std::fs::{File};
use std::io::{BufReader, Read};
use std::error::{Error};
use std::cmp;

fn read_u8(reader: &mut Read) -> u8 {
    use std::mem;

    let mut buf: [u8; 1] = [0];
    match reader.read_exact(&mut buf).map(|_| {
        let data: u8 = unsafe { mem::transmute(buf) };
        data
    }) {
        Err(reason) => panic!("failed to read u8: {}", Error::description(&reason)),
        Ok(byte)    => byte,
    }
}

fn read_u32(reader: &mut Read) -> u32 {
    use std::mem;

    let mut buf: [u8; 4] = [0, 0, 0, 0];
    match reader.read_exact(&mut buf).map(|_| {
        let data: u32 = unsafe { mem::transmute(buf) };
        data
    }) {
        Err(reason) => panic!("failed to read u32: {}", Error::description(&reason)),
        Ok(byte)    => byte,
    }
}

fn read_mnist(labels_path: &Path, labels_checknum: u32, data_path: &Path, data_checknum: u32, batch_size: usize, samples: Option<usize>) {
    let labels_file = match File::open(&labels_path) {
        Err(reason) => panic!("failed to open {}: {}", labels_path.display(), Error::description(&reason)),
        Ok(file)    => file,
    };
    let data_file = match File::open(&data_path) {
        Err(reason) => panic!("failed to open {}: {}", data_path.display(), Error::description(&reason)),
        Ok(file)    => file,
    };
    let ref mut labels_reader = BufReader::new(labels_file);
    let ref mut data_reader = BufReader::new(data_file);

    let labels_magic = u32::from_be(read_u32(labels_reader));
    let data_magic = u32::from_be(read_u32(data_reader));

    assert_eq!(labels_magic, labels_checknum);
    assert_eq!(data_magic, data_checknum);

    let labels_count = u32::from_be(read_u32(labels_reader)) as usize;
    let data_count = u32::from_be(read_u32(data_reader)) as usize;
    let sample_count = cmp::min(labels_count, data_count);
    let sample_count = cmp::min(sample_count, samples.unwrap_or(sample_count));

    let rows = u32::from_be(read_u32(data_reader)) as usize;
    let columns = u32::from_be(read_u32(data_reader)) as usize;

    let mut sample_vec: Vec<(Vec<u8>, Vec<u8>)> = Vec::with_capacity(sample_count/batch_size);
    for _ in 0..sample_count/batch_size {
        let mut sample_data = vec![0u8; batch_size*rows*columns];
        match data_reader.read_exact(sample_data.as_mut()) {
            Err(reason) => panic!("failed to read data byte array: {}", Error::description(&reason)),
            Ok(_)       => (),
        }
        let mut sample_labels = vec![0u8; batch_size];
        match labels_reader.read_exact(sample_labels.as_mut()) {
            Err(reason) => panic!("failed to read labels byte array: {}", Error::description(&reason)),
            Ok(_)       => (),
        }
        sample_vec.push((sample_data, sample_labels));
    }
}

#[test]
#[ignore]
fn mnist(){
    let train_labels_path = Path::new("data/train-labels-idx1-ubyte");
    let train_data_path = Path::new("data/train-images-idx3-ubyte");
    read_mnist(&train_labels_path, 2049, &train_data_path, 2051, 16, Some(4096));

    ///////////////
    // Variables //
    ///////////////

    let input_x = Arc::new(Variable::new("input_x".to_string(), Vec2(0, 28 * 28)));
    let target_y = Arc::new(Variable::new("target_y".to_string(), Vec2(0, 10)));

    ///////////
    // Graph //
    ///////////

    let layers: usize = 2;
    let mut states = Vec::<Arc<State>>::with_capacity(2 * layers);
    let mut graph_head: Arc<Graph<f64>> = input_x.clone();

    {
        let w = Arc::new(State::new(format!("weight_w_{}", 1), Vec2(28 * 28, 16)));
        let b = Arc::new(State::new(format!("weight_b_{}", 1), Vec2(1, 16)));

        let dot = Arc::new(k::op::dot::<f64>(format!("layer_{}_dot", 1), graph_head.clone(), w.clone()));
        let add = Arc::new(k::op::add::<f64>(format!("layer_{}_add", 1), dot.clone(), b.clone()));

        let relu = Arc::new(k::op::relu_f64(format!("layer_{}_relu", 1), add.clone()));

        graph_head = relu.clone();

        states.push(w.clone());
        states.push(b.clone());
    }

    {
        let w = Arc::new(State::new(format!("weight_w_{}", 1), Vec2(2, 4)));
        let b = Arc::new(State::new(format!("weight_b_{}", 1), Vec2(1, 4)));

        let dot = Arc::new(k::op::dot::<f64>(format!("layer_{}_dot", 1), graph_head.clone(), w.clone()));
        let add = Arc::new(k::op::add::<f64>(format!("layer_{}_add", 1), dot.clone(), b.clone()));

        let relu = Arc::new(k::op::relu_f64(format!("layer_{}_relu", 1), add.clone()));

        graph_head = relu.clone();

        states.push(w.clone());
        states.push(b.clone());
    }
}
<commit_msg>need to configure training<commit_after>extern crate ktensor as k;
use k::{Arc, Vec2, Tensor, Context, Graph, State, Variable};
use std::path::{Path};
use std::fs::{File};
use std::io::{BufReader, Read};
use std::error::{Error};
use std::cmp;

fn read_u8(reader: &mut Read) -> u8 {
    use std::mem;

    let mut buf: [u8; 1] = [0];
    match reader.read_exact(&mut buf).map(|_| {
        let data: u8 = unsafe { mem::transmute(buf) };
        data
    }) {
        Err(reason) => panic!("failed to read u8: {}", Error::description(&reason)),
        Ok(byte)    => byte,
    }
}

fn read_u32(reader: &mut Read) -> u32 {
    use std::mem;

    let mut buf: [u8; 4] = [0, 0, 0, 0];
    match reader.read_exact(&mut buf).map(|_| {
        let data: u32 = unsafe { mem::transmute(buf) };
        data
    }) {
        Err(reason) => panic!("failed to read u32: {}", Error::description(&reason)),
        Ok(byte)    => byte,
    }
}

fn read_mnist(labels_path: &Path, labels_checknum: u32, data_path: &Path, data_checknum: u32, batch_size: usize, samples: Option<usize>) {
    let labels_file = match File::open(&labels_path) {
        Err(reason) => panic!("failed to open {}: {}", labels_path.display(), Error::description(&reason)),
        Ok(file)    => file,
    };
    let data_file = match File::open(&data_path) {
        Err(reason) => panic!("failed to open {}: {}", data_path.display(), Error::description(&reason)),
        Ok(file)    => file,
    };
    let ref mut labels_reader = BufReader::new(labels_file);
    let ref mut data_reader = BufReader::new(data_file);

    let labels_magic = u32::from_be(read_u32(labels_reader));
    let data_magic = u32::from_be(read_u32(data_reader));

    assert_eq!(labels_magic, labels_checknum);
    assert_eq!(data_magic, data_checknum);

    let labels_count = u32::from_be(read_u32(labels_reader)) as usize;
    let data_count = u32::from_be(read_u32(data_reader)) as usize;
    let sample_count = cmp::min(labels_count, data_count);
    let sample_count = cmp::min(sample_count, samples.unwrap_or(sample_count));

    let rows = u32::from_be(read_u32(data_reader)) as usize;
    let columns = u32::from_be(read_u32(data_reader)) as usize;

    let mut sample_vec: Vec<(Vec<u8>, Vec<u8>)> = Vec::with_capacity(sample_count/batch_size);
    for _ in 0..sample_count/batch_size {
        let mut sample_data = vec![0u8; batch_size*rows*columns];
        match data_reader.read_exact(sample_data.as_mut()) {
            Err(reason) => panic!("failed to read data byte array: {}", Error::description(&reason)),
            Ok(_)       => (),
        }
        let mut sample_labels = vec![0u8; batch_size];
        match labels_reader.read_exact(sample_labels.as_mut()) {
            Err(reason) => panic!("failed to read labels byte array: {}", Error::description(&reason)),
            Ok(_)       => (),
        }
        sample_vec.push((sample_data, sample_labels));
    }
}

#[test]
#[ignore]
fn mnist(){
    let train_labels_path = Path::new("data/train-labels-idx1-ubyte");
    let train_data_path = Path::new("data/train-images-idx3-ubyte");
    read_mnist(&train_labels_path, 2049, &train_data_path, 2051, 16, Some(4096));

    ///////////////
    // Variables //
    ///////////////

    let input_x = Arc::new(Variable::new("input_x".to_string(), Vec2(0, 28 * 28)));
    let target_y = Arc::new(Variable::new("target_y".to_string(), Vec2(0, 10)));

    ///////////
    // Graph //
    ///////////

    let layers: usize = 2;
    let mut states = Vec::<Arc<State>>::with_capacity(2 * layers);
    let mut graph_head: Arc<Graph<f32>> = input_x.clone();

    {
        let w = Arc::new(State::new(format!("weight_w_{}", 1), Vec2(28 * 28, 16)));
        let b = Arc::new(State::new(format!("weight_b_{}", 1), Vec2(1, 16)));

        let dot = Arc::new(k::op::dot::<f32>(format!("layer_{}_dot", 1), graph_head.clone(), w.clone()));
        let add = Arc::new(k::op::add::<f32>(format!("layer_{}_add", 1), dot, b.clone()));

        let relu = Arc::new(k::op::relu_f32(format!("layer_{}_relu", 1), add));

        graph_head = relu;

        states.push(w);
        states.push(b);
    }

    {
        let w = Arc::new(State::new(format!("weight_w_{}", 2), Vec2(16, 10)));
        let b = Arc::new(State::new(format!("weight_b_{}", 2), Vec2(1, 10)));

        let dot = Arc::new(k::op::dot::<f32>(format!("layer_{}_dot", 2), graph_head.clone(), w.clone()));
        let add = Arc::new(k::op::add::<f32>(format!("layer_{}_add", 2), dot, b.clone()));

        let relu = Arc::new(k::op::relu_f32(format!("layer_{}_relu", 2), add);

        graph_head = relu;

        states.push(w);
        states.push(b);
    }

    let softmax2 = Arc::new(k::op::softmax_f32(format!("layer_{}_softmax", 3), graph_head.clone()));
    let xentropy2 = Arc::new(k::cost::softmax_cross_entropy_f32(format!("layer_{}_xentropy", 3), softmax2.clone(), target_y.clone()));

    // initialize states
    let mut state_context = Context::<f32>::with_capacity(2 * layers);
    State::init_f32(states, &mut state_context);

    //////////////
    // training //
    //////////////

    let training_vec = (
        Tensor::from_vec(Vec2(4, 2), vec![
        0.0, 0.0,
        0.0, 1.0,
        1.0, 0.0,
        1.0, 1.0,
        ]),
        Tensor::from_vec(Vec2(4, 2), vec![
        0.0, 1.0,
        1.0, 0.0,
        1.0, 0.0,
        0.0, 1.0,
        ]),
    );

    let batch = true;
    let iterations = 16384;
    let learning_rate = -0.1;
    let print_rate = 4096;

    let mut history = Context::<f64>::with_capacity(5 * layers + 4);

    for i in 0..iterations {
        let (ref a, ref b) = training_vec[i % training_vec.len()];
        variable_context.set(input_x.get_id(), a.clone());
        variable_context.set(target_y.get_id(), b.clone());

        k::train(xentropy2.clone(), &mut state_context, &variable_context, &mut history, learning_rate);

        // test print
        if i % print_rate == 0 {
            variable_context.set(input_x.get_id(), training_set.0.clone());
            variable_context.set(target_y.get_id(), training_set.1.clone());
            println!("\niteration: {} | xentropy2 output:", i);
            let final_test = k::execute(xentropy2.clone(), &state_context, &variable_context);
            for i in 0..4 {
                println!("{} {}", final_test.get(Vec2(i, 0)), final_test.get(Vec2(i, 1)));
            }
        }
    }

    ////////////////
    // final test //
    ////////////////

}
<|endoftext|>


<commit_before>fn test_str(exe: &str, s: &str) {
    use std::process::{Command, Stdio};
    use std::io::Write;
    use std::str::from_utf8;
    let mut cmd = Command::new(exe)
        .stdin(Stdio::piped())
        .stderr(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    write!(cmd.stdin.as_mut().unwrap(), "{}", s).unwrap();
    let res = cmd.wait_with_output().unwrap();
    println!("stdout: {}", from_utf8(&res.stdout).unwrap());
    println!("stderr: {}", from_utf8(&res.stderr).unwrap());
    println!("status: {:?}", res.status);
    assert!(res.status.success());
}

#[test]
fn run() {
    test_str("test_tuple", "42, 99, Ä");
}

#[test]
fn run2() {
    test_str("test_tuple", "42,\t99,\nÄ");
}

#[test]
#[should_panic]
fn run_fail() {
    test_str("test_tuple", "42,99, Ä");
}

#[test]
fn run_read() {
    test_str("test_read", "the answer™: 42");
}
<commit_msg>debugging with the println hammer<commit_after>fn test_str(exe: &str, s: &str) {
    use std::process::{Command, Stdio};
    use std::io::Write;
    use std::str::from_utf8;
    let mut cmd = Command::new(exe)
        .stdin(Stdio::piped())
        .stderr(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    println!("started cmd");
    write!(cmd.stdin.as_mut().unwrap(), "{}", s).unwrap();
    println!("wrote to stdin");
    let res = cmd.wait_with_output().unwrap();
    println!("stdout: {}", from_utf8(&res.stdout).unwrap());
    println!("stderr: {}", from_utf8(&res.stderr).unwrap());
    println!("status: {:?}", res.status);
    assert!(res.status.success());
}

#[test]
fn run() {
    test_str("test_tuple", "42, 99, Ä");
}

#[test]
fn run2() {
    test_str("test_tuple", "42,\t99,\nÄ");
}

#[test]
#[should_panic]
fn run_fail() {
    test_str("test_tuple", "42,99, Ä");
}

#[test]
fn run_read() {
    test_str("test_read", "the answer™: 42");
}
<|endoftext|>


<commit_before>/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ecr::{Error, Region, PKG_VERSION};
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
struct Opt {
    /// The AWS Region.
    #[structopt(short, long)]
    region: Option<String>,

    /// The name of the repository.
    #[structopt(long)]
    repository: String,

    /// Whether to display additional information.
    #[structopt(short, long)]
    verbose: bool,
}

// Show the images in a repository.
// snippet-start:[ecr.rust.list-images]
async fn show_images(
    client: &aws_sdk_ecr::Client,
    repository: &str,
) -> Result<(), aws_sdk_ecr::Error> {
    let rsp = client
        .list_images()
        .repository_name(repository)
        .send()
        .await?;

    let images = rsp.image_ids.unwrap_or_default();

    println!("found {} images", images.len());

    for image in images {
        println!(
            "image: {}:{}",
            image.image_tag.unwrap(),
            image.image_digest.unwrap()
        );
    }

    Ok(())
}
// snippet-end:[ecr.rust.list-images]

/// Lists the images in an Amazon Elastic Container Registry repository.
/// # Arguments
///
/// * `[-repository REPOSITORY]` - The ECR repository containing images.
/// * `[-r REGION]` - The Region in which the client is created.
///   If not supplied, uses the value of the **AWS_REGION** environment variable.
///   If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.

#[tokio::main]
async fn main() -> Result<(), Error> {
    let Opt {
        region,
        repository,
        verbose,
    } = Opt::from_args();

    if verbose {
        tracing_subscriber::fmt::init();
    }

    let region_provider = RegionProviderChain::first_try(region.map(Region::new))
        .or_default_provider()
        .or_else(Region::new("us-west-2"));

    if verbose {
        println!();
        println!("ECR client version: {}", PKG_VERSION);
        println!(
            "Region:             {}",
            region_provider.region().await.unwrap().as_ref()
        );
        println!("Repository:         {}", &repository);
        println!();
    }

    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = aws_sdk_ecr::Client::new(&shared_config);

    show_images(&client, &repository).await
}
<commit_msg>Updated Rust code example to use accessor functions instead of public fields<commit_after>/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ecr::{Error, Region, PKG_VERSION};
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
struct Opt {
    /// The AWS Region.
    #[structopt(short, long)]
    region: Option<String>,

    /// The name of the repository.
    #[structopt(long)]
    repository: String,

    /// Whether to display additional information.
    #[structopt(short, long)]
    verbose: bool,
}

// Show the images in a repository.
// snippet-start:[ecr.rust.list-images]
async fn show_images(
    client: &aws_sdk_ecr::Client,
    repository: &str,
) -> Result<(), aws_sdk_ecr::Error> {
    let rsp = client
        .list_images()
        .repository_name(repository)
        .send()
        .await?;

    let images = rsp.image_ids().unwrap_or_default();

    println!("found {} images", images.len());

    for image in images {
        println!(
            "image: {}:{}",
            image.image_tag().unwrap(),
            image.image_digest().unwrap()
        );
    }

    Ok(())
}
// snippet-end:[ecr.rust.list-images]

/// Lists the images in an Amazon Elastic Container Registry repository.
/// # Arguments
///
/// * `[-repository REPOSITORY]` - The ECR repository containing images.
/// * `[-r REGION]` - The Region in which the client is created.
///   If not supplied, uses the value of the **AWS_REGION** environment variable.
///   If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.

#[tokio::main]
async fn main() -> Result<(), Error> {
    let Opt {
        region,
        repository,
        verbose,
    } = Opt::from_args();

    if verbose {
        tracing_subscriber::fmt::init();
    }

    let region_provider = RegionProviderChain::first_try(region.map(Region::new))
        .or_default_provider()
        .or_else(Region::new("us-west-2"));

    if verbose {
        println!();
        println!("ECR client version: {}", PKG_VERSION);
        println!(
            "Region:             {}",
            region_provider.region().await.unwrap().as_ref()
        );
        println!("Repository:         {}", &repository);
        println!();
    }

    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = aws_sdk_ecr::Client::new(&shared_config);

    show_images(&client, &repository).await
}
<|endoftext|>


<commit_before>use std::io::{File, Open, Read};
use std::string::{String};
use std::path::Path;
use std::os;
use std::str;

fn print_hex (bytes: &Vec<u8>) {
	println!("Len of bytes: {}", bytes.len());
}

fn main() {
	let args = os::args();
	let mut iter = args.iter().skip(1); // skip the program name
	let mut file_name : &String = (iter.next().as_slice())[0];

	println!("Filename: {}", file_name);
	let path = Path::new(file_name.as_bytes());
	/*let file = match File::open_mode(path, Open, Read) {
		Ok(f) => f,
		Err(e) => fail!("file error: {}", e),
	};*/
	let mut file = File::open(&path);
	let fread_result = file.read_to_end();
	let contents : Option<Vec<u8>> = None;
	match fread_result {
	    // The read was valid
	    Ok(x) => {
	    	println!("File was valid");
	    	contents = x.clone();
	    },
	    // The read was invalid
	    Err(e) => {
	    	println!("File was invalid");
	    	contents = Vec::new();
	    }
	}
	let sz : u64 = path.stat().unwrap().size;
	let s = format!("Filename: {:s} Size: {:x}", *file_name, sz);
	let s = format!("Contents Len: {:x}", contents.len());
	println!("{}",s);
	//print_hex (contents);
}<commit_msg>trying to figure out how to handle the error<commit_after>use std::io::{File, Open, Read};
use std::string::{String};
use std::path::Path;
use std::os;
use std::str;

fn print_hex (bytes: &Vec<u8>) {
	println!("Len of bytes: {}", bytes.len());
}

fn main() {
	let args = os::args();
	let mut iter = args.iter().skip(1); // skip the program name
	let mut file_name : &String = (iter.next().as_slice())[0];

	println!("Filename: {}", file_name);
	let path = Path::new(file_name.as_bytes());
	/*let file = match File::open_mode(path, Open, Read) {
		Ok(f) => f,
		Err(e) => fail!("file error: {}", e),
	};*/
	let mut file = File::open(&path);
	let fread_result = file.read_to_end();
	let contents : Vec<u8>;
	match fread_result {
	    // The read was valid
	    Ok(x) => {
	    	println!("File was valid");
	    	contents = x.clone();
	    },
	    // The read was invalid
	    Err(e) => {
	    //None => {
	    	println!("File was invalid");
	    	contents = Vec::new();
	    }
	}
	let sz : u64 = path.stat().unwrap().size;
	let mut s = format!("Filename: {:s} Size: {:x}", *file_name, sz);
	println!("{}",s);
	s = format!("Contents Len: {:x}", contents.len());
	println!("{}",s);
	//print_hex (contents);
}<|endoftext|>


<commit_before>#[macro_use]
mod macros;

use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree};
use std::iter::FromIterator;
use syn::{Expr, Type};

#[test]
fn parse_interpolated_leading_component() {
    // mimics the token stream corresponding to `$mod::rest`
    let tokens = TokenStream::from_iter(vec![
        TokenTree::Group(Group::new(
            Delimiter::None,
            TokenStream::from_iter(vec![TokenTree::Ident(Ident::new(
                "first",
                Span::call_site(),
            ))]),
        )),
        TokenTree::Punct(Punct::new(':', Spacing::Joint)),
        TokenTree::Punct(Punct::new(':', Spacing::Alone)),
        TokenTree::Ident(Ident::new("rest", Span::call_site())),
    ]);

    snapshot!(tokens.clone() as Expr, @r###"
    Expr::Path {
        path: Path {
            segments: [
                PathSegment {
                    ident: "first",
                    arguments: None,
                },
                PathSegment {
                    ident: "rest",
                    arguments: None,
                },
            ],
        },
    }
    "###);

    snapshot!(tokens as Type, @r###"
    Type::Path {
        path: Path {
            segments: [
                PathSegment {
                    ident: "first",
                    arguments: None,
                },
                PathSegment {
                    ident: "rest",
                    arguments: None,
                },
            ],
        },
    }
    "###);
}
<commit_msg>Clean up path test using quote<commit_after>#[macro_use]
mod macros;

use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree};
use quote::quote;
use std::iter::FromIterator;
use syn::{Expr, Type};

#[test]
fn parse_interpolated_leading_component() {
    // mimics the token stream corresponding to `$mod::rest`
    let tokens = TokenStream::from_iter(vec![
        TokenTree::Group(Group::new(Delimiter::None, quote! { first })),
        TokenTree::Punct(Punct::new(':', Spacing::Joint)),
        TokenTree::Punct(Punct::new(':', Spacing::Alone)),
        TokenTree::Ident(Ident::new("rest", Span::call_site())),
    ]);

    snapshot!(tokens.clone() as Expr, @r###"
    Expr::Path {
        path: Path {
            segments: [
                PathSegment {
                    ident: "first",
                    arguments: None,
                },
                PathSegment {
                    ident: "rest",
                    arguments: None,
                },
            ],
        },
    }
    "###);

    snapshot!(tokens as Type, @r###"
    Type::Path {
        path: Path {
            segments: [
                PathSegment {
                    ident: "first",
                    arguments: None,
                },
                PathSegment {
                    ident: "rest",
                    arguments: None,
                },
            ],
        },
    }
    "###);
}
<|endoftext|>