<commit_before>
// Use our internal types module.
use types;
use term;

fn project_color_id_map(color: u8) -> term::color::Color {

    // The color of the project (a number between 0 and 11, or between 0 and 21 for premium users).
    match color {

        //
   // Normal Colors
   //

   // #95ef63
        0 => term::color::BRIGHT_GREEN,
        // #ff8581 - A pinkish, red.
        1 => term::color::BRIGHT_RED,
        // #ffc471 - Orange
        2 => term::color::RED,
        // #f9ec75
        3 => term::color::YELLOW,
        // #a8c8e4 - A light blue.
        4 => term::color::BRIGHT_BLUE,
        // #d2b8a3 - A tan color
        5 => term::color::WHITE,
        // #e2a8e4 - Another pink.
        6 => term::color::BRIGHT_RED,
        // #cccccc - A gray, map to white
        7 => term::color::WHITE,
        // #fb886e - Orange, map to red
        8 => term::color::RED,
        // #ffcc00
        9 => term::color::YELLOW,
        // #74e8d3 - bright green
        10 => term::color::BRIGHT_GREEN,
        // #3bd5fb
        11 => term::color::BRIGHT_BLUE,

        //
   // Premium Colors
   //

   // #dc4fad - pinkish
        12 => term::color::BRIGHT_RED,
        // #ac193d - dark red
        13 => term::color::MAGENTA,
        // #d24726 - normal red
        14 => term::color::RED,
        // #82ba00 - medium green
        15 => term::color::GREEN,
        // #03b3b2
        16 => term::color::BRIGHT_CYAN,
        // #008299
        17 => term::color::CYAN,
        // #5db2ff
        18 => term::color::BRIGHT_BLUE,
        // #0072c6
        19 => term::color::BLUE,
        // #000000
        20 => term::color::BLACK,
        // #777777 - Gray, we don't have default to white.
        21 => term::color::WHITE,

        // Default handler.
        _ => unreachable!("Unknown color id! {}", color),
    }
}

pub fn render_project(project: types::ProjectStruct) {
    // Switch the term to the color the project has set.
    let mut terminal = term::stdout().unwrap();
    let color = project_color_id_map(project.color);

    // Double the indention level so we have a nice visual indent.
    let ident = usize::from(project.indent * 2);

    terminal.fg(color).unwrap();

    println!("{:ident$}{}", "", project.name, ident = ident);

    terminal.reset().unwrap();
}

pub fn render_item(item: types::ItemStruct) {
    // Double the indention level so we have a nice visual indent.
    let ident = usize::from(item.indent * 2);

     println!("{:ident$}{} ({})",
                 "",
                 item.content,
                 item.date_string,
                 ident = ident);
}
<commit_msg>Render: Fix comments that got mangled by rustfmt.<commit_after>///!
///! Defines methods for rendering output to the console.
///!
///! The goal being that we seperate formatting text and
///! all of that business from the actual processing of
///! the various data exposed from the API.
///!

// Use our internal types module.
use types;
use term;

fn project_color_id_map(color: u8) -> term::color::Color {

    // The color of the project (a number between 0 and 11, or between 0 and 21 for premium users).
    match color {

    // Normal Colors

        // #95ef63
        0 => term::color::BRIGHT_GREEN,
        // #ff8581 - A pinkish, red.
        1 => term::color::BRIGHT_RED,
        // #ffc471 - Orange
        2 => term::color::RED,
        // #f9ec75
        3 => term::color::YELLOW,
        // #a8c8e4 - A light blue.
        4 => term::color::BRIGHT_BLUE,
        // #d2b8a3 - A tan color
        5 => term::color::WHITE,
        // #e2a8e4 - Another pink.
        6 => term::color::BRIGHT_RED,
        // #cccccc - A gray, map to white
        7 => term::color::WHITE,
        // #fb886e - Orange, map to red
        8 => term::color::RED,
        // #ffcc00
        9 => term::color::YELLOW,
        // #74e8d3 - bright green
        10 => term::color::BRIGHT_GREEN,
        // #3bd5fb
        11 => term::color::BRIGHT_BLUE,

    // Premium Colors

        // #dc4fad - pinkish
        12 => term::color::BRIGHT_RED,
        // #ac193d - dark red
        13 => term::color::MAGENTA,
        // #d24726 - normal red
        14 => term::color::RED,
        // #82ba00 - medium green
        15 => term::color::GREEN,
        // #03b3b2
        16 => term::color::BRIGHT_CYAN,
        // #008299
        17 => term::color::CYAN,
        // #5db2ff
        18 => term::color::BRIGHT_BLUE,
        // #0072c6
        19 => term::color::BLUE,
        // #000000
        20 => term::color::BLACK,
        // #777777 - Gray, we don't have default to white.
        21 => term::color::WHITE,

        // Default handler.
        _ => unreachable!("Unknown color id! {}", color),
    }
}

pub fn render_project(project: types::ProjectStruct) {
    // Switch the term to the color the project has set.
    let mut terminal = term::stdout().unwrap();
    let color = project_color_id_map(project.color);

    // Double the indention level so we have a nice visual indent.
    let ident = usize::from(project.indent * 2);

    terminal.fg(color).unwrap();

    println!("{:ident$}{}", "", project.name, ident = ident);

    terminal.reset().unwrap();
}

pub fn render_item(item: types::ItemStruct) {
    // Double the indention level so we have a nice visual indent.
    let ident = usize::from(item.indent * 2);

     println!("{:ident$}{} ({})",
                 "",
                 item.content,
                 item.date_string,
                 ident = ident);
}
<|endoftext|>


<commit_before>extern crate rs_release;

use rs_release::get_os_release;

fn main() {
    match get_os_release() {
        Ok(os_release) => {
            println!("Parsed os-release:");
            for (k, v) in os_release {
                println!("{}={}", k, v);
            }
        }
        Err(e) => println!("ERROR: {:?}", e),
    }
}
<commit_msg>examples/get_os_release: Use first passed argument as os-release path<commit_after>extern crate rs_release;

use rs_release::{get_os_release, parse_os_release};
use std::env;

fn main() {
    let args = env::args();

    let os_release = if let Some(os_release_path) = args.skip(1).next() {
        parse_os_release(os_release_path)
    } else {
        get_os_release()
    };

    match os_release {
        Ok(os_release) => {
            println!("Parsed os-release:");
            for (k, v) in os_release {
                println!("{}={}", k, v);
            }
        }
        Err(e) => println!("ERROR: {:?}", e),
    }
}
<|endoftext|>


<commit_before>use std::path::PathBuf;
use std::process::Command;
use std::env;

fn main() {
    let target = env::var("TARGET").expect("Environnement variable TARGET not set");
    // let out_dir = env::var("OUT_DIR").expect("Failed to get output directory");
    let current_dir = env::current_dir().expect("Failed to get current directory");

    // println!("target:      {:?}", target);
    // println!("out_dir:     {:?}", out_dir);
    // println!("current_dir: {:?}", current_dir);

    let libqmlbind_dir = current_dir.join("libqmlbind");
    let libqmlbind_build_dir = libqmlbind_dir.join("build");

    std::fs::create_dir_all(&libqmlbind_build_dir).unwrap_or_else(|e| panic!("Failed to create libqmlbind build directory: {}", e));

    // Initialize git submodule
    if !libqmlbind_dir.join(".git").exists() {
        let _ = Command::new("git").args(&["submodule", "update", "--init"])
                                   .status()
                                   .unwrap_or_else(|e| panic!("Failed to initialize git submodule: {}", e));
    }

    let output = Command::new("qmake").arg("../qmlbind")
                                      .current_dir(&libqmlbind_build_dir)
                                      .output()
                                      .unwrap_or_else(|e| panic!("Failed execute qmake: {}", e));
    println!("output.status: {}", output.status);
    println!("output.stdout: {}", String::from_utf8_lossy(&output.stdout));
    println!("output.stderr: {}", String::from_utf8_lossy(&output.stderr));
    assert!(output.status.success(), "failed to execute qmake process");

    let output = Command::new("make")
                                .current_dir(&libqmlbind_build_dir)
                                .output()
                                .unwrap_or_else(|e| panic!("Failed execute make : {}", e));
    println!("output.status: {}", output.status);
    println!("output.stdout: {}", String::from_utf8_lossy(&output.stdout));
    println!("output.stderr: {}", String::from_utf8_lossy(&output.stderr));
    assert!(output.status.success(), "failed to execute make process");

    let output = Command::new("make").arg("staticlib")
                                     .current_dir(&libqmlbind_build_dir)
                                     .output()
                                     .unwrap_or_else(|e| panic!("Failed execute 'make staticlib': {}", e));
    println!("output.status: {}", output.status);
    println!("output.stdout: {}", String::from_utf8_lossy(&output.stdout));
    println!("output.stderr: {}", String::from_utf8_lossy(&output.stderr));
    assert!(output.status.success(), "failed to execute 'make staticlib' process");

    println!("cargo:rustc-link-search={}", libqmlbind_build_dir.to_str().unwrap());
    println!("cargo:rustc-link-lib=static=qmlbind");

    let qt_dir = env::var("QT_DIR").map(|p| PathBuf::from(p)).unwrap_or({
        println!("Environnement variable 'QT_DIR' not set!");
        println!("Defaulting to ${{HOME}}/Qt/${{QT_VER}}/${{QT_COMP}} where:");
        let home_dir = env::home_dir().map(|p| PathBuf::from(p)).unwrap();
        let default_qt_ver = "5.7".to_string();
        let default_qt_comp = if target.contains("linux") {
            "gcc_64".to_string()
        } else if target.contains("darwin") {
            "clang_64".to_string()
        } else {
            panic!("Unsuported platform in gallery's build.rs!")
        };
        println!("    QT_VER:  {}", default_qt_ver);
        println!("    QT_COMP: {}", default_qt_comp);
        let qt_dir_default = home_dir.join("Qt")
                                  .join(env::var("QT_VER").unwrap_or(default_qt_ver))
                                  .join(env::var("QT_COMP").unwrap_or(default_qt_comp));
        qt_dir_default
    });
    println!("Using Qt directory: {:?}", qt_dir);
    println!("Use QT_DIR environment variable to ovewrite.");

    let qt_lib_dir = qt_dir.join("lib").to_str().unwrap().to_string();

    let osx_framework = if target.contains("darwin") { "=framework" }
                        else  { "" };
    // On Linux, libraries are name "Qt5Core", not "QtCore" as on OSX
    let linux_qt_lib_ver = if target.contains("linux") { "5" }
                           else  { "" };

    println!("cargo:rustc-link-search{}={}", osx_framework, qt_lib_dir);

    println!("cargo:rustc-link-lib{}=Qt{}Core", osx_framework, linux_qt_lib_ver);
    println!("cargo:rustc-link-lib{}=Qt{}Network", osx_framework, linux_qt_lib_ver);
    println!("cargo:rustc-link-lib{}=Qt{}Gui", osx_framework, linux_qt_lib_ver);
    println!("cargo:rustc-link-lib{}=Qt{}Qml", osx_framework, linux_qt_lib_ver);
    println!("cargo:rustc-link-lib{}=Qt{}Widgets", osx_framework, linux_qt_lib_ver);

    // On Linux, Qt needs icui18n, icuuc and icudata
    if target.contains("linux") {
        println!("cargo:rustc-link-lib=icui18n");
        println!("cargo:rustc-link-lib=icuuc");
        println!("cargo:rustc-link-lib=icudata");
    }

    println!("cargo:rustc-flags=-l stdc++");
}
<commit_msg>libqmlbind-sys: Move QT_DIR handling up in build.rs, use full path for qmake.<commit_after>use std::path::PathBuf;
use std::process::Command;
use std::env;

fn main() {
    let target = env::var("TARGET").expect("Environnement variable TARGET not set");
    // let out_dir = env::var("OUT_DIR").expect("Failed to get output directory");
    let current_dir = env::current_dir().expect("Failed to get current directory");

    // println!("target:      {:?}", target);
    // println!("out_dir:     {:?}", out_dir);
    // println!("current_dir: {:?}", current_dir);

    let libqmlbind_dir = current_dir.join("libqmlbind");
    let libqmlbind_build_dir = libqmlbind_dir.join("build");

    let qt_dir = env::var("QT_DIR").map(|p| PathBuf::from(p)).unwrap_or({
        println!("Environnement variable 'QT_DIR' not set!");
        println!("Defaulting to ${{HOME}}/Qt/${{QT_VER}}/${{QT_COMP}} where:");
        let home_dir = env::home_dir().map(|p| PathBuf::from(p)).unwrap();
        let default_qt_ver = "5.7".to_string();
        let default_qt_comp = if target.contains("linux") {
            "gcc_64".to_string()
        } else if target.contains("darwin") {
            "clang_64".to_string()
        } else {
            panic!("Unsuported platform in gallery's build.rs!")
        };
        println!("    QT_VER:  {}", default_qt_ver);
        println!("    QT_COMP: {}", default_qt_comp);
        let qt_dir_default = home_dir.join("Qt")
                                  .join(env::var("QT_VER").unwrap_or(default_qt_ver))
                                  .join(env::var("QT_COMP").unwrap_or(default_qt_comp));
        qt_dir_default
    });
    println!("Using Qt directory: {:?}", qt_dir);
    println!("Use QT_DIR environment variable to overwrite.");

    let qt_lib_dir = qt_dir.join("lib");
    let qt_bin_dir = qt_dir.join("bin");

    std::fs::create_dir_all(&libqmlbind_build_dir).unwrap_or_else(|e| panic!("Failed to create libqmlbind build directory: {}", e));

    // Initialize git submodule
    if !libqmlbind_dir.join(".git").exists() {
        let _ = Command::new("git").args(&["submodule", "update", "--init"])
                                   .status()
                                   .unwrap_or_else(|e| panic!("Failed to initialize git submodule: {}", e));
    }

    let output = Command::new(qt_bin_dir.join("qmake")).arg("../qmlbind")
                                      .current_dir(&libqmlbind_build_dir)
                                      .output()
                                      .unwrap_or_else(|e| panic!("Failed execute qmake: {}", e));
    println!("output.status: {}", output.status);
    println!("output.stdout: {}", String::from_utf8_lossy(&output.stdout));
    println!("output.stderr: {}", String::from_utf8_lossy(&output.stderr));
    assert!(output.status.success(), "failed to execute qmake process");

    let output = Command::new("make")
                                .current_dir(&libqmlbind_build_dir)
                                .output()
                                .unwrap_or_else(|e| panic!("Failed execute make : {}", e));
    println!("output.status: {}", output.status);
    println!("output.stdout: {}", String::from_utf8_lossy(&output.stdout));
    println!("output.stderr: {}", String::from_utf8_lossy(&output.stderr));
    assert!(output.status.success(), "failed to execute make process");

    let output = Command::new("make").arg("staticlib")
                                     .current_dir(&libqmlbind_build_dir)
                                     .output()
                                     .unwrap_or_else(|e| panic!("Failed execute 'make staticlib': {}", e));
    println!("output.status: {}", output.status);
    println!("output.stdout: {}", String::from_utf8_lossy(&output.stdout));
    println!("output.stderr: {}", String::from_utf8_lossy(&output.stderr));
    assert!(output.status.success(), "failed to execute 'make staticlib' process");

    println!("cargo:rustc-link-search={}", libqmlbind_build_dir.to_str().unwrap());
    println!("cargo:rustc-link-lib=static=qmlbind");

    let osx_framework = if target.contains("darwin") { "=framework" }
                        else  { "" };
    // On Linux, libraries are name "Qt5Core", not "QtCore" as on OSX
    let linux_qt_lib_ver = if target.contains("linux") { "5" }
                           else  { "" };

    println!("cargo:rustc-link-search{}={}", osx_framework, qt_lib_dir.to_str().unwrap());

    println!("cargo:rustc-link-lib{}=Qt{}Core", osx_framework, linux_qt_lib_ver);
    println!("cargo:rustc-link-lib{}=Qt{}Network", osx_framework, linux_qt_lib_ver);
    println!("cargo:rustc-link-lib{}=Qt{}Gui", osx_framework, linux_qt_lib_ver);
    println!("cargo:rustc-link-lib{}=Qt{}Qml", osx_framework, linux_qt_lib_ver);
    println!("cargo:rustc-link-lib{}=Qt{}Widgets", osx_framework, linux_qt_lib_ver);

    // On Linux, Qt needs icui18n, icuuc and icudata
    if target.contains("linux") {
        println!("cargo:rustc-link-lib=icui18n");
        println!("cargo:rustc-link-lib=icuuc");
        println!("cargo:rustc-link-lib=icudata");
    }

    println!("cargo:rustc-flags=-l stdc++");
}
<|endoftext|>


<commit_before>extern crate pencil;
extern crate typemap;
#[macro_use] extern crate log;
extern crate env_logger;

use std::collections::BTreeMap;
use typemap::Key;
use pencil::{Pencil, Request, Response, PencilResult};
use pencil::jsonify;
use pencil::HTTPError;
use pencil::{redirect, abort};
use pencil::method::Get;
use pencil::Module;

fn hello(_: &mut Request) -> PencilResult {
    Ok(Response::from("Hello World!"))
}

fn user(r: &mut Request) -> PencilResult {
    let user_id = r.view_args.get("user_id").unwrap();
    Ok(format!("user {}", user_id).into())
}

fn app_info(_: &mut Request) -> PencilResult {
    let mut d = BTreeMap::new();
    d.insert("name", "hello");
    d.insert("version", "0.1.0");
    return jsonify(&d);
}

fn page_not_found(_: HTTPError) -> PencilResult {
    let mut response = Response::from("Customized 404 :)");
    response.status_code = 404;
    Ok(response)
}

fn hello_template(request: &mut Request) -> PencilResult {
    let mut context = BTreeMap::new();
    context.insert("name".to_string(), "template".to_string());
    return request.app.render_template("hello.html", &context);
}

struct KeyType;
struct Value(i32);
impl Key for KeyType { type Value = Value; }

fn before_request(request: &mut Request) -> Option<PencilResult> {
    request.extensions_data.insert::<KeyType>(Value(100));
    None
}

fn github(_: &mut Request) -> PencilResult {
    return redirect("https://github.com/", 302);
}

fn login(_: &mut Request) -> PencilResult {
    return abort(401);
}

fn search(request: &mut Request) -> PencilResult {
    let keyword = match request.args().get("q") {
        Some(q) => q as &str,
        None => "",
    };
    Ok(Response::from(format!("You are searching for {}", keyword)))
}

fn hi_module(_: &mut Request) -> PencilResult {
    Ok("Hi module.".into())
}

fn main() {
    let mut app = Pencil::new("/web/hello");
    app.set_debug(true);
    app.set_log_level();
    env_logger::init().unwrap();
    app.enable_static_file_handling();
    app.register_template("hello.html");
    app.before_request(before_request);

    app.httperrorhandler(404, page_not_found);

    app.get("/", "hello", hello);
    app.get("/user/<user_id:int>", "user", user);
    app.get("/info", "app_info", app_info);
    app.get("/hello_template", "hello_template", hello_template);
    app.get("/github", "github", github);
    app.get("/login", "login", login);
    app.get("/search", "search", search);

    let mut demo_module = Module::new("demo", "/web/hello/demo");
    demo_module.route("/demo/hi", &[Get], "hi", hi_module);
    app.register_module(demo_module);

    debug!("* Running on http://localhost:5000/");
    app.run("127.0.0.1:5000");
}
<commit_msg>Use env to get hello app root path<commit_after>extern crate pencil;
extern crate typemap;
#[macro_use] extern crate log;
extern crate env_logger;

use std::env;
use std::collections::BTreeMap;
use typemap::Key;
use pencil::{Pencil, Request, Response, PencilResult};
use pencil::jsonify;
use pencil::HTTPError;
use pencil::{redirect, abort};
use pencil::method::Get;
use pencil::Module;

fn hello(_: &mut Request) -> PencilResult {
    Ok(Response::from("Hello World!"))
}

fn user(r: &mut Request) -> PencilResult {
    let user_id = r.view_args.get("user_id").unwrap();
    Ok(format!("user {}", user_id).into())
}

fn app_info(_: &mut Request) -> PencilResult {
    let mut d = BTreeMap::new();
    d.insert("name", "hello");
    d.insert("version", "0.1.0");
    return jsonify(&d);
}

fn page_not_found(_: HTTPError) -> PencilResult {
    let mut response = Response::from("Customized 404 :)");
    response.status_code = 404;
    Ok(response)
}

fn hello_template(request: &mut Request) -> PencilResult {
    let mut context = BTreeMap::new();
    context.insert("name".to_string(), "template".to_string());
    return request.app.render_template("hello.html", &context);
}

struct KeyType;
struct Value(i32);
impl Key for KeyType { type Value = Value; }

fn before_request(request: &mut Request) -> Option<PencilResult> {
    request.extensions_data.insert::<KeyType>(Value(100));
    None
}

fn github(_: &mut Request) -> PencilResult {
    return redirect("https://github.com/", 302);
}

fn login(_: &mut Request) -> PencilResult {
    return abort(401);
}

fn search(request: &mut Request) -> PencilResult {
    let keyword = match request.args().get("q") {
        Some(q) => q as &str,
        None => "",
    };
    Ok(Response::from(format!("You are searching for {}", keyword)))
}

fn hi_module(_: &mut Request) -> PencilResult {
    Ok("Hi module.".into())
}

fn main() {
    let mut app = Pencil::new(env::var("HELLO_ROOT_PATH").unwrap().as_ref());
    app.set_debug(true);
    app.set_log_level();
    env_logger::init().unwrap();
    app.enable_static_file_handling();
    app.register_template("hello.html");
    app.before_request(before_request);

    app.httperrorhandler(404, page_not_found);

    app.get("/", "hello", hello);
    app.get("/user/<user_id:int>", "user", user);
    app.get("/info", "app_info", app_info);
    app.get("/hello_template", "hello_template", hello_template);
    app.get("/github", "github", github);
    app.get("/login", "login", login);
    app.get("/search", "search", search);

    let mut demo_module = Module::new("demo", "/web/hello/demo");
    demo_module.route("/demo/hi", &[Get], "hi", hi_module);
    app.register_module(demo_module);

    debug!("* Running on http://localhost:5000/");
    app.run("127.0.0.1:5000");
}
<|endoftext|>


<commit_before>#![no_main]
use libfuzzer_sys::fuzz_target;

use breakpad_symbols::fuzzing_private_exports::{eval_win_expr_for_fuzzer, StackInfoWin, WinStackThing};
use breakpad_symbols::FrameWalker;
use std::collections::HashMap;

fuzz_target!(|data: ([u32; 14], &str)| {
    test_stack_win_doc_example(data.0, data.1);
});

// Eugh, need this to memoize register names to static
static STATIC_REGS: [&str; 14] = [
    "cfa", "ra", "esp", "eip", "ebp", "eax", "ebx", "rsp", "rip", "rbp", "rax", "rbx", "x11", "x12",
];

struct TestFrameWalker<Reg> {
    instruction: Reg,
    grand_callee_param_size: u32,
    callee_regs: HashMap<&'static str, Reg>,
    caller_regs: HashMap<&'static str, Reg>,
    stack: Vec<u8>,
}

trait Int {
    const BYTES: usize;
    fn from_bytes(bytes: &[u8]) -> Self;
    fn into_u64(self) -> u64;
    fn from_u64(val: u64) -> Self;
}
impl Int for u32 {
    const BYTES: usize = 4;
    fn from_bytes(bytes: &[u8]) -> Self {
        let mut buf = [0; Self::BYTES];
        buf.copy_from_slice(bytes);
        u32::from_le_bytes(buf)
    }
    fn into_u64(self) -> u64 {
        self as u64
    }
    fn from_u64(val: u64) -> Self {
        val as u32
    }
}
impl Int for u64 {
    const BYTES: usize = 8;
    fn from_bytes(bytes: &[u8]) -> Self {
        let mut buf = [0; Self::BYTES];
        buf.copy_from_slice(bytes);
        u64::from_le_bytes(buf)
    }
    fn into_u64(self) -> u64 {
        self
    }
    fn from_u64(val: u64) -> Self {
        val
    }
}

impl<Reg: Int + Copy> FrameWalker for TestFrameWalker<Reg> {
    fn get_instruction(&self) -> u64 {
        self.instruction.into_u64()
    }
    fn get_grand_callee_parameter_size(&self) -> u32 {
        self.grand_callee_param_size
    }
    /// Get a register-sized value stored at this address.
    fn get_register_at_address(&self, address: u64) -> Option<u64> {
        let addr = address as usize;
        self.stack
            .get(addr..addr + Reg::BYTES)
            .map(|slice| Reg::from_bytes(slice).into_u64())
    }
    /// Get the value of a register from the callee's frame.
    fn get_callee_register(&self, name: &str) -> Option<u64> {
        self.callee_regs.get(name).map(|val| val.into_u64())
    }
    /// Set the value of a register for the caller's frame.
    fn set_caller_register(&mut self, name: &str, val: u64) -> Option<()> {
        STATIC_REGS.iter().position(|&reg| reg == name).map(|idx| {
            let memoized_reg = STATIC_REGS[idx];
            self.caller_regs.insert(memoized_reg, Reg::from_u64(val));
        })
    }
    fn clear_caller_register(&mut self, name: &str) {
        self.caller_regs.remove(name);
    }
    /// Set whatever registers in the caller should be set based on the cfa (e.g. rsp).
    fn set_cfa(&mut self, val: u64) -> Option<()> {
        self.caller_regs.insert("cfa", Reg::from_u64(val));
        Some(())
    }
    /// Set whatever registers in the caller should be set based on the return address (e.g. rip).
    fn set_ra(&mut self, val: u64) -> Option<()> {
        self.caller_regs.insert("ra", Reg::from_u64(val));
        Some(())
    }
}

impl<Reg: Int + Copy> TestFrameWalker<Reg> {
    fn new(stack: Vec<u8>, callee_regs: HashMap<&'static str, Reg>) -> Self {
        TestFrameWalker {
            stack,
            callee_regs,
            caller_regs: HashMap::new(),

            // Arbitrary values
            instruction: Reg::from_u64(0xF1CEFA32),
            grand_callee_param_size: 4,
        }
    }
}

/// Arbitrary default values in case needed.
fn whatever_win_info() -> StackInfoWin {
    StackInfoWin {
        address: 0xFEA4A123,
        size: 16,
        prologue_size: 4,
        epilogue_size: 8,
        parameter_size: 16,
        saved_register_size: 12,
        local_size: 24,
        max_stack_size: 64,
        program_string_or_base_pointer: WinStackThing::AllocatesBasePointer(false),
    }
}

fn test_stack_win_doc_example(regs: [u32; 14], expr: &str) {
    let input = STATIC_REGS
        .iter()
        .zip(regs)
        .map(|(&reg, val)| (reg, val))
        .collect();
    let mut stack = vec![0; 1600];

    const FINAL_EBP: u32 = 0xFA1EF2E6;
    const FINAL_EIP: u32 = 0xB3EF04CE;

    stack[16..20].copy_from_slice(&FINAL_EBP.to_le_bytes());
    stack[20..24].copy_from_slice(&FINAL_EIP.to_le_bytes());

    let mut walker = TestFrameWalker::new(stack, input);
    let info = whatever_win_info();

    eval_win_expr_for_fuzzer(expr, &info, &mut walker);
}
<commit_msg>Format CFI eval fuzzer<commit_after>#![no_main]
use libfuzzer_sys::fuzz_target;

use breakpad_symbols::fuzzing_private_exports::{
    eval_win_expr_for_fuzzer, StackInfoWin, WinStackThing,
};
use breakpad_symbols::FrameWalker;
use std::collections::HashMap;

fuzz_target!(|data: ([u32; 14], &str)| {
    test_stack_win_doc_example(data.0, data.1);
});

// Eugh, need this to memoize register names to static
static STATIC_REGS: [&str; 14] = [
    "cfa", "ra", "esp", "eip", "ebp", "eax", "ebx", "rsp", "rip", "rbp", "rax", "rbx", "x11", "x12",
];

struct TestFrameWalker<Reg> {
    instruction: Reg,
    grand_callee_param_size: u32,
    callee_regs: HashMap<&'static str, Reg>,
    caller_regs: HashMap<&'static str, Reg>,
    stack: Vec<u8>,
}

trait Int {
    const BYTES: usize;
    fn from_bytes(bytes: &[u8]) -> Self;
    fn into_u64(self) -> u64;
    fn from_u64(val: u64) -> Self;
}
impl Int for u32 {
    const BYTES: usize = 4;
    fn from_bytes(bytes: &[u8]) -> Self {
        let mut buf = [0; Self::BYTES];
        buf.copy_from_slice(bytes);
        u32::from_le_bytes(buf)
    }
    fn into_u64(self) -> u64 {
        self as u64
    }
    fn from_u64(val: u64) -> Self {
        val as u32
    }
}
impl Int for u64 {
    const BYTES: usize = 8;
    fn from_bytes(bytes: &[u8]) -> Self {
        let mut buf = [0; Self::BYTES];
        buf.copy_from_slice(bytes);
        u64::from_le_bytes(buf)
    }
    fn into_u64(self) -> u64 {
        self
    }
    fn from_u64(val: u64) -> Self {
        val
    }
}

impl<Reg: Int + Copy> FrameWalker for TestFrameWalker<Reg> {
    fn get_instruction(&self) -> u64 {
        self.instruction.into_u64()
    }
    fn get_grand_callee_parameter_size(&self) -> u32 {
        self.grand_callee_param_size
    }
    /// Get a register-sized value stored at this address.
    fn get_register_at_address(&self, address: u64) -> Option<u64> {
        let addr = address as usize;
        self.stack
            .get(addr..addr + Reg::BYTES)
            .map(|slice| Reg::from_bytes(slice).into_u64())
    }
    /// Get the value of a register from the callee's frame.
    fn get_callee_register(&self, name: &str) -> Option<u64> {
        self.callee_regs.get(name).map(|val| val.into_u64())
    }
    /// Set the value of a register for the caller's frame.
    fn set_caller_register(&mut self, name: &str, val: u64) -> Option<()> {
        STATIC_REGS.iter().position(|&reg| reg == name).map(|idx| {
            let memoized_reg = STATIC_REGS[idx];
            self.caller_regs.insert(memoized_reg, Reg::from_u64(val));
        })
    }
    fn clear_caller_register(&mut self, name: &str) {
        self.caller_regs.remove(name);
    }
    /// Set whatever registers in the caller should be set based on the cfa (e.g. rsp).
    fn set_cfa(&mut self, val: u64) -> Option<()> {
        self.caller_regs.insert("cfa", Reg::from_u64(val));
        Some(())
    }
    /// Set whatever registers in the caller should be set based on the return address (e.g. rip).
    fn set_ra(&mut self, val: u64) -> Option<()> {
        self.caller_regs.insert("ra", Reg::from_u64(val));
        Some(())
    }
}

impl<Reg: Int + Copy> TestFrameWalker<Reg> {
    fn new(stack: Vec<u8>, callee_regs: HashMap<&'static str, Reg>) -> Self {
        TestFrameWalker {
            stack,
            callee_regs,
            caller_regs: HashMap::new(),

            // Arbitrary values
            instruction: Reg::from_u64(0xF1CEFA32),
            grand_callee_param_size: 4,
        }
    }
}

/// Arbitrary default values in case needed.
fn whatever_win_info() -> StackInfoWin {
    StackInfoWin {
        address: 0xFEA4A123,
        size: 16,
        prologue_size: 4,
        epilogue_size: 8,
        parameter_size: 16,
        saved_register_size: 12,
        local_size: 24,
        max_stack_size: 64,
        program_string_or_base_pointer: WinStackThing::AllocatesBasePointer(false),
    }
}

fn test_stack_win_doc_example(regs: [u32; 14], expr: &str) {
    let input = STATIC_REGS
        .iter()
        .zip(regs)
        .map(|(&reg, val)| (reg, val))
        .collect();
    let mut stack = vec![0; 1600];

    const FINAL_EBP: u32 = 0xFA1EF2E6;
    const FINAL_EIP: u32 = 0xB3EF04CE;

    stack[16..20].copy_from_slice(&FINAL_EBP.to_le_bytes());
    stack[20..24].copy_from_slice(&FINAL_EIP.to_le_bytes());

    let mut walker = TestFrameWalker::new(stack, input);
    let info = whatever_win_info();

    eval_win_expr_for_fuzzer(expr, &info, &mut walker);
}
<|endoftext|>


<commit_before>use app_units::Au;
use display_item::{DisplayItem, SpecificDisplayItem, ImageDisplayItem};
use display_item::{RectangleDisplayItem, TextDisplayItem, GradientDisplayItem};
use display_item::{BorderDisplayItem, BoxShadowDisplayItem};
use euclid::{Point2D, Rect, Size2D};
use std::mem;
use types::{ClipRegion, ColorF, FontKey, ImageKey, PipelineId, StackingLevel};
use types::{BorderRadius, BorderSide, BoxShadowClipMode, GlyphInstance};
use types::{DisplayListMode, GradientStop, StackingContextId};

pub struct DrawListInfo {
    pub items: Vec<DisplayItem>,
}

pub struct StackingContextInfo {
    pub id: StackingContextId,
}

#[derive(Debug, Clone)]
pub struct IframeInfo {
    pub id: PipelineId,
    pub offset: Point2D<f32>,
    pub clip: Rect<f32>,
}

pub enum SpecificDisplayListItem {
    DrawList(DrawListInfo),
    StackingContext(StackingContextInfo),
    Iframe(Box<IframeInfo>),
}

pub struct DisplayListItem {
    pub stacking_level: StackingLevel,
    pub specific: SpecificDisplayListItem,
}

pub struct DisplayListBuilder {
    pub mode: DisplayListMode,
    pub has_stacking_contexts: bool,

    pub work_background_and_borders: Vec<DisplayItem>,
    pub work_block_backgrounds_and_borders: Vec<DisplayItem>,
    pub work_floats: Vec<DisplayItem>,
    pub work_content: Vec<DisplayItem>,
    pub work_positioned_content: Vec<DisplayItem>,
    pub work_outlines: Vec<DisplayItem>,

    pub items: Vec<DisplayListItem>,
}

impl DisplayListBuilder {
    pub fn new() -> DisplayListBuilder {
        DisplayListBuilder {
            mode: DisplayListMode::Default,
            has_stacking_contexts: false,

            work_background_and_borders: Vec::new(),
            work_block_backgrounds_and_borders: Vec::new(),
            work_floats: Vec::new(),
            work_content: Vec::new(),
            work_positioned_content: Vec::new(),
            work_outlines: Vec::new(),

            items: Vec::new(),
        }
    }

    pub fn push_rect(&mut self,
                     level: StackingLevel,
                     rect: Rect<f32>,
                     clip: ClipRegion,
                     color: ColorF) {
        let item = RectangleDisplayItem {
            color: color,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::Rectangle(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_image(&mut self,
                      level: StackingLevel,
                      rect: Rect<f32>,
                      clip: ClipRegion,
                      stretch_size: Size2D<f32>,
                      key: ImageKey) {
        let item = ImageDisplayItem {
            image_key: key,
            stretch_size: stretch_size,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::Image(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_text(&mut self,
                     level: StackingLevel,
                     rect: Rect<f32>,
                     clip: ClipRegion,
                     glyphs: Vec<GlyphInstance>,
                     font_key: FontKey,
                     color: ColorF,
                     size: Au,
                     blur_radius: Au) {
        let item = TextDisplayItem {
            color: color,
            glyphs: glyphs,
            font_key: font_key,
            size: size,
            blur_radius: blur_radius,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::Text(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_border(&mut self,
                       level: StackingLevel,
                       rect: Rect<f32>,
                       clip: ClipRegion,
                       left: BorderSide,
                       top: BorderSide,
                       right: BorderSide,
                       bottom: BorderSide,
                       radius: BorderRadius) {
        let item = BorderDisplayItem {
            left: left,
            top: top,
            right: right,
            bottom: bottom,
            radius: radius,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::Border(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_box_shadow(&mut self,
                           level: StackingLevel,
                           rect: Rect<f32>,
                           clip: ClipRegion,
                           box_bounds: Rect<f32>,
                           offset: Point2D<f32>,
                           color: ColorF,
                           blur_radius: f32,
                           spread_radius: f32,
                           border_radius: f32,
                           clip_mode: BoxShadowClipMode) {
        let item = BoxShadowDisplayItem {
            box_bounds: box_bounds,
            offset: offset,
            color: color,
            blur_radius: blur_radius,
            spread_radius: spread_radius,
            border_radius: border_radius,
            clip_mode: clip_mode,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::BoxShadow(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_stacking_context(&mut self,
                                 level: StackingLevel,
                                 stacking_context_id: StackingContextId) {
        self.has_stacking_contexts = true;
        self.flush_list(level);
        let info = StackingContextInfo {
            id: stacking_context_id,
        };
        let item = DisplayListItem {
            stacking_level: level,
            specific: SpecificDisplayListItem::StackingContext(info),
        };
        self.items.push(item);
    }

    pub fn push_gradient(&mut self,
                         level: StackingLevel,
                         rect: Rect<f32>,
                         clip: ClipRegion,
                         start_point: Point2D<f32>,
                         end_point: Point2D<f32>,
                         stops: Vec<GradientStop>) {
        let item = GradientDisplayItem {
            start_point: start_point,
            end_point: end_point,
            stops: stops,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::Gradient(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_iframe(&mut self,
                       level: StackingLevel,
                       rect: Rect<f32>,
                       clip: ClipRegion,
                       iframe: PipelineId) {
        self.flush_list(level);
        let info = Box::new(IframeInfo {
            id: iframe,
            offset: rect.origin,
            clip: clip.main,
        });
        let item = DisplayListItem {
            stacking_level: level,
            specific: SpecificDisplayListItem::Iframe(info),
        };
        self.items.push(item);
    }

    fn push_item(&mut self, level: StackingLevel, item: DisplayItem) {
        match level {
            StackingLevel::BackgroundAndBorders => {
                self.work_background_and_borders.push(item);
            }
            StackingLevel::BlockBackgroundAndBorders => {
                self.work_block_backgrounds_and_borders.push(item);
            }
            StackingLevel::Floats => {
                self.work_floats.push(item);
            }
            StackingLevel::Content => {
                self.work_content.push(item);
            }
            StackingLevel::PositionedContent => {
                self.work_positioned_content.push(item);
            }
            StackingLevel::Outlines => {
                self.work_outlines.push(item);
            }
        }
    }

    fn flush_list(&mut self, level: StackingLevel) {
        let list = match level {
            StackingLevel::BackgroundAndBorders => {
                &mut self.work_background_and_borders
            }
            StackingLevel::BlockBackgroundAndBorders => {
                &mut self.work_block_backgrounds_and_borders
            }
            StackingLevel::Floats => {
                &mut self.work_floats
            }
            StackingLevel::Content => {
                &mut self.work_content
            }
            StackingLevel::PositionedContent => {
                &mut self.work_positioned_content
            }
            StackingLevel::Outlines => {
                &mut self.work_outlines
            }
        };

        let items = mem::replace(list, Vec::new());
        if items.len() > 0 {
            let draw_list = DrawListInfo {
                items: items,
            };
            self.items.push(DisplayListItem {
                stacking_level: level,
                specific: SpecificDisplayListItem::DrawList(draw_list),
            });
        }
    }

    fn flush(&mut self) {
        self.flush_list(StackingLevel::BackgroundAndBorders);
        self.flush_list(StackingLevel::BlockBackgroundAndBorders);
        self.flush_list(StackingLevel::Floats);
        self.flush_list(StackingLevel::Content);
        self.flush_list(StackingLevel::PositionedContent);
        self.flush_list(StackingLevel::Outlines);
    }

    pub fn finalize(&mut self) {
        self.flush();
    }
}
<commit_msg>Fix iframe clip<commit_after>use app_units::Au;
use display_item::{DisplayItem, SpecificDisplayItem, ImageDisplayItem};
use display_item::{RectangleDisplayItem, TextDisplayItem, GradientDisplayItem};
use display_item::{BorderDisplayItem, BoxShadowDisplayItem};
use euclid::{Point2D, Rect, Size2D};
use std::mem;
use types::{ClipRegion, ColorF, FontKey, ImageKey, PipelineId, StackingLevel};
use types::{BorderRadius, BorderSide, BoxShadowClipMode, GlyphInstance};
use types::{DisplayListMode, GradientStop, StackingContextId};

pub struct DrawListInfo {
    pub items: Vec<DisplayItem>,
}

pub struct StackingContextInfo {
    pub id: StackingContextId,
}

#[derive(Debug, Clone)]
pub struct IframeInfo {
    pub id: PipelineId,
    pub offset: Point2D<f32>,
    pub clip: Rect<f32>,
}

pub enum SpecificDisplayListItem {
    DrawList(DrawListInfo),
    StackingContext(StackingContextInfo),
    Iframe(Box<IframeInfo>),
}

pub struct DisplayListItem {
    pub stacking_level: StackingLevel,
    pub specific: SpecificDisplayListItem,
}

pub struct DisplayListBuilder {
    pub mode: DisplayListMode,
    pub has_stacking_contexts: bool,

    pub work_background_and_borders: Vec<DisplayItem>,
    pub work_block_backgrounds_and_borders: Vec<DisplayItem>,
    pub work_floats: Vec<DisplayItem>,
    pub work_content: Vec<DisplayItem>,
    pub work_positioned_content: Vec<DisplayItem>,
    pub work_outlines: Vec<DisplayItem>,

    pub items: Vec<DisplayListItem>,
}

impl DisplayListBuilder {
    pub fn new() -> DisplayListBuilder {
        DisplayListBuilder {
            mode: DisplayListMode::Default,
            has_stacking_contexts: false,

            work_background_and_borders: Vec::new(),
            work_block_backgrounds_and_borders: Vec::new(),
            work_floats: Vec::new(),
            work_content: Vec::new(),
            work_positioned_content: Vec::new(),
            work_outlines: Vec::new(),

            items: Vec::new(),
        }
    }

    pub fn push_rect(&mut self,
                     level: StackingLevel,
                     rect: Rect<f32>,
                     clip: ClipRegion,
                     color: ColorF) {
        let item = RectangleDisplayItem {
            color: color,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::Rectangle(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_image(&mut self,
                      level: StackingLevel,
                      rect: Rect<f32>,
                      clip: ClipRegion,
                      stretch_size: Size2D<f32>,
                      key: ImageKey) {
        let item = ImageDisplayItem {
            image_key: key,
            stretch_size: stretch_size,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::Image(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_text(&mut self,
                     level: StackingLevel,
                     rect: Rect<f32>,
                     clip: ClipRegion,
                     glyphs: Vec<GlyphInstance>,
                     font_key: FontKey,
                     color: ColorF,
                     size: Au,
                     blur_radius: Au) {
        let item = TextDisplayItem {
            color: color,
            glyphs: glyphs,
            font_key: font_key,
            size: size,
            blur_radius: blur_radius,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::Text(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_border(&mut self,
                       level: StackingLevel,
                       rect: Rect<f32>,
                       clip: ClipRegion,
                       left: BorderSide,
                       top: BorderSide,
                       right: BorderSide,
                       bottom: BorderSide,
                       radius: BorderRadius) {
        let item = BorderDisplayItem {
            left: left,
            top: top,
            right: right,
            bottom: bottom,
            radius: radius,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::Border(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_box_shadow(&mut self,
                           level: StackingLevel,
                           rect: Rect<f32>,
                           clip: ClipRegion,
                           box_bounds: Rect<f32>,
                           offset: Point2D<f32>,
                           color: ColorF,
                           blur_radius: f32,
                           spread_radius: f32,
                           border_radius: f32,
                           clip_mode: BoxShadowClipMode) {
        let item = BoxShadowDisplayItem {
            box_bounds: box_bounds,
            offset: offset,
            color: color,
            blur_radius: blur_radius,
            spread_radius: spread_radius,
            border_radius: border_radius,
            clip_mode: clip_mode,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::BoxShadow(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_stacking_context(&mut self,
                                 level: StackingLevel,
                                 stacking_context_id: StackingContextId) {
        self.has_stacking_contexts = true;
        self.flush_list(level);
        let info = StackingContextInfo {
            id: stacking_context_id,
        };
        let item = DisplayListItem {
            stacking_level: level,
            specific: SpecificDisplayListItem::StackingContext(info),
        };
        self.items.push(item);
    }

    pub fn push_gradient(&mut self,
                         level: StackingLevel,
                         rect: Rect<f32>,
                         clip: ClipRegion,
                         start_point: Point2D<f32>,
                         end_point: Point2D<f32>,
                         stops: Vec<GradientStop>) {
        let item = GradientDisplayItem {
            start_point: start_point,
            end_point: end_point,
            stops: stops,
        };

        let display_item = DisplayItem {
            item: SpecificDisplayItem::Gradient(item),
            rect: rect,
            clip: clip,
        };

        self.push_item(level, display_item);
    }

    pub fn push_iframe(&mut self,
                       level: StackingLevel,
                       rect: Rect<f32>,
                       _clip: ClipRegion,
                       iframe: PipelineId) {
        self.flush_list(level);
        let info = Box::new(IframeInfo {
            id: iframe,
            offset: rect.origin,
            clip: rect,
        });
        let item = DisplayListItem {
            stacking_level: level,
            specific: SpecificDisplayListItem::Iframe(info),
        };
        self.items.push(item);
    }

    fn push_item(&mut self, level: StackingLevel, item: DisplayItem) {
        match level {
            StackingLevel::BackgroundAndBorders => {
                self.work_background_and_borders.push(item);
            }
            StackingLevel::BlockBackgroundAndBorders => {
                self.work_block_backgrounds_and_borders.push(item);
            }
            StackingLevel::Floats => {
                self.work_floats.push(item);
            }
            StackingLevel::Content => {
                self.work_content.push(item);
            }
            StackingLevel::PositionedContent => {
                self.work_positioned_content.push(item);
            }
            StackingLevel::Outlines => {
                self.work_outlines.push(item);
            }
        }
    }

    fn flush_list(&mut self, level: StackingLevel) {
        let list = match level {
            StackingLevel::BackgroundAndBorders => {
                &mut self.work_background_and_borders
            }
            StackingLevel::BlockBackgroundAndBorders => {
                &mut self.work_block_backgrounds_and_borders
            }
            StackingLevel::Floats => {
                &mut self.work_floats
            }
            StackingLevel::Content => {
                &mut self.work_content
            }
            StackingLevel::PositionedContent => {
                &mut self.work_positioned_content
            }
            StackingLevel::Outlines => {
                &mut self.work_outlines
            }
        };

        let items = mem::replace(list, Vec::new());
        if items.len() > 0 {
            let draw_list = DrawListInfo {
                items: items,
            };
            self.items.push(DisplayListItem {
                stacking_level: level,
                specific: SpecificDisplayListItem::DrawList(draw_list),
            });
        }
    }

    fn flush(&mut self) {
        self.flush_list(StackingLevel::BackgroundAndBorders);
        self.flush_list(StackingLevel::BlockBackgroundAndBorders);
        self.flush_list(StackingLevel::Floats);
        self.flush_list(StackingLevel::Content);
        self.flush_list(StackingLevel::PositionedContent);
        self.flush_list(StackingLevel::Outlines);
    }

    pub fn finalize(&mut self) {
        self.flush();
    }
}
<|endoftext|>


<commit_before>use ::syn::Ident;
use ::yaml_rust::Yaml;

use infer::path;
use infer::TokensResult;

pub(super) fn infer_v3(api_st: &Ident, schema: &Yaml) -> TokensResult {
    let mut tokens = quote! {
        extern crate tapioca;
        use tapioca::Schema;

        impl Schema for #api_st {
            fn get(&self) {
                //!TODO: Replace for compile_error! macro
                //! when rust-lang/rust#40872 implemented
                panic!("GET not allowed for /")
            }
        }
    };

    let paths = schema["paths"].clone();
    for (path, path_schema) in paths.as_hash().expect("Paths must be a map.") {
        let path = path.as_str().expect("Path must be a string.");
        tokens.append(path::infer_v3(&api_st, &path, &path_schema)?);
    }

    Ok(tokens)
}
<commit_msg>Remove useless compile-erroring method<commit_after>use ::syn::Ident;
use ::yaml_rust::Yaml;

use infer::path;
use infer::TokensResult;

pub(super) fn infer_v3(api_st: &Ident, schema: &Yaml) -> TokensResult {
    let mut tokens = quote! {
        extern crate tapioca;
        use tapioca::Schema;
    };

    let paths = schema["paths"].clone();
    for (path, path_schema) in paths.as_hash().expect("Paths must be a map.") {
        let path = path.as_str().expect("Path must be a string.");
        tokens.append(path::infer_v3(&api_st, &path, &path_schema)?);
    }

    Ok(tokens)
}
<|endoftext|>


<commit_before>extern crate portmidi as pm;

use std::thread::sleep_ms;

use pm::{PortMidiDeviceId, Result};
use pm::PmError::PmInvalidDeviceId;

pub mod common;

fn main() {
    // get the device number from the command line, or die()
    let device_id = match common::get_arg(1) {
        Some(id) => id,
        None => {
            common::die();
            return;
        }
    };

    // run the monitor, print an error if it returns one
    if let Err(e) = monitor(device_id) {
        println!("Error: {:?}", e);
    }
}

fn monitor(device_id: PortMidiDeviceId) -> Result<()> {
    // initialize portmidi
    try!(pm::initialize());

    // get the device and check it exists
    let device = try!(pm::DeviceInfo::new(device_id).ok_or(PmInvalidDeviceId));
    println!("Opening: {}", device.name);

    // open the input
    let mut input = pm::InputPort::new(device_id, 1024);
    try!(input.open());

    let qw = common::QuitWatcher::new();
    qw.start();

    while qw.is_running() {
        // read all the data in the buffer
        while let Some(event) = try!(input.read()) {
            // filter midi time stamps and active sensing
            if event.message.status != 248 && event.message.status != 254 {
                println!("{} {:?}", event.timestamp, event.message);
            }
        }

        // no more data? wait a little before trying again
        sleep_ms(50);
    }

    // close the input and terminate portmidi
    try!(input.close());
    pm::terminate()
}
<commit_msg>Fix `monitor_device` example<commit_after>extern crate portmidi as pm;

fn main() {
    let context = pm::PortMidi::new().unwrap();
    let info = context.default_input_device_id().and_then(|id| context.device_info(id));
    println!("{:?}", info);
    let mut in_port = context.default_input_port().unwrap();

    while let Ok(avail) = in_port.poll() {
        if let Ok(Some(event)) = in_port.read() {
            println!("{:?}", event);
        }
    }
}
<|endoftext|>


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

use cg;
use quote::Tokens;
use syn::DeriveInput;
use synstructure;

pub fn derive(input: DeriveInput) -> Tokens {
    let name = &input.ident;
    let trait_path = &["style_traits", "ToCss"];
    let (impl_generics, ty_generics, mut where_clause) =
        cg::trait_parts(&input, trait_path);

    let input_attrs = cg::parse_input_attrs::<CssInputAttrs>(&input);
    let style = synstructure::BindStyle::Ref.into();
    let match_body = synstructure::each_variant(&input, &style, |bindings, variant| {
        let mut identifier = cg::to_css_identifier(variant.ident.as_ref());
        let variant_attrs = cg::parse_variant_attrs::<CssVariantAttrs>(variant);
        let separator = if variant_attrs.comma { ", " } else { " " };

        if variant_attrs.dimension {
            assert_eq!(bindings.len(), 1);
            assert!(!variant_attrs.function, "That makes no sense");
        }

        let mut expr = if !bindings.is_empty() {
            let mut expr = quote! {};
            if variant_attrs.function && variant_attrs.iterable {
                assert_eq!(bindings.len(), 1);
                let binding = &bindings[0];
                expr = quote! {
                    #expr

                    for item in #binding.iter() {
                        writer.item(item)?;
                    }
                };
            } else {
                for binding in bindings {
                    where_clause.add_trait_bound(&binding.field.ty);
                    expr = quote! {
                        #expr
                        writer.item(#binding)?;
                    };
                }
            }

            quote! {{
                let mut writer = ::style_traits::values::SequenceWriter::new(&mut *dest, #separator);
                #expr
                Ok(())
            }}
        } else {
            quote! {
                ::std::fmt::Write::write_str(dest, #identifier)
            }
        };

        if variant_attrs.dimension {
            expr = quote! {
                #expr?;
                ::std::fmt::Write::write_str(dest, #identifier)
            }
        } else if variant_attrs.function {
            identifier.push_str("(");
            expr = quote! {
                ::std::fmt::Write::write_str(dest, #identifier)?;
                #expr?;
                ::std::fmt::Write::write_str(dest, ")")
            }
        }
        Some(expr)
    });

    let mut impls = quote! {
        impl #impl_generics ::style_traits::ToCss for #name #ty_generics #where_clause {
            #[allow(unused_variables)]
            #[inline]
            fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result
            where
                W: ::std::fmt::Write
            {
                match *self {
                    #match_body
                }
            }
        }
    };

    if input_attrs.derive_debug {
        impls.append(quote! {
            impl #impl_generics ::std::fmt::Debug for #name #ty_generics #where_clause {
                fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                    ::style_traits::ToCss::to_css(self, f)
                }
            }
        });
    }

    impls
}

#[darling(attributes(css), default)]
#[derive(Default, FromDeriveInput)]
struct CssInputAttrs {
    derive_debug: bool,
    function: bool,
    comma: bool,
}

#[darling(attributes(css), default)]
#[derive(Default, FromVariant)]
struct CssVariantAttrs {
    function: bool,
    iterable: bool,
    comma: bool,
    dimension: bool,
}
<commit_msg>style_derive: Allow css(iterable) to work on non-functions too, as long as there's only one binding.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use cg;
use quote::Tokens;
use syn::DeriveInput;
use synstructure;

pub fn derive(input: DeriveInput) -> Tokens {
    let name = &input.ident;
    let trait_path = &["style_traits", "ToCss"];
    let (impl_generics, ty_generics, mut where_clause) =
        cg::trait_parts(&input, trait_path);

    let input_attrs = cg::parse_input_attrs::<CssInputAttrs>(&input);
    let style = synstructure::BindStyle::Ref.into();
    let match_body = synstructure::each_variant(&input, &style, |bindings, variant| {
        let mut identifier = cg::to_css_identifier(variant.ident.as_ref());
        let variant_attrs = cg::parse_variant_attrs::<CssVariantAttrs>(variant);
        let separator = if variant_attrs.comma { ", " } else { " " };

        if variant_attrs.dimension {
            assert_eq!(bindings.len(), 1);
            assert!(!variant_attrs.function, "That makes no sense");
        }

        let mut expr = if !bindings.is_empty() {
            let mut expr = quote! {};
            if variant_attrs.iterable {
                assert_eq!(bindings.len(), 1);
                let binding = &bindings[0];
                expr = quote! {
                    #expr

                    for item in #binding.iter() {
                        writer.item(item)?;
                    }
                };
            } else {
                for binding in bindings {
                    where_clause.add_trait_bound(&binding.field.ty);
                    expr = quote! {
                        #expr
                        writer.item(#binding)?;
                    };
                }
            }

            quote! {{
                let mut writer = ::style_traits::values::SequenceWriter::new(&mut *dest, #separator);
                #expr
                Ok(())
            }}
        } else {
            quote! {
                ::std::fmt::Write::write_str(dest, #identifier)
            }
        };

        if variant_attrs.dimension {
            expr = quote! {
                #expr?;
                ::std::fmt::Write::write_str(dest, #identifier)
            }
        } else if variant_attrs.function {
            identifier.push_str("(");
            expr = quote! {
                ::std::fmt::Write::write_str(dest, #identifier)?;
                #expr?;
                ::std::fmt::Write::write_str(dest, ")")
            }
        }
        Some(expr)
    });

    let mut impls = quote! {
        impl #impl_generics ::style_traits::ToCss for #name #ty_generics #where_clause {
            #[allow(unused_variables)]
            #[inline]
            fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result
            where
                W: ::std::fmt::Write
            {
                match *self {
                    #match_body
                }
            }
        }
    };

    if input_attrs.derive_debug {
        impls.append(quote! {
            impl #impl_generics ::std::fmt::Debug for #name #ty_generics #where_clause {
                fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                    ::style_traits::ToCss::to_css(self, f)
                }
            }
        });
    }

    impls
}

#[darling(attributes(css), default)]
#[derive(Default, FromDeriveInput)]
struct CssInputAttrs {
    derive_debug: bool,
    function: bool,
    comma: bool,
}

#[darling(attributes(css), default)]
#[derive(Default, FromVariant)]
struct CssVariantAttrs {
    function: bool,
    iterable: bool,
    comma: bool,
    dimension: bool,
}
<|endoftext|>


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

#[cfg(not(target_os = "android"))]
use std::env;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

lazy_static! {
    static ref CMD_RESOURCE_DIR: Arc<Mutex<Option<String>>> = {
        Arc::new(Mutex::new(None))
    };
}

pub fn set_resources_path(path: Option<String>) {
    let mut dir = CMD_RESOURCE_DIR.lock().unwrap();
    *dir = path;
}

#[cfg(target_os = "android")]
pub fn resources_dir_path() -> PathBuf {
    PathBuf::from("/sdcard/servo/")
}

#[cfg(not(target_os = "android"))]
pub fn resources_dir_path() -> PathBuf {
    let mut dir = CMD_RESOURCE_DIR.lock().unwrap();

    if let Some(ref path) = *dir {
        return PathBuf::from(path);
    }

    // FIXME: Find a way to not rely on the executable being
    // under `<servo source>[/$target_triple]/target/debug`
    // or `<servo source>[/$target_triple]/target/release`.
    let mut path = env::current_exe().expect("can't get exe path");
    // Follow symlink
    path = path.canonicalize().expect("path does not exist");

    while path.pop() {
        path.push("resources");
        if path.is_dir() {
            break;
        }
        path.pop();
    }
    *dir = Some(path.to_str().unwrap().to_owned());
    path
}

pub fn read_resource_file<P: AsRef<Path>>(relative_path: P) -> io::Result<Vec<u8>> {
    let mut path = resources_dir_path();
    path.push(relative_path);
    let mut file = try!(File::open(&path));
    let mut data = Vec::new();
    try!(file.read_to_end(&mut data));
    Ok(data)
}
<commit_msg>Auto merge of #12137 - ConnorGBrewster:resources_case_sensitive, r=aneeshusa<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#[cfg(not(target_os = "android"))]
use std::env;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

lazy_static! {
    static ref CMD_RESOURCE_DIR: Arc<Mutex<Option<String>>> = {
        Arc::new(Mutex::new(None))
    };
}

pub fn set_resources_path(path: Option<String>) {
    let mut dir = CMD_RESOURCE_DIR.lock().unwrap();
    *dir = path;
}

#[cfg(target_os = "android")]
pub fn resources_dir_path() -> PathBuf {
    PathBuf::from("/sdcard/servo/")
}

#[cfg(not(target_os = "android"))]
pub fn resources_dir_path() -> PathBuf {
    let mut dir = CMD_RESOURCE_DIR.lock().unwrap();

    if let Some(ref path) = *dir {
        return PathBuf::from(path);
    }

    // FIXME: Find a way to not rely on the executable being
    // under `<servo source>[/$target_triple]/target/debug`
    // or `<servo source>[/$target_triple]/target/release`.
    let mut path = env::current_exe().expect("can't get exe path");
    // Follow symlink
    path = path.canonicalize().expect("path does not exist");

    while path.pop() {
        path.push("resources");
        if path.is_dir() {
            break;
        }
        path.pop();
        // Check for Resources on mac when using a case sensitive filesystem.
        path.push("Resources");
        if path.is_dir() {
            break;
        }
        path.pop();
    }
    *dir = Some(path.to_str().unwrap().to_owned());
    path
}

pub fn read_resource_file<P: AsRef<Path>>(relative_path: P) -> io::Result<Vec<u8>> {
    let mut path = resources_dir_path();
    path.push(relative_path);
    let mut file = try!(File::open(&path));
    let mut data = Vec::new();
    try!(file.read_to_end(&mut data));
    Ok(data)
}
<|endoftext|>


<commit_before>//! AST node definitions which will be parsed into. Based off of the
//! `graphql-js` [`ast.js`][1] definitions.
//!
//! [1]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js

/// All AST node types implement this trait.
trait Node {}

macro_rules! impl_node_for {
  ($struct:ident) => {
    impl Node for $struct {}
  }
}

/// Name :: /[_A-Za-z][_0-9A-Za-z]*/
pub struct Name {
  pub value: String
}

impl_node_for! { Name }

/// IntValue :: IntegerPart
pub struct IntValue {
  pub value: String
}

impl_node_for! { IntValue }

/// FloatValue ::
///   - IntegerPart FractionalPart
///   - IntegerPart ExponentPart
///   - IntegerPart FractionalPart ExponentPart
pub struct FloatValue {
  pub value: String
}

impl_node_for! { FloatValue }

/// StringValue ::
///   - `""`
///   - `"` StringCharacter+ `"`
pub struct StringValue {
  pub value: String
}

impl_node_for! { StringValue }

/// Document : Definition+
pub struct Document {
  pub definitions: Vec<Definition>
}

impl_node_for! { Document }

/// Definition :
///   - OperationDefinition
///   - FragmentDefinition
pub enum Definition {
  Operation(OperationDefinition),
  Fragment(FragmentDefinition)
}

/// OperationDefinition :
///   - SelectionSet
///   - OperationType Name? VariableDefinitions? Directives? SelectionSet
pub struct OperationDefinition {
  pub operation: OperationType,
  pub name: Option<Name>,
  pub variable_definitions: Option<VariableDefinitions>,
  pub directives: Option<Directives>,
  pub selection_set: SelectionSet
}

impl_node_for! { OperationDefinition }

/// OperationType : one of query mutation
pub enum OperationType {
  Query,
  Mutation
}

/// SelectionSet : { Selection+ }
pub struct SelectionSet {
  pub selections: Vec<Selection>
}

impl_node_for! { SelectionSet }

/// Selection :
///   - Field
///   - FragmentSpread
///   - InlineFragment
pub enum Selection {
  Field(Field),
  FragmentSpread(FragmentSpread),
  InlineFragment(InlineFragment)
}

/// Field : Alias? Name Arguments? Directives? SelectionSet?
pub struct Field {
  pub alias: Option<Alias>,
  pub name: Name,
  pub arguments: Option<Arguments>,
  pub directives: Option<Directives>,
  pub selection_set: Option<SelectionSet>
}

impl_node_for! { Field }

/// Alias : Name :
pub type Alias = Name;

/// Arguments : ( Argument+ )
pub type Arguments = Vec<Argument>;

/// Argument : Name : Value
pub struct Argument {
  pub name: Name,
  pub value: Value
}

impl_node_for! { Argument }

/// FragmentSpread : ... FragmentName Directives?
pub struct FragmentSpread {
  pub name: Name,
  pub directives: Option<Directives>
}

impl_node_for! { FragmentSpread }

/// InlineFragment : ... TypeCondition? Directives? SelectionSet
pub struct InlineFragment {
  pub type_condition: Option<TypeCondition>,
  pub directives: Option<Directives>,
  pub selection_set: SelectionSet
}

impl_node_for! { InlineFragment }

/// FragmentDefinition : fragment FragmentName TypeCondition Directives? SelectionSet
pub struct FragmentDefinition {
  pub name: Name,
  pub type_condition: TypeCondition,
  pub directives: Option<Directives>,
  pub selection_set: SelectionSet
}

impl_node_for! { FragmentDefinition }

/// FragmentName : Name but not `on`
pub type FragmentName = Name;

/// TypeCondition : on NamedType
pub type TypeCondition = NamedType;

/// Value[Const] :
///   - [~Const] Variable
///   - IntValue
///   - FloatValue
///   - StringValue
///   - BooleanValue
///   - EnumValue
///   - ListValue[?Const]
///   - ObjectValue[?Const]
pub enum Value {
  Variable(Variable),
  Int(IntValue),
  Float(FloatValue),
  String(StringValue),
  Boolean(BooleanValue),
  Enum(EnumValue),
  List(ListValue),
  Object(ObjectValue)
}

/// BooleanValue : one of `true` `false`
pub enum BooleanValue {
  True,
  False
}

impl_node_for! { BooleanValue }

/// EnumValue : Name but not `true`, `false` or `null`
pub struct EnumValue {
  pub name: Name
}

impl_node_for! { EnumValue }

/// ListValue[Const] :
///   - [ ]
///   - [ Value[?Const]+ ]
pub struct ListValue {
  pub values: Vec<Value>
}

impl_node_for! { ListValue }

/// ObjectValue[Const] :
///   - { }
///   - { ObjectField[?Const]+ }
pub struct ObjectValue {
  pub fields: Vec<ObjectField>
}

impl_node_for! { ObjectValue }

/// ObjectField[Const] : Name : Value[?Const]
pub struct ObjectField {
  pub name: Name,
  pub value: Value
}

impl_node_for! { ObjectField }

/// VariableDefinitions : ( VariableDefinition+ )
pub type VariableDefinitions = Vec<VariableDefinition>;

/// VariableDefinition : Variable : Type DefaultValue?
pub struct VariableDefinition {
  pub variable: Variable,
  pub type_: Type,
  pub default_value: Option<DefaultValue>
}

impl_node_for! { VariableDefinition }

/// Variable : $ Name
pub struct Variable {
  pub name: Name
}

impl_node_for! { Variable }

/// DefaultValue : = Value[Const]
pub type DefaultValue = Value;

/// Type :
///   - NamedType
///   - ListType
///   - NonNullType
pub enum Type {
  Named(NamedType),
  List(ListType),
  NonNullNamed(NonNullNamedType),
  NonNullList(NonNullListType)
}

/// NamedType : Name
pub struct NamedType {
  pub name: Name
}

impl_node_for! { NamedType }

/// ListType : [ Type ]
pub struct ListType {
  pub type_: Type
}

impl_node_for! { ListType }

/// NonNullType :
///   - NamedType !
///   - ListType !
///
/// Are implementation deviates from the spec here. This is because
/// `NonNullType` is expected to be a [node][1], but it is also expected to be
/// a [union][2]. The best way to express this in Rust is with two types.
///
/// [1]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js#L49
/// [2]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js#L254
pub struct NonNullNamedType {
  pub type_: NamedType
}

impl_node_for! { NonNullNamedType }

/// See documentation for the `NonNullNamedType` struct.
pub struct NonNullListType {
  pub type_: ListType
}

impl_node_for! { NonNullListType }

/// Directives : Directive+
pub type Directives = Vec<Directive>;

/// Directive : @ Name Arguments?
pub struct Directive {
  pub name: Name,
  pub arguments: Option<Arguments>
}

impl_node_for! { Directive }
<commit_msg>feat(ast): add location storage<commit_after>//! AST node definitions which will be parsed into. Based off of the
//! `graphql-js` [`ast.js`][1] definitions.
//!
//! [1]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js

use source::Source;

/// Contains some character offsets that identify where the source of the AST
/// is from.
pub struct Location<'a> {
  pub start: usize,
  pub end: usize,
  pub source: Option<&'a Source<'a>>
}

/// All AST node types implement this trait.
pub trait Node<'a> {
  fn location(&self) -> Option<Location<'a>>;
}

macro_rules! impl_node_for {
  ($data:ident) => {
    impl<'a> Node<'a> for $data<'a> {
      fn location(&self) -> Option<Location<'a>> {
        self.loc
      }
    }
  }
}

/// Name :: /[_A-Za-z][_0-9A-Za-z]*/
pub struct Name<'a> {
  pub loc: Option<Location<'a>>,
  pub value: String
}

impl_node_for! { Name }

/// IntValue :: IntegerPart
pub struct IntValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: String
}

impl_node_for! { IntValue }

/// FloatValue ::
///   - IntegerPart FractionalPart
///   - IntegerPart ExponentPart
///   - IntegerPart FractionalPart ExponentPart
pub struct FloatValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: String
}

impl_node_for! { FloatValue }

/// StringValue ::
///   - `""`
///   - `"` StringCharacter+ `"`
pub struct StringValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: String
}

impl_node_for! { StringValue }

/// Document : Definition+
pub struct Document<'a> {
  pub loc: Option<Location<'a>>,
  pub definitions: Vec<Definition<'a>>
}

impl_node_for! { Document }

/// Definition :
///   - OperationDefinition
///   - FragmentDefinition
pub enum Definition<'a> {
  Operation(OperationDefinition<'a>),
  Fragment(FragmentDefinition<'a>)
}

/// OperationDefinition :
///   - SelectionSet
///   - OperationType Name? VariableDefinitions? Directives? SelectionSet
pub struct OperationDefinition<'a> {
  pub loc: Option<Location<'a>>,
  pub operation: OperationType,
  pub name: Option<Name<'a>>,
  pub variable_definitions: Option<VariableDefinitions<'a>>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: SelectionSet<'a>
}

impl_node_for! { OperationDefinition }

/// OperationType : one of query mutation
pub enum OperationType {
  Query,
  Mutation
}

/// SelectionSet : { Selection+ }
pub struct SelectionSet<'a> {
  pub loc: Option<Location<'a>>,
  pub selections: Vec<Selection<'a>>
}

impl_node_for! { SelectionSet }

/// Selection :
///   - Field
///   - FragmentSpread
///   - InlineFragment
pub enum Selection<'a> {
  Field(Field<'a>),
  FragmentSpread(FragmentSpread<'a>),
  InlineFragment(InlineFragment<'a>)
}

/// Field : Alias? Name Arguments? Directives? SelectionSet?
pub struct Field<'a> {
  pub loc: Option<Location<'a>>,
  pub alias: Option<Alias<'a>>,
  pub name: Name<'a>,
  pub arguments: Option<Arguments<'a>>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: Option<SelectionSet<'a>>
}

impl_node_for! { Field }

/// Alias : Name :
pub type Alias<'a> = Name<'a>;

/// Arguments : ( Argument+ )
pub type Arguments<'a> = Vec<Argument<'a>>;

/// Argument : Name : Value
pub struct Argument<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub value: Value<'a>
}

impl_node_for! { Argument }

/// FragmentSpread : ... FragmentName Directives?
pub struct FragmentSpread<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub directives: Option<Directives<'a>>
}

impl_node_for! { FragmentSpread }

/// InlineFragment : ... TypeCondition? Directives? SelectionSet
pub struct InlineFragment<'a> {
  pub loc: Option<Location<'a>>,
  pub type_condition: Option<TypeCondition<'a>>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: SelectionSet<'a>
}

impl_node_for! { InlineFragment }

/// FragmentDefinition : fragment FragmentName TypeCondition Directives? SelectionSet
pub struct FragmentDefinition<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub type_condition: TypeCondition<'a>,
  pub directives: Option<Directives<'a>>,
  pub selection_set: SelectionSet<'a>
}

impl_node_for! { FragmentDefinition }

/// FragmentName : Name but not `on`
pub type FragmentName<'a> = Name<'a>;

/// TypeCondition : on NamedType
pub type TypeCondition<'a> = NamedType<'a>;

/// Value[Const] :
///   - [~Const] Variable
///   - IntValue
///   - FloatValue
///   - StringValue
///   - BooleanValue
///   - EnumValue
///   - ListValue[?Const]
///   - ObjectValue[?Const]
pub enum Value<'a> {
  Variable(Variable<'a>),
  Int(IntValue<'a>),
  Float(FloatValue<'a>),
  String(StringValue<'a>),
  Boolean(BooleanValue<'a>),
  Enum(EnumValue<'a>),
  List(ListValue<'a>),
  Object(ObjectValue<'a>)
}

/// BooleanValue : one of `true` `false`
pub struct BooleanValue<'a> {
  pub loc: Option<Location<'a>>,
  pub value: bool
}

impl_node_for! { BooleanValue }

/// EnumValue : Name but not `true`, `false` or `null`
pub struct EnumValue<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>
}

impl_node_for! { EnumValue }

/// ListValue[Const] :
///   - [ ]
///   - [ Value[?Const]+ ]
pub struct ListValue<'a> {
  pub loc: Option<Location<'a>>,
  pub values: Vec<Value<'a>>
}

impl_node_for! { ListValue }

/// ObjectValue[Const] :
///   - { }
///   - { ObjectField[?Const]+ }
pub struct ObjectValue<'a> {
  pub loc: Option<Location<'a>>,
  pub fields: Vec<ObjectField<'a>>
}

impl_node_for! { ObjectValue }

/// ObjectField[Const] : Name : Value[?Const]
pub struct ObjectField<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub value: Value<'a>
}

impl_node_for! { ObjectField }

/// VariableDefinitions : ( VariableDefinition+ )
pub type VariableDefinitions<'a> = Vec<VariableDefinition<'a>>;

/// VariableDefinition : Variable : Type DefaultValue?
pub struct VariableDefinition<'a> {
  pub loc: Option<Location<'a>>,
  pub variable: Variable<'a>,
  pub type_: Type<'a>,
  pub default_value: Option<DefaultValue<'a>>
}

impl_node_for! { VariableDefinition }

/// Variable : $ Name
pub struct Variable<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>
}

impl_node_for! { Variable }

/// DefaultValue : = Value[Const]
pub type DefaultValue<'a> = Value<'a>;

/// Type :
///   - NamedType
///   - ListType
///   - NonNullType
pub enum Type<'a> {
  Named(NamedType<'a>),
  List(Box<ListType<'a>>),
  NonNullNamed(Box<NonNullNamedType<'a>>),
  NonNullList(Box<NonNullListType<'a>>)
}

/// NamedType : Name
pub struct NamedType<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>
}

impl_node_for! { NamedType }

/// ListType : [ Type ]
pub struct ListType<'a> {
  pub loc: Option<Location<'a>>,
  pub type_: Type<'a>
}

impl_node_for! { ListType }

/// NonNullType :
///   - NamedType !
///   - ListType !
///
/// Are implementation deviates from the spec here. This is because
/// `NonNullType` is expected to be a [node][1], but it is also expected to be
/// a [union][2]. The best way to express this in Rust is with two types.
///
/// [1]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js#L49
/// [2]: https://github.com/graphql/graphql-js/blob/dfe676c3011efe9560b9fa0fcbd2b7bd87476d02/src/language/ast.js#L254
pub struct NonNullNamedType<'a> {
  pub loc: Option<Location<'a>>,
  pub type_: NamedType<'a>
}

impl_node_for! { NonNullNamedType }

/// See documentation for the `NonNullNamedType` struct.
pub struct NonNullListType<'a> {
  pub loc: Option<Location<'a>>,
  pub type_: ListType<'a>
}

impl_node_for! { NonNullListType }

/// Directives : Directive+
pub type Directives<'a> = Vec<Directive<'a>>;

/// Directive : @ Name Arguments?
pub struct Directive<'a> {
  pub loc: Option<Location<'a>>,
  pub name: Name<'a>,
  pub arguments: Option<Arguments<'a>>
}

impl_node_for! { Directive }
<|endoftext|>


<commit_before>//use nannou::prelude::*;
use nannou::color::pixel::Srgb;
use nannou::color::Mix;
use nannou::color::Rgb;
use nannou::color::Hsv;

pub struct Palette {
    pub colors: Vec<Rgb>,
    pub len: usize,
}

impl Palette {
    pub fn new() -> Self {
        //anime sky
        let colors: [u32; 49] = [0xFF15283D,0xFF0F1925,0xFF203D59,0xFF2E2A33,0xFF3B4259,0xFF487EB3,0xFF4F537E,0xFF325C83,0xFF5A5366,0xFF5696C3,0xFF2D3A68,0xFF71729D,0xFF4C344D,0xFF6B5457,0xFF785272,0xFF7B697E,0xFF472429,0xFF43649F,0xFF682D44,0xFF61AEE9,0xFF9387AA,0xFF9D4A60,0xFF822E37,0xFFB98377,0xFF87A0D1,0xFFAA6E81,0xFFC5737A,0xFFB69EB0,0xFF8D5658,0xFF907070,0xFFD69D9E,0xFFF5BC9F,0xFFB87BA0,0xFFFFFCE1,0xFFFCDCC5,0xFF73D3F6,0xFFE287A3,0xFFDA4945,0xFFF19888,0xFFFDD89E,0xFFEAC2BE,0xFFFEF3C6,0xFFD89A76,0xFFD8616A,0xFFF6B873,0xFFB4594E,0xFFF17F63,0xFFE0E1EA,0xFFA4A9A5];
        let colorsv = colors.to_vec();

        //do the conversion myself
        let mut colsrgb : Vec<Rgb> = colorsv.into_iter().map(|c| {
            let blue: u8 = (c & 0xFF) as u8;
            let green: u8 = (( c >> 8 ) & 0xFF) as u8;
            let red: u8 = (( c >> 16 ) & 0xFF) as u8;
            let c = Srgb::new_u8(red, green,blue);
            c.into()
        }).collect();

        //sort on sat/value/hue
        colsrgb.sort_unstable_by(|&a, &b| {
            let ahsv:Hsv = a.into();
            let bhsv:Hsv = b.into();
            //colors are rgb
            //convert to hsv
            let ahue = ahsv.hue.to_positive_radians();
            let bhue = bhsv.hue.to_positive_radians();
            ahue.partial_cmp(&bhue).unwrap()
        });

        let len = colors.len();
        Palette {colors : colsrgb, len: len}
    }

    pub fn somecolor_mod(&self, index:usize) -> Rgb {
        self.colors[index % self.colors.len()]
    }
    pub fn somecolor_frac(&self, mut frac:f32) -> Rgb {
        while frac < 0.0 {
            frac += 1.0;
        }
        while frac >= 1.0 {
            frac -= 1.0;
        }

        let index = (frac*self.colors.len() as f32 ) as usize;
        self.colors[index]
    }
    pub fn somecolor_frac_interpol(&self, mut frac:f32) -> Rgb {
        while frac < 0.0 { frac += 1.0; }
        while frac >= 1.0 { frac -= 1.0; }
        let index = (frac*(self.colors.len()) as f32 ).floor() as usize;
        let mut index2 = index+1;
        if index2 > self.colors.len()-1 {
            index2 = 0
        }
        let frac_remainder = (frac*(self.colors.len()) as f32)-(index as f32);
        let a = self.colors[index];
        let b = self.colors[index2];
        a.mix(&b,frac_remainder)
    }
}
<commit_msg>added name again<commit_after>// Colors tools
// Alexis Andre (@mactuitui)

use nannou::color::pixel::Srgb;
use nannou::color::Mix;
use nannou::color::Rgb;
use nannou::color::Hsv;

pub struct Palette {
    pub colors: Vec<Rgb>,
    pub len: usize,
}

impl Palette {
    pub fn new() -> Self {
        //anime sky
        let colors: [u32; 49] = [0xFF15283D,0xFF0F1925,0xFF203D59,0xFF2E2A33,0xFF3B4259,0xFF487EB3,0xFF4F537E,0xFF325C83,0xFF5A5366,0xFF5696C3,0xFF2D3A68,0xFF71729D,0xFF4C344D,0xFF6B5457,0xFF785272,0xFF7B697E,0xFF472429,0xFF43649F,0xFF682D44,0xFF61AEE9,0xFF9387AA,0xFF9D4A60,0xFF822E37,0xFFB98377,0xFF87A0D1,0xFFAA6E81,0xFFC5737A,0xFFB69EB0,0xFF8D5658,0xFF907070,0xFFD69D9E,0xFFF5BC9F,0xFFB87BA0,0xFFFFFCE1,0xFFFCDCC5,0xFF73D3F6,0xFFE287A3,0xFFDA4945,0xFFF19888,0xFFFDD89E,0xFFEAC2BE,0xFFFEF3C6,0xFFD89A76,0xFFD8616A,0xFFF6B873,0xFFB4594E,0xFFF17F63,0xFFE0E1EA,0xFFA4A9A5];
        let colorsv = colors.to_vec();

        //do the conversion myself
        let mut colsrgb : Vec<Rgb> = colorsv.into_iter().map(|c| {
            let blue: u8 = (c & 0xFF) as u8;
            let green: u8 = (( c >> 8 ) & 0xFF) as u8;
            let red: u8 = (( c >> 16 ) & 0xFF) as u8;
            let c = Srgb::new_u8(red, green,blue);
            c.into()
        }).collect();

        //sort on sat/value/hue
        colsrgb.sort_unstable_by(|&a, &b| {
            let ahsv:Hsv = a.into();
            let bhsv:Hsv = b.into();
            //colors are rgb
            //convert to hsv
            let ahue = ahsv.hue.to_positive_radians();
            let bhue = bhsv.hue.to_positive_radians();
            ahue.partial_cmp(&bhue).unwrap()
        });

        let len = colors.len();
        Palette {colors : colsrgb, len: len}
    }

    pub fn somecolor_mod(&self, index:usize) -> Rgb {
        self.colors[index % self.colors.len()]
    }
    pub fn somecolor_frac(&self, mut frac:f32) -> Rgb {
        while frac < 0.0 {
            frac += 1.0;
        }
        while frac >= 1.0 {
            frac -= 1.0;
        }

        let index = (frac*self.colors.len() as f32 ) as usize;
        self.colors[index]
    }
    pub fn somecolor_frac_interpol(&self, mut frac:f32) -> Rgb {
        while frac < 0.0 { frac += 1.0; }
        while frac >= 1.0 { frac -= 1.0; }
        let index = (frac*(self.colors.len()) as f32 ).floor() as usize;
        let mut index2 = index+1;
        if index2 > self.colors.len()-1 {
            index2 = 0
        }
        let frac_remainder = (frac*(self.colors.len()) as f32)-(index as f32);
        let a = self.colors[index];
        let b = self.colors[index2];
        a.mix(&b,frac_remainder)
    }
}
<|endoftext|>


<commit_before>#![deny(warnings)]
extern crate coreutils;
extern crate extra;

use std::env;
use std::fs::File;
use std::io::{stderr, stdout, Read, Write};
use std::time::Instant;
use std::process::exit;
use coreutils::{ArgParser, to_human_readable_string};
use extra::option::OptionalExt;
use extra::io::fail;

const MAN_PAGE: &'static str = /* @MANSTART{du} */ r#"
NAME
    dd - copy a file

SYNOPSIS
    dd [ -h | --help ] if=[FILE] of=[FILE]

DESCRIPTION
    The dd tool copies from a file to another file in 512-byte block sizes

OPTIONS
    -h
    --help
        display this help and exit

    bs=n
        set input and output block size to n bytes
    count=n
        copy only n blocks
    if=file
        read from file instead of standard input
    of=file
        write output to file instead of standard out

"#; /* @MANEND */

fn main() {
    let stdout = stdout();
    let mut stdout = stdout.lock();
    let mut stderr = stderr();

    let mut parser = ArgParser::new(5)
        .add_flag(&["h", "help"])
        .add_setting_default("bs", "512")
        .add_setting_default("count", "-1")
        .add_setting("if")
        .add_setting("of");
    parser.parse(env::args());

    if parser.found("help") {
        stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr);
        stdout.flush().try(&mut stderr);
        exit(0);
    } else if !parser.found("if") {
        fail("missing if argument", &mut stderr);
    } else if !parser.found("of") {
        fail("missing of argument", &mut stderr);
    }

    let bs: usize = parser.get_setting("bs").unwrap().parse::<usize>().unwrap();
    let count = parser.get_setting("count").unwrap().parse::<i32>().unwrap();

    let in_path: String = parser.get_setting("if").unwrap();
    let out_path = parser.get_setting("of").unwrap();
    let status = 1;

    let mut input = File::open(in_path).expect("dd: failed to open if");
    let mut output = File::create(out_path).expect("dd: failed to open of");

    let mut in_recs = 0;
    let mut in_extra = 0;
    let mut out_recs = 0;
    let mut out_extra = 0;
    let mut out_total = 0;
    let mut running = true;
    let mut buffer = vec![0; bs];
    let mut last_print = 0;
    let mut last_print_out = 0;
    let start = Instant::now();
    while running {
        let in_count = input.read(&mut buffer).expect("dd: failed to read if");
        if in_count < bs {
            if in_count > 0 {
                in_extra += 1;
            }
            running = false;
        } else {
            in_recs += 1;
            if count != -1 {
                if in_recs >= count {
                    running = false;
                }
            }
        }

        let out_count = output.write(&buffer[.. in_count]).expect("dd: failed to write of");
        if out_count < bs {
            if out_count > 0 {
                out_extra += 1;
            }
            running = false;
        } else {
            out_recs += 1;
        }

        out_total += out_count as u64;

        if status >= 2 {
            let elapsed = start.elapsed().as_secs();
            if elapsed > last_print {
                let _ = write!(stderr, "\r\x1B[K{} bytes ({}B) copied, {} s, {}B/s", out_total, to_human_readable_string(out_total), elapsed, to_human_readable_string(out_total - last_print_out));
                let _ = stderr.flush();
                last_print = elapsed;
                last_print_out = out_total;
            }
        }
    }

    if status >= 1 {
        let elapsed_duration = start.elapsed();
        let elapsed = elapsed_duration.as_secs() as f64 + (elapsed_duration.subsec_nanos() as f64)/1000000000.0;

        if status >= 2 && last_print > 0 {
            let _ = writeln!(stderr, "");
        }

        let _ = writeln!(stderr, "{}+{} records in", in_recs, in_extra);
        let _ = writeln!(stderr, "{}+{} records out", out_recs, out_extra);
        let _ = writeln!(stderr, "{} bytes ({}B) copied, {} s, {}B/s", out_total, to_human_readable_string(out_total), elapsed, to_human_readable_string((out_total as f64/elapsed) as u64));
    }
}
<commit_msg>Add support for stdin and stdout for dd<commit_after>#![deny(warnings)]
extern crate coreutils;
extern crate extra;

use std::env;
use std::fs::File;
use std::io::{self, stderr, stdin, stdout, Read, Write};
use std::time::Instant;
use std::process::exit;
use coreutils::{ArgParser, to_human_readable_string};
use extra::option::OptionalExt;

const MAN_PAGE: &'static str = /* @MANSTART{du} */ r#"
NAME
    dd - copy a file

SYNOPSIS
    dd [ -h | --help ] if=[FILE] of=[FILE]

DESCRIPTION
    The dd tool copies from a file to another file in 512-byte block sizes

OPTIONS
    -h
    --help
        display this help and exit

    bs=n
        set input and output block size to n bytes
    count=n
        copy only n blocks
    if=file
        read from file instead of standard input
    of=file
        write output to file instead of standard out

"#; /* @MANEND */

enum Input<'a> {
    File(File),
    Standard(io::StdinLock<'a>)
}

impl<'a> io::Read for Input<'a> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match *self {
            Input::File(ref mut f) => f.read(buf),
            Input::Standard(ref mut s) => s.read(buf),
        }
    }
}

enum Output<'a> {
    File(File),
    Standard(io::StdoutLock<'a>)
}

impl<'a> io::Write for Output<'a> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match *self {
            Output::File(ref mut f) => f.write(buf),
            Output::Standard(ref mut s) => s.write(buf),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match *self {
            Output::File(ref mut f) => f.flush(),
            Output::Standard(ref mut s) => s.flush(),
        }
    }
}

fn main() {
    let stdin = stdin();
    let stdin = stdin.lock();
    let stdout = stdout();
    let mut stdout = stdout.lock();
    let mut stderr = stderr();

    let mut parser = ArgParser::new(5)
        .add_flag(&["h", "help"])
        .add_setting_default("bs", "512")
        .add_setting_default("count", "-1")
        .add_setting("if")
        .add_setting("of");
    parser.parse(env::args());

    if parser.found("help") {
        stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr);
        stdout.flush().try(&mut stderr);
        exit(0);
    }

    let bs: usize = parser.get_setting("bs").unwrap().parse::<usize>().unwrap();
    let count = parser.get_setting("count").unwrap().parse::<i32>().unwrap();

    let mut input = match parser.found("if") {
        true => {
            let path = parser.get_setting("if").unwrap();
            Input::File(File::open(path).expect("dd: failed to open if"))
        },
        false => Input::Standard(stdin)
    };

    let mut output = match parser.found("of") {
        true => {
            let path = parser.get_setting("of").unwrap();
            Output::File(File::create(path).expect("dd: failed to open of"))
        },
        false => Output::Standard(stdout)
    };

    let status = 1;
    let mut in_recs = 0;
    let mut in_extra = 0;
    let mut out_recs = 0;
    let mut out_extra = 0;
    let mut out_total = 0;
    let mut running = true;
    let mut buffer = vec![0; bs];
    let mut last_print = 0;
    let mut last_print_out = 0;
    let start = Instant::now();
    while running {
        let in_count = input.read(&mut buffer).expect("dd: failed to read if");
        if in_count < bs {
            if in_count > 0 {
                in_extra += 1;
            }
            running = false;
        } else {
            in_recs += 1;
            if count != -1 {
                if in_recs >= count {
                    running = false;
                }
            }
        }

        let out_count = output.write(&buffer[.. in_count]).expect("dd: failed to write of");
        if out_count < bs {
            if out_count > 0 {
                out_extra += 1;
            }
            running = false;
        } else {
            out_recs += 1;
        }

        out_total += out_count as u64;

        if status >= 2 {
            let elapsed = start.elapsed().as_secs();
            if elapsed > last_print {
                let _ = write!(stderr, "\r\x1B[K{} bytes ({}B) copied, {} s, {}B/s", out_total, to_human_readable_string(out_total), elapsed, to_human_readable_string(out_total - last_print_out));
                let _ = stderr.flush();
                last_print = elapsed;
                last_print_out = out_total;
            }
        }
    }

    if status >= 1 {
        let elapsed_duration = start.elapsed();
        let elapsed = elapsed_duration.as_secs() as f64 + (elapsed_duration.subsec_nanos() as f64)/1000000000.0;

        if status >= 2 && last_print > 0 {
            let _ = writeln!(stderr, "");
        }

        let _ = writeln!(stderr, "{}+{} records in", in_recs, in_extra);
        let _ = writeln!(stderr, "{}+{} records out", out_recs, out_extra);
        let _ = writeln!(stderr, "{} bytes ({}B) copied, {} s, {}B/s", out_total, to_human_readable_string(out_total), elapsed, to_human_readable_string((out_total as f64/elapsed) as u64));
    }
}
<|endoftext|>