<commit_before>use std::collections::{BTreeSet, HashMap, HashSet};
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;

use semver::Version;

use super::BuildContext;
use crate::core::{Edition, InternedString, Package, PackageId, Target};
use crate::util::{self, join_paths, process, CargoResult, CfgExpr, Config, ProcessBuilder};

pub struct Doctest {
    /// The package being doc-tested.
    pub package: Package,
    /// The target being tested (currently always the package's lib).
    pub target: Target,
    /// Extern dependencies needed by `rustdoc`. The path is the location of
    /// the compiled lib.
    pub deps: Vec<(InternedString, PathBuf)>,
}

/// A structure returning the result of a compilation.
pub struct Compilation<'cfg> {
    /// An array of all tests created during this compilation.
    /// `(package, target, path_to_test_exe)`
    pub tests: Vec<(Package, Target, PathBuf)>,

    /// An array of all binaries created.
    pub binaries: Vec<PathBuf>,

    /// All directories for the output of native build commands.
    ///
    /// This is currently used to drive some entries which are added to the
    /// LD_LIBRARY_PATH as appropriate.
    ///
    /// The order should be deterministic.
    pub native_dirs: BTreeSet<PathBuf>,

    /// Root output directory (for the local package's artifacts)
    pub root_output: PathBuf,

    /// Output directory for rust dependencies.
    /// May be for the host or for a specific target.
    pub deps_output: PathBuf,

    /// Output directory for the rust host dependencies.
    pub host_deps_output: PathBuf,

    /// The path to rustc's own libstd
    pub host_dylib_path: PathBuf,

    /// The path to libstd for the target
    pub target_dylib_path: PathBuf,

    /// Extra environment variables that were passed to compilations and should
    /// be passed to future invocations of programs.
    pub extra_env: HashMap<PackageId, Vec<(String, String)>>,

    /// Libraries to test with rustdoc.
    pub to_doc_test: Vec<Doctest>,

    /// Features per package enabled during this compilation.
    pub cfgs: HashMap<PackageId, HashSet<String>>,

    /// Flags to pass to rustdoc when invoked from cargo test, per package.
    pub rustdocflags: HashMap<PackageId, Vec<String>>,

    pub host: String,
    pub target: String,

    config: &'cfg Config,
    rustc_process: ProcessBuilder,
    primary_unit_rustc_process: Option<ProcessBuilder>,

    target_runner: Option<(PathBuf, Vec<String>)>,
}

impl<'cfg> Compilation<'cfg> {
    pub fn new<'a>(bcx: &BuildContext<'a, 'cfg>) -> CargoResult<Compilation<'cfg>> {
        let mut rustc = bcx.rustc.process();

        let mut primary_unit_rustc_process = bcx.build_config.primary_unit_rustc.clone();

        if bcx.config.extra_verbose() {
            rustc.display_env_vars();

            if let Some(rustc) = primary_unit_rustc_process.as_mut() {
                rustc.display_env_vars();
            }
        }

        Ok(Compilation {
            // TODO: deprecated; remove.
            native_dirs: BTreeSet::new(),
            root_output: PathBuf::from("/"),
            deps_output: PathBuf::from("/"),
            host_deps_output: PathBuf::from("/"),
            host_dylib_path: bcx.host_info.sysroot_libdir.clone(),
            target_dylib_path: bcx.target_info.sysroot_libdir.clone(),
            tests: Vec::new(),
            binaries: Vec::new(),
            extra_env: HashMap::new(),
            to_doc_test: Vec::new(),
            cfgs: HashMap::new(),
            rustdocflags: HashMap::new(),
            config: bcx.config,
            rustc_process: rustc,
            primary_unit_rustc_process,
            host: bcx.host_triple().to_string(),
            target: bcx.target_triple().to_string(),
            target_runner: target_runner(bcx)?,
        })
    }

    /// See `process`.
    pub fn rustc_process(
        &self,
        pkg: &Package,
        target: &Target,
        is_primary: bool,
    ) -> CargoResult<ProcessBuilder> {
        let rustc = if is_primary {
            self.primary_unit_rustc_process
                .clone()
                .unwrap_or_else(|| self.rustc_process.clone())
        } else {
            self.rustc_process.clone()
        };

        let mut p = self.fill_env(rustc, pkg, true)?;
        if target.edition() != Edition::Edition2015 {
            p.arg(format!("--edition={}", target.edition()));
        }
        Ok(p)
    }

    /// See `process`.
    pub fn rustdoc_process(&self, pkg: &Package, target: &Target) -> CargoResult<ProcessBuilder> {
        let mut p = self.fill_env(process(&*self.config.rustdoc()?), pkg, false)?;
        if target.edition() != Edition::Edition2015 {
            p.arg(format!("--edition={}", target.edition()));
        }
        Ok(p)
    }

    /// See `process`.
    pub fn host_process<T: AsRef<OsStr>>(
        &self,
        cmd: T,
        pkg: &Package,
    ) -> CargoResult<ProcessBuilder> {
        self.fill_env(process(cmd), pkg, true)
    }

    fn target_runner(&self) -> &Option<(PathBuf, Vec<String>)> {
        &self.target_runner
    }

    /// See `process`.
    pub fn target_process<T: AsRef<OsStr>>(
        &self,
        cmd: T,
        pkg: &Package,
    ) -> CargoResult<ProcessBuilder> {
        let builder = if let Some((ref runner, ref args)) = *self.target_runner() {
            let mut builder = process(runner);
            builder.args(args);
            builder.arg(cmd);
            builder
        } else {
            process(cmd)
        };
        self.fill_env(builder, pkg, false)
    }

    /// Prepares a new process with an appropriate environment to run against
    /// the artifacts produced by the build process.
    ///
    /// The package argument is also used to configure environment variables as
    /// well as the working directory of the child process.
    fn fill_env(
        &self,
        mut cmd: ProcessBuilder,
        pkg: &Package,
        is_host: bool,
    ) -> CargoResult<ProcessBuilder> {
        let mut search_path = if is_host {
            let mut search_path = vec![self.host_deps_output.clone()];
            search_path.push(self.host_dylib_path.clone());
            search_path
        } else {
            let mut search_path =
                super::filter_dynamic_search_path(self.native_dirs.iter(), &self.root_output);
            search_path.push(self.deps_output.clone());
            search_path.push(self.root_output.clone());
            search_path.push(self.target_dylib_path.clone());
            search_path
        };

        let dylib_path = util::dylib_path();
        let dylib_path_is_empty = dylib_path.is_empty();
        search_path.extend(dylib_path.into_iter());
        if cfg!(target_os = "macos") && dylib_path_is_empty {
            // These are the defaults when DYLD_FALLBACK_LIBRARY_PATH isn't
            // set or set to an empty string. Since Cargo is explicitly setting
            // the value, make sure the defaults still work.
            if let Some(home) = env::var_os("HOME") {
                search_path.push(PathBuf::from(home).join("lib"));
            }
            search_path.push(PathBuf::from("/usr/local/lib"));
            search_path.push(PathBuf::from("/usr/lib"));
        }
        let search_path = join_paths(&search_path, util::dylib_path_envvar())?;

        cmd.env(util::dylib_path_envvar(), &search_path);
        if let Some(env) = self.extra_env.get(&pkg.package_id()) {
            for &(ref k, ref v) in env {
                cmd.env(k, v);
            }
        }

        let metadata = pkg.manifest().metadata();

        let cargo_exe = self.config.cargo_exe()?;
        cmd.env(crate::CARGO_ENV, cargo_exe);

        // When adding new environment variables depending on
        // crate properties which might require rebuild upon change
        // consider adding the corresponding properties to the hash
        // in BuildContext::target_metadata()
        cmd.env("CARGO_MANIFEST_DIR", pkg.root())
            .env("CARGO_PKG_VERSION_MAJOR", &pkg.version().major.to_string())
            .env("CARGO_PKG_VERSION_MINOR", &pkg.version().minor.to_string())
            .env("CARGO_PKG_VERSION_PATCH", &pkg.version().patch.to_string())
            .env(
                "CARGO_PKG_VERSION_PRE",
                &pre_version_component(pkg.version()),
            )
            .env("CARGO_PKG_VERSION", &pkg.version().to_string())
            .env("CARGO_PKG_NAME", &*pkg.name())
            .env(
                "CARGO_PKG_DESCRIPTION",
                metadata.description.as_ref().unwrap_or(&String::new()),
            )
            .env(
                "CARGO_PKG_HOMEPAGE",
                metadata.homepage.as_ref().unwrap_or(&String::new()),
            )
            .env(
                "CARGO_PKG_REPOSITORY",
                metadata.repository.as_ref().unwrap_or(&String::new()),
            )
            .env("CARGO_PKG_AUTHORS", &pkg.authors().join(":"))
            .cwd(pkg.root());
        Ok(cmd)
    }
}

fn pre_version_component(v: &Version) -> String {
    if v.pre.is_empty() {
        return String::new();
    }

    let mut ret = String::new();

    for (i, x) in v.pre.iter().enumerate() {
        if i != 0 {
            ret.push('.')
        };
        ret.push_str(&x.to_string());
    }

    ret
}

fn target_runner(bcx: &BuildContext<'_, '_>) -> CargoResult<Option<(PathBuf, Vec<String>)>> {
    let target = bcx.target_triple();

    // try target.{}.runner
    let key = format!("target.{}.runner", target);
    if let Some(v) = bcx.config.get_path_and_args(&key)? {
        return Ok(Some(v.val));
    }

    // try target.'cfg(...)'.runner
    if let Some(table) = bcx.config.get_table("target")? {
        let mut matching_runner = None;

        for key in table.val.keys() {
            if CfgExpr::matches_key(key, bcx.target_info.cfg()) {
                let key = format!("target.{}.runner", key);
                if let Some(runner) = bcx.config.get_path_and_args(&key)? {
                    // more than one match, error out
                    if matching_runner.is_some() {
                        failure::bail!(
                            "several matching instances of `target.'cfg(..)'.runner` \
                             in `.cargo/config`"
                        )
                    }

                    matching_runner = Some(runner.val);
                }
            }
        }

        return Ok(matching_runner);
    }

    Ok(None)
}
<commit_msg>Pass --crate-type to rustdoc<commit_after>use std::collections::{BTreeSet, HashMap, HashSet};
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;

use semver::Version;

use super::BuildContext;
use crate::core::{Edition, InternedString, Package, PackageId, Target};
use crate::util::{self, join_paths, process, CargoResult, CfgExpr, Config, ProcessBuilder};

pub struct Doctest {
    /// The package being doc-tested.
    pub package: Package,
    /// The target being tested (currently always the package's lib).
    pub target: Target,
    /// Extern dependencies needed by `rustdoc`. The path is the location of
    /// the compiled lib.
    pub deps: Vec<(InternedString, PathBuf)>,
}

/// A structure returning the result of a compilation.
pub struct Compilation<'cfg> {
    /// An array of all tests created during this compilation.
    /// `(package, target, path_to_test_exe)`
    pub tests: Vec<(Package, Target, PathBuf)>,

    /// An array of all binaries created.
    pub binaries: Vec<PathBuf>,

    /// All directories for the output of native build commands.
    ///
    /// This is currently used to drive some entries which are added to the
    /// LD_LIBRARY_PATH as appropriate.
    ///
    /// The order should be deterministic.
    pub native_dirs: BTreeSet<PathBuf>,

    /// Root output directory (for the local package's artifacts)
    pub root_output: PathBuf,

    /// Output directory for rust dependencies.
    /// May be for the host or for a specific target.
    pub deps_output: PathBuf,

    /// Output directory for the rust host dependencies.
    pub host_deps_output: PathBuf,

    /// The path to rustc's own libstd
    pub host_dylib_path: PathBuf,

    /// The path to libstd for the target
    pub target_dylib_path: PathBuf,

    /// Extra environment variables that were passed to compilations and should
    /// be passed to future invocations of programs.
    pub extra_env: HashMap<PackageId, Vec<(String, String)>>,

    /// Libraries to test with rustdoc.
    pub to_doc_test: Vec<Doctest>,

    /// Features per package enabled during this compilation.
    pub cfgs: HashMap<PackageId, HashSet<String>>,

    /// Flags to pass to rustdoc when invoked from cargo test, per package.
    pub rustdocflags: HashMap<PackageId, Vec<String>>,

    pub host: String,
    pub target: String,

    config: &'cfg Config,
    rustc_process: ProcessBuilder,
    primary_unit_rustc_process: Option<ProcessBuilder>,

    target_runner: Option<(PathBuf, Vec<String>)>,
}

impl<'cfg> Compilation<'cfg> {
    pub fn new<'a>(bcx: &BuildContext<'a, 'cfg>) -> CargoResult<Compilation<'cfg>> {
        let mut rustc = bcx.rustc.process();

        let mut primary_unit_rustc_process = bcx.build_config.primary_unit_rustc.clone();

        if bcx.config.extra_verbose() {
            rustc.display_env_vars();

            if let Some(rustc) = primary_unit_rustc_process.as_mut() {
                rustc.display_env_vars();
            }
        }

        Ok(Compilation {
            // TODO: deprecated; remove.
            native_dirs: BTreeSet::new(),
            root_output: PathBuf::from("/"),
            deps_output: PathBuf::from("/"),
            host_deps_output: PathBuf::from("/"),
            host_dylib_path: bcx.host_info.sysroot_libdir.clone(),
            target_dylib_path: bcx.target_info.sysroot_libdir.clone(),
            tests: Vec::new(),
            binaries: Vec::new(),
            extra_env: HashMap::new(),
            to_doc_test: Vec::new(),
            cfgs: HashMap::new(),
            rustdocflags: HashMap::new(),
            config: bcx.config,
            rustc_process: rustc,
            primary_unit_rustc_process,
            host: bcx.host_triple().to_string(),
            target: bcx.target_triple().to_string(),
            target_runner: target_runner(bcx)?,
        })
    }

    /// See `process`.
    pub fn rustc_process(
        &self,
        pkg: &Package,
        target: &Target,
        is_primary: bool,
    ) -> CargoResult<ProcessBuilder> {
        let rustc = if is_primary {
            self.primary_unit_rustc_process
                .clone()
                .unwrap_or_else(|| self.rustc_process.clone())
        } else {
            self.rustc_process.clone()
        };

        let mut p = self.fill_env(rustc, pkg, true)?;
        if target.edition() != Edition::Edition2015 {
            p.arg(format!("--edition={}", target.edition()));
        }
        Ok(p)
    }

    /// See `process`.
    pub fn rustdoc_process(&self, pkg: &Package, target: &Target) -> CargoResult<ProcessBuilder> {
        let mut p = self.fill_env(process(&*self.config.rustdoc()?), pkg, false)?;
        if target.edition() != Edition::Edition2015 {
            p.arg(format!("--edition={}", target.edition()));
        }
        for crate_type in target.rustc_crate_types() {
            p.arg("--crate-type").arg(crate_type);
        }

        Ok(p)
    }

    /// See `process`.
    pub fn host_process<T: AsRef<OsStr>>(
        &self,
        cmd: T,
        pkg: &Package,
    ) -> CargoResult<ProcessBuilder> {
        self.fill_env(process(cmd), pkg, true)
    }

    fn target_runner(&self) -> &Option<(PathBuf, Vec<String>)> {
        &self.target_runner
    }

    /// See `process`.
    pub fn target_process<T: AsRef<OsStr>>(
        &self,
        cmd: T,
        pkg: &Package,
    ) -> CargoResult<ProcessBuilder> {
        let builder = if let Some((ref runner, ref args)) = *self.target_runner() {
            let mut builder = process(runner);
            builder.args(args);
            builder.arg(cmd);
            builder
        } else {
            process(cmd)
        };
        self.fill_env(builder, pkg, false)
    }

    /// Prepares a new process with an appropriate environment to run against
    /// the artifacts produced by the build process.
    ///
    /// The package argument is also used to configure environment variables as
    /// well as the working directory of the child process.
    fn fill_env(
        &self,
        mut cmd: ProcessBuilder,
        pkg: &Package,
        is_host: bool,
    ) -> CargoResult<ProcessBuilder> {
        let mut search_path = if is_host {
            let mut search_path = vec![self.host_deps_output.clone()];
            search_path.push(self.host_dylib_path.clone());
            search_path
        } else {
            let mut search_path =
                super::filter_dynamic_search_path(self.native_dirs.iter(), &self.root_output);
            search_path.push(self.deps_output.clone());
            search_path.push(self.root_output.clone());
            search_path.push(self.target_dylib_path.clone());
            search_path
        };

        let dylib_path = util::dylib_path();
        let dylib_path_is_empty = dylib_path.is_empty();
        search_path.extend(dylib_path.into_iter());
        if cfg!(target_os = "macos") && dylib_path_is_empty {
            // These are the defaults when DYLD_FALLBACK_LIBRARY_PATH isn't
            // set or set to an empty string. Since Cargo is explicitly setting
            // the value, make sure the defaults still work.
            if let Some(home) = env::var_os("HOME") {
                search_path.push(PathBuf::from(home).join("lib"));
            }
            search_path.push(PathBuf::from("/usr/local/lib"));
            search_path.push(PathBuf::from("/usr/lib"));
        }
        let search_path = join_paths(&search_path, util::dylib_path_envvar())?;

        cmd.env(util::dylib_path_envvar(), &search_path);
        if let Some(env) = self.extra_env.get(&pkg.package_id()) {
            for &(ref k, ref v) in env {
                cmd.env(k, v);
            }
        }

        let metadata = pkg.manifest().metadata();

        let cargo_exe = self.config.cargo_exe()?;
        cmd.env(crate::CARGO_ENV, cargo_exe);

        // When adding new environment variables depending on
        // crate properties which might require rebuild upon change
        // consider adding the corresponding properties to the hash
        // in BuildContext::target_metadata()
        cmd.env("CARGO_MANIFEST_DIR", pkg.root())
            .env("CARGO_PKG_VERSION_MAJOR", &pkg.version().major.to_string())
            .env("CARGO_PKG_VERSION_MINOR", &pkg.version().minor.to_string())
            .env("CARGO_PKG_VERSION_PATCH", &pkg.version().patch.to_string())
            .env(
                "CARGO_PKG_VERSION_PRE",
                &pre_version_component(pkg.version()),
            )
            .env("CARGO_PKG_VERSION", &pkg.version().to_string())
            .env("CARGO_PKG_NAME", &*pkg.name())
            .env(
                "CARGO_PKG_DESCRIPTION",
                metadata.description.as_ref().unwrap_or(&String::new()),
            )
            .env(
                "CARGO_PKG_HOMEPAGE",
                metadata.homepage.as_ref().unwrap_or(&String::new()),
            )
            .env(
                "CARGO_PKG_REPOSITORY",
                metadata.repository.as_ref().unwrap_or(&String::new()),
            )
            .env("CARGO_PKG_AUTHORS", &pkg.authors().join(":"))
            .cwd(pkg.root());
        Ok(cmd)
    }
}

fn pre_version_component(v: &Version) -> String {
    if v.pre.is_empty() {
        return String::new();
    }

    let mut ret = String::new();

    for (i, x) in v.pre.iter().enumerate() {
        if i != 0 {
            ret.push('.')
        };
        ret.push_str(&x.to_string());
    }

    ret
}

fn target_runner(bcx: &BuildContext<'_, '_>) -> CargoResult<Option<(PathBuf, Vec<String>)>> {
    let target = bcx.target_triple();

    // try target.{}.runner
    let key = format!("target.{}.runner", target);
    if let Some(v) = bcx.config.get_path_and_args(&key)? {
        return Ok(Some(v.val));
    }

    // try target.'cfg(...)'.runner
    if let Some(table) = bcx.config.get_table("target")? {
        let mut matching_runner = None;

        for key in table.val.keys() {
            if CfgExpr::matches_key(key, bcx.target_info.cfg()) {
                let key = format!("target.{}.runner", key);
                if let Some(runner) = bcx.config.get_path_and_args(&key)? {
                    // more than one match, error out
                    if matching_runner.is_some() {
                        failure::bail!(
                            "several matching instances of `target.'cfg(..)'.runner` \
                             in `.cargo/config`"
                        )
                    }

                    matching_runner = Some(runner.val);
                }
            }
        }

        return Ok(matching_runner);
    }

    Ok(None)
}
<|endoftext|>


<commit_before>/**
Katy Williamson kcw4sn
Ben Terner bt3ze
@virginia.edu

Final Project for CS4414 - Operating Systems
A parallel MST implementation on images in Rust

*/

/*
some documentation:
Pixel object is composed of r,g,b values, a color, and an x,y index that takes the place of its adjacency list
Point is just an (x,y) value to denote a pixel's location
Edge contains two points: source and dest, along with the edge cost between them

*/

extern mod extra;
use std::{os, num,hashmap} ;
use extra::{arc,priority_queue};

struct Pixel{
    r: int,
    b: int,
    g: int,
    color: int,
    x: int,
    y: int
}

impl Pixel {
    fn new(red: int, blue: int, green: int, x: int, y: int) -> Pixel {
        Pixel{
            r: red,
            b: blue,
            g: green,
            color: -1,
            x: x,
            y: y
        }
    }
}

impl Clone for Pixel{
    fn clone(&self) -> Pixel {
        Pixel{
            r: self.r,
            b: self.b,
            g: self.g,
            color: self.color,
            x: self.x,
            y: self.y
        }
    }
}

struct Point {
    x: int,
    y: int
}

impl Point{
    fn new(x: int, y: int)-> Point {
        Point {
            x: x,
            y: y
        }
    }
}

struct Edge {
    source: Point,
    dest: Point,
    cost: float
}

impl Edge {
    fn new(s: Point, d: Point, cost: float) -> Edge {
        Edge {
            source: s,
            dest: d,
            cost: cost
        }
    }
}

impl Ord for Edge {
    fn lt(&self, other: &Edge) -> bool {
        self.cost < other.cost
    }
}

fn edgeCost(a: &Pixel, b: &Pixel) -> float {
    num::sqrt( (
            (a.r-b.r)*(a.r-b.r) + (a.g-b.g)*(a.g-b.g) + (a.b-b.b)*(a.b-b.b) ) as float)
}

fn readImage( filename: &~str) -> ~ [ ~[Pixel]] {
    ~[~[]]
}

fn main(){
    let argv =  os::args();
    println(argv.to_str());

    let pixels: ~[ ~[Pixel] ] = readImage(&argv[1]);

    // width and height should be replaced by just reading them from the file
    let width = match from_str::<int>(argv[2]) {
        Some(x) => x,
        None() => 0
    };
    let height = match from_str::<int>(argv[3]) {
        Some(x) => x,
        None() => 0
    };

    let mut find_arcs: ~[ ~[arc::RWArc<Pixel>] ] =  ~[ ~[]];
    let mut heit = 0;
    let mut wid = 0;
    loop {
        loop {
            find_arcs[heit][wid] = arc::RWArc::new(pixels[heit][wid]);
                wid+=1;
            if(wid == width) {
                wid = 0;
                break;
            }
        }
        heit+=1;
        if(heit == height) {
            break;
        }
    }

    let arcs = find_arcs; // now we have an immutable array that can be shared

    let corners = [ (0,0),(0,width-1),(height-1,0),(height-1,width-1) ];

    for &corner in corners.iter() {
        let (a,b) = corner;
        let shared_arcs = arcs.clone();
        do spawn { // split into threads here

            let mut x=a;
            let mut y=b;
            /*
            weird compiler error:
            let corners = [ (0,0),(0,width-1),(height-1,0),(height-1,width-1) ];
            for &corner in corners.iter(){
            do spawn {
            let mut x = 0;
            let mut y = 0;
            (x,y) = corner
                 }
             }
             */

            let mut queue: priority_queue::PriorityQueue<Edge> =  priority_queue::PriorityQueue::new();
            let mut visited: hashmap::HashMap<(int,int),bool> = hashmap::HashMap::new();

            let mut newvisit: bool = true;

            loop { // iterate through items in the queue, which contains all of the edges/vertices
                if(newvisit){
                    let neighbors = [ (x,y-1),(x+1,y), (x,y+1), (x,y-1)];
                    for &coord in neighbors.iter() {
                        let (w,z) = coord;
                        if w >=0 && w < width && z >=0 && z < height { // bounds checking
                            // if neighbor at coord has not been or colored
                            let mut newvertex = false;
                            let mut uncolored = false;
                            do shared_arcs[w][z].read |dest| {
                                if dest.color < 0 {
                                    uncolored = true; }
                            }
                            if uncolored {
                                do shared_arcs[w][z].write |dest| {
                                    if dest.color < 0 {
                                        do shared_arcs[x][y].read |src| {
                                            dest.color = src.color;
                                        }
                                        newvertex = true;
                                    }
                                }
                            }
                            if newvertex { // then we have a new vertex
                                do shared_arcs[x][y].read |src| {
                                    do shared_arcs[w][z].read |dest| {
                                        queue.push( Edge::new(Point::new(x,y),Point::new(w,z),edgeCost(src,dest)));
                                    }
                                }
                            }
                        }
                    }
                }

                let edge = queue.maybe_pop();
                match edge {
                    Some(e) => {
                        // not in any tree
                        let coord = (e.dest.x,e.dest.y);
                        if *visited.get(&coord) == false { // use visited hashmap to figure out if we're at a new vertex. returns false if it can't return a vertex?
                            visited.insert(coord,true);
                            x = e.dest.x;
                            y = e.dest.y;
                            newvisit = true;
                        } else {
                            newvisit = false;
                        }
                    },
                    None => { break; } // this should execute at the end when there are no more unvisited or uncolored nodes for a thread
                }
            }
        }
    }
}
<commit_msg>Addition of fileReader function, some subsequent debugging for pixels[][] processing<commit_after>/**
Katy Williamson kcw4sn
Ben Terner bt3ze
@virginia.edu

Final Project for CS4414 - Operating Systems
A parallel MST implementation on images in Rust

*/

/*
some documentation:
Pixel object is composed of r,g,b values, a color, and an x,y index that takes the place of its adjacency list
Point is just an (x,y) value to denote a pixel's location
Edge contains two points: source and dest, along with the edge cost between them

*/

extern mod extra;
use std::{os, num, hashmap} ;
use extra::{arc,priority_queue};

struct Pixel{
    r: int,
    b: int,
    g: int,
    color: int,
    x: int,
    y: int
}

impl Pixel {
    fn new(red: int, blue: int, green: int, x: int, y: int) -> Pixel {
        Pixel{
            r: red,
            b: blue,
            g: green,
            color: -1,
            x: x,
            y: y
        }
    }
}

impl Clone for Pixel{
    fn clone(&self) -> Pixel {
        Pixel{
            r: self.r,
            b: self.b,
            g: self.g,
            color: self.color,
            x: self.x,
            y: self.y
        }
    }
}

struct Point {
    x: int,
    y: int
}

impl Point{
    fn new(x: int, y: int)-> Point {
        Point {
            x: x,
            y: y
        }
    }
}

struct Edge {
    source: Point,
    dest: Point,
    cost: float
}

impl Edge {
    fn new(s: Point, d: Point, cost: float) -> Edge {
        Edge {
            source: s,
            dest: d,
            cost: cost
        }
    }
}

impl Ord for Edge {
    fn lt(&self, other: &Edge) -> bool {
        self.cost < other.cost
    }
}

fn edgeCost(a: &Pixel, b: &Pixel) -> float {
    num::sqrt( (
            (a.r-b.r)*(a.r-b.r) + (a.g-b.g)*(a.g-b.g) + (a.b-b.b)*(a.b-b.b) ) as float)
}

fn readImage( filename: &~str) -> ~ [ ~[Pixel]] {
    let mut retval: ~[~[Pixel]] = ~[~[]];

    let file: &str = filename.to_owned();
    let file2: ~str = file.to_owned();
    let split_filename: ~[&str] = file.split_iter('.').collect();
    let file_data: &str = split_filename[0] + ".txt";

    println(fmt!("The image name is [%?]", file));
    println(fmt!("The image data will be stored at [%?]", file_data));

    //read in the .txt associated with the file title
    let path = &PosixPath(file_data);

    match std::io::file_reader(path) {
	Ok(reader) => {
	    //run the java program to process the image
	    let program: &str = "java ImageReader";
	    let argv: ~[~str] = ~[file2];

	    let mut prog = std::run::Process::new(program, argv,
		std::run::ProcessOptions {
			env: None,
			dir: None,
			in_fd: None,
			out_fd: None,
			err_fd: None
		}
	    );
	    prog.finish();

	    //parse out the array dimensions
    	    let dimensions_str: &str = reader.read_line();
    	    //println(dimensions_str);
	    let mut h: int = 0;
	    let mut w: int = 0;
	    match dimensions_str[0] as char {
		'H' => {
		    let split_dim: ~[&str] = dimensions_str.split_iter('W').collect();
		    h = from_str(split_dim[0].slice(1,split_dim[0].len())).unwrap();
		    w = from_str(split_dim[1]).unwrap();
		    println(fmt!("Dimensions passed: H %? W %?",h,w));
		    //let retval: ~[ ~[Pixel, ..w], ..h];
		}
		_ => {println("Dimensions corrupted! Abort");}
	    }

	    //fill in the retVal array with pixel data
	    for row in range(0,h){
		retval.push(~[]);
		for col in range(0,w){
	    	    if !reader.eof() {
			let line: &str = reader.read_line();
			//println(line);
			let rpos:uint = match line.find('R') { Some(n)=>n,None=>line.len() };
			let gpos:uint = match line.find('G') { Some(n)=>n,None=>line.len() };
			let bpos:uint = match line.find('B') { Some(n)=>n,None=>line.len() };

			if rpos == line.len() || gpos == line.len() || bpos == line.len() {
			    println("Pixel data corrupted! Abort");
			}

			let R:int = from_str(line.slice(rpos+1,gpos)).unwrap();
			let G:int = from_str(line.slice(gpos+1,bpos)).unwrap();
			let B:int = from_str(line.slice(bpos+1,line.len())).unwrap();

			//println(fmt!("R %? G %? B %?",R,G,B));

			//fn new(red: int, blue: int, green: int, x: int, y: int) -> Pixel {
			retval[row].push(Pixel::new(R,G,B,col,row));

		    }
		    else {
			println("Data file corrupted! Abort");
		    }
		}
	    }
	},
	Err(err)   => { fail!(err) }
    }

    retval
}

fn main(){
    let argv =  os::args();
    println(argv.to_str());

    let pixels: ~[ ~[Pixel] ] = readImage(&argv[1]);

    // width and height should be replaced by just reading them from the file
    /*let width = match from_str::<int>(argv[2]) {
        Some(x) => x,
        None() => 0
    };
    let height = match from_str::<int>(argv[3]) {
        Some(x) => x,
        None() => 0
    };*/
    let height = pixels.len() as int - 1;
    let width = pixels[0].len() as int;

    println(fmt!("Dimensions received: H %? W %?",height,width));

    let mut find_arcs: ~[ ~[arc::RWArc<Pixel>] ] =  ~[ ~[]];
    for h in range(0,height){
	find_arcs.push(~[]);
	for w in range(0,width){
	    println(fmt!("pix %?",pixels[h][w]));
	    find_arcs[h].push(arc::RWArc::new(pixels[h][w]));
	}
    }	//runtime error after this, referring to hashmap...

  /*  let mut find_arcs: ~[ ~[arc::RWArc<Pixel>] ] =  ~[ ~[]];
    let mut heit = 0;
    let mut wid = 0;
    loop {
        loop {
            find_arcs[heit][wid] = arc::RWArc::new(pixels[heit][wid]);
            wid+=1;
            if(wid == width) {
                wid = 0;
                break;
            }
        }
        heit+=1;
        if(heit == height) {
            break;
        }
    }*/

    let arcs = find_arcs; // now we have an immutable array that can be shared

    let corners = [ (0,0),(0,width-1),(height-1,0),(height-1,width-1) ];

    for &corner in corners.iter() {
        let (a,b) = corner;
        let shared_arcs = arcs.clone();
        do spawn { // split into threads here

            let mut x=a;
            let mut y=b;
            /*
            weird compiler error:
            let corners = [ (0,0),(0,width-1),(height-1,0),(height-1,width-1) ];
            for &corner in corners.iter(){
            do spawn {
            let mut x = 0;
            let mut y = 0;
            (x,y) = corner
                 }
             }
             */

            let mut queue: priority_queue::PriorityQueue<Edge> =  priority_queue::PriorityQueue::new();
            let mut visited: hashmap::HashMap<(int,int),bool> = hashmap::HashMap::new();

            let mut newvisit: bool = true;

            loop { // iterate through items in the queue, which contains all of the edges/vertices
                if(newvisit){
                    let neighbors = [ (x,y-1),(x+1,y), (x,y+1), (x,y-1)];
                    for &coord in neighbors.iter() {
                        let (w,z) = coord;
                        if w >=0 && w < width && z >=0 && z < height { // bounds checking
                            // if neighbor at coord has not been or colored
                            let mut newvertex = false;
                            let mut uncolored = false;
                            do shared_arcs[w][z].read |dest| {
                                if dest.color < 0 {
                                    uncolored = true; }
                            }
                            if uncolored {
                                do shared_arcs[w][z].write |dest| {
                                    if dest.color < 0 {
                                        do shared_arcs[x][y].read |src| {
                                            dest.color = src.color;
                                        }
                                        newvertex = true;
                                    }
                                }
                            }
                            if newvertex { // then we have a new vertex
                                do shared_arcs[x][y].read |src| {
                                    do shared_arcs[w][z].read |dest| {
                                        queue.push( Edge::new(Point::new(x,y),Point::new(w,z),edgeCost(src,dest)));
                                    }
                                }
                            }
                        }
                    }
                }

                let edge = queue.maybe_pop();
                match edge {
                    Some(e) => {
                        // not in any tree
                        let coord = (e.dest.x,e.dest.y);
                        if *visited.get(&coord) == false { // use visited hashmap to figure out if we're at a new vertex. returns false if it can't return a vertex?
                            visited.insert(coord,true);
                            x = e.dest.x;
                            y = e.dest.y;
                            newvisit = true;
                        } else {
                            newvisit = false;
                        }
                    },
                    None => { break; } // this should execute at the end when there are no more unvisited or uncolored nodes for a thread
                }
            }
        }
    }
}
<|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_attr(feature = "nightly", feature(nonzero))]
#![cfg_attr(feature = "serde_derive", feature(rustc_attrs, rustc_macro, structural_match))]

extern crate app_units;
extern crate byteorder;
#[cfg(feature = "nightly")]
extern crate core;
extern crate euclid;
extern crate gleam;
extern crate heapsize;
extern crate ipc_channel;
extern crate offscreen_gl_context;
extern crate serde;
#[cfg(feature = "serde_derive")]
#[macro_use]
extern crate serde_derive;

#[cfg(target_os = "macos")] extern crate core_graphics;

#[cfg(feature = "serde_codegen")]
include!(concat!(env!("OUT_DIR"), "/types.rs"));

#[cfg(feature = "serde_derive")]
include!("types.rs");

mod api;
mod display_item;
mod display_list;
mod stacking_context;
mod webgl;

pub use api::RenderApi;
pub use display_list::{AuxiliaryListsBuilder, DisplayListBuilder};
<commit_msg>Auto merge of #435 - servo:derive, r=emilio<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_attr(feature = "nightly", feature(nonzero))]
#![cfg_attr(feature = "serde_derive", feature(proc_macro, rustc_attrs, structural_match))]

extern crate app_units;
extern crate byteorder;
#[cfg(feature = "nightly")]
extern crate core;
extern crate euclid;
extern crate gleam;
extern crate heapsize;
extern crate ipc_channel;
extern crate offscreen_gl_context;
extern crate serde;
#[cfg(feature = "serde_derive")]
#[macro_use]
extern crate serde_derive;

#[cfg(target_os = "macos")] extern crate core_graphics;

#[cfg(feature = "serde_codegen")]
include!(concat!(env!("OUT_DIR"), "/types.rs"));

#[cfg(feature = "serde_derive")]
include!("types.rs");

mod api;
mod display_item;
mod display_list;
mod stacking_context;
mod webgl;

pub use api::RenderApi;
pub use display_list::{AuxiliaryListsBuilder, DisplayListBuilder};
<|endoftext|>


<commit_before>use std::convert::TryInto;
use std::io::Read;
use std::vec;
use byteorder::{BigEndian, ReadBytesExt};
use serde::de;
use serde::de::{DeserializeSeed, SeqVisitor, Visitor};

use super::error::{Error, ResultE};
use super::maybeskipcomma::MaybeSkipComma;
use oscarg::OscArg;

/// Deserializes a single message, within a packet.
pub struct MsgVisitor<R: Read> {
    read: R,
    state: State,
}

/// Which part of the OSC message is being parsed
enum State {
    /// Deserializing the address pattern.
    Address,
    /// Deserializing the typestring.
    Typestring,
    /// Deserializing the argument data.
    /// Each entry in the Vec is the typecode we parsed earlier
    /// We store this as an iterator to avoid tracking the index of the current arg.
    Arguments(MaybeSkipComma<vec::IntoIter<u8>>),
}

/// Struct to deserialize a single element from the OSC message sequence.
/// (e.g. just the address, or the first argument, etc).
struct MsgItemDeserializer {
    item: OscArg,
}

impl<R> MsgVisitor<R>
    where R: Read
{
    pub fn new(read: R) -> Self {
        Self {
            read: read,
            state: State::Address,
        }
    }
    /// Strings in OSC are ascii and null-terminated.
    /// Strict specification is 1-4 null terminators, to make them end on a 4-byte boundary.
    fn read_0term_bytes(&mut self) -> ResultE<Vec<u8>> {
        let mut data = Vec::new();
        // Because of the 4-byte required padding, we can process 4 characters at a time
        let mut buf: [u8; 4] = [0, 0, 0, 0];
        let mut num_zeros = 0;
        while num_zeros == 0 {
            self.read.read_exact(&mut buf)?;
            // Copy the NON-NULL characters to the buffer.
            num_zeros = buf.iter().filter(|c| **c == 0).count();
            if buf[4-num_zeros..4].iter().any(|c| *c != 0) {
                // We had data after the null terminator.
                return Err(Error::BadPadding);
            }
            data.extend_from_slice(&buf[0..4-num_zeros]);
        }
        Ok(data)
    }
    fn parse_str(&mut self) -> ResultE<String> {
        // Note: although OSC specifies ascii only, we may have data >= 128 in the vector.
        // We can safely assume a UTF-8 encoding, because no byte of any multibyte UTF-8
        // contains a zero; the only zero possible in a UTF-8 string is the ASCII zero.
        // See the UTF-8 table here: https://en.wikipedia.org/wiki/UTF-8#History
        let bytes = self.read_0term_bytes()?;
        Ok(String::from_utf8(bytes)?)
    }
    fn parse_typetag(&mut self) -> ResultE<MaybeSkipComma<vec::IntoIter<u8>>> {
        // The type tag is a string type, with 4-byte null padding.
        // The type tag must begin with a ","
        // Note: the 1.0 specs recommend to be robust in the case of a missing type tag string.
        self.read_0term_bytes().map(|bytes| MaybeSkipComma::new(bytes.into_iter()))
    }

    fn parse_next(&mut self) -> ResultE<Option<OscArg>> {
        let typetag = match self.state {
            State::Address => {
                let address = self.parse_str()?;
                // Successfully parsed the address component; advance to the typestring.
                self.state = State::Typestring;
                return Ok(Some(OscArg::s(address)));
            },
            State::Typestring => {
                // parse the type tag
                let mut tags = self.parse_typetag()?;
                let first_tag = tags.next();
                self.state = State::Arguments(tags);
                first_tag
            },
            State::Arguments(ref mut tags) => {
                // Because parse_arg borrows self as mut, we need to do this weird
                // thing where we pop the typetag here, and then call parse_arg OUTSIDE
                tags.next()
            },
        };
        match typetag {
            None => Ok(None),
            Some(tag) => self.parse_arg(tag).map(|arg| Some(arg))
        }
    }
    fn parse_arg(&mut self, typecode: u8) -> ResultE<OscArg> {
        match typecode {
            b'i' => self.parse_i32().map(|i| { OscArg::i(i) }),
            b'f' => self.parse_f32().map(|f| { OscArg::f(f) }),
            b's' => self.parse_str().map(|s| { OscArg::s(s) }),
            b'b' => self.parse_blob().map(|b| { OscArg::b(b) }),
            c => Err(Error::UnknownType(c)),
        }
    }
    fn parse_i32(&mut self) -> ResultE<i32> {
       Ok( self.read.read_i32::<BigEndian>()?)
    }
    fn parse_f32(&mut self) -> ResultE<f32> {
        Ok(self.read.read_f32::<BigEndian>()?)
    }
    fn parse_blob(&mut self) -> ResultE<Vec<u8>> {
        let size: usize = self.parse_i32()?.try_into()?;
        // Blobs are padded to a 4-byte boundary
        let padding = (4-size)%4;
        let padded_size = size + padding;
        // Read EXACTLY this much data:
        let mut data = vec![0; padded_size];
        self.read.read_exact(&mut data)?;
        // Ensure these extra bytes where NULL (sanity check)
        if data.drain(size..padded_size).any(|c| c == 0) {
            Err(Error::BadPadding)
        } else {
            Ok(data)
        }
    }
}

impl de::Deserializer for MsgItemDeserializer {
    type Error = Error;
    // deserializes a single item from the message, consuming self.
    fn deserialize<V>(self, visitor: V) -> ResultE<V::Value>
    where
        V: Visitor
    {
        match self.item {
            OscArg::i(i) => visitor.visit_i32(i),
            OscArg::f(f) => visitor.visit_f32(f),
            OscArg::s(s) => visitor.visit_string(s),
            OscArg::b(b) => visitor.visit_byte_buf(b),
        }
    }

    // OSC messages are strongly typed, so we don't make use of any type hints.
    // More info: https://github.com/serde-rs/serde/blob/b7d6c5d9f7b3085a4d40a446eeb95976d2337e07/serde/src/macros.rs#L106
    forward_to_deserialize! {
        bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
        seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
        tuple_struct struct struct_field tuple enum ignored_any
    }
}

impl<R> SeqVisitor for MsgVisitor<R>
    where R: Read
{
    type Error = Error;
    fn visit_seed<T>(&mut self, seed: T) -> ResultE<Option<T::Value>>
        where T: DeserializeSeed
    {
        // Return None when the message has been fully parsed,
        // else call seed.deserialize to deserialize the next item.
        let value = self.parse_next()?;
        match value {
            // end of sequence
            None => Ok(None),
            Some(osc_arg) => seed.deserialize(MsgItemDeserializer{ item: osc_arg })
                .map(|value| { Some(value) }),
        }
    }
}
<commit_msg>Fix underflow when parsing blobs<commit_after>use std::convert::TryInto;
use std::io::Read;
use std::vec;
use byteorder::{BigEndian, ReadBytesExt};
use serde::de;
use serde::de::{DeserializeSeed, SeqVisitor, Visitor};

use super::error::{Error, ResultE};
use super::maybeskipcomma::MaybeSkipComma;
use oscarg::OscArg;

/// Deserializes a single message, within a packet.
pub struct MsgVisitor<R: Read> {
    read: R,
    state: State,
}

/// Which part of the OSC message is being parsed
enum State {
    /// Deserializing the address pattern.
    Address,
    /// Deserializing the typestring.
    Typestring,
    /// Deserializing the argument data.
    /// Each entry in the Vec is the typecode we parsed earlier
    /// We store this as an iterator to avoid tracking the index of the current arg.
    Arguments(MaybeSkipComma<vec::IntoIter<u8>>),
}

/// Struct to deserialize a single element from the OSC message sequence.
/// (e.g. just the address, or the first argument, etc).
struct MsgItemDeserializer {
    item: OscArg,
}

impl<R> MsgVisitor<R>
    where R: Read
{
    pub fn new(read: R) -> Self {
        Self {
            read: read,
            state: State::Address,
        }
    }
    /// Strings in OSC are ascii and null-terminated.
    /// Strict specification is 1-4 null terminators, to make them end on a 4-byte boundary.
    fn read_0term_bytes(&mut self) -> ResultE<Vec<u8>> {
        let mut data = Vec::new();
        // Because of the 4-byte required padding, we can process 4 characters at a time
        let mut buf: [u8; 4] = [0, 0, 0, 0];
        let mut num_zeros = 0;
        while num_zeros == 0 {
            self.read.read_exact(&mut buf)?;
            // Copy the NON-NULL characters to the buffer.
            num_zeros = buf.iter().filter(|c| **c == 0).count();
            if buf[4-num_zeros..4].iter().any(|c| *c != 0) {
                // We had data after the null terminator.
                return Err(Error::BadPadding);
            }
            data.extend_from_slice(&buf[0..4-num_zeros]);
        }
        Ok(data)
    }
    fn parse_str(&mut self) -> ResultE<String> {
        // Note: although OSC specifies ascii only, we may have data >= 128 in the vector.
        // We can safely assume a UTF-8 encoding, because no byte of any multibyte UTF-8
        // contains a zero; the only zero possible in a UTF-8 string is the ASCII zero.
        // See the UTF-8 table here: https://en.wikipedia.org/wiki/UTF-8#History
        let bytes = self.read_0term_bytes()?;
        Ok(String::from_utf8(bytes)?)
    }
    fn parse_typetag(&mut self) -> ResultE<MaybeSkipComma<vec::IntoIter<u8>>> {
        // The type tag is a string type, with 4-byte null padding.
        // The type tag must begin with a ","
        // Note: the 1.0 specs recommend to be robust in the case of a missing type tag string.
        self.read_0term_bytes().map(|bytes| MaybeSkipComma::new(bytes.into_iter()))
    }

    fn parse_next(&mut self) -> ResultE<Option<OscArg>> {
        let typetag = match self.state {
            State::Address => {
                let address = self.parse_str()?;
                // Successfully parsed the address component; advance to the typestring.
                self.state = State::Typestring;
                return Ok(Some(OscArg::s(address)));
            },
            State::Typestring => {
                // parse the type tag
                let mut tags = self.parse_typetag()?;
                let first_tag = tags.next();
                self.state = State::Arguments(tags);
                first_tag
            },
            State::Arguments(ref mut tags) => {
                // Because parse_arg borrows self as mut, we need to do this weird
                // thing where we pop the typetag here, and then call parse_arg OUTSIDE
                tags.next()
            },
        };
        match typetag {
            None => Ok(None),
            Some(tag) => self.parse_arg(tag).map(|arg| Some(arg))
        }
    }
    fn parse_arg(&mut self, typecode: u8) -> ResultE<OscArg> {
        match typecode {
            b'i' => self.parse_i32().map(|i| { OscArg::i(i) }),
            b'f' => self.parse_f32().map(|f| { OscArg::f(f) }),
            b's' => self.parse_str().map(|s| { OscArg::s(s) }),
            b'b' => self.parse_blob().map(|b| { OscArg::b(b) }),
            c => Err(Error::UnknownType(c)),
        }
    }
    fn parse_i32(&mut self) -> ResultE<i32> {
       Ok( self.read.read_i32::<BigEndian>()?)
    }
    fn parse_f32(&mut self) -> ResultE<f32> {
        Ok(self.read.read_f32::<BigEndian>()?)
    }
    fn parse_blob(&mut self) -> ResultE<Vec<u8>> {
        let size: usize = self.parse_i32()?.try_into()?;
        // Blobs are padded to a 4-byte boundary
        let padded_size = (size + 3) & !0x3;
        // Read EXACTLY this much data:
        let mut data = vec![0; padded_size];
        self.read.read_exact(&mut data)?;
        // Ensure these extra bytes where NULL (sanity check)
        if data.drain(size..padded_size).any(|c| c == 0) {
            Err(Error::BadPadding)
        } else {
            Ok(data)
        }
    }
}

impl de::Deserializer for MsgItemDeserializer {
    type Error = Error;
    // deserializes a single item from the message, consuming self.
    fn deserialize<V>(self, visitor: V) -> ResultE<V::Value>
    where
        V: Visitor
    {
        match self.item {
            OscArg::i(i) => visitor.visit_i32(i),
            OscArg::f(f) => visitor.visit_f32(f),
            OscArg::s(s) => visitor.visit_string(s),
            OscArg::b(b) => visitor.visit_byte_buf(b),
        }
    }

    // OSC messages are strongly typed, so we don't make use of any type hints.
    // More info: https://github.com/serde-rs/serde/blob/b7d6c5d9f7b3085a4d40a446eeb95976d2337e07/serde/src/macros.rs#L106
    forward_to_deserialize! {
        bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
        seq seq_fixed_size bytes byte_buf map unit_struct newtype_struct
        tuple_struct struct struct_field tuple enum ignored_any
    }
}

impl<R> SeqVisitor for MsgVisitor<R>
    where R: Read
{
    type Error = Error;
    fn visit_seed<T>(&mut self, seed: T) -> ResultE<Option<T::Value>>
        where T: DeserializeSeed
    {
        // Return None when the message has been fully parsed,
        // else call seed.deserialize to deserialize the next item.
        let value = self.parse_next()?;
        match value {
            // end of sequence
            None => Ok(None),
            Some(osc_arg) => seed.deserialize(MsgItemDeserializer{ item: osc_arg })
                .map(|value| { Some(value) }),
        }
    }
}
<|endoftext|>


<commit_before>// https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/
pub fn min_operations_max_profit(
    customers: Vec<i32>,
    boarding_cost: i32,
    running_cost: i32,
) -> i32 {
    todo!()
}

fn main() {
    println!("{}", min_operations_max_profit(vec![8, 3], 5, 6)); // 3
    println!("{}", min_operations_max_profit(vec![10, 9, 6], 6, 4)); // 7
    println!("{}", min_operations_max_profit(vec![3, 4, 0, 5, 1], 1, 92)); // -1
}
<commit_msg>Update problem 1599<commit_after>// https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/
pub fn min_operations_max_profit(
    customers: Vec<i32>,
    boarding_cost: i32,
    running_cost: i32,
) -> i32 {
    let mut answer = 0;
    let mut i = 1;
    let mut wait = 0;
    for customer in customers {
        todo!();
        i += 1;
    }
    if answer < 0 {
        -1
    } else {
        answer
    }
}

fn main() {
    println!("{}", min_operations_max_profit(vec![8, 3], 5, 6)); // 3
    println!("{}", min_operations_max_profit(vec![10, 9, 6], 6, 4)); // 7
    println!("{}", min_operations_max_profit(vec![3, 4, 0, 5, 1], 1, 92)); // -1
}
<|endoftext|>


<commit_before>// https://leetcode.com/problems/number-of-unequal-triplets-in-array/
pub fn unequal_triplets(nums: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!("{}", unequal_triplets(vec![4, 4, 2, 4, 3])); // 3
    println!("{}", unequal_triplets(vec![4, 4, 2, 4, 3, 4])); // 4
    println!("{}", unequal_triplets(vec![4, 4, 2, 4, 3, 4, 5])); // 13
    println!("{}", unequal_triplets(vec![4, 4, 2, 4, 3, 4, 5, 5])); // 22
    println!("{}", unequal_triplets(vec![1, 1, 1, 1, 1])); // 0
    println!("{}", unequal_triplets(vec![1, 2, 3, 4])); // 4
    println!("{}", unequal_triplets(vec![1, 2, 3, 4, 5])); // 10
}
<commit_msg>Solve problem 2475<commit_after>// https://leetcode.com/problems/number-of-unequal-triplets-in-array/
pub fn unequal_triplets(nums: Vec<i32>) -> i32 {
    let mut answer = 0;
    for i in 0..nums.len() {
        for j in i + 1..nums.len() {
            for k in j + 1..nums.len() {
                if nums[i] != nums[j] && nums[i] != nums[k] && nums[j] != nums[k] {
                    answer += 1;
                }
            }
        }
    }
    answer
}

fn main() {
    println!("{}", unequal_triplets(vec![4, 4, 2, 4, 3])); // 3
    println!("{}", unequal_triplets(vec![4, 4, 2, 4, 3, 4])); // 4
    println!("{}", unequal_triplets(vec![4, 4, 2, 4, 3, 4, 5])); // 13
    println!("{}", unequal_triplets(vec![4, 4, 2, 4, 3, 4, 5, 5])); // 22
    println!("{}", unequal_triplets(vec![1, 1, 1, 1, 1])); // 0
    println!("{}", unequal_triplets(vec![1, 2, 3, 4])); // 4
    println!("{}", unequal_triplets(vec![1, 2, 3, 4, 5])); // 10
}
<|endoftext|>


<commit_before>fn main() {

    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));

}

static mut A: [u32; 1000000] = [1;1000000];
static mut I: u32 = 0;

fn dbl_linear(n: u32) -> u32{

    unsafe {
        if I >= n {
            return A[n as usize]
        }
    }

    let mut v:Vec<u32> = vec![];

    v.push(1);

    let mut b = n;

    while b >= 10 {
        for i in 0..n {
            let x = v[i as usize];
            v.push( 2 * x + 1 );
            v.push( 3 * x + 1 );
        }

        v.sort();
        v.dedup();

        v.truncate((n + 1) as usize);

        b = b/10;
    }

    unsafe {
        for i in 0..v.len() {
            A[i as usize] = v[i as usize];
        }

        I = v.len() as u32;
    }

    v[n as usize]
}

#[test]
fn basics_remove_nb() {
    assert_eq!(dbl_linear(10), 22);
    assert_eq!(dbl_linear(20), 57);
    assert_eq!(dbl_linear(30), 91);
    assert_eq!(dbl_linear(50), 175);
    assert_eq!(dbl_linear(100), 447);
    assert_eq!(dbl_linear(1000), 8488);
    assert_eq!(dbl_linear(2000), 19773);
    assert_eq!(dbl_linear(6000), 80914);
    assert_eq!(dbl_linear(60000), 1511311);
    assert_eq!(dbl_linear(600000), 28864270);
}<commit_msg>new puzzler<commit_after>fn main() {

    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));
    println!("{}",dbl_linear(100000));

}

// static mut A: [u32; 1000000] = [1;1000000];
// static mut I: u32 = 0;

fn dbl_linear(n: u32) -> u32 {

    // unsafe {
    //     if I >= n {
    //         return A[n as usize]
    //     }
    // }

    let mut v:Vec<u32> = vec![0; (n+2) as usize];
    v[0] = 1;
    // let mut b = n;

    // while b >= 10 {
        for i in 0..n - 2 {
            let x: u32 = v[i as usize];
            println!("{}", 2 * x + 1);
            let y = 2 * x + 1;
            let mut j = i + 1;

            while j < v.len() as u32 {
                if (y < v[j as usize] as u32) || (v[j as usize] == 0) {
                    v[j as usize] = y;
                    break;
                }
                j += 1;
            }

            let z = 3 * x + 1;

            j = i + 1;

            while j < v.len() as u32 {
                if (z < v[j as usize] as u32) || (v[j as usize] == 0) {
                    v[j as usize] = z;
                    break;
                }
                j += 1;
            }
        }

        // v.sort();
        // v.dedup();

        // v.truncate((n + 1) as usize);

        // b = b/10;
    // }

    // unsafe {
    //     for i in 0..v.len() {
    //         A[i as usize] = v[i as usize];
    //     }

    //     I = v.len() as u32;
    // }

    v[n as usize]
}

#[test]
fn basics_remove_nb() {
    assert_eq!(dbl_linear(10), 22);
    assert_eq!(dbl_linear(20), 57);
    assert_eq!(dbl_linear(30), 91);
    assert_eq!(dbl_linear(50), 175);
    assert_eq!(dbl_linear(100), 447);
    assert_eq!(dbl_linear(1000), 8488);
    assert_eq!(dbl_linear(2000), 19773);
    assert_eq!(dbl_linear(6000), 80914);
    assert_eq!(dbl_linear(60000), 1511311);
    assert_eq!(dbl_linear(600000), 28864270);
}<|endoftext|>


<commit_before>#![feature(custom_derive, plugin, custom_attribute, box_syntax)]
#![plugin(docopt_macros)]
extern crate serde_json;
extern crate serde;
extern crate pbr;
extern crate regex;
extern crate curl;
extern crate docopt;
extern crate rustc_serialize;
extern crate env_logger;
#[macro_use] extern crate log;
#[macro_use] extern crate sonicd;

mod util;

use std::path::PathBuf;
use pbr::ProgressBar;
use sonicd::*;
use util::*;
use std::process;
use std::io::{Write, self};
use serde_json::Value;

docopt!(Args derive Debug, "
.
                           d8b
                           Y8P

.d8888b   .d88b.  88888b.  888  .d8888b
88K      d88\"\"88b 888 \"88b 888 d88P\"
\"Y8888b. 888  888 888  888 888 888
     X88 Y88..88P 888  888 888 Y88b.
 88888P'  \"Y88P\"  888  888 888  \"Y8888P

Usage:
  sonic <source> [-d <var>...] [options] -e <query>
  sonic <source> [-d <var>...] [options] -f <file>
  sonic -h | --help
  sonic --version

Options:
  --execute, -e         run command literal
  --file, -f            run command from file
  -c <config>           use config file (default: $HOME/.sonicrc)
  -d                    inject variable name to value (i.e. -d foo=bar)
  -r, --rows-only       print rows only
  -h, --help            show this message
  --version             show daemon and cli version
");

static VERSION: &'static str = env!("CARGO_PKG_VERSION");
static COMMIT: Option<&'static str> = option_env!("SONIC_COMMIT");

fn _main(args: Args) -> Result<Receipt> {

    let config: ClientConfig = if args.flag_c != "" {
        debug!("sourcing passed config in path '{:?}'", &args.flag_c);
        try!(read_cfg(PathBuf::from(args.flag_c.clone())))
    } else {
        debug!("sourcing default config in path '$HOME/.sonicrc'");
        try!(source_sonicrc())
    };

    let vars = try!(split_key_value(&args.arg_var));

    let query = if args.flag_file {
        try!(read_file_contents(PathBuf::from(&args.arg_file)))
    } else if args.flag_execute {
        args.arg_query.clone()
    } else {
        let daemon_v = try!(version(&config.sonicd, &config.http_port)
                            .map_err(|e| Receipt::error(format!("{}", e))));

        println!("sonic cli version {} ({}); daemon version {}",
        VERSION,
        COMMIT.unwrap_or_else(|| "unknown-commit"),
        daemon_v);
        return Ok(Receipt::success());
    };

    let injected = try!(inject_vars(&query, &vars));

    let query = try!(build(&args.arg_source, config.sources.clone(), &injected));

    let mut pb = ProgressBar::new(100);
    pb.format("╢░░_╟");

    let fn_out = |msg: SonicMessage| {
        match msg.payload {
            Some(Value::Array(d)) => {
                println!("{}", d.iter().fold(String::new(), |acc, x| {
                    format!("{}{:?}\t",acc, x)
                }).trim_right());
            }
            e => panic!("protocol error: expected array in output payload but found {:?}", e)
        }
    };

    let fn_meta = |msg: SonicMessage| {
        if !args.flag_rows_only {
            match msg.payload {
                Some(Value::Array(d)) => {
                    debug!("recv type metadata: {:?}", d);
                    println!("{}", d.iter().fold(String::new(), |acc, col| {
                        format!("{}{:?}\t", acc, col.as_array().unwrap()[0])
                    }).trim_right())
                },
                e => panic!("protocol error: expected json array in metadata payload but found {:?}", e)
            }
        }
    };

    let fn_prog = |msg: SonicMessage| {
        let fields = msg.payload.unwrap();
        fields.find("progress").and_then(|p| {
            p.as_i64().map(|pi| {
                if pi >= 99 {
                    pb.finish();
                } else {
                    pb.add(pi as usize);
                }
            })
        });
        fields.find("output")
            .and_then(|o| o.as_string().map(|os| {
                io::stderr().write(&format!("{}", os).as_bytes()).unwrap();
            }));
    };

    try!(stream(query, &config.sonicd, &config.tcp_port, fn_out, fn_prog, fn_meta)
         .map_err(|e| {
             match e {
                 Error::StreamError(rec) => rec,
                 e => Receipt::error(format!("{}", e))
             }
         }));

    Ok(Receipt::success())
}

fn main() {

    let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());

    env_logger::init().unwrap();

    debug!("Parsed args {:?}", args);

    match _main(args) {
        Ok(r) => {
            if !r.success {
                io::stderr().write(&format!("{}", r).as_bytes()).unwrap();
                process::exit(1)
            } else if r.message.is_some() {
                io::stderr().write(&format!("{}", r).as_bytes()).unwrap();
            }
        },
        Err(r) =>  {
            io::stderr().write(&format!("{}", r).as_bytes()).unwrap();
            process::exit(1)
        }
    }
}
<commit_msg>fixed division by zero when query progress is truncated to 0<commit_after>#![feature(custom_derive, plugin, custom_attribute, box_syntax)]
#![plugin(docopt_macros)]
extern crate serde_json;
extern crate serde;
extern crate pbr;
extern crate regex;
extern crate curl;
extern crate docopt;
extern crate rustc_serialize;
extern crate env_logger;
#[macro_use] extern crate log;
#[macro_use] extern crate sonicd;

mod util;

use std::path::PathBuf;
use pbr::ProgressBar;
use sonicd::*;
use util::*;
use std::process;
use std::io::{Write, self};
use serde_json::Value;

docopt!(Args derive Debug, "
.
                           d8b
                           Y8P

.d8888b   .d88b.  88888b.  888  .d8888b
88K      d88\"\"88b 888 \"88b 888 d88P\"
\"Y8888b. 888  888 888  888 888 888
     X88 Y88..88P 888  888 888 Y88b.
 88888P'  \"Y88P\"  888  888 888  \"Y8888P

Usage:
  sonic <source> [-d <var>...] [options] -e <query>
  sonic <source> [-d <var>...] [options] -f <file>
  sonic -h | --help
  sonic --version

Options:
  --execute, -e         run command literal
  --file, -f            run command from file
  -c <config>           use config file (default: $HOME/.sonicrc)
  -d                    inject variable name to value (i.e. -d foo=bar)
  -r, --rows-only       print rows only
  -h, --help            show this message
  --version             show daemon and cli version
");

static VERSION: &'static str = env!("CARGO_PKG_VERSION");
static COMMIT: Option<&'static str> = option_env!("SONIC_COMMIT");

fn _main(args: Args) -> Result<Receipt> {

    let config: ClientConfig = if args.flag_c != "" {
        debug!("sourcing passed config in path '{:?}'", &args.flag_c);
        try!(read_cfg(PathBuf::from(args.flag_c.clone())))
    } else {
        debug!("sourcing default config in path '$HOME/.sonicrc'");
        try!(source_sonicrc())
    };

    let vars = try!(split_key_value(&args.arg_var));

    let query = if args.flag_file {
        try!(read_file_contents(PathBuf::from(&args.arg_file)))
    } else if args.flag_execute {
        args.arg_query.clone()
    } else {
        let daemon_v = try!(version(&config.sonicd, &config.http_port)
                            .map_err(|e| Receipt::error(format!("{}", e))));

        println!("sonic cli version {} ({}); daemon version {}",
        VERSION,
        COMMIT.unwrap_or_else(|| "unknown-commit"),
        daemon_v);
        return Ok(Receipt::success());
    };

    let injected = try!(inject_vars(&query, &vars));

    let query = try!(build(&args.arg_source, config.sources.clone(), &injected));

    let mut pb = ProgressBar::new(100);
    pb.format("╢░░_╟");

    let fn_out = |msg: SonicMessage| {
        match msg.payload {
            Some(Value::Array(d)) => {
                println!("{}", d.iter().fold(String::new(), |acc, x| {
                    format!("{}{:?}\t",acc, x)
                }).trim_right());
            }
            e => panic!("protocol error: expected array in output payload but found {:?}", e)
        }
    };

    let fn_meta = |msg: SonicMessage| {
        if !args.flag_rows_only {
            match msg.payload {
                Some(Value::Array(d)) => {
                    debug!("recv type metadata: {:?}", d);
                    println!("{}", d.iter().fold(String::new(), |acc, col| {
                        format!("{}{:?}\t", acc, col.as_array().unwrap()[0])
                    }).trim_right())
                },
                e => panic!("protocol error: expected json array in metadata payload but found {:?}", e)
            }
        }
    };

    let fn_prog = |msg: SonicMessage| {
        let fields = msg.payload.unwrap();
        fields.find("progress").and_then(|p| {
            p.as_f64().map(|pi| {
                if pi >= 99.0 {
                    pb.finish();
                } else if pi >= 1.0 {
                    pb.add(pi as usize);
                }
            })
        });
        fields.find("output")
            .and_then(|o| o.as_string().map(|os| {
                io::stderr().write(&format!("{}", os).as_bytes()).unwrap();
            }));
    };

    try!(stream(query, &config.sonicd, &config.tcp_port, fn_out, fn_prog, fn_meta)
         .map_err(|e| {
             match e {
                 Error::StreamError(rec) => rec,
                 e => Receipt::error(format!("{}", e))
             }
         }));

    Ok(Receipt::success())
}

fn main() {

    let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());

    env_logger::init().unwrap();

    debug!("Parsed args {:?}", args);

    match _main(args) {
        Ok(r) => {
            if !r.success {
                io::stderr().write(&format!("{}", r).as_bytes()).unwrap();
                process::exit(1)
            } else if r.message.is_some() {
                io::stderr().write(&format!("{}", r).as_bytes()).unwrap();
            }
        },
        Err(r) =>  {
            io::stderr().write(&format!("{}", r).as_bytes()).unwrap();
            process::exit(1)
        }
    }
}
<|endoftext|>


<commit_before>extern crate cc;
extern crate pkg_config;

use std::{env, fs, io::Write, path::Path, process::Command};

use wayland_scanner::{generate_code, Side};

const PROTOCOL_DIR: &str = "../protocols";

fn main() {
    dump_git_version();
    build_wayland_glib_interface();
    generate_custom_protocols();
}

/// Writes the current git hash to a file that is read by Way Cooler
///
/// If this is a release build, the file will be empty.
fn dump_git_version() {
    let out_dir = env::var("OUT_DIR").expect("Could not find out directory!");
    let dest_path = Path::new(&out_dir).join("git-version.txt");
    let mut f = fs::File::create(&dest_path)
        .expect("Could not write git version to out directory");
    if let Some(git_version) = git_version() {
        f.write_all(git_version.as_ref())
            .expect("Could not write to git version file");
    }
}

/// Gets the current hash of HEAD. Returns None if for some reason
/// that could not be retrieved (e.g not in a git repository)
fn git_version() -> Option<String> {
    if !in_release_commit() {
        Command::new("git")
            .arg("rev-parse")
            .arg("HEAD")
            .output()
            .ok()
            .map(|output| output.stdout)
            .map(|hash| String::from_utf8_lossy(&hash).trim().into())
    } else {
        None
    }
}

/// Determines if the current HEAD is tagged with a release
fn in_release_commit() -> bool {
    let result = Command::new("git")
        .arg("describe")
        .arg("--exact-match")
        .arg("--tags")
        .arg("HEAD")
        .output()
        .unwrap();
    result.status.success()
}

/// Build the wayland-glib interface as a static library
fn build_wayland_glib_interface() {
    let glib = pkg_config::probe_library("glib-2.0").unwrap();
    let dbus = pkg_config::probe_library("dbus-1").unwrap();
    let wayland = pkg_config::probe_library("wayland-client").unwrap();

    let mut builder = cc::Build::new();

    let include_paths = glib
        .include_paths
        .iter()
        .chain(dbus.include_paths.iter())
        .chain(wayland.include_paths.iter());

    for path in include_paths {
        builder.include(path);
    }

    builder
        .file("src/wayland_glib_interface.c")
        .compile("wayland_glib_interface");
    println!("cargo:rustc-flags=-l wayland-client");
}

fn generate_custom_protocols() {
    let out_dir_str = env::var("OUT_DIR").unwrap();
    let out_dir = Path::new(&out_dir_str);

    let protocols =
        fs::read_dir(PROTOCOL_DIR).expect("../protocols does not exist");
    for protocol in protocols {
        let protocol = protocol.expect("Could not read protocol");
        let path = protocol.path();

        let is_xml = path
            .extension()
            .map(|extension| extension == "xml")
            .unwrap_or(false);
        if protocol.file_type().unwrap().is_dir() || !is_xml {
            continue;
        }

        generate_code(path, out_dir.join("mouse_grabber_api.rs"), Side::Client);
    }

    println!("cargo:rerun-if-changed={}", PROTOCOL_DIR);
}
<commit_msg>Fixing generation mouse_grabber_api.rs<commit_after>extern crate cc;
extern crate pkg_config;

use std::{env, fs, io::Write, path::Path, process::Command};

use wayland_scanner::{generate_code, Side};

const PROTOCOL_DIR: &str = "../protocols";

fn main() {
    dump_git_version();
    build_wayland_glib_interface();
    generate_custom_protocols();
}

/// Writes the current git hash to a file that is read by Way Cooler
///
/// If this is a release build, the file will be empty.
fn dump_git_version() {
    let out_dir = env::var("OUT_DIR").expect("Could not find out directory!");
    let dest_path = Path::new(&out_dir).join("git-version.txt");
    let mut f = fs::File::create(&dest_path)
        .expect("Could not write git version to out directory");
    if let Some(git_version) = git_version() {
        f.write_all(git_version.as_ref())
            .expect("Could not write to git version file");
    }
}

/// Gets the current hash of HEAD. Returns None if for some reason
/// that could not be retrieved (e.g not in a git repository)
fn git_version() -> Option<String> {
    if !in_release_commit() {
        Command::new("git")
            .arg("rev-parse")
            .arg("HEAD")
            .output()
            .ok()
            .map(|output| output.stdout)
            .map(|hash| String::from_utf8_lossy(&hash).trim().into())
    } else {
        None
    }
}

/// Determines if the current HEAD is tagged with a release
fn in_release_commit() -> bool {
    let result = Command::new("git")
        .arg("describe")
        .arg("--exact-match")
        .arg("--tags")
        .arg("HEAD")
        .output()
        .unwrap();
    result.status.success()
}

/// Build the wayland-glib interface as a static library
fn build_wayland_glib_interface() {
    let glib = pkg_config::probe_library("glib-2.0").unwrap();
    let dbus = pkg_config::probe_library("dbus-1").unwrap();
    let wayland = pkg_config::probe_library("wayland-client").unwrap();

    let mut builder = cc::Build::new();

    let include_paths = glib
        .include_paths
        .iter()
        .chain(dbus.include_paths.iter())
        .chain(wayland.include_paths.iter());

    for path in include_paths {
        builder.include(path);
    }

    builder
        .file("src/wayland_glib_interface.c")
        .compile("wayland_glib_interface");
    println!("cargo:rustc-flags=-l wayland-client");
}

fn generate_custom_protocols() {
    let out_dir_str = env::var("OUT_DIR").unwrap();
    let out_dir = Path::new(&out_dir_str);
    let path = Path::new(PROTOCOL_DIR).join("way-cooler-mousegrabber-unstable-v1.xml");
    generate_code(path, out_dir.join("mouse_grabber_api.rs"), Side::Client);
    println!("cargo:rerun-if-changed={}", PROTOCOL_DIR);
}
<|endoftext|>


<commit_before>extern crate clap;

use clap::{Arg, App, AppSettings};
use std::fs::File;

fn main() {
    let matches = App::new("updatefw_rs")
        .version("1.0")
        .author("guiglin & nicolattuso")
        .about("implementation of cat in Rust!")
        .setting(AppSettings::TrailingVarArg)
        .arg(Arg::with_name("number")
             .short("n")
             .long("number")
             .help("number all output lines"))
        .arg(Arg::with_name("files")
             .multiple(true)
             .required(true))
        .get_matches();
    let files = matches.values_of("files").unwrap();
    let file_list: Vec<&str> = files.collect();
    println!("{}", file_list.join(" "));

    //let f = File::open(file_list[0]);
    //let mut buffer: Vec<String> = Vec::new();
//    f.read_to_end(&mut buffer);
//
//    for argument in &buffer {
//        println!("{}", argument);
//    }
}
<commit_msg>use bufread instead but problem of trait bound<commit_after>extern crate clap;

use clap::{Arg, App, AppSettings};
use std::io::{self, BufReader};
use std::io::prelude::*;
use std::fs::File;

fn main() {
    let matches = App::new("updatefw_rs")
        .version("1.0")
        .author("guiglin & nicolattuso")
        .about("implementation of cat in Rust!")
        .setting(AppSettings::TrailingVarArg)
        .arg(Arg::with_name("number")
             .short("n")
             .long("number")
             .help("number all output lines"))
        .arg(Arg::with_name("files")
             .multiple(true)
             .required(true))
        .get_matches();
    let files = matches.values_of("files").unwrap();
    let file_list: Vec<&str> = files.collect();
    println!("{}", file_list.join(" "));

    let f = File::open(file_list[0]);
    let f = BufReader::new(f);

    for line in f.lines() {
        println!("{}", line.unwrap);
    }
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
extern crate hashbrown;
extern crate regex;
extern crate rsass;
extern crate serde_json;

mod error;
mod generate;
mod loader;
mod logger;
mod parse;
mod test;
mod util;

#[cfg(test)]
mod tests;

use self::loader::Loader;
use clap::{App, Arg, SubCommand};
use std::env;
use std::path::Path;
use std::process::exit;
use std::usize;

fn main() {
    if let Err(e) = run() {
        eprintln!("{}", e.0);
        exit(1);
    }
}

fn run() -> error::Result<()> {
    let matches = App::new("tree-sitter")
        .version("0.1")
        .author("Max Brunsfeld <maxbrunsfeld@gmail.com>")
        .about("Generates and tests parsers")
        .subcommand(
            SubCommand::with_name("generate")
                .about("Generate a parser")
                .arg(Arg::with_name("log").long("log"))
                .arg(Arg::with_name("properties-only").long("properties"))
                .arg(
                    Arg::with_name("state-ids-to-log")
                        .long("log-state")
                        .takes_value(true),
                )
                .arg(Arg::with_name("no-minimize").long("no-minimize")),
        )
        .subcommand(
            SubCommand::with_name("parse")
                .about("Parse a file")
                .arg(Arg::with_name("path").index(1).required(true))
                .arg(Arg::with_name("debug").long("debug").short("d"))
                .arg(Arg::with_name("debug-graph").long("debug-graph").short("D")),
        )
        .subcommand(
            SubCommand::with_name("test")
                .about("Run a parser's tests")
                .arg(
                    Arg::with_name("filter")
                        .long("filter")
                        .short("f")
                        .takes_value(true),
                )
                .arg(Arg::with_name("debug").long("debug").short("d"))
                .arg(Arg::with_name("debug-graph").long("debug-graph").short("D")),
        )
        .get_matches();

    let home_dir = dirs::home_dir().unwrap();
    let current_dir = env::current_dir().unwrap();
    let mut loader = Loader::new(home_dir.join(".tree-sitter"));

    if let Some(matches) = matches.subcommand_matches("generate") {
        if matches.is_present("log") {
            logger::init();
        }

        let minimize = !matches.is_present("no-minimize");
        let properties_only = matches.is_present("properties-only");
        let state_ids_to_log = matches
            .values_of("state-ids-to-log")
            .map_or(Vec::new(), |ids| {
                ids.filter_map(|id| usize::from_str_radix(id, 10).ok())
                    .collect()
            });
        generate::generate_parser_in_directory(
            &current_dir,
            minimize,
            state_ids_to_log,
            properties_only,
        )?;
    } else if let Some(matches) = matches.subcommand_matches("test") {
        let debug = matches.is_present("debug");
        let debug_graph = matches.is_present("debug-graph");
        let filter = matches.value_of("filter");
        let corpus_path = current_dir.join("corpus");
        if let Some(language) = loader.language_at_path(&current_dir)? {
            test::run_tests_at_path(language, &corpus_path, debug, debug_graph, filter)?;
        } else {
            eprintln!("No language found");
        }
    } else if let Some(matches) = matches.subcommand_matches("parse") {
        let debug = matches.is_present("debug");
        let debug_graph = matches.is_present("debug-graph");
        loader.find_all_languages(&vec![home_dir.join("github")])?;
        let source_path = Path::new(matches.value_of("path").unwrap());
        if let Some((language, _)) = loader.language_configuration_for_file_name(source_path)? {
            parse::parse_file_at_path(language, source_path, debug, debug_graph)?;
        } else {
            eprintln!("No language found");
        }
    }

    Ok(())
}
<commit_msg>Ensure the .tree-sitter directory exists<commit_after>#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
extern crate hashbrown;
extern crate regex;
extern crate rsass;
extern crate serde_json;

mod error;
mod generate;
mod loader;
mod logger;
mod parse;
mod test;
mod util;

#[cfg(test)]
mod tests;

use self::loader::Loader;
use clap::{App, Arg, SubCommand};
use std::env;
use std::fs;
use std::path::Path;
use std::process::exit;
use std::usize;

fn main() {
    if let Err(e) = run() {
        eprintln!("{}", e.0);
        exit(1);
    }
}

fn run() -> error::Result<()> {
    let matches = App::new("tree-sitter")
        .version("0.1")
        .author("Max Brunsfeld <maxbrunsfeld@gmail.com>")
        .about("Generates and tests parsers")
        .subcommand(
            SubCommand::with_name("generate")
                .about("Generate a parser")
                .arg(Arg::with_name("log").long("log"))
                .arg(Arg::with_name("properties-only").long("properties"))
                .arg(
                    Arg::with_name("state-ids-to-log")
                        .long("log-state")
                        .takes_value(true),
                )
                .arg(Arg::with_name("no-minimize").long("no-minimize")),
        )
        .subcommand(
            SubCommand::with_name("parse")
                .about("Parse a file")
                .arg(Arg::with_name("path").index(1).required(true))
                .arg(Arg::with_name("debug").long("debug").short("d"))
                .arg(Arg::with_name("debug-graph").long("debug-graph").short("D")),
        )
        .subcommand(
            SubCommand::with_name("test")
                .about("Run a parser's tests")
                .arg(
                    Arg::with_name("filter")
                        .long("filter")
                        .short("f")
                        .takes_value(true),
                )
                .arg(Arg::with_name("debug").long("debug").short("d"))
                .arg(Arg::with_name("debug-graph").long("debug-graph").short("D")),
        )
        .get_matches();

    let home_dir = dirs::home_dir().unwrap();
    let current_dir = env::current_dir().unwrap();
    let config_dir = home_dir.join(".tree-sitter");
    fs::create_dir_all(&config_dir).unwrap();
    let mut loader = Loader::new(config_dir);

    if let Some(matches) = matches.subcommand_matches("generate") {
        if matches.is_present("log") {
            logger::init();
        }

        let minimize = !matches.is_present("no-minimize");
        let properties_only = matches.is_present("properties-only");
        let state_ids_to_log = matches
            .values_of("state-ids-to-log")
            .map_or(Vec::new(), |ids| {
                ids.filter_map(|id| usize::from_str_radix(id, 10).ok())
                    .collect()
            });
        generate::generate_parser_in_directory(
            &current_dir,
            minimize,
            state_ids_to_log,
            properties_only,
        )?;
    } else if let Some(matches) = matches.subcommand_matches("test") {
        let debug = matches.is_present("debug");
        let debug_graph = matches.is_present("debug-graph");
        let filter = matches.value_of("filter");
        let corpus_path = current_dir.join("corpus");
        if let Some(language) = loader.language_at_path(&current_dir)? {
            test::run_tests_at_path(language, &corpus_path, debug, debug_graph, filter)?;
        } else {
            eprintln!("No language found");
        }
    } else if let Some(matches) = matches.subcommand_matches("parse") {
        let debug = matches.is_present("debug");
        let debug_graph = matches.is_present("debug-graph");
        loader.find_all_languages(&vec![home_dir.join("github")])?;
        let source_path = Path::new(matches.value_of("path").unwrap());
        if let Some((language, _)) = loader.language_configuration_for_file_name(source_path)? {
            parse::parse_file_at_path(language, source_path, debug, debug_graph)?;
        } else {
            eprintln!("No language found");
        }
    }

    Ok(())
}
<|endoftext|>


<commit_before>//extern crate test;

extern crate caliburn;

use self::caliburn::rfc2812;
use self::caliburn::line_parser;

#[test]
#[should_panic(expected = "assertion failed: `(left == right)`")]
fn localhost_is_not_user() {
    let testcase = line_parser::Message {
            prefix: line_parser::Prefix::User {
                nickname: "localhost",
                user: None,
                host: None
            },
            command: line_parser::Command::Verb("NAME"),
            params: vec!["test".to_string()]
        };

    let res = rfc2812::irc_msg(":localhost NAME :test").unwrap();
    println!("Testcase: {:?}, Parsed: {:?}", testcase, res);
    assert_eq!(res,
        testcase);
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn prefixed_user_ident_without_host() {
    let res = rfc2812::irc_msg(":test!user NAME :test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn too_many_args() {
    let res = rfc2812::irc_msg(":irc.example.com A B C D E F G H I J K L M N O P Q R S :T");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn middle_param_has_colon() {
    let res = rfc2812::irc_msg(":irc.example.com HELL:O :WORLD");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn numeric_too_short() {
    let res = rfc2812::irc_msg(":irc.example.com 42 :Invalid numeric (too short)");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip4_host_as_ip6_invalid_ip4() {
    let res = rfc2812::irc_msg(":test!user@0:0:0:0:0:FFFF:127.0..1 NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip4_host_invalid_empty_segment() {
    let res = rfc2812::irc_msg(":test!127.0..1 NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip4_host_invalid_fewer_segments() {
    let res = rfc2812::irc_msg(":test!127.0.1 NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip6_host_invalid_fewer_segments() {
    let res = rfc2812::irc_msg(":test!aaaa:aaaa:aaaa:aaaa:aaaa NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip6_host_invalid_mixed_case() {
    let res = rfc2812::irc_msg(":test!aaaa:aaaa:aaaa:aaaa:aaaa:AAAA:AAAA:AAAA NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip6_host_invalid_empty_segment() {
    let res = rfc2812::irc_msg(":test!aaaa:aaaa:aaaa:aaaa:aaaa:aaaa::aaaa NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn command_with_invalid_char() {
    let res = rfc2812::irc_msg("NAME!EMAN test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn numeric_with_invalid_char() {
    let res = rfc2812::irc_msg("1N2 test");
    assert!(res.is_ok());
}
<commit_msg>More unit test coverage improvements<commit_after>//extern crate test;

extern crate caliburn;

use self::caliburn::rfc2812;
use self::caliburn::line_parser;

#[test]
#[should_panic(expected = "assertion failed: `(left == right)`")]
fn localhost_is_not_user() {
    let testcase = line_parser::Message {
            prefix: line_parser::Prefix::User {
                nickname: "localhost",
                user: None,
                host: None
            },
            command: line_parser::Command::Verb("NAME"),
            params: vec!["test".to_string()]
        };

    let res = rfc2812::irc_msg(":localhost NAME :test").unwrap();
    println!("Testcase: {:?}, Parsed: {:?}", testcase, res);
    assert_eq!(res,
        testcase);
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn prefixed_user_ident_without_host() {
    let res = rfc2812::irc_msg(":test!user NAME :test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn too_many_args() {
    let res = rfc2812::irc_msg(":irc.example.com A B C D E F G H I J K L M N O P Q R S :T");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn middle_param_has_colon() {
    let res = rfc2812::irc_msg(":irc.example.com HELL:O :WORLD");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn numeric_too_short() {
    let res = rfc2812::irc_msg(":irc.example.com 42 :Invalid numeric (too short)");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip4_host_as_ip6_invalid_ip4() {
    let res = rfc2812::irc_msg(":test!user@0:0:0:0:0:FFFF:127.0..1 NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip4_host_invalid_empty_segment() {
    let res = rfc2812::irc_msg(":test!127.0..1 NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip4_host_invalid_fewer_segments() {
    let res = rfc2812::irc_msg(":test!127.0.1 NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip6_host_invalid_fewer_segments() {
    let res = rfc2812::irc_msg(":test!aaaa:aaaa:aaaa:aaaa:aaaa NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip6_host_invalid_mixed_case() {
    let res = rfc2812::irc_msg(":test!aaaa:aaaa:aaaa:aaaa:aaaa:AAAA:AAAA:AAAA NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn parse_prefixed_user_ip6_host_invalid_empty_segment() {
    let res = rfc2812::irc_msg(":test!aaaa:aaaa:aaaa:aaaa:aaaa:aaaa::aaaa NAME test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn command_with_invalid_char() {
    let res = rfc2812::irc_msg("NAME!EMAN test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn numeric_with_invalid_char() {
    let res = rfc2812::irc_msg("1N2 test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn empty_line_should_fail() {
    let res = rfc2812::irc_msg("");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn host_only() {
    let res = rfc2812::irc_msg(":test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn user_only() {
    let res = rfc2812::irc_msg(":test!test@test");
    assert!(res.is_ok());
}

#[test]
#[should_panic(expected = "res.is_ok()")]
fn no_command() {
    let res = rfc2812::irc_msg(":test!test@test :hello");
    assert!(res.is_ok());
}
<|endoftext|>