<commit_before>use std::collections::HashMap;
use metrics::metric::Metric;
use reporter::base::Reporter;

pub trait Registry<'a>: Send + Sync {
    fn add_scheduled_reporter(&mut self, reporter: Box<Reporter>);
    fn get(&'a self, name: &'a str) -> &'a Metric;
    fn get_metrics_names(&self) -> Vec<&str>;
    fn insert<T: Metric + 'a>(&mut self, name: &'a str, metric: T);
}

pub struct StdRegistry<'a> {
    metrics: HashMap<&'a str, Box<Metric + 'a>>,
    reporter: HashMap<&'a str, Box<Reporter>>,
}

// Specific stuff for registry goes here
impl<'a> Registry<'a> for StdRegistry<'a> {
    fn add_scheduled_reporter(&mut self, reporter: Box<Reporter>) {
        let reporter_name = reporter.get_unique_reporter_name();
        self.reporter.insert(reporter_name, reporter);
    }

    fn get(&'a self, name: &'a str) -> &'a Metric {
        &*self.metrics[name]
    }

    fn insert<T: Metric + 'a>(&mut self, name: &'a str, metric: T) {
        let boxed = Box::new(metric);
        self.metrics.insert(name, boxed);
    }

    fn get_metrics_names(&self) -> Vec<&str> {
        self.metrics.keys().cloned().collect()
    }
}

impl<'a> StdRegistry<'a> {
    #[allow(dead_code)]
    pub fn new() -> StdRegistry<'a> {
        StdRegistry {
            metrics: HashMap::new(),
            reporter: HashMap::new(),
        }
    }
}

#[cfg(test)]
mod test {
    use metrics::meter::{Meter, StdMeter};
    use metrics::counter::{Counter, StdCounter};
    use metrics::gauge::{Gauge, StdGauge};
    use registry::{Registry, StdRegistry};
    use histogram::*;

    #[test]
    fn meter() {
        let mut r = StdRegistry::new();
        let m = StdMeter::new();
        m.mark(100);
        r.insert("meter1", m);
    }

    #[test]
    fn gauge() {
        let mut r = StdRegistry::new();
        let mut g: StdGauge = StdGauge { value: 0f64 };
        g.set(1.2);
        r.insert("gauge1", g);
    }

    #[test]
    fn counter() {
        let mut r = StdRegistry::new();
        let mut c: StdCounter = StdCounter::new();
        c.add(1 as f64);
        r.insert("counter1", c);
    }

    #[test]
    fn histogram() {
        let mut r = StdRegistry::new();
        let mut c = HistogramConfig::new();
        c.max_value(100).precision(1);
        let mut h = Histogram::configured(c).unwrap();
        h.record(1, 1);
        r.insert("histogram", h);
    }
}
<commit_msg>Add some to be done<commit_after>use std::collections::HashMap;
use metrics::metric::Metric;
use reporter::base::Reporter;

// TODO break out any notion of metrics. Instead we should have a notion of a collector.
// A collector should be able to insert metrics, and a registry should not.
pub trait Registry<'a>: Send + Sync {
    fn add_scheduled_reporter(&mut self, reporter: Box<Reporter>);
    fn get(&'a self, name: &'a str) -> &'a Metric;
    fn get_metrics_names(&self) -> Vec<&str>;
    fn insert<T: Metric + 'a>(&mut self, name: &'a str, metric: T);
}

pub struct StdRegistry<'a> {
    metrics: HashMap<&'a str, Box<Metric + 'a>>,
    reporter: HashMap<&'a str, Box<Reporter>>,
}

// Specific stuff for registry goes here
impl<'a> Registry<'a> for StdRegistry<'a> {
    fn add_scheduled_reporter(&mut self, reporter: Box<Reporter>) {
        let reporter_name = reporter.get_unique_reporter_name();
        self.reporter.insert(reporter_name, reporter);
    }

    fn get(&'a self, name: &'a str) -> &'a Metric {
        &*self.metrics[name]
    }

    fn insert<T: Metric + 'a>(&mut self, name: &'a str, metric: T) {
        let boxed = Box::new(metric);
        self.metrics.insert(name, boxed);
    }

    fn get_metrics_names(&self) -> Vec<&str> {
        self.metrics.keys().cloned().collect()
    }
}

impl<'a> StdRegistry<'a> {
    #[allow(dead_code)]
    pub fn new() -> StdRegistry<'a> {
        StdRegistry {
            metrics: HashMap::new(),
            reporter: HashMap::new(),
        }
    }
}

#[cfg(test)]
mod test {
    use metrics::meter::{Meter, StdMeter};
    use metrics::counter::{Counter, StdCounter};
    use metrics::gauge::{Gauge, StdGauge};
    use registry::{Registry, StdRegistry};
    use histogram::*;

    #[test]
    fn meter() {
        let mut r = StdRegistry::new();
        let m = StdMeter::new();
        m.mark(100);
        r.insert("meter1", m);
    }

    #[test]
    fn gauge() {
        let mut r = StdRegistry::new();
        let mut g: StdGauge = StdGauge { value: 0f64 };
        g.set(1.2);
        r.insert("gauge1", g);
    }

    #[test]
    fn counter() {
        let mut r = StdRegistry::new();
        let mut c: StdCounter = StdCounter::new();
        c.add(1 as f64);
        r.insert("counter1", c);
    }

    #[test]
    fn histogram() {
        let mut r = StdRegistry::new();
        let mut c = HistogramConfig::new();
        c.max_value(100).precision(1);
        let mut h = Histogram::configured(c).unwrap();
        h.record(1, 1);
        r.insert("histogram", h);
    }
}
<|endoftext|>


<commit_before><commit_msg>add clear and move clear_entity & tag.remove<commit_after><|endoftext|>


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

//! Machinery for hygienic macros, as described in the MTWT[1] paper.
//!
//! [1] Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce Findler.
//! 2012. *Macros that work together: Compile-time bindings, partial expansion,
//! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216.
//! DOI=10.1017/S0956796812000093 http://dx.doi.org/10.1017/S0956796812000093

pub use self::SyntaxContext_::*;

use ast::{Ident, Mrk, Name, SyntaxContext};

use std::cell::RefCell;
use std::collections::HashMap;

/// The SCTable contains a table of SyntaxContext_'s. It
/// represents a flattened tree structure, to avoid having
/// managed pointers everywhere (that caused an ICE).
/// the `marks` and `renames` fields are side-tables
/// that ensure that adding the same mark to the same context
/// gives you back the same context as before. This should cut
/// down on memory use *a lot*; applying a mark to a tree containing
/// 50 identifiers would otherwise generate 50 new contexts.
pub struct SCTable {
    table: RefCell<Vec<SyntaxContext_>>,
    marks: RefCell<HashMap<(SyntaxContext,Mrk),SyntaxContext>>,
    renames: RefCell<HashMap<Name,SyntaxContext>>,
}

#[derive(PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, Clone)]
pub enum SyntaxContext_ {
    EmptyCtxt,
    Mark (Mrk,SyntaxContext),
    Rename (Name),
    /// actually, IllegalCtxt may not be necessary.
    IllegalCtxt
}

/// A list of ident->name renamings
pub type RenameList = Vec<(Ident, Name)>;

/// Extend a syntax context with a given mark
pub fn apply_mark(m: Mrk, ctxt: SyntaxContext) -> SyntaxContext {
    with_sctable(|table| apply_mark_internal(m, ctxt, table))
}

/// Extend a syntax context with a given mark and sctable (explicit memoization)
fn apply_mark_internal(m: Mrk, ctxt: SyntaxContext, table: &SCTable) -> SyntaxContext {
    let ctxts = &mut *table.table.borrow_mut();
    match ctxts[ctxt.0 as usize] {
        // Applying the same mark twice is a no-op.
        Mark(outer_mark, prev_ctxt) if outer_mark == m => return prev_ctxt,
        _ => *table.marks.borrow_mut().entry((ctxt, m)).or_insert_with(|| {
            SyntaxContext(idx_push(ctxts, Mark(m, ctxt)))
        }),
    }
}

/// Extend a syntax context with a given rename
pub fn apply_rename(from: Ident, to: Name, ident: Ident) -> Ident {
    with_sctable(|table| apply_rename_internal(from, to, ident, table))
}

/// Extend a syntax context with a given rename and sctable (explicit memoization)
fn apply_rename_internal(from: Ident, to: Name, ident: Ident, table: &SCTable) -> Ident {
    if (ident.name, ident.ctxt) != (from.name, from.ctxt) {
        return ident;
    }
    let ctxt = *table.renames.borrow_mut().entry(to).or_insert_with(|| {
        SyntaxContext(idx_push(&mut *table.table.borrow_mut(), Rename(to)))
    });
    Ident { ctxt: ctxt, ..ident }
}

/// Apply a list of renamings to a context
// if these rename lists get long, it would make sense
// to consider memoizing this fold. This may come up
// when we add hygiene to item names.
pub fn apply_renames(renames: &RenameList, ident: Ident) -> Ident {
    renames.iter().fold(ident, |ident, &(from, to)| {
        apply_rename(from, to, ident)
    })
}

/// Fetch the SCTable from TLS, create one if it doesn't yet exist.
pub fn with_sctable<T, F>(op: F) -> T where
    F: FnOnce(&SCTable) -> T,
{
    thread_local!(static SCTABLE_KEY: SCTable = new_sctable_internal());
    SCTABLE_KEY.with(move |slot| op(slot))
}

// Make a fresh syntax context table with EmptyCtxt in slot zero
// and IllegalCtxt in slot one.
fn new_sctable_internal() -> SCTable {
    SCTable {
        table: RefCell::new(vec!(EmptyCtxt, IllegalCtxt)),
        marks: RefCell::new(HashMap::new()),
        renames: RefCell::new(HashMap::new()),
    }
}

/// Print out an SCTable for debugging
pub fn display_sctable(table: &SCTable) {
    error!("SC table:");
    for (idx,val) in table.table.borrow().iter().enumerate() {
        error!("{:4} : {:?}",idx,val);
    }
}

/// Clear the tables from TLD to reclaim memory.
pub fn clear_tables() {
    with_sctable(|table| {
        *table.table.borrow_mut() = Vec::new();
        *table.marks.borrow_mut() = HashMap::new();
        *table.renames.borrow_mut() = HashMap::new();
    });
}

/// Reset the tables to their initial state
pub fn reset_tables() {
    with_sctable(|table| {
        *table.table.borrow_mut() = vec!(EmptyCtxt, IllegalCtxt);
        *table.marks.borrow_mut() = HashMap::new();
        *table.renames.borrow_mut() = HashMap::new();
    });
}

/// Add a value to the end of a vec, return its index
fn idx_push<T>(vec: &mut Vec<T>, val: T) -> u32 {
    vec.push(val);
    (vec.len() - 1) as u32
}

/// Resolve a syntax object to a name, per MTWT.
pub fn resolve(id: Ident) -> Name {
    with_sctable(|sctable| {
        resolve_internal(id, sctable)
    })
}

/// Resolve a syntax object to a name, per MTWT.
/// adding memoization to resolve 500+ seconds in resolve for librustc (!)
fn resolve_internal(id: Ident, table: &SCTable) -> Name {
    match table.table.borrow()[id.ctxt.0 as usize] {
        EmptyCtxt => id.name,
        // ignore marks here:
        Mark(_, subctxt) => resolve_internal(Ident::new(id.name, subctxt), table),
        Rename(name) => name,
        IllegalCtxt => panic!("expected resolvable context, got IllegalCtxt")
    }
}

/// Return the outer mark for a context with a mark at the outside.
/// FAILS when outside is not a mark.
pub fn outer_mark(ctxt: SyntaxContext) -> Mrk {
    with_sctable(|sctable| {
        match (*sctable.table.borrow())[ctxt.0 as usize] {
            Mark(mrk, _) => mrk,
            _ => panic!("can't retrieve outer mark when outside is not a mark")
        }
    })
}

#[cfg(test)]
mod tests {
    use ast::{EMPTY_CTXT, Ident, Mrk, Name, SyntaxContext};
    use super::{resolve, apply_mark_internal, new_sctable_internal};
    use super::{SCTable, Mark};

    fn id(n: u32, s: SyntaxContext) -> Ident {
        Ident::new(Name(n), s)
    }

    // extend a syntax context with a sequence of marks given
    // in a vector. v[0] will be the outermost mark.
    fn unfold_marks(mrks: Vec<Mrk> , tail: SyntaxContext, table: &SCTable)
                    -> SyntaxContext {
        mrks.iter().rev().fold(tail, |tail:SyntaxContext, mrk:&Mrk|
                   {apply_mark_internal(*mrk,tail,table)})
    }

    #[test] fn unfold_marks_test() {
        let mut t = new_sctable_internal();

        assert_eq!(unfold_marks(vec!(3,7),EMPTY_CTXT,&mut t),SyntaxContext(3));
        {
            let table = t.table.borrow();
            assert!((*table)[2] == Mark(7,EMPTY_CTXT));
            assert!((*table)[3] == Mark(3,SyntaxContext(2)));
        }
    }

    #[test]
    fn mtwt_resolve_test(){
        let a = 40;
        assert_eq!(resolve(id(a,EMPTY_CTXT)),Name(a));
    }

    #[test]
    fn hashing_tests () {
        let mut t = new_sctable_internal();
        assert_eq!(apply_mark_internal(12,EMPTY_CTXT,&mut t),SyntaxContext(2));
        assert_eq!(apply_mark_internal(13,EMPTY_CTXT,&mut t),SyntaxContext(3));
        // using the same one again should result in the same index:
        assert_eq!(apply_mark_internal(12,EMPTY_CTXT,&mut t),SyntaxContext(2));
        // I'm assuming that the rename table will behave the same....
    }
}
<commit_msg>Remove `IllegalCtxt`<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Machinery for hygienic macros, as described in the MTWT[1] paper.
//!
//! [1] Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce Findler.
//! 2012. *Macros that work together: Compile-time bindings, partial expansion,
//! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216.
//! DOI=10.1017/S0956796812000093 http://dx.doi.org/10.1017/S0956796812000093

pub use self::SyntaxContext_::*;

use ast::{Ident, Mrk, Name, SyntaxContext};

use std::cell::RefCell;
use std::collections::HashMap;

/// The SCTable contains a table of SyntaxContext_'s. It
/// represents a flattened tree structure, to avoid having
/// managed pointers everywhere (that caused an ICE).
/// the `marks` and `renames` fields are side-tables
/// that ensure that adding the same mark to the same context
/// gives you back the same context as before. This should cut
/// down on memory use *a lot*; applying a mark to a tree containing
/// 50 identifiers would otherwise generate 50 new contexts.
pub struct SCTable {
    table: RefCell<Vec<SyntaxContext_>>,
    marks: RefCell<HashMap<(SyntaxContext,Mrk),SyntaxContext>>,
    renames: RefCell<HashMap<Name,SyntaxContext>>,
}

#[derive(PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, Clone)]
pub enum SyntaxContext_ {
    EmptyCtxt,
    Mark (Mrk,SyntaxContext),
    Rename (Name),
}

/// A list of ident->name renamings
pub type RenameList = Vec<(Ident, Name)>;

/// Extend a syntax context with a given mark
pub fn apply_mark(m: Mrk, ctxt: SyntaxContext) -> SyntaxContext {
    with_sctable(|table| apply_mark_internal(m, ctxt, table))
}

/// Extend a syntax context with a given mark and sctable (explicit memoization)
fn apply_mark_internal(m: Mrk, ctxt: SyntaxContext, table: &SCTable) -> SyntaxContext {
    let ctxts = &mut *table.table.borrow_mut();
    match ctxts[ctxt.0 as usize] {
        // Applying the same mark twice is a no-op.
        Mark(outer_mark, prev_ctxt) if outer_mark == m => return prev_ctxt,
        _ => *table.marks.borrow_mut().entry((ctxt, m)).or_insert_with(|| {
            SyntaxContext(idx_push(ctxts, Mark(m, ctxt)))
        }),
    }
}

/// Extend a syntax context with a given rename
pub fn apply_rename(from: Ident, to: Name, ident: Ident) -> Ident {
    with_sctable(|table| apply_rename_internal(from, to, ident, table))
}

/// Extend a syntax context with a given rename and sctable (explicit memoization)
fn apply_rename_internal(from: Ident, to: Name, ident: Ident, table: &SCTable) -> Ident {
    if (ident.name, ident.ctxt) != (from.name, from.ctxt) {
        return ident;
    }
    let ctxt = *table.renames.borrow_mut().entry(to).or_insert_with(|| {
        SyntaxContext(idx_push(&mut *table.table.borrow_mut(), Rename(to)))
    });
    Ident { ctxt: ctxt, ..ident }
}

/// Apply a list of renamings to a context
// if these rename lists get long, it would make sense
// to consider memoizing this fold. This may come up
// when we add hygiene to item names.
pub fn apply_renames(renames: &RenameList, ident: Ident) -> Ident {
    renames.iter().fold(ident, |ident, &(from, to)| {
        apply_rename(from, to, ident)
    })
}

/// Fetch the SCTable from TLS, create one if it doesn't yet exist.
pub fn with_sctable<T, F>(op: F) -> T where
    F: FnOnce(&SCTable) -> T,
{
    thread_local!(static SCTABLE_KEY: SCTable = new_sctable_internal());
    SCTABLE_KEY.with(move |slot| op(slot))
}

// Make a fresh syntax context table with EmptyCtxt in slot zero.
fn new_sctable_internal() -> SCTable {
    SCTable {
        table: RefCell::new(vec![EmptyCtxt]),
        marks: RefCell::new(HashMap::new()),
        renames: RefCell::new(HashMap::new()),
    }
}

/// Print out an SCTable for debugging
pub fn display_sctable(table: &SCTable) {
    error!("SC table:");
    for (idx,val) in table.table.borrow().iter().enumerate() {
        error!("{:4} : {:?}",idx,val);
    }
}

/// Clear the tables from TLD to reclaim memory.
pub fn clear_tables() {
    with_sctable(|table| {
        *table.table.borrow_mut() = Vec::new();
        *table.marks.borrow_mut() = HashMap::new();
        *table.renames.borrow_mut() = HashMap::new();
    });
}

/// Reset the tables to their initial state
pub fn reset_tables() {
    with_sctable(|table| {
        *table.table.borrow_mut() = vec![EmptyCtxt];
        *table.marks.borrow_mut() = HashMap::new();
        *table.renames.borrow_mut() = HashMap::new();
    });
}

/// Add a value to the end of a vec, return its index
fn idx_push<T>(vec: &mut Vec<T>, val: T) -> u32 {
    vec.push(val);
    (vec.len() - 1) as u32
}

/// Resolve a syntax object to a name, per MTWT.
pub fn resolve(id: Ident) -> Name {
    with_sctable(|sctable| {
        resolve_internal(id, sctable)
    })
}

/// Resolve a syntax object to a name, per MTWT.
/// adding memoization to resolve 500+ seconds in resolve for librustc (!)
fn resolve_internal(id: Ident, table: &SCTable) -> Name {
    match table.table.borrow()[id.ctxt.0 as usize] {
        EmptyCtxt => id.name,
        // ignore marks here:
        Mark(_, subctxt) => resolve_internal(Ident::new(id.name, subctxt), table),
        Rename(name) => name,
    }
}

/// Return the outer mark for a context with a mark at the outside.
/// FAILS when outside is not a mark.
pub fn outer_mark(ctxt: SyntaxContext) -> Mrk {
    with_sctable(|sctable| {
        match (*sctable.table.borrow())[ctxt.0 as usize] {
            Mark(mrk, _) => mrk,
            _ => panic!("can't retrieve outer mark when outside is not a mark")
        }
    })
}

#[cfg(test)]
mod tests {
    use ast::{EMPTY_CTXT, Ident, Mrk, Name, SyntaxContext};
    use super::{resolve, apply_mark_internal, new_sctable_internal};
    use super::{SCTable, Mark};

    fn id(n: u32, s: SyntaxContext) -> Ident {
        Ident::new(Name(n), s)
    }

    // extend a syntax context with a sequence of marks given
    // in a vector. v[0] will be the outermost mark.
    fn unfold_marks(mrks: Vec<Mrk> , tail: SyntaxContext, table: &SCTable)
                    -> SyntaxContext {
        mrks.iter().rev().fold(tail, |tail:SyntaxContext, mrk:&Mrk|
                   {apply_mark_internal(*mrk,tail,table)})
    }

    #[test] fn unfold_marks_test() {
        let mut t = new_sctable_internal();

        assert_eq!(unfold_marks(vec!(3,7),EMPTY_CTXT,&mut t),SyntaxContext(2));
        {
            let table = t.table.borrow();
            assert!((*table)[1] == Mark(7,EMPTY_CTXT));
            assert!((*table)[2] == Mark(3,SyntaxContext(1)));
        }
    }

    #[test]
    fn mtwt_resolve_test(){
        let a = 40;
        assert_eq!(resolve(id(a,EMPTY_CTXT)),Name(a));
    }

    #[test]
    fn hashing_tests () {
        let mut t = new_sctable_internal();
        assert_eq!(apply_mark_internal(12,EMPTY_CTXT,&mut t),SyntaxContext(1));
        assert_eq!(apply_mark_internal(13,EMPTY_CTXT,&mut t),SyntaxContext(2));
        // using the same one again should result in the same index:
        assert_eq!(apply_mark_internal(12,EMPTY_CTXT,&mut t),SyntaxContext(1));
        // I'm assuming that the rename table will behave the same....
    }
}
<|endoftext|>


<commit_before>use clap::ArgMatches;
use diesel::expression::sql;
#[cfg(feature = "postgres")]
use diesel::pg::PgConnection;
#[cfg(feature = "sqlite")]
use diesel::sqlite::SqliteConnection;
use diesel::types::Bool;
use diesel::{migrations, Connection, select, LoadDsl};

use database_error::{DatabaseError, DatabaseResult};

use std::error::Error;
use std::{env, fs};

use std::path::Path;

macro_rules! call_with_conn {
    ( $database_url:ident,
      $func:path
    ) => {{
        match ::database::backend(&$database_url) {
            #[cfg(feature = "postgres")]
            "postgres" => {
                let conn = PgConnection::establish(&$database_url).unwrap();
                $func(&conn)
            },
            #[cfg(feature = "sqlite")]
            "sqlite" => {
                let conn = SqliteConnection::establish(&$database_url).unwrap();
                $func(&conn)
            },
            _ => unreachable!("The backend function should ensure we never get here."),
        }
    }};
}

pub fn reset_database(args: &ArgMatches) -> DatabaseResult<()> {
    try!(drop_database(&database_url(args)));
    setup_database(args)
}

pub fn setup_database(args: &ArgMatches) -> DatabaseResult<()> {
    let database_url = database_url(args);

    try!(create_database_if_needed(&database_url));
    create_schema_table_and_run_migrations_if_needed(&database_url)
}

pub fn drop_database_command(args: &ArgMatches) -> DatabaseResult<()> {
    drop_database(&database_url(args))
}

/// Creates the database specified in the connection url. It returns an error
/// it it was unable to create the database.
fn create_database_if_needed(database_url: &String) -> DatabaseResult<()> {
    match backend(database_url) {
        #[cfg(feature = "postgres")]
        "postgres" => {
            if PgConnection::establish(database_url).is_err() {
                let (database, postgres_url) = split_pg_connection_string(database_url);
                println!("Creating database: {}", database);
                let conn = try!(PgConnection::establish(&postgres_url));
                try!(conn.execute(&format!("CREATE DATABASE {}", database)));
            }
        },
        #[cfg(feature = "sqlite")]
        "sqlite" => {
            if !Path::new(database_url).exists() {
                println!("Creating database: {}", database_url);
                try!(SqliteConnection::establish(database_url));
            }
        },
        _ => unreachable!("The backend function should ensure we never get here."),
    }

    Ok(())
}

/// Creates the __diesel_schema_migrations table if it doesn't exist. If the
/// table didn't exist, it also runs any pending migrations. Returns a
/// `DatabaseError::ConnectionError` if it can't create the table, and exits
/// with a migration error if it can't run migrations.
fn create_schema_table_and_run_migrations_if_needed(database_url: &String)
    -> DatabaseResult<()>
{
    if !schema_table_exists(database_url).unwrap_or_else(handle_error) {
        try!(call_with_conn!(database_url, migrations::setup_database));
        call_with_conn!(database_url, migrations::run_pending_migrations).unwrap_or_else(handle_error);
    };
    Ok(())
}

/// Drops the database specified in the connection url. It returns an error
/// if it was unable to drop the database.
fn drop_database(database_url: &String) -> DatabaseResult<()> {
    match backend(database_url) {
        #[cfg(feature = "postgres")]
        "postgres" => {
            let (database, postgres_url) = split_pg_connection_string(database_url);
            println!("Dropping database: {}", database);
            let conn = try!(PgConnection::establish(&postgres_url));
            try!(conn.silence_notices(|| {
                conn.execute(&format!("DROP DATABASE IF EXISTS {}", database))
            }));
        },
        #[cfg(feature = "sqlite")]
        "sqlite" => {
            println!("Dropping database: {}", database_url);
            try!(fs::remove_file(&database_url));
        },
        _ => unreachable!("The backend function should ensure we never get here."),
    }
    Ok(())
}

/// Returns true if the '__diesel_schema_migrations' table exists in the
/// database we connect to, returns false if it does not.
pub fn schema_table_exists(database_url: &String) -> DatabaseResult<bool> {
    let result = match backend(database_url) {
        #[cfg(feature = "postgres")]
        "postgres" => {
            let conn = PgConnection::establish(database_url).unwrap();
            try!(select(sql::<Bool>("EXISTS \
                    (SELECT 1 \
                     FROM information_schema.tables \
                     WHERE table_name = '__diesel_schema_migrations')"))
                .get_result(&conn))
        },
        #[cfg(feature = "sqlite")]
        "sqlite" => {
            let conn = SqliteConnection::establish(database_url).unwrap();
            try!(select(sql::<Bool>("EXISTS \
                    (SELECT 1 \
                     FROM sqlite_master \
                     WHERE type = 'table' \
                     AND name = '__diesel_schema_migrations')"))
                .get_result(&conn))
        },
        _ => unreachable!("The backend function should ensure we never get here."),
    };
    Ok(result)
}

pub fn database_url(matches: &ArgMatches) -> String {
    matches.value_of("DATABASE_URL")
        .map(|s| s.into())
        .or(env::var("DATABASE_URL").ok())
        .unwrap_or_else(|| {
            handle_error(DatabaseError::DatabaseUrlMissing)
        })
}

/// Returns a &str representing the type of backend being used, determined
/// by the format of the database url.
pub fn backend(database_url: &String) -> &str {
    if database_url.starts_with("postgres://") || database_url.starts_with("postgresql://") {
        "postgres"
    } else {
        "sqlite"
    }
}

fn split_pg_connection_string(database_url: &String) -> (String, String) {
    let mut split: Vec<&str> = database_url.split("/").collect();
    let database = split.pop().unwrap();
    let postgres_url = format!("{}/{}", split.join("/"), "postgres");
    (database.to_owned(), postgres_url)
}

fn handle_error<E: Error, T>(error: E) -> T {
    println!("{}", error);
    ::std::process::exit(1);
}

#[cfg(test)]
mod tests {
    use super::split_pg_connection_string;

    #[test]
    fn split_pg_connection_string_returns_postgres_url_and_database() {
        let database = "database".to_owned();
        let base_url = "postgresql://localhost:5432".to_owned();
        let database_url = format!("{}/{}", base_url, database);
        let postgres_url = format!("{}/{}", base_url, "postgres");
        assert_eq!((database, postgres_url), split_pg_connection_string(&database_url));
    }

    #[test]
    fn split_pg_connection_string_handles_user_and_password() {
        let database = "database".to_owned();
        let base_url = "postgresql://user:password@localhost:5432".to_owned();
        let database_url = format!("{}/{}", base_url, database);
        let postgres_url = format!("{}/{}", base_url, "postgres");
        assert_eq!((database, postgres_url), split_pg_connection_string(&database_url));
    }
}
<commit_msg>Give an error message when an invalid PG url is given to CLI<commit_after>use clap::ArgMatches;
use diesel::expression::sql;
#[cfg(feature = "postgres")]
use diesel::pg::PgConnection;
#[cfg(feature = "sqlite")]
use diesel::sqlite::SqliteConnection;
use diesel::types::Bool;
use diesel::{migrations, Connection, select, LoadDsl};

use database_error::{DatabaseError, DatabaseResult};

use std::error::Error;
use std::{env, fs};

use std::path::Path;

macro_rules! call_with_conn {
    ( $database_url:ident,
      $func:path
    ) => {{
        match ::database::backend(&$database_url) {
            #[cfg(feature = "postgres")]
            "postgres" => {
                let conn = PgConnection::establish(&$database_url).unwrap();
                $func(&conn)
            },
            #[cfg(feature = "sqlite")]
            "sqlite" => {
                let conn = SqliteConnection::establish(&$database_url).unwrap();
                $func(&conn)
            },
            _ => unreachable!("The backend function should ensure we never get here."),
        }
    }};
}

pub fn reset_database(args: &ArgMatches) -> DatabaseResult<()> {
    try!(drop_database(&database_url(args)));
    setup_database(args)
}

pub fn setup_database(args: &ArgMatches) -> DatabaseResult<()> {
    let database_url = database_url(args);

    try!(create_database_if_needed(&database_url));
    create_schema_table_and_run_migrations_if_needed(&database_url)
}

pub fn drop_database_command(args: &ArgMatches) -> DatabaseResult<()> {
    drop_database(&database_url(args))
}

/// Creates the database specified in the connection url. It returns an error
/// it it was unable to create the database.
fn create_database_if_needed(database_url: &String) -> DatabaseResult<()> {
    match backend(database_url) {
        #[cfg(feature = "postgres")]
        "postgres" => {
            if PgConnection::establish(database_url).is_err() {
                let (database, postgres_url) = split_pg_connection_string(database_url);
                println!("Creating database: {}", database);
                let conn = try!(PgConnection::establish(&postgres_url));
                try!(conn.execute(&format!("CREATE DATABASE {}", database)));
            }
        },
        #[cfg(feature = "sqlite")]
        "sqlite" => {
            if !Path::new(database_url).exists() {
                println!("Creating database: {}", database_url);
                try!(SqliteConnection::establish(database_url));
            }
        },
        _ => unreachable!("The backend function should ensure we never get here."),
    }

    Ok(())
}

/// Creates the __diesel_schema_migrations table if it doesn't exist. If the
/// table didn't exist, it also runs any pending migrations. Returns a
/// `DatabaseError::ConnectionError` if it can't create the table, and exits
/// with a migration error if it can't run migrations.
fn create_schema_table_and_run_migrations_if_needed(database_url: &String)
    -> DatabaseResult<()>
{
    if !schema_table_exists(database_url).unwrap_or_else(handle_error) {
        try!(call_with_conn!(database_url, migrations::setup_database));
        call_with_conn!(database_url, migrations::run_pending_migrations).unwrap_or_else(handle_error);
    };
    Ok(())
}

/// Drops the database specified in the connection url. It returns an error
/// if it was unable to drop the database.
fn drop_database(database_url: &String) -> DatabaseResult<()> {
    match backend(database_url) {
        #[cfg(feature = "postgres")]
        "postgres" => {
            let (database, postgres_url) = split_pg_connection_string(database_url);
            println!("Dropping database: {}", database);
            let conn = try!(PgConnection::establish(&postgres_url));
            try!(conn.silence_notices(|| {
                conn.execute(&format!("DROP DATABASE IF EXISTS {}", database))
            }));
        },
        #[cfg(feature = "sqlite")]
        "sqlite" => {
            println!("Dropping database: {}", database_url);
            try!(fs::remove_file(&database_url));
        },
        _ => unreachable!("The backend function should ensure we never get here."),
    }
    Ok(())
}

/// Returns true if the '__diesel_schema_migrations' table exists in the
/// database we connect to, returns false if it does not.
pub fn schema_table_exists(database_url: &String) -> DatabaseResult<bool> {
    let result = match backend(database_url) {
        #[cfg(feature = "postgres")]
        "postgres" => {
            let conn = PgConnection::establish(database_url).unwrap();
            try!(select(sql::<Bool>("EXISTS \
                    (SELECT 1 \
                     FROM information_schema.tables \
                     WHERE table_name = '__diesel_schema_migrations')"))
                .get_result(&conn))
        },
        #[cfg(feature = "sqlite")]
        "sqlite" => {
            let conn = SqliteConnection::establish(database_url).unwrap();
            try!(select(sql::<Bool>("EXISTS \
                    (SELECT 1 \
                     FROM sqlite_master \
                     WHERE type = 'table' \
                     AND name = '__diesel_schema_migrations')"))
                .get_result(&conn))
        },
        _ => unreachable!("The backend function should ensure we never get here."),
    };
    Ok(result)
}

pub fn database_url(matches: &ArgMatches) -> String {
    matches.value_of("DATABASE_URL")
        .map(|s| s.into())
        .or(env::var("DATABASE_URL").ok())
        .unwrap_or_else(|| {
            handle_error(DatabaseError::DatabaseUrlMissing)
        })
}

/// Returns a &str representing the type of backend being used, determined
/// by the format of the database url.
pub fn backend(database_url: &String) -> &str {
    if database_url.starts_with("postgres://") || database_url.starts_with("postgresql://") && cfg!(feature = "postgres") {
        "postgres"
    } else if cfg!(feature = "sqlite") {
        "sqlite"
    } else {
        panic!("{:?} is not a valid PostgreSQL URL. It should start with\
                `postgres://` or `postgresql://`", database_url);
    }
}

fn split_pg_connection_string(database_url: &String) -> (String, String) {
    let mut split: Vec<&str> = database_url.split("/").collect();
    let database = split.pop().unwrap();
    let postgres_url = format!("{}/{}", split.join("/"), "postgres");
    (database.to_owned(), postgres_url)
}

fn handle_error<E: Error, T>(error: E) -> T {
    println!("{}", error);
    ::std::process::exit(1);
}

#[cfg(test)]
mod tests {
    use super::split_pg_connection_string;

    #[test]
    fn split_pg_connection_string_returns_postgres_url_and_database() {
        let database = "database".to_owned();
        let base_url = "postgresql://localhost:5432".to_owned();
        let database_url = format!("{}/{}", base_url, database);
        let postgres_url = format!("{}/{}", base_url, "postgres");
        assert_eq!((database, postgres_url), split_pg_connection_string(&database_url));
    }

    #[test]
    fn split_pg_connection_string_handles_user_and_password() {
        let database = "database".to_owned();
        let base_url = "postgresql://user:password@localhost:5432".to_owned();
        let database_url = format!("{}/{}", base_url, database);
        let postgres_url = format!("{}/{}", base_url, "postgres");
        assert_eq!((database, postgres_url), split_pg_connection_string(&database_url));
    }
}
<|endoftext|>


<commit_before><commit_msg>Underscore does not keeps the ownership<commit_after>use std::ops::Drop;

struct A;
impl Drop for A {
    fn drop(&mut self) {
        println!("drop");
    }
}

fn main() {
    println!("1");
    A;
    println!("2");
    let a = A;
    println!("3");
    let _ = A;
    println!("4");
    let _a = A;
    println!("5");
}
<|endoftext|>


<commit_before>extern crate libc;

use self::libc::{c_char, c_uchar};

/// Issues claim.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// schema_id: id of schema.
/// attributes:  all names of attributes as a byte array.
/// claim_request:
///     A claim request containing prover ID and prover-generated values as a byte array.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Returns Claim.
///
/// #Errors
/// No method specific errors.
/// See `AnoncredsError` docs for common errors description.
#[no_mangle]
pub extern fn anoncreds_create_claim(client_id: i32, command_id: i32,
                                     schema_id: *const c_char, attributes: *const c_char,
                                     claim_request: *const c_char,
                                     cb: extern fn(xcommand_id: i32, err: i32, claim: *const c_char)) {
    unimplemented!();
}

/// Creates claim request.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// schema_id: id of schema.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Claim request.
///
/// #Errors
/// No method specific errors.
/// See `AnoncredsError` docs for common errors description.
#[no_mangle]
pub extern fn anoncreds_create_claim_request(client_id: i32, command_id: i32,
                                             schema_id: *const c_char,
                                             cb: extern fn(xcommand_id: i32, err: i32,
                                                           claim_req: *const c_char)) {
    unimplemented!();
}

/// Creates proof.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// proof_input: description of a proof to be presented
///     (revealed attributes, predicates, timestamps for non-revocation).
///     For example: {
///         names:['name', 'height'],
///         predicates: [{predicate: 'gt', value: 18, attr: age}]
///     }
/// nonce: verifier's nonce.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Proof.
///
/// #Errors
/// No method specific errors.
/// See `AnoncredsError` docs for common errors description.
#[no_mangle]
pub extern fn anoncreds_create_proof(client_id: i32, command_id: i32,
                                     proof_input: *const c_char,
                                     nonce: *const c_uchar,
                                     cb: extern fn(xcommand_id: i32, err: i32,
                                                   proof: *const c_char, attrs: *const c_char)) {
    unimplemented!();
}

/// Verifies proof.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// proof_input: description of a proof to be presented
///     (revealed attributes, predicates, timestamps for non-revocation).
///     For example: {
///         names:['name', 'height'],
///         predicates: [{predicate: 'gt', value: 18, attr: age}]
///     }
/// proof: a proof.
/// revealed_attributes:
///     values of revealed attributes (initial values, non-encoded).
/// nonce: verifier's nonce.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Claim request.
///
/// #Errors
/// No method specific errors.
/// See `AnoncredsError` docs for common errors description.
#[no_mangle]
pub extern fn anoncreds_verify_proof(client_id: i32, command_id: i32,
                                     proof_input: *const c_char,
                                     proof: *const c_uchar,
                                     revealed_attributes: *const c_uchar,
                                     nonce: *const c_uchar,
                                     cb: extern fn(xcommand_id: i32, err: i32)) {
    unimplemented!();
}<commit_msg>minor changes<commit_after>extern crate libc;

use self::libc::{c_char, c_uchar};

/// Issues claim.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// schema_id: id of schema.
/// attributes:  all names of attributes as a byte array.
/// claim_request:
///     A claim request containing prover ID and prover-generated values as a byte array.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Returns Claim.
///
/// #Errors
/// No method specific errors.
/// See `AnoncredsError` docs for common errors description.
#[no_mangle]
pub extern fn anoncreds_create_claim(client_id: i32, command_id: i32,
                                     schema_id: *const c_char, attributes: *const c_char,
                                     claim_request: *const c_char,
                                     cb: extern fn(xcommand_id: i32, err: i32, claim: *const c_char)) {
    unimplemented!();
}

/// Creates claim request.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// schema_id: id of schema.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Claim request.
///
/// #Errors
/// No method specific errors.
/// See `AnoncredsError` docs for common errors description.
#[no_mangle]
pub extern fn anoncreds_create_claim_request(client_id: i32, command_id: i32,
                                             schema_id: *const c_char,
                                             cb: extern fn(xcommand_id: i32, err: i32,
                                                           claim_req: *const c_char)) {
    unimplemented!();
}

/// Creates proof.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// proof_input: description of a proof to be presented
///     (revealed attributes, predicates, timestamps for non-revocation).
///     For example: {
///         names:['name', 'height'],
///         predicates: [{predicate: 'gt', value: 18, attr: age}]
///     }
/// nonce: verifier's nonce.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Proof.
///
/// #Errors
/// No method specific errors.
/// See `AnoncredsError` docs for common errors description.
#[no_mangle]
pub extern fn anoncreds_create_proof(client_id: i32, command_id: i32,
                                     proof_input: *const c_char,
                                     nonce: *const c_uchar,
                                     cb: extern fn(xcommand_id: i32, err: i32,
                                                   proof: *const c_char, attrs: *const c_char)) {
    unimplemented!();
}

/// Verifies proof.
///
/// #Params
/// client_id: id of sovrin client instance.
/// command_id: command id to map of callback to user context.
/// proof_input: description of a proof to be presented
///     (revealed attributes, predicates, timestamps for non-revocation).
///     For example: {
///         names:['name', 'height'],
///         predicates: [{predicate: 'gt', value: 18, attr: age}]
///     }
/// proof: a proof.
/// revealed_attributes:
///     values of revealed attributes (initial values, non-encoded).
/// nonce: verifier's nonce.
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// True if verified successfully and false otherwise.
///
/// #Errors
/// No method specific errors.
/// See `AnoncredsError` docs for common errors description.
#[no_mangle]
pub extern fn anoncreds_verify_proof(client_id: i32, command_id: i32,
                                     proof_input: *const c_char,
                                     proof: *const c_uchar,
                                     revealed_attributes: *const c_uchar,
                                     nonce: *const c_uchar,
                                     cb: extern fn(xcommand_id: i32, err: i32)) {
    unimplemented!();
}<|endoftext|>


<commit_before><commit_msg>objects now update screen location when window resizes<commit_after><|endoftext|>


<commit_before><commit_msg>Further cleanup removing lines by moving the clones directly, seems like a better pattern<commit_after><|endoftext|>


<commit_before><commit_msg>letsencrypt workaround<commit_after><|endoftext|>


<commit_before><commit_msg>function finish,redirect fixed,clean code<commit_after><|endoftext|>


<commit_before><commit_msg>Move towards per-node-type rendering.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unwraps<commit_after><|endoftext|>


<commit_before><commit_msg>problem: no running status solution: display app name, version and addr<commit_after><|endoftext|>


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

use dom::bindings::codegen::Bindings::URLSearchParamsBinding;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods;
use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{StringOrURLSearchParams, eURLSearchParams, eString};
use dom::bindings::error::{Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};

use servo_util::str::DOMString;

use encoding::all::UTF_8;
use encoding::types::{EncodingRef, EncodeReplace};

use std::cell::RefCell;
use std::collections::hashmap::HashMap;
use std::fmt::radix;
use std::ascii::OwnedStrAsciiExt;

#[dom_struct]
pub struct URLSearchParams {
    data: RefCell<HashMap<DOMString, Vec<DOMString>>>,
    reflector_: Reflector,
}

impl URLSearchParams {
    fn new_inherited() -> URLSearchParams {
        URLSearchParams {
            data: RefCell::new(HashMap::new()),
            reflector_: Reflector::new(),
        }
    }

    pub fn new(global: &GlobalRef) -> Temporary<URLSearchParams> {
        reflect_dom_object(box URLSearchParams::new_inherited(), global, URLSearchParamsBinding::Wrap)
    }

    pub fn Constructor(global: &GlobalRef, init: Option<StringOrURLSearchParams>) -> Fallible<Temporary<URLSearchParams>> {
        let usp = URLSearchParams::new(global).root();
        match init {
            Some(eString(_s)) => {
                // XXXManishearth we need to parse the input here
                // http://url.spec.whatwg.org/#concept-urlencoded-parser
                // We can use rust-url's implementation here:
                // https://github.com/SimonSapin/rust-url/blob/master/form_urlencoded.rs#L29
            },
            Some(eURLSearchParams(u)) => {
                let u = u.root();
                let mut map = usp.data.borrow_mut();
                *map = u.data.borrow().clone();
            },
            None => {}
        }
        Ok(Temporary::from_rooted(*usp))
    }
}

impl<'a> URLSearchParamsMethods for JSRef<'a, URLSearchParams> {
    fn Append(self, name: DOMString, value: DOMString) {
        self.data.borrow_mut().insert_or_update_with(name, vec!(value.clone()),
                                                             |_k, v| v.push(value.clone()));
        self.update_steps();
    }

    fn Delete(self, name: DOMString) {
        self.data.borrow_mut().remove(&name);
        self.update_steps();
    }

    fn Get(self, name: DOMString) -> Option<DOMString> {
        self.data.borrow().find_equiv(&name).map(|v| v[0].clone())
    }

    fn Has(self, name: DOMString) -> bool {
        self.data.borrow().contains_key_equiv(&name)
    }

    fn Set(self, name: DOMString, value: DOMString) {
        self.data.borrow_mut().insert(name, vec!(value));
        self.update_steps();
    }
}

impl Reflectable for URLSearchParams {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        &self.reflector_
    }
}

pub trait URLSearchParamsHelpers {
    fn serialize(&self, encoding: Option<EncodingRef>) -> Vec<u8>;
    fn update_steps(&self);
}

impl URLSearchParamsHelpers for URLSearchParams {
    fn serialize(&self, encoding: Option<EncodingRef>) -> Vec<u8> {
        // http://url.spec.whatwg.org/#concept-urlencoded-serializer
        fn serialize_string(value: &DOMString, encoding: EncodingRef) -> Vec<u8> {
            // http://url.spec.whatwg.org/#concept-urlencoded-byte-serializer

            let value = value.as_slice();
            // XXXManishearth should this be a strict encoding? Can unwrap()ing the result fail?
            let value = encoding.encode(value, EncodeReplace).unwrap();
            let mut buf = vec!();
            for i in value.iter() {
                let append = match *i {
                    0x20 => vec!(0x2B),
                    0x2A | 0x2D | 0x2E |
                    0x30 .. 0x39 | 0x41 .. 0x5A |
                    0x5F | 0x61..0x7A => vec!(*i),
                    a => {
                        // http://url.spec.whatwg.org/#percent-encode
                        let mut encoded = vec!(0x25); // %
                        let s = format!("{}", radix(a, 16)).into_ascii_upper();
                        let bytes = s.as_bytes();
                        encoded.push_all(bytes);
                        encoded
                    }
                };
                buf.push_all(append.as_slice());
            }
            buf
        }
        let encoding = encoding.unwrap_or(UTF_8 as EncodingRef);
        let mut buf = vec!();
        let mut first_pair = true;
        for (k, v) in self.data.borrow().iter() {
            let name = serialize_string(k, encoding);
            for val in v.iter() {
                let value = serialize_string(val, encoding);
                if first_pair {
                    first_pair = false;
                } else {
                    buf.push(0x26); // &
                }
                buf.push_all(name.as_slice());
                buf.push(0x3D); // =
                buf.push_all(value.as_slice())
            }
        }
        buf
    }

    fn update_steps(&self) {
        // XXXManishearth Implement this when the URL interface is implemented
        // http://url.spec.whatwg.org/#concept-uq-update
    }
}
<commit_msg>Use DOMRefCell for URLSearchParams.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods;
use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{StringOrURLSearchParams, eURLSearchParams, eString};
use dom::bindings::error::{Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};

use servo_util::str::DOMString;

use encoding::all::UTF_8;
use encoding::types::{EncodingRef, EncodeReplace};

use std::collections::hashmap::HashMap;
use std::fmt::radix;
use std::ascii::OwnedStrAsciiExt;

#[dom_struct]
pub struct URLSearchParams {
    data: DOMRefCell<HashMap<DOMString, Vec<DOMString>>>,
    reflector_: Reflector,
}

impl URLSearchParams {
    fn new_inherited() -> URLSearchParams {
        URLSearchParams {
            data: DOMRefCell::new(HashMap::new()),
            reflector_: Reflector::new(),
        }
    }

    pub fn new(global: &GlobalRef) -> Temporary<URLSearchParams> {
        reflect_dom_object(box URLSearchParams::new_inherited(), global, URLSearchParamsBinding::Wrap)
    }

    pub fn Constructor(global: &GlobalRef, init: Option<StringOrURLSearchParams>) -> Fallible<Temporary<URLSearchParams>> {
        let usp = URLSearchParams::new(global).root();
        match init {
            Some(eString(_s)) => {
                // XXXManishearth we need to parse the input here
                // http://url.spec.whatwg.org/#concept-urlencoded-parser
                // We can use rust-url's implementation here:
                // https://github.com/SimonSapin/rust-url/blob/master/form_urlencoded.rs#L29
            },
            Some(eURLSearchParams(u)) => {
                let u = u.root();
                let mut map = usp.data.borrow_mut();
                *map = u.data.borrow().clone();
            },
            None => {}
        }
        Ok(Temporary::from_rooted(*usp))
    }
}

impl<'a> URLSearchParamsMethods for JSRef<'a, URLSearchParams> {
    fn Append(self, name: DOMString, value: DOMString) {
        self.data.borrow_mut().insert_or_update_with(name, vec!(value.clone()),
                                                             |_k, v| v.push(value.clone()));
        self.update_steps();
    }

    fn Delete(self, name: DOMString) {
        self.data.borrow_mut().remove(&name);
        self.update_steps();
    }

    fn Get(self, name: DOMString) -> Option<DOMString> {
        self.data.borrow().find_equiv(&name).map(|v| v[0].clone())
    }

    fn Has(self, name: DOMString) -> bool {
        self.data.borrow().contains_key_equiv(&name)
    }

    fn Set(self, name: DOMString, value: DOMString) {
        self.data.borrow_mut().insert(name, vec!(value));
        self.update_steps();
    }
}

impl Reflectable for URLSearchParams {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        &self.reflector_
    }
}

pub trait URLSearchParamsHelpers {
    fn serialize(&self, encoding: Option<EncodingRef>) -> Vec<u8>;
    fn update_steps(&self);
}

impl URLSearchParamsHelpers for URLSearchParams {
    fn serialize(&self, encoding: Option<EncodingRef>) -> Vec<u8> {
        // http://url.spec.whatwg.org/#concept-urlencoded-serializer
        fn serialize_string(value: &DOMString, encoding: EncodingRef) -> Vec<u8> {
            // http://url.spec.whatwg.org/#concept-urlencoded-byte-serializer

            let value = value.as_slice();
            // XXXManishearth should this be a strict encoding? Can unwrap()ing the result fail?
            let value = encoding.encode(value, EncodeReplace).unwrap();
            let mut buf = vec!();
            for i in value.iter() {
                let append = match *i {
                    0x20 => vec!(0x2B),
                    0x2A | 0x2D | 0x2E |
                    0x30 .. 0x39 | 0x41 .. 0x5A |
                    0x5F | 0x61..0x7A => vec!(*i),
                    a => {
                        // http://url.spec.whatwg.org/#percent-encode
                        let mut encoded = vec!(0x25); // %
                        let s = format!("{}", radix(a, 16)).into_ascii_upper();
                        let bytes = s.as_bytes();
                        encoded.push_all(bytes);
                        encoded
                    }
                };
                buf.push_all(append.as_slice());
            }
            buf
        }
        let encoding = encoding.unwrap_or(UTF_8 as EncodingRef);
        let mut buf = vec!();
        let mut first_pair = true;
        for (k, v) in self.data.borrow().iter() {
            let name = serialize_string(k, encoding);
            for val in v.iter() {
                let value = serialize_string(val, encoding);
                if first_pair {
                    first_pair = false;
                } else {
                    buf.push(0x26); // &
                }
                buf.push_all(name.as_slice());
                buf.push(0x3D); // =
                buf.push_all(value.as_slice())
            }
        }
        buf
    }

    fn update_steps(&self) {
        // XXXManishearth Implement this when the URL interface is implemented
        // http://url.spec.whatwg.org/#concept-uq-update
    }
}
<|endoftext|>


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

use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods;
use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams;
use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eURLSearchParams, eString};
use dom::bindings::error::{Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object};

use util::str::DOMString;

use encoding::all::UTF_8;
use encoding::types::{EncodingRef, EncoderTrap};

use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::fmt::radix;
use std::ascii::OwnedAsciiExt;

#[dom_struct]
pub struct URLSearchParams {
    reflector_: Reflector,
    data: DOMRefCell<HashMap<DOMString, Vec<DOMString>>>,
}

impl URLSearchParams {
    fn new_inherited() -> URLSearchParams {
        URLSearchParams {
            reflector_: Reflector::new(),
            data: DOMRefCell::new(HashMap::new()),
        }
    }

    pub fn new(global: GlobalRef) -> Temporary<URLSearchParams> {
        reflect_dom_object(box URLSearchParams::new_inherited(), global, URLSearchParamsBinding::Wrap)
    }

    pub fn Constructor(global: GlobalRef, init: Option<StringOrURLSearchParams>) -> Fallible<Temporary<URLSearchParams>> {
        let usp = URLSearchParams::new(global).root();
        match init {
            Some(eString(_s)) => {
                // XXXManishearth we need to parse the input here
                // http://url.spec.whatwg.org/#concept-urlencoded-parser
                // We can use rust-url's implementation here:
                // https://github.com/SimonSapin/rust-url/blob/master/form_urlencoded.rs#L29
            },
            Some(eURLSearchParams(u)) => {
                let u = u.root();
                let usp = usp.r();
                let mut map = usp.data.borrow_mut();
                // FIXME(https://github.com/rust-lang/rust/issues/23338)
                let r = u.r();
                let data = r.data.borrow();
                *map = data.clone();
            },
            None => {}
        }
        Ok(Temporary::from_rooted(usp.r()))
    }
}

impl<'a> URLSearchParamsMethods for JSRef<'a, URLSearchParams> {
    fn Append(self, name: DOMString, value: DOMString) {
        let mut data = self.data.borrow_mut();

        match data.entry(name) {
            Occupied(entry) => entry.into_mut().push(value),
            Vacant(entry) => {
                entry.insert(vec!(value));
            }
        }

        self.update_steps();
    }

    fn Delete(self, name: DOMString) {
        self.data.borrow_mut().remove(&name);
        self.update_steps();
    }

    fn Get(self, name: DOMString) -> Option<DOMString> {
        // FIXME(https://github.com/rust-lang/rust/issues/23338)
        let data = self.data.borrow();
        data.get(&name).map(|v| v[0].clone())
    }

    fn Has(self, name: DOMString) -> bool {
        // FIXME(https://github.com/rust-lang/rust/issues/23338)
        let data = self.data.borrow();
        data.contains_key(&name)
    }

    fn Set(self, name: DOMString, value: DOMString) {
        self.data.borrow_mut().insert(name, vec!(value));
        self.update_steps();
    }
}

pub trait URLSearchParamsHelpers {
    fn serialize(&self, encoding: Option<EncodingRef>) -> Vec<u8>;
    fn update_steps(&self);
}

impl URLSearchParamsHelpers for URLSearchParams {
    fn serialize(&self, encoding: Option<EncodingRef>) -> Vec<u8> {
        // http://url.spec.whatwg.org/#concept-urlencoded-serializer
        fn serialize_string(value: &DOMString, encoding: EncodingRef) -> Vec<u8> {
            // http://url.spec.whatwg.org/#concept-urlencoded-byte-serializer

            let value = value.as_slice();
            // XXXManishearth should this be a strict encoding? Can unwrap()ing the result fail?
            let value = encoding.encode(value, EncoderTrap::Replace).unwrap();
            let mut buf = vec!();
            for i in value.iter() {
                let append = match *i {
                    0x20 => vec!(0x2B),
                    0x2A | 0x2D | 0x2E |
                    0x30 ... 0x39 | 0x41 ... 0x5A |
                    0x5F | 0x61...0x7A => vec!(*i),
                    a => {
                        // http://url.spec.whatwg.org/#percent-encode
                        let mut encoded = vec!(0x25); // %
                        let s = format!("{}", radix(a, 16)).into_ascii_uppercase();
                        let bytes = s.as_bytes();
                        encoded.push_all(bytes);
                        encoded
                    }
                };
                buf.push_all(append.as_slice());
            }
            buf
        }
        let encoding = encoding.unwrap_or(UTF_8 as EncodingRef);
        let mut buf = vec!();
        let mut first_pair = true;
        for (k, v) in self.data.borrow().iter() {
            let name = serialize_string(k, encoding);
            for val in v.iter() {
                let value = serialize_string(val, encoding);
                if first_pair {
                    first_pair = false;
                } else {
                    buf.push(0x26); // &
                }
                buf.push_all(name.as_slice());
                buf.push(0x3D); // =
                buf.push_all(value.as_slice())
            }
        }
        buf
    }

    fn update_steps(&self) {
        // XXXManishearth Implement this when the URL interface is implemented
        // http://url.spec.whatwg.org/#concept-uq-update
    }
}
<commit_msg>dom::urlsearchparams cleanup and documentation<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods;
use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams;
use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eURLSearchParams, eString};
use dom::bindings::error::{Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object};

use util::str::DOMString;

use encoding::all::UTF_8;
use encoding::types::{EncodingRef, EncoderTrap};

use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::fmt::radix;
use std::ascii::OwnedAsciiExt;

#[dom_struct]
pub struct URLSearchParams {
    reflector_: Reflector,
    data: DOMRefCell<HashMap<DOMString, Vec<DOMString>>>,
}

impl URLSearchParams {
    fn new_inherited() -> URLSearchParams {
        URLSearchParams {
            reflector_: Reflector::new(),
            data: DOMRefCell::new(HashMap::new()),
        }
    }

    pub fn new(global: GlobalRef) -> Temporary<URLSearchParams> {
        reflect_dom_object(box URLSearchParams::new_inherited(), global,
                           URLSearchParamsBinding::Wrap)
    }

    pub fn Constructor(global: GlobalRef, init: Option<StringOrURLSearchParams>) ->
                       Fallible<Temporary<URLSearchParams>> {
        let usp = URLSearchParams::new(global).root();
        match init {
            Some(eString(_s)) => {
                // XXXManishearth we need to parse the input here
                // http://url.spec.whatwg.org/#concept-urlencoded-parser
                // We can use rust-url's implementation here:
                // https://github.com/SimonSapin/rust-url/blob/master/form_urlencoded.rs#L29
            },
            Some(eURLSearchParams(u)) => {
                let u = u.root();
                let usp = usp.r();
                let mut map = usp.data.borrow_mut();
                // FIXME(https://github.com/rust-lang/rust/issues/23338)
                let r = u.r();
                let data = r.data.borrow();
                *map = data.clone();
            },
            None => {}
        }
        Ok(Temporary::from_rooted(usp.r()))
    }
}

impl<'a> URLSearchParamsMethods for JSRef<'a, URLSearchParams> {
    fn Append(self, name: DOMString, value: DOMString) {
        let mut data = self.data.borrow_mut();

        match data.entry(name) {
            Occupied(entry) => entry.into_mut().push(value),
            Vacant(entry) => {
                entry.insert(vec!(value));
            }
        }

        self.update_steps();
    }

    fn Delete(self, name: DOMString) {
        self.data.borrow_mut().remove(&name);
        self.update_steps();
    }

    fn Get(self, name: DOMString) -> Option<DOMString> {
        // FIXME(https://github.com/rust-lang/rust/issues/23338)
        let data = self.data.borrow();
        data.get(&name).map(|v| v[0].clone())
    }

    fn Has(self, name: DOMString) -> bool {
        // FIXME(https://github.com/rust-lang/rust/issues/23338)
        let data = self.data.borrow();
        data.contains_key(&name)
    }

    fn Set(self, name: DOMString, value: DOMString) {
        self.data.borrow_mut().insert(name, vec!(value));
        self.update_steps();
    }
}

pub trait URLSearchParamsHelpers {
    fn serialize(&self, encoding: Option<EncodingRef>) -> Vec<u8>;
    fn update_steps(&self);
}

impl URLSearchParamsHelpers for URLSearchParams {
    fn serialize(&self, encoding: Option<EncodingRef>) -> Vec<u8> {
        // http://url.spec.whatwg.org/#concept-urlencoded-serializer
        fn serialize_string(value: &DOMString, encoding: EncodingRef) -> Vec<u8> {
            // http://url.spec.whatwg.org/#concept-urlencoded-byte-serializer

            let value = value.as_slice();
            // XXXManishearth should this be a strict encoding? Can unwrap()ing the result fail?
            let value = encoding.encode(value, EncoderTrap::Replace).unwrap();

            // Step 1.
            let mut buf = vec!();

            // Step 2.
            for i in &value {
                let append = match *i {
                    // Convert spaces:
                    // ' ' => '+'
                    0x20 => vec!(0x2B),

                    // Retain the following characters:
                    // '*', '-', '.', '0'...'9', 'A'...'Z', '_', 'a'...'z'
                    0x2A | 0x2D | 0x2E | 0x30...0x39 |
                        0x41...0x5A | 0x5F | 0x61...0x7A => vec!(*i),

                    // Encode everything else using 'percented-encoded bytes'
                    // http://url.spec.whatwg.org/#percent-encode
                    a => {
                        let mut encoded = vec!(0x25); // %
                        let s = format!("{}", radix(a, 16)).into_ascii_uppercase();
                        let bytes = s.as_bytes();
                        encoded.push_all(bytes);
                        encoded
                    }
                };
                buf.push_all(&append);
            }

            // Step 3.
            buf
        }
        let encoding = encoding.unwrap_or(UTF_8 as EncodingRef);
        let mut buf = vec!();
        let mut first_pair = true;
        for (k, v) in self.data.borrow().iter() {
            let name = serialize_string(k, encoding);
            for val in v {
                let value = serialize_string(val, encoding);
                if first_pair {
                    first_pair = false;
                } else {
                    buf.push(0x26); // &
                }
                buf.push_all(&name);
                buf.push(0x3D); // =
                buf.push_all(&value)
            }
        }
        buf
    }

    fn update_steps(&self) {
        // XXXManishearth Implement this when the URL interface is implemented
        // http://url.spec.whatwg.org/#concept-uq-update
    }
}
<|endoftext|>


<commit_before><commit_msg>Derive Copy for suitable types<commit_after><|endoftext|>


<commit_before><commit_msg>Add Sudodu solver in Rust<commit_after>const N: usize = 9;
const UNASSIGNED: u8 = 0;

type Board = [[u8; N]; N];

fn solve_sudoku(grid: &mut Board) -> bool {
    let row;
    let col;

    if let Some((r, c)) = find_unassigned_cells(&grid) {
        row = r;
        col = c;
    } else {
        // SOLVED
        return true;
    }
    for num in 1..=9 {
        if is_safe(&grid, row, col, num) {
            grid[row][col] = num;

            if solve_sudoku(grid) {
                return true;
            }

            // Failed, try again
            grid[row][col] = UNASSIGNED;
        }
    }
    false
}

fn used_in_row(grid: &Board, row: usize, num: u8) -> bool {
    for col in 0..N {
        if grid[row][col] == num {
            return true;
        }
    }
    false
}

fn used_in_col(grid: &Board, col: usize, num: u8) -> bool {
    for row in grid.iter().take(N) {
        if row[col] == num {
            return true;
        }
    }
    false
}

fn used_in_box(grid: &Board, row_start: usize, col_start: usize, num: u8) -> bool {
    for row in 0..3 {
        for col in 0..3 {
            if grid[row + row_start][col + col_start] == num {
                return true;
            }
        }
    }
    false
}

fn is_safe(grid: &Board, row: usize, col: usize, num: u8) -> bool {
    !used_in_row(grid, row, num)
        && !used_in_col(grid, col, num)
        && !used_in_box(grid, row - (row % 3), col - (col % 3), num)
}

fn find_unassigned_cells(grid: &Board) -> Option<(usize, usize)> {
    for (row, _) in grid.iter().enumerate().take(N) {
        for col in 0..N {
            if grid[row][col] == UNASSIGNED {
                return Some((row, col));
            }
        }
    }
    None
}

fn print_grid(grid: &Board) {
    for row in grid.iter().take(N) {
        for col in 0..N {
            print!("{}  ", row[col]);
        }
        println!();
    }
}

fn main() {
    let mut board = [
        [3, 0, 6, 5, 0, 8, 4, 0, 0],
        [5, 2, 0, 0, 0, 0, 0, 0, 0],
        [0, 8, 7, 0, 0, 0, 0, 3, 1],
        [0, 0, 3, 0, 1, 0, 0, 8, 0],
        [9, 0, 0, 8, 6, 3, 0, 0, 5],
        [0, 5, 0, 0, 9, 0, 6, 0, 0],
        [1, 3, 0, 0, 0, 0, 2, 5, 0],
        [0, 0, 0, 0, 0, 0, 0, 7, 4],
        [0, 0, 5, 2, 0, 6, 3, 0, 0],
    ];
    if solve_sudoku(&mut board) {
        print_grid(&board);
    } else {
        println!("Cant Solve");
    }
}

#[test]
fn test1() {
    let mut board = [
        [3, 0, 6, 5, 0, 8, 4, 0, 0],
        [5, 2, 0, 0, 0, 0, 0, 0, 0],
        [0, 8, 7, 0, 0, 0, 0, 3, 1],
        [0, 0, 3, 0, 1, 0, 0, 8, 0],
        [9, 0, 0, 8, 6, 3, 0, 0, 5],
        [0, 5, 0, 0, 9, 0, 6, 0, 0],
        [1, 3, 0, 0, 0, 0, 2, 5, 0],
        [0, 0, 0, 0, 0, 0, 0, 7, 4],
        [0, 0, 5, 2, 0, 6, 3, 0, 0],
    ];
    // Can solve
    assert!(solve_sudoku(&mut board));
    let solved_board = [
        [3, 1, 6, 5, 7, 8, 4, 9, 2],
        [5, 2, 9, 1, 3, 4, 7, 6, 8],
        [4, 8, 7, 6, 2, 9, 5, 3, 1],
        [2, 6, 3, 4, 1, 5, 9, 8, 7],
        [9, 7, 4, 8, 6, 3, 1, 2, 5],
        [8, 5, 1, 7, 9, 2, 6, 4, 3],
        [1, 3, 8, 9, 4, 7, 2, 5, 6],
        [6, 9, 2, 3, 5, 1, 8, 7, 4],
        [7, 4, 5, 2, 8, 6, 3, 1, 9],
    ];
    assert_eq!(board, solved_board)
}

#[test]
fn test2() {
    let mut board = [
        [2, 0, 0, 9, 0, 0, 1, 0, 0],
        [6, 0, 0, 0, 5, 1, 0, 0, 0],
        [0, 9, 5, 2, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 2, 0, 0],
        [5, 0, 9, 1, 0, 2, 4, 0, 3],
        [0, 0, 8, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 5, 6, 3, 0],
        [0, 0, 0, 4, 6, 0, 0, 0, 9],
        [0, 0, 3, 0, 0, 9, 0, 0, 2],
    ];
    // Can solve
    assert!(solve_sudoku(&mut board));
    let solved = [
        [2, 3, 4, 9, 7, 6, 1, 8, 5],
        [6, 8, 7, 3, 5, 1, 9, 2, 4],
        [1, 9, 5, 2, 4, 8, 3, 7, 6],
        [4, 1, 6, 5, 3, 7, 2, 9, 8],
        [5, 7, 9, 1, 8, 2, 4, 6, 3],
        [3, 2, 8, 6, 9, 4, 7, 5, 1],
        [9, 4, 1, 8, 2, 5, 6, 3, 7],
        [7, 5, 2, 4, 6, 3, 8, 1, 9],
        [8, 6, 3, 7, 1, 9, 5, 4, 2],
    ];
    assert_eq!(board, solved);
}
<|endoftext|>


<commit_before><commit_msg>style(tmux/pane): Remove spacing<commit_after><|endoftext|>


<commit_before><commit_msg>Clean up from_iter call<commit_after><|endoftext|>


<commit_before><commit_msg>mvar stuff<commit_after>use std;

// TODO: Return any PoisonErrors.

pub struct T<X> {
  full: std::sync::Condvar,
  data: std::sync::Mutex<Option<X>>,
}

unsafe impl<X> Send for T<X> {}
unsafe impl<X> Sync for T<X> {}

pub fn new<X>() -> T<X> {
  T {
    full: std::sync::Condvar::new(),
    data: std::sync::Mutex::new(None),
  }
}

impl<X> T<X> {
  pub fn overwrite(&self, val: X) {
    let mut data = self.data.lock().unwrap();
    *data = Some(val);
    self.full.notify_one();
  }

  pub fn take(&self) -> X {
    let mut data = self.data.lock().unwrap();
    loop {
      data = self.full.wait(data).unwrap();

      let mut r = None;
      std::mem::swap(&mut r, &mut *data);
      match r {
        None => {},
        Some(r) => return r,
      }
    }
  }
}
<|endoftext|>


<commit_before>use std::path::{Path, PathBuf, Component};
use std::error::Error;
use std::fs::{self, metadata, File};

/// This is copied from the rust source code until Path_ Ext stabilizes.
/// You can use it, but be aware that it will be removed when those features go to rust stable
pub trait PathExt {
    fn exists(&self) -> bool;
    fn is_file(&self) -> bool;
    fn is_dir(&self) -> bool;
}

impl PathExt for Path {
    fn exists(&self) -> bool {
        metadata(self).is_ok()
    }

    fn is_file(&self) -> bool {
       metadata(self).map(|s| s.is_file()).unwrap_or(false)
    }

    fn is_dir(&self) -> bool {
       metadata(self).map(|s| s.is_dir()).unwrap_or(false)
    }
}

/// Takes a path and returns a path containing just enough `../` to point to the root of the given path.
///
/// This is mostly interesting for a relative path to point back to the directory from where the
/// path starts.
///
/// ```ignore
/// let mut path = Path::new("some/relative/path");
///
/// println!("{}", path_to_root(&path));
/// ```
///
/// **Outputs**
///
/// ```text
/// "../../"
/// ```
///
/// **note:** it's not very fool-proof, if you find a situation where it doesn't return the correct
/// path. Consider [submitting a new issue](https://github.com/azerupi/mdBook/issues) or a
/// [pull-request](https://github.com/azerupi/mdBook/pulls) to improve it.

pub fn path_to_root(path: &Path) -> String {
    debug!("[fn]: path_to_root");
    // Remove filename and add "../" for every directory

    path.to_path_buf().parent().expect("")
        .components().fold(String::new(), |mut s, c| {
            match c {
                Component::Normal(_) => s.push_str("../"),
                _ => {
                    debug!("[*]: Other path component... {:?}", c);
                }
            }
            s
        })
}

/// This function checks for every component in a path if the directory exists,
/// if it does not it is created.

pub fn create_path(path: &Path) -> Result<(), Box<Error>> {
    debug!("[fn]: create_path");

    // Create directories if they do not exist
    let mut constructed_path = PathBuf::new();

    for component in path.components() {

        let dir;
        match component {
            Component::Normal(_) => { dir = PathBuf::from(component.as_os_str()); },
            Component::RootDir => {
                debug!("[*]: Root directory");
                // This doesn't look very compatible with Windows...
                constructed_path.push("/");
                continue
            },
            _ => continue,
        }

        constructed_path.push(&dir);
        debug!("[*]: {:?}", constructed_path);

        if !constructed_path.exists() || !constructed_path.is_dir() {
            try!(fs::create_dir(&constructed_path));
            debug!("[*]: Directory created {:?}", constructed_path);
        } else {
            debug!("[*]: Directory exists {:?}", constructed_path);
            continue
        }

    }

    debug!("[*]: Constructed path: {:?}", constructed_path);

    Ok(())
}

/// This function creates a file and returns it. But before creating the file it checks every
/// directory in the path to see if it exists, and if it does not it will be created.

pub fn create_file(path: &Path) -> Result<File, Box<Error>> {
    debug!("[fn]: create_file");

    // Construct path
    if let Some(p) = path.parent() {
        try!(create_path(p));
    }

    debug!("[*]: Create file: {:?}", path);
    let f = try!(File::create(path));

    Ok(f)
}

/// Removes all the content of a directory but not the directory itself

pub fn remove_dir_content(dir: &Path) -> Result<(), Box<Error>> {
    for item in try!(fs::read_dir(dir)) {
        if let Ok(item) = item {
            let item = item.path();
            if item.is_dir() { try!(fs::remove_dir_all(item)); } else { try!(fs::remove_file(item)); }
        }
    }
    Ok(())
}

/// **Untested!**
///
/// Copies all files of a directory to another one except the files with the extensions given in the
/// `ext_blacklist` array

pub fn copy_files_except_ext(from: &Path, to: &Path, recursive: bool, ext_blacklist: &[&str]) -> Result<(), Box<Error>> {
    debug!("[fn] copy_files_except_ext");
    // Check that from and to are different
    if from == to { return Ok(()) }
    debug!("[*] Loop");
    for entry in try!(fs::read_dir(from)) {
        let entry = try!(entry);
        debug!("[*] {:?}", entry.path());
        let metadata = try!(entry.metadata());

        // If the entry is a dir and the recursive option is enabled, call itself
        if metadata.is_dir() && recursive {
            if entry.path() == to.to_path_buf() { continue }
            debug!("[*] is dir");
            try!(fs::create_dir(&to.join(entry.file_name())));
            try!(copy_files_except_ext(
                &from.join(entry.file_name()),
                &to.join(entry.file_name()),
                true,
                ext_blacklist
            ));
        } else if metadata.is_file() {

            // Check if it is in the blacklist
            if let Some(ext) = entry.path().extension() {
                if ext_blacklist.contains(&ext.to_str().unwrap()) { continue }
                debug!("[*] creating path for file: {:?}", &to.join(entry.path().file_name().expect("a file should have a file name...")));
                //try!(create_path(&to.join(entry.path())));
                output!("[*] copying file: {:?}\n    to {:?}", entry.path(), &to.join(entry.path().file_name().expect("a file should have a file name...")));
                try!(fs::copy(entry.path(), &to.join(entry.path().file_name().expect("a file should have a file name..."))));
            }
        }
    }
    Ok(())
}

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------

// tests

#[cfg(test)]
mod tests {
    extern crate tempdir;

    use super::copy_files_except_ext;
    use super::PathExt;
    use std::fs;

    #[test]
    fn copy_files_except_ext_test() {
        let tmp = match tempdir::TempDir::new("") {
            Ok(t) => t,
            Err(_) => panic!("Could not create a temp dir"),
        };

        // Create a couple of files
        if let Err(_) =  fs::File::create(&tmp.path().join("file.txt")) { panic!("Could not create file.txt") }
        if let Err(_) =  fs::File::create(&tmp.path().join("file.md")) { panic!("Could not create file.md") }
        if let Err(_) =  fs::File::create(&tmp.path().join("file.png")) { panic!("Could not create file.png") }
        if let Err(_) =  fs::create_dir(&tmp.path().join("sub_dir")) { panic!("Could not create sub_dir") }
        if let Err(_) =  fs::File::create(&tmp.path().join("sub_dir/file.png")) { panic!("Could not create sub_dir/file.png") }

        // Create output dir
        if let Err(_) =  fs::create_dir(&tmp.path().join("output")) { panic!("Could not create output") }

        match copy_files_except_ext(&tmp.path(), &tmp.path().join("output"), true, &["md"]) {
            Err(e) => panic!("Error while executing the function:\n{:?}", e),
            Ok(_) => {},
        }

        // Check if the correct files where created
        if !(&tmp.path().join("output/file.txt")).exists() { panic!("output/file.txt should exist") }
        if (&tmp.path().join("output/file.md")).exists() { panic!("output/file.md should not exist") }
        if !(&tmp.path().join("output/file.png")).exists() { panic!("output/file.png should exist") }
        if !(&tmp.path().join("output/sub_dir/file.png")).exists() { panic!("output/sub_dir/file.png should exist") }

    }
}
<commit_msg>Fixed the error in copy_files_except_ext #55<commit_after>use std::path::{Path, PathBuf, Component};
use std::error::Error;
use std::fs::{self, metadata, File};

/// This is copied from the rust source code until Path_ Ext stabilizes.
/// You can use it, but be aware that it will be removed when those features go to rust stable
pub trait PathExt {
    fn exists(&self) -> bool;
    fn is_file(&self) -> bool;
    fn is_dir(&self) -> bool;
}

impl PathExt for Path {
    fn exists(&self) -> bool {
        metadata(self).is_ok()
    }

    fn is_file(&self) -> bool {
       metadata(self).map(|s| s.is_file()).unwrap_or(false)
    }

    fn is_dir(&self) -> bool {
       metadata(self).map(|s| s.is_dir()).unwrap_or(false)
    }
}

/// Takes a path and returns a path containing just enough `../` to point to the root of the given path.
///
/// This is mostly interesting for a relative path to point back to the directory from where the
/// path starts.
///
/// ```ignore
/// let mut path = Path::new("some/relative/path");
///
/// println!("{}", path_to_root(&path));
/// ```
///
/// **Outputs**
///
/// ```text
/// "../../"
/// ```
///
/// **note:** it's not very fool-proof, if you find a situation where it doesn't return the correct
/// path. Consider [submitting a new issue](https://github.com/azerupi/mdBook/issues) or a
/// [pull-request](https://github.com/azerupi/mdBook/pulls) to improve it.

pub fn path_to_root(path: &Path) -> String {
    debug!("[fn]: path_to_root");
    // Remove filename and add "../" for every directory

    path.to_path_buf().parent().expect("")
        .components().fold(String::new(), |mut s, c| {
            match c {
                Component::Normal(_) => s.push_str("../"),
                _ => {
                    debug!("[*]: Other path component... {:?}", c);
                }
            }
            s
        })
}

/// This function checks for every component in a path if the directory exists,
/// if it does not it is created.

pub fn create_path(path: &Path) -> Result<(), Box<Error>> {
    debug!("[fn]: create_path");

    // Create directories if they do not exist
    let mut constructed_path = PathBuf::new();

    for component in path.components() {

        let dir;
        match component {
            Component::Normal(_) => { dir = PathBuf::from(component.as_os_str()); },
            Component::RootDir => {
                debug!("[*]: Root directory");
                // This doesn't look very compatible with Windows...
                constructed_path.push("/");
                continue
            },
            _ => continue,
        }

        constructed_path.push(&dir);
        debug!("[*]: {:?}", constructed_path);

        if !constructed_path.exists() || !constructed_path.is_dir() {
            try!(fs::create_dir(&constructed_path));
            debug!("[*]: Directory created {:?}", constructed_path);
        } else {
            debug!("[*]: Directory exists {:?}", constructed_path);
            continue
        }

    }

    debug!("[*]: Constructed path: {:?}", constructed_path);

    Ok(())
}

/// This function creates a file and returns it. But before creating the file it checks every
/// directory in the path to see if it exists, and if it does not it will be created.

pub fn create_file(path: &Path) -> Result<File, Box<Error>> {
    debug!("[fn]: create_file");

    // Construct path
    if let Some(p) = path.parent() {
        try!(create_path(p));
    }

    debug!("[*]: Create file: {:?}", path);
    let f = try!(File::create(path));

    Ok(f)
}

/// Removes all the content of a directory but not the directory itself

pub fn remove_dir_content(dir: &Path) -> Result<(), Box<Error>> {
    for item in try!(fs::read_dir(dir)) {
        if let Ok(item) = item {
            let item = item.path();
            if item.is_dir() { try!(fs::remove_dir_all(item)); } else { try!(fs::remove_file(item)); }
        }
    }
    Ok(())
}

/// **Untested!**
///
/// Copies all files of a directory to another one except the files with the extensions given in the
/// `ext_blacklist` array

pub fn copy_files_except_ext(from: &Path, to: &Path, recursive: bool, ext_blacklist: &[&str]) -> Result<(), Box<Error>> {
    debug!("[fn] copy_files_except_ext");
    // Check that from and to are different
    if from == to { return Ok(()) }
    debug!("[*] Loop");
    for entry in try!(fs::read_dir(from)) {
        let entry = try!(entry);
        debug!("[*] {:?}", entry.path());
        let metadata = try!(entry.metadata());

        // If the entry is a dir and the recursive option is enabled, call itself
        if metadata.is_dir() && recursive {
            if entry.path() == to.to_path_buf() { continue }
            debug!("[*] is dir");

            // check if output dir already exists
            if !to.join(entry.file_name()).exists() {
                try!(fs::create_dir(&to.join(entry.file_name())));
            }

            try!(copy_files_except_ext(
                &from.join(entry.file_name()),
                &to.join(entry.file_name()),
                true,
                ext_blacklist
            ));
        } else if metadata.is_file() {

            // Check if it is in the blacklist
            if let Some(ext) = entry.path().extension() {
                if ext_blacklist.contains(&ext.to_str().unwrap()) { continue }
                debug!("[*] creating path for file: {:?}", &to.join(entry.path().file_name().expect("a file should have a file name...")));
                //try!(create_path(&to.join(entry.path())));
                output!("[*] copying file: {:?}\n    to {:?}", entry.path(), &to.join(entry.path().file_name().expect("a file should have a file name...")));
                try!(fs::copy(entry.path(), &to.join(entry.path().file_name().expect("a file should have a file name..."))));
            }
        }
    }
    Ok(())
}

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------

// tests

#[cfg(test)]
mod tests {
    extern crate tempdir;

    use super::copy_files_except_ext;
    use super::PathExt;
    use std::fs;

    #[test]
    fn copy_files_except_ext_test() {
        let tmp = match tempdir::TempDir::new("") {
            Ok(t) => t,
            Err(_) => panic!("Could not create a temp dir"),
        };

        // Create a couple of files
        if let Err(_) =  fs::File::create(&tmp.path().join("file.txt")) { panic!("Could not create file.txt") }
        if let Err(_) =  fs::File::create(&tmp.path().join("file.md")) { panic!("Could not create file.md") }
        if let Err(_) =  fs::File::create(&tmp.path().join("file.png")) { panic!("Could not create file.png") }
        if let Err(_) =  fs::create_dir(&tmp.path().join("sub_dir")) { panic!("Could not create sub_dir") }
        if let Err(_) =  fs::File::create(&tmp.path().join("sub_dir/file.png")) { panic!("Could not create sub_dir/file.png") }

        // Create output dir
        if let Err(_) =  fs::create_dir(&tmp.path().join("output")) { panic!("Could not create output") }

        match copy_files_except_ext(&tmp.path(), &tmp.path().join("output"), true, &["md"]) {
            Err(e) => panic!("Error while executing the function:\n{:?}", e),
            Ok(_) => {},
        }

        // Check if the correct files where created
        if !(&tmp.path().join("output/file.txt")).exists() { panic!("output/file.txt should exist") }
        if (&tmp.path().join("output/file.md")).exists() { panic!("output/file.md should not exist") }
        if !(&tmp.path().join("output/file.png")).exists() { panic!("output/file.png should exist") }
        if !(&tmp.path().join("output/sub_dir/file.png")).exists() { panic!("output/sub_dir/file.png should exist") }

    }
}
<|endoftext|>


<commit_before><commit_msg>Add a driver for builtin LED<commit_after>use sysctl;
use gpio;

pub const RED: u32 = gpio::PIN1;
pub const BLUE: u32 = gpio::PIN2;
pub const GREEN: u32 = gpio::PIN3;

pub fn led_init()
{
    sysctl::peripheral_enable(sysctl::SYSCTL_PERIPH_GPIOF);
    gpio::make_output(gpio::PORTF_BASE, RED + BLUE + GREEN);
}

pub fn set_red(state: bool) {
    let value = if state { RED } else { 0 };
    gpio::write(gpio::PORTF_BASE, RED, value);
}

pub fn set_blue(state: bool) {
    let value = if state { BLUE } else { 0 };
    gpio::write(gpio::PORTF_BASE, BLUE, value);
}

<|endoftext|>