<commit_before>// Copyright 2013-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.

//! Collection types.
//!
//! See [std::collections](../std/collections) for a detailed discussion of collections in Rust.

#![crate_name = "collections"]
#![unstable(feature = "collections")]
#![staged_api]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
       html_root_url = "http://doc.rust-lang.org/nightly/",
       html_playground_url = "http://play.rust-lang.org/")]

#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core)]
#![feature(hash)]
#![feature(staged_api)]
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unsafe_destructor, slicing_syntax)]
#![cfg_attr(test, feature(test))]
#![cfg_attr(test, allow(deprecated))] // rand

#![no_std]

#[macro_use]
extern crate core;

extern crate unicode;
extern crate alloc;

#[cfg(test)] extern crate test;
#[cfg(test)] #[macro_use] extern crate std;
#[cfg(test)] #[macro_use] extern crate log;

pub use binary_heap::BinaryHeap;
pub use bitv::Bitv;
pub use bitv_set::BitvSet;
pub use btree_map::BTreeMap;
pub use btree_set::BTreeSet;
pub use dlist::DList;
pub use enum_set::EnumSet;
pub use ring_buf::RingBuf;
pub use string::String;
pub use vec::Vec;
pub use vec_map::VecMap;

// Needed for the vec! macro
pub use alloc::boxed;

#[macro_use]
mod macros;

pub mod binary_heap;
mod bit;
mod btree;
pub mod dlist;
pub mod enum_set;
pub mod ring_buf;
pub mod slice;
pub mod str;
pub mod string;
pub mod vec;
pub mod vec_map;

#[unstable(feature = "collections",
           reason = "RFC 509")]
pub mod bitv {
    pub use bit::{Bitv, Iter};
}

#[unstable(feature = "collections",
           reason = "RFC 509")]
pub mod bitv_set {
    pub use bit::{BitvSet, Union, Intersection, Difference, SymmetricDifference};
    pub use bit::SetIter as Iter;
}

#[stable(feature = "rust1", since = "1.0.0")]
pub mod btree_map {
    pub use btree::map::*;
}

#[stable(feature = "rust1", since = "1.0.0")]
pub mod btree_set {
    pub use btree::set::*;
}

#[cfg(test)] mod bench;

// FIXME(#14344) this shouldn't be necessary
#[doc(hidden)]
pub fn fixme_14344_be_sure_to_link_to_collections() {}

#[cfg(not(test))]
mod std {
    pub use core::fmt;      // necessary for panic!()
    pub use core::option;   // necessary for panic!()
    pub use core::clone;    // derive(Clone)
    pub use core::cmp;      // derive(Eq, Ord, etc.)
    pub use core::marker;   // derive(Copy)
    pub use core::hash;     // derive(Hash)
    pub use core::ops;      // RangeFull
    // for-loops
    pub use core::iter;
}

#[cfg(test)]
mod prelude {
    // from core.
    pub use core::borrow::IntoCow;
    pub use core::clone::Clone;
    pub use core::cmp::{PartialEq, Eq, PartialOrd, Ord};
    pub use core::cmp::Ordering::{Less, Equal, Greater};
    pub use core::iter::range;
    pub use core::iter::{FromIterator, Extend, IteratorExt};
    pub use core::iter::{Iterator, DoubleEndedIterator, RandomAccessIterator};
    pub use core::iter::{ExactSizeIterator};
    pub use core::marker::{Copy, Send, Sized, Sync};
    pub use core::mem::drop;
    pub use core::ops::{Drop, Fn, FnMut, FnOnce};
    pub use core::option::Option;
    pub use core::option::Option::{Some, None};
    pub use core::ptr::PtrExt;
    pub use core::result::Result;
    pub use core::result::Result::{Ok, Err};

    // in core and collections (may differ).
    pub use slice::{AsSlice, SliceExt};
    pub use str::{Str, StrExt};

    // from other crates.
    pub use alloc::boxed::Box;
    pub use unicode::char::CharExt;

    // from collections.
    pub use slice::SliceConcatExt;
    pub use string::{String, ToString};
    pub use vec::Vec;
}

/// An endpoint of a range of keys.
pub enum Bound<T> {
    /// An inclusive bound.
    Included(T),
    /// An exclusive bound.
    Excluded(T),
    /// An infinite endpoint. Indicates that there is no bound in this direction.
    Unbounded,
}
<commit_msg>add missing features to libcollections tests<commit_after>// Copyright 2013-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.

//! Collection types.
//!
//! See [std::collections](../std/collections) for a detailed discussion of collections in Rust.

#![crate_name = "collections"]
#![unstable(feature = "collections")]
#![staged_api]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
       html_root_url = "http://doc.rust-lang.org/nightly/",
       html_playground_url = "http://play.rust-lang.org/")]

#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core)]
#![feature(hash)]
#![feature(staged_api)]
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unsafe_destructor, slicing_syntax)]
#![cfg_attr(test, feature(rand, rustc_private, test))]
#![cfg_attr(test, allow(deprecated))] // rand

#![no_std]

#[macro_use]
extern crate core;

extern crate unicode;
extern crate alloc;

#[cfg(test)] extern crate test;
#[cfg(test)] #[macro_use] extern crate std;
#[cfg(test)] #[macro_use] extern crate log;

pub use binary_heap::BinaryHeap;
pub use bitv::Bitv;
pub use bitv_set::BitvSet;
pub use btree_map::BTreeMap;
pub use btree_set::BTreeSet;
pub use dlist::DList;
pub use enum_set::EnumSet;
pub use ring_buf::RingBuf;
pub use string::String;
pub use vec::Vec;
pub use vec_map::VecMap;

// Needed for the vec! macro
pub use alloc::boxed;

#[macro_use]
mod macros;

pub mod binary_heap;
mod bit;
mod btree;
pub mod dlist;
pub mod enum_set;
pub mod ring_buf;
pub mod slice;
pub mod str;
pub mod string;
pub mod vec;
pub mod vec_map;

#[unstable(feature = "collections",
           reason = "RFC 509")]
pub mod bitv {
    pub use bit::{Bitv, Iter};
}

#[unstable(feature = "collections",
           reason = "RFC 509")]
pub mod bitv_set {
    pub use bit::{BitvSet, Union, Intersection, Difference, SymmetricDifference};
    pub use bit::SetIter as Iter;
}

#[stable(feature = "rust1", since = "1.0.0")]
pub mod btree_map {
    pub use btree::map::*;
}

#[stable(feature = "rust1", since = "1.0.0")]
pub mod btree_set {
    pub use btree::set::*;
}

#[cfg(test)] mod bench;

// FIXME(#14344) this shouldn't be necessary
#[doc(hidden)]
pub fn fixme_14344_be_sure_to_link_to_collections() {}

#[cfg(not(test))]
mod std {
    pub use core::fmt;      // necessary for panic!()
    pub use core::option;   // necessary for panic!()
    pub use core::clone;    // derive(Clone)
    pub use core::cmp;      // derive(Eq, Ord, etc.)
    pub use core::marker;   // derive(Copy)
    pub use core::hash;     // derive(Hash)
    pub use core::ops;      // RangeFull
    // for-loops
    pub use core::iter;
}

#[cfg(test)]
mod prelude {
    // from core.
    pub use core::borrow::IntoCow;
    pub use core::clone::Clone;
    pub use core::cmp::{PartialEq, Eq, PartialOrd, Ord};
    pub use core::cmp::Ordering::{Less, Equal, Greater};
    pub use core::iter::range;
    pub use core::iter::{FromIterator, Extend, IteratorExt};
    pub use core::iter::{Iterator, DoubleEndedIterator, RandomAccessIterator};
    pub use core::iter::{ExactSizeIterator};
    pub use core::marker::{Copy, Send, Sized, Sync};
    pub use core::mem::drop;
    pub use core::ops::{Drop, Fn, FnMut, FnOnce};
    pub use core::option::Option;
    pub use core::option::Option::{Some, None};
    pub use core::ptr::PtrExt;
    pub use core::result::Result;
    pub use core::result::Result::{Ok, Err};

    // in core and collections (may differ).
    pub use slice::{AsSlice, SliceExt};
    pub use str::{Str, StrExt};

    // from other crates.
    pub use alloc::boxed::Box;
    pub use unicode::char::CharExt;

    // from collections.
    pub use slice::SliceConcatExt;
    pub use string::{String, ToString};
    pub use vec::Vec;
}

/// An endpoint of a range of keys.
pub enum Bound<T> {
    /// An inclusive bound.
    Included(T),
    /// An exclusive bound.
    Excluded(T),
    /// An infinite endpoint. Indicates that there is no bound in this direction.
    Unbounded,
}
<|endoftext|>


<commit_before><commit_msg>Spliting page method allocating page part<commit_after><|endoftext|>


<commit_before><commit_msg>Add comments; implement final Cont-free machine<commit_after><|endoftext|>


<commit_before><commit_msg>Doc tests got complexified. Undo it.<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for #29988<commit_after>// compile-flags: -C no-prepopulate-passes
// Regression test for #29988

#[repr(C)]
struct S {
    f1: i32,
    f2: i32,
    f3: i32,
}

extern {
    fn foo(s: S);
}

fn main() {
    let s = S { f1: 1, f2: 2, f3: 3 };
    unsafe {
        // CHECK: load { i64, i32 }, { i64, i32 }* {{.*}}, align 4
        // CHECK: call void @foo({ i64, i32 } {{.*}})
        foo(s);
    }
}
<|endoftext|>


<commit_before><commit_msg>impl Default for Direction<commit_after><|endoftext|>


<commit_before><commit_msg>fix for file ignore glob in new command<commit_after><|endoftext|>


<commit_before><commit_msg>Updated syntax<commit_after><|endoftext|>


<commit_before><commit_msg>named arguments in formatter - awesome<commit_after>fn main() {
    assert_eq!(format!("{description:.<25}{quantity:2} @ {price:5.2}",
                       price=3.25,
                       quantity=3,
                       description="Maple Turmeric Latte"),
               "Maple Turmeric Latte..... 3 @  3.25");
}
<|endoftext|>


<commit_before>use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs::File as FSFile;
use std::ops::Deref;
use std::io::Write;

pub mod path;
pub mod file;
pub mod parser;
pub mod json;

use module::Module;
use runtime::Runtime;
use storage::file::File;
use storage::file::id::FileID;
use storage::file::id_type::FileIDType;
use storage::file::hash::FileHash;
use storage::parser::{FileHeaderParser, Parser, ParserError};
use storage::file::header::data::FileHeaderData;

type Cache = HashMap<FileID, Rc<RefCell<File>>>;

pub struct Store {
    storepath: String,
    cache : RefCell<Cache>,
}

impl Store {

    pub fn new(storepath: String) -> Store {
        Store {
            storepath: storepath,
            cache: RefCell::new(HashMap::new()),
        }
    }

    fn put_in_cache(&self, f: File) -> FileID {
        let res = f.id().clone();
        self.cache.borrow_mut().insert(f.id().clone(), Rc::new(RefCell::new(f)));
        res
    }

    pub fn new_file(&self, module: &Module)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: FileHeaderData::Null,
            data: String::from(""),
            id: self.get_new_file_id(),
        };

        debug!("Create new File object: {:?}", &f);
        self.put_in_cache(f)
    }

    pub fn new_file_from_parser_result(&self,
                                       module: &Module,
                                       id: FileID,
                                       header: FileHeaderData,
                                       data: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: header,
            data: data,
            id: id,
        };
        debug!("Create new File object from parser result: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_header(&self,
                                module: &Module,
                                h: FileHeaderData)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: h,
            data: String::from(""),
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with header: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_data(&self, module: &Module, d: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: FileHeaderData::Null,
            data: d,
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with data: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_content(&self,
                                 module: &Module,
                                 h: FileHeaderData,
                                 d: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: h,
            data: d,
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with content: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn persist<HP>(&self,
                       p: &Parser<HP>,
                       f: Rc<RefCell<File>>) -> bool
        where HP: FileHeaderParser
    {
        let file = f.deref().borrow();
        let text = p.write(file.contents());
        if text.is_err() {
            error!("Error: {}", text.err().unwrap());
            return false;
        }

        let path = {
            let ids : String = file.id().clone().into();
            format!("{}/{}-{}.imag", self.storepath, file.owning_module_name, ids)
        };

        FSFile::create(&path).map(|mut fsfile| {
            fsfile.write_all(&text.unwrap().clone().into_bytes()[..])
        }).map_err(|writeerr|  {
            debug!("Could not create file at '{}'", path);
        }).and(Ok(true)).unwrap()
    }

    pub fn load(&self, id: &FileID) -> Option<Rc<RefCell<File>>> {
        debug!("Loading '{:?}'", id);
        self.cache.borrow().get(id).cloned()
    }

    pub fn remove(&self, id: FileID) -> bool {
        use std::fs::remove_file;

        self.cache
            .borrow_mut()
            .remove(&id)
            .map(|file| {
                let idstr : String = id.into();
                let path = format!("{}/{}-{}.imag",
                                   self.storepath,
                                   file.deref().borrow().owner_name(),
                                   idstr);
                remove_file(path).is_ok()
            })
            .unwrap_or(false)
    }

    fn get_new_file_id(&self) -> FileID {
        use uuid::Uuid;
        let hash = FileHash::from(Uuid::new_v4().to_hyphenated_string());
        FileID::new(FileIDType::UUID, hash)
    }

}
<commit_msg>Add Store::ensure_store_path_exists()<commit_after>use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs::File as FSFile;
use std::ops::Deref;
use std::io::Write;

pub mod path;
pub mod file;
pub mod parser;
pub mod json;

use module::Module;
use runtime::Runtime;
use storage::file::File;
use storage::file::id::FileID;
use storage::file::id_type::FileIDType;
use storage::file::hash::FileHash;
use storage::parser::{FileHeaderParser, Parser, ParserError};
use storage::file::header::data::FileHeaderData;

type Cache = HashMap<FileID, Rc<RefCell<File>>>;

pub struct Store {
    storepath: String,
    cache : RefCell<Cache>,
}

impl Store {

    pub fn new(storepath: String) -> Store {
        Store {
            storepath: storepath,
            cache: RefCell::new(HashMap::new()),
        }
    }

    fn put_in_cache(&self, f: File) -> FileID {
        let res = f.id().clone();
        self.cache.borrow_mut().insert(f.id().clone(), Rc::new(RefCell::new(f)));
        res
    }

    pub fn new_file(&self, module: &Module)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: FileHeaderData::Null,
            data: String::from(""),
            id: self.get_new_file_id(),
        };

        debug!("Create new File object: {:?}", &f);
        self.put_in_cache(f)
    }

    pub fn new_file_from_parser_result(&self,
                                       module: &Module,
                                       id: FileID,
                                       header: FileHeaderData,
                                       data: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: header,
            data: data,
            id: id,
        };
        debug!("Create new File object from parser result: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_header(&self,
                                module: &Module,
                                h: FileHeaderData)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: h,
            data: String::from(""),
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with header: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_data(&self, module: &Module, d: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: FileHeaderData::Null,
            data: d,
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with data: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn new_file_with_content(&self,
                                 module: &Module,
                                 h: FileHeaderData,
                                 d: String)
        -> FileID
    {
        let f = File {
            owning_module_name: module.name(),
            header: h,
            data: d,
            id: self.get_new_file_id(),
        };
        debug!("Create new File object with content: {:?}", f);
        self.put_in_cache(f)
    }

    pub fn persist<HP>(&self,
                       p: &Parser<HP>,
                       f: Rc<RefCell<File>>) -> bool
        where HP: FileHeaderParser
    {
        let file = f.deref().borrow();
        let text = p.write(file.contents());
        if text.is_err() {
            error!("Error: {}", text.err().unwrap());
            return false;
        }

        let path = {
            let ids : String = file.id().clone().into();
            format!("{}/{}-{}.imag", self.storepath, file.owning_module_name, ids)
        };

        self.ensure_store_path_exists();

        FSFile::create(&path).map(|mut fsfile| {
            fsfile.write_all(&text.unwrap().clone().into_bytes()[..])
        }).map_err(|writeerr|  {
            debug!("Could not create file at '{}'", path);
        }).and(Ok(true)).unwrap()
    }

    fn ensure_store_path_exists(&self) {
        use std::fs::create_dir_all;
        use std::process::exit;

        create_dir_all(&self.storepath).unwrap_or_else(|e| {
            error!("Could not create store: '{}'", self.storepath);
            error!("Error                 : '{}'", e);
            error!("Killing myself now");
            exit(1);
        })
    }

    pub fn load(&self, id: &FileID) -> Option<Rc<RefCell<File>>> {
        debug!("Loading '{:?}'", id);
        self.cache.borrow().get(id).cloned()
    }

    pub fn remove(&self, id: FileID) -> bool {
        use std::fs::remove_file;

        self.cache
            .borrow_mut()
            .remove(&id)
            .map(|file| {
                let idstr : String = id.into();
                let path = format!("{}/{}-{}.imag",
                                   self.storepath,
                                   file.deref().borrow().owner_name(),
                                   idstr);
                remove_file(path).is_ok()
            })
            .unwrap_or(false)
    }

    fn get_new_file_id(&self) -> FileID {
        use uuid::Uuid;
        let hash = FileHash::from(Uuid::new_v4().to_hyphenated_string());
        FileID::new(FileIDType::UUID, hash)
    }

}
<|endoftext|>


<commit_before>// Copyright 2012-2013 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.

use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::{Path, PathBuf};

use common::Config;
use common;
use util;

pub struct TestProps {
    // Lines that should be expected, in order, on standard out
    pub error_patterns: Vec<String> ,
    // Extra flags to pass to the compiler
    pub compile_flags: Option<String>,
    // Extra flags to pass when the compiled code is run (such as --bench)
    pub run_flags: Option<String>,
    // If present, the name of a file that this test should match when
    // pretty-printed
    pub pp_exact: Option<PathBuf>,
    // Modules from aux directory that should be compiled
    pub aux_builds: Vec<String> ,
    // Environment settings to use during execution
    pub exec_env: Vec<(String,String)> ,
    // Lines to check if they appear in the expected debugger output
    pub check_lines: Vec<String> ,
    // Build documentation for all specified aux-builds as well
    pub build_aux_docs: bool,
    // Flag to force a crate to be built with the host architecture
    pub force_host: bool,
    // Check stdout for error-pattern output as well as stderr
    pub check_stdout: bool,
    // Don't force a --crate-type=dylib flag on the command line
    pub no_prefer_dynamic: bool,
    // Run --pretty expanded when running pretty printing tests
    pub pretty_expanded: bool,
    // Which pretty mode are we testing with, default to 'normal'
    pub pretty_mode: String,
    // Only compare pretty output and don't try compiling
    pub pretty_compare_only: bool,
    // Patterns which must not appear in the output of a cfail test.
    pub forbid_output: Vec<String>,
}

// Load any test directives embedded in the file
pub fn load_props(testfile: &Path) -> TestProps {
    let mut error_patterns = Vec::new();
    let mut aux_builds = Vec::new();
    let mut exec_env = Vec::new();
    let mut compile_flags = None;
    let mut run_flags = None;
    let mut pp_exact = None;
    let mut check_lines = Vec::new();
    let mut build_aux_docs = false;
    let mut force_host = false;
    let mut check_stdout = false;
    let mut no_prefer_dynamic = false;
    let mut pretty_expanded = false;
    let mut pretty_mode = None;
    let mut pretty_compare_only = false;
    let mut forbid_output = Vec::new();
    iter_header(testfile, &mut |ln| {
        if let Some(ep) = parse_error_pattern(ln) {
           error_patterns.push(ep);
        }

        if compile_flags.is_none() {
            compile_flags = parse_compile_flags(ln);
        }

        if run_flags.is_none() {
            run_flags = parse_run_flags(ln);
        }

        if pp_exact.is_none() {
            pp_exact = parse_pp_exact(ln, testfile);
        }

        if !build_aux_docs {
            build_aux_docs = parse_build_aux_docs(ln);
        }

        if !force_host {
            force_host = parse_force_host(ln);
        }

        if !check_stdout {
            check_stdout = parse_check_stdout(ln);
        }

        if !no_prefer_dynamic {
            no_prefer_dynamic = parse_no_prefer_dynamic(ln);
        }

        if !pretty_expanded {
            pretty_expanded = parse_pretty_expanded(ln);
        }

        if pretty_mode.is_none() {
            pretty_mode = parse_pretty_mode(ln);
        }

        if !pretty_compare_only {
            pretty_compare_only = parse_pretty_compare_only(ln);
        }

        if let  Some(ab) = parse_aux_build(ln) {
            aux_builds.push(ab);
        }

        if let Some(ee) = parse_exec_env(ln) {
            exec_env.push(ee);
        }

        if let Some(cl) =  parse_check_line(ln) {
            check_lines.push(cl);
        }

        if let Some(of) = parse_forbid_output(ln) {
            forbid_output.push(of);
        }

        true
    });

    for key in vec!["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] {
        match env::var(key) {
            Ok(val) =>
                if exec_env.iter().find(|&&(ref x, _)| *x == key).is_none() {
                    exec_env.push((key.to_owned(), val))
                },
            Err(..) => {}
        }
    }

    TestProps {
        error_patterns: error_patterns,
        compile_flags: compile_flags,
        run_flags: run_flags,
        pp_exact: pp_exact,
        aux_builds: aux_builds,
        exec_env: exec_env,
        check_lines: check_lines,
        build_aux_docs: build_aux_docs,
        force_host: force_host,
        check_stdout: check_stdout,
        no_prefer_dynamic: no_prefer_dynamic,
        pretty_expanded: pretty_expanded,
        pretty_mode: pretty_mode.unwrap_or("normal".to_owned()),
        pretty_compare_only: pretty_compare_only,
        forbid_output: forbid_output,
    }
}

pub fn is_test_ignored(config: &Config, testfile: &Path) -> bool {
    fn ignore_target(config: &Config) -> String {
        format!("ignore-{}", util::get_os(&config.target))
    }
    fn ignore_architecture(config: &Config) -> String {
        format!("ignore-{}", util::get_arch(&config.target))
    }
    fn ignore_stage(config: &Config) -> String {
        format!("ignore-{}",
                config.stage_id.split('-').next().unwrap())
    }
    fn ignore_env(config: &Config) -> String {
        format!("ignore-{}", util::get_env(&config.target).unwrap_or("<unknown>"))
    }
    fn ignore_gdb(config: &Config, line: &str) -> bool {
        if config.mode != common::DebugInfoGdb {
            return false;
        }

        if parse_name_directive(line, "ignore-gdb") {
            return true;
        }

        if let Some(ref actual_version) = config.gdb_version {
            if line.contains("min-gdb-version") {
                let min_version = line.trim()
                                      .split(' ')
                                      .last()
                                      .expect("Malformed GDB version directive");
                // Ignore if actual version is smaller the minimum required
                // version
                gdb_version_to_int(actual_version) <
                    gdb_version_to_int(min_version)
            } else {
                false
            }
        } else {
            false
        }
    }

    fn ignore_lldb(config: &Config, line: &str) -> bool {
        if config.mode != common::DebugInfoLldb {
            return false;
        }

        if parse_name_directive(line, "ignore-lldb") {
            return true;
        }

        if let Some(ref actual_version) = config.lldb_version {
            if line.contains("min-lldb-version") {
                let min_version = line.trim()
                                      .split(' ')
                                      .last()
                                      .expect("Malformed lldb version directive");
                // Ignore if actual version is smaller the minimum required
                // version
                lldb_version_to_int(actual_version) <
                    lldb_version_to_int(min_version)
            } else {
                false
            }
        } else {
            false
        }
    }

    let val = iter_header(testfile, &mut |ln| {
        !parse_name_directive(ln, "ignore-test") &&
        !parse_name_directive(ln, &ignore_target(config)) &&
        !parse_name_directive(ln, &ignore_architecture(config)) &&
        !parse_name_directive(ln, &ignore_stage(config)) &&
        !parse_name_directive(ln, &ignore_env(config)) &&
        !(config.mode == common::Pretty && parse_name_directive(ln, "ignore-pretty")) &&
        !(config.target != config.host && parse_name_directive(ln, "ignore-cross-compile")) &&
        !ignore_gdb(config, ln) &&
        !ignore_lldb(config, ln)
    });

    !val
}

fn iter_header(testfile: &Path, it: &mut FnMut(&str) -> bool) -> bool {
    let rdr = BufReader::new(File::open(testfile).unwrap());
    for ln in rdr.lines() {
        // Assume that any directives will be found before the first
        // module or function. This doesn't seem to be an optimization
        // with a warm page cache. Maybe with a cold one.
        let ln = ln.unwrap();
        let ln = ln.trim();
        if ln.starts_with("fn") ||
                ln.starts_with("mod") {
            return true;
        } else if ln.starts_with("//") {
            if !it(&ln[2..]) {
                return false;
            }
        }
    }
    return true;
}

fn parse_error_pattern(line: &str) -> Option<String> {
    parse_name_value_directive(line, "error-pattern")
}

fn parse_forbid_output(line: &str) -> Option<String> {
    parse_name_value_directive(line, "forbid-output")
}

fn parse_aux_build(line: &str) -> Option<String> {
    parse_name_value_directive(line, "aux-build")
}

fn parse_compile_flags(line: &str) -> Option<String> {
    parse_name_value_directive(line, "compile-flags")
}

fn parse_run_flags(line: &str) -> Option<String> {
    parse_name_value_directive(line, "run-flags")
}

fn parse_check_line(line: &str) -> Option<String> {
    parse_name_value_directive(line, "check")
}

fn parse_force_host(line: &str) -> bool {
    parse_name_directive(line, "force-host")
}

fn parse_build_aux_docs(line: &str) -> bool {
    parse_name_directive(line, "build-aux-docs")
}

fn parse_check_stdout(line: &str) -> bool {
    parse_name_directive(line, "check-stdout")
}

fn parse_no_prefer_dynamic(line: &str) -> bool {
    parse_name_directive(line, "no-prefer-dynamic")
}

fn parse_pretty_expanded(line: &str) -> bool {
    parse_name_directive(line, "pretty-expanded")
}

fn parse_pretty_mode(line: &str) -> Option<String> {
    parse_name_value_directive(line, "pretty-mode")
}

fn parse_pretty_compare_only(line: &str) -> bool {
    parse_name_directive(line, "pretty-compare-only")
}

fn parse_exec_env(line: &str) -> Option<(String, String)> {
    parse_name_value_directive(line, "exec-env").map(|nv| {
        // nv is either FOO or FOO=BAR
        let mut strs: Vec<String> = nv
                                      .splitn(2, '=')
                                      .map(str::to_owned)
                                      .collect();

        match strs.len() {
          1 => (strs.pop().unwrap(), "".to_owned()),
          2 => {
              let end = strs.pop().unwrap();
              (strs.pop().unwrap(), end)
          }
          n => panic!("Expected 1 or 2 strings, not {}", n)
        }
    })
}

fn parse_pp_exact(line: &str, testfile: &Path) -> Option<PathBuf> {
    if let Some(s) = parse_name_value_directive(line, "pp-exact") {
        Some(PathBuf::from(&s))
    } else {
        if parse_name_directive(line, "pp-exact") {
            testfile.file_name().map(PathBuf::from)
        } else {
            None
        }
    }
}

fn parse_name_directive(line: &str, directive: &str) -> bool {
    // This 'no-' rule is a quick hack to allow pretty-expanded and no-pretty-expanded to coexist
    line.contains(directive) && !line.contains(&("no-".to_owned() + directive))
}

pub fn parse_name_value_directive(line: &str, directive: &str)
                                  -> Option<String> {
    let keycolon = format!("{}:", directive);
    if let Some(colon) = line.find(&keycolon) {
        let value = line[(colon + keycolon.len()) .. line.len()].to_owned();
        debug!("{}: {}", directive, value);
        Some(value)
    } else {
        None
    }
}

pub fn gdb_version_to_int(version_string: &str) -> isize {
    let error_string = format!(
        "Encountered GDB version string with unexpected format: {}",
        version_string);
    let error_string = error_string;

    let components: Vec<&str> = version_string.trim().split('.').collect();

    if components.len() != 2 {
        panic!("{}", error_string);
    }

    let major: isize = components[0].parse().ok().expect(&error_string);
    let minor: isize = components[1].parse().ok().expect(&error_string);

    return major * 1000 + minor;
}

pub fn lldb_version_to_int(version_string: &str) -> isize {
    let error_string = format!(
        "Encountered LLDB version string with unexpected format: {}",
        version_string);
    let error_string = error_string;
    let major: isize = version_string.parse().ok().expect(&error_string);
    return major;
}
<commit_msg>refactor header parsing so it can work "in-place"<commit_after>// Copyright 2012-2013 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.

use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::{Path, PathBuf};

use common::Config;
use common;
use util;

pub struct TestProps {
    // Lines that should be expected, in order, on standard out
    pub error_patterns: Vec<String> ,
    // Extra flags to pass to the compiler
    pub compile_flags: Option<String>,
    // Extra flags to pass when the compiled code is run (such as --bench)
    pub run_flags: Option<String>,
    // If present, the name of a file that this test should match when
    // pretty-printed
    pub pp_exact: Option<PathBuf>,
    // Modules from aux directory that should be compiled
    pub aux_builds: Vec<String> ,
    // Environment settings to use during execution
    pub exec_env: Vec<(String,String)> ,
    // Lines to check if they appear in the expected debugger output
    pub check_lines: Vec<String> ,
    // Build documentation for all specified aux-builds as well
    pub build_aux_docs: bool,
    // Flag to force a crate to be built with the host architecture
    pub force_host: bool,
    // Check stdout for error-pattern output as well as stderr
    pub check_stdout: bool,
    // Don't force a --crate-type=dylib flag on the command line
    pub no_prefer_dynamic: bool,
    // Run --pretty expanded when running pretty printing tests
    pub pretty_expanded: bool,
    // Which pretty mode are we testing with, default to 'normal'
    pub pretty_mode: String,
    // Only compare pretty output and don't try compiling
    pub pretty_compare_only: bool,
    // Patterns which must not appear in the output of a cfail test.
    pub forbid_output: Vec<String>,
}

// Load any test directives embedded in the file
pub fn load_props(testfile: &Path) -> TestProps {
    let error_patterns = Vec::new();
    let aux_builds = Vec::new();
    let exec_env = Vec::new();
    let compile_flags = None;
    let run_flags = None;
    let pp_exact = None;
    let check_lines = Vec::new();
    let build_aux_docs = false;
    let force_host = false;
    let check_stdout = false;
    let no_prefer_dynamic = false;
    let pretty_expanded = false;
    let pretty_compare_only = false;
    let forbid_output = Vec::new();
    let mut props = TestProps {
        error_patterns: error_patterns,
        compile_flags: compile_flags,
        run_flags: run_flags,
        pp_exact: pp_exact,
        aux_builds: aux_builds,
        exec_env: exec_env,
        check_lines: check_lines,
        build_aux_docs: build_aux_docs,
        force_host: force_host,
        check_stdout: check_stdout,
        no_prefer_dynamic: no_prefer_dynamic,
        pretty_expanded: pretty_expanded,
        pretty_mode: format!("normal"),
        pretty_compare_only: pretty_compare_only,
        forbid_output: forbid_output,
    };
    load_props_into(&mut props, testfile);
    props
}

pub fn load_props_into(props: &mut TestProps, testfile: &Path) {
    iter_header(testfile, &mut |ln| {
        if let Some(ep) = parse_error_pattern(ln) {
            props.error_patterns.push(ep);
        }

        if props.compile_flags.is_none() {
            props.compile_flags = parse_compile_flags(ln);
        }

        if props.run_flags.is_none() {
            props.run_flags = parse_run_flags(ln);
        }

        if props.pp_exact.is_none() {
            props.pp_exact = parse_pp_exact(ln, testfile);
        }

        if !props.build_aux_docs {
            props.build_aux_docs = parse_build_aux_docs(ln);
        }

        if !props.force_host {
            props.force_host = parse_force_host(ln);
        }

        if !props.check_stdout {
            props.check_stdout = parse_check_stdout(ln);
        }

        if !props.no_prefer_dynamic {
            props.no_prefer_dynamic = parse_no_prefer_dynamic(ln);
        }

        if !props.pretty_expanded {
            props.pretty_expanded = parse_pretty_expanded(ln);
        }

        if let Some(m) = parse_pretty_mode(ln) {
            props.pretty_mode = m;
        }

        if !props.pretty_compare_only {
            props.pretty_compare_only = parse_pretty_compare_only(ln);
        }

        if let  Some(ab) = parse_aux_build(ln) {
            props.aux_builds.push(ab);
        }

        if let Some(ee) = parse_exec_env(ln) {
            props.exec_env.push(ee);
        }

        if let Some(cl) =  parse_check_line(ln) {
            props.check_lines.push(cl);
        }

        if let Some(of) = parse_forbid_output(ln) {
            props.forbid_output.push(of);
        }

        true
    });

    for key in vec!["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] {
        match env::var(key) {
            Ok(val) =>
                if props.exec_env.iter().find(|&&(ref x, _)| *x == key).is_none() {
                    props.exec_env.push((key.to_owned(), val))
                },
            Err(..) => {}
        }
    }
}

pub fn is_test_ignored(config: &Config, testfile: &Path) -> bool {
    fn ignore_target(config: &Config) -> String {
        format!("ignore-{}", util::get_os(&config.target))
    }
    fn ignore_architecture(config: &Config) -> String {
        format!("ignore-{}", util::get_arch(&config.target))
    }
    fn ignore_stage(config: &Config) -> String {
        format!("ignore-{}",
                config.stage_id.split('-').next().unwrap())
    }
    fn ignore_env(config: &Config) -> String {
        format!("ignore-{}", util::get_env(&config.target).unwrap_or("<unknown>"))
    }
    fn ignore_gdb(config: &Config, line: &str) -> bool {
        if config.mode != common::DebugInfoGdb {
            return false;
        }

        if parse_name_directive(line, "ignore-gdb") {
            return true;
        }

        if let Some(ref actual_version) = config.gdb_version {
            if line.contains("min-gdb-version") {
                let min_version = line.trim()
                                      .split(' ')
                                      .last()
                                      .expect("Malformed GDB version directive");
                // Ignore if actual version is smaller the minimum required
                // version
                gdb_version_to_int(actual_version) <
                    gdb_version_to_int(min_version)
            } else {
                false
            }
        } else {
            false
        }
    }

    fn ignore_lldb(config: &Config, line: &str) -> bool {
        if config.mode != common::DebugInfoLldb {
            return false;
        }

        if parse_name_directive(line, "ignore-lldb") {
            return true;
        }

        if let Some(ref actual_version) = config.lldb_version {
            if line.contains("min-lldb-version") {
                let min_version = line.trim()
                                      .split(' ')
                                      .last()
                                      .expect("Malformed lldb version directive");
                // Ignore if actual version is smaller the minimum required
                // version
                lldb_version_to_int(actual_version) <
                    lldb_version_to_int(min_version)
            } else {
                false
            }
        } else {
            false
        }
    }

    let val = iter_header(testfile, &mut |ln| {
        !parse_name_directive(ln, "ignore-test") &&
        !parse_name_directive(ln, &ignore_target(config)) &&
        !parse_name_directive(ln, &ignore_architecture(config)) &&
        !parse_name_directive(ln, &ignore_stage(config)) &&
        !parse_name_directive(ln, &ignore_env(config)) &&
        !(config.mode == common::Pretty && parse_name_directive(ln, "ignore-pretty")) &&
        !(config.target != config.host && parse_name_directive(ln, "ignore-cross-compile")) &&
        !ignore_gdb(config, ln) &&
        !ignore_lldb(config, ln)
    });

    !val
}

fn iter_header(testfile: &Path, it: &mut FnMut(&str) -> bool) -> bool {
    let rdr = BufReader::new(File::open(testfile).unwrap());
    for ln in rdr.lines() {
        // Assume that any directives will be found before the first
        // module or function. This doesn't seem to be an optimization
        // with a warm page cache. Maybe with a cold one.
        let ln = ln.unwrap();
        let ln = ln.trim();
        if ln.starts_with("fn") || ln.starts_with("mod") {
            return true;
        } else if ln.starts_with("//") {
            if !it(&ln[2..]) {
                return false;
            }
        }
    }
    return true;
}

fn parse_error_pattern(line: &str) -> Option<String> {
    parse_name_value_directive(line, "error-pattern")
}

fn parse_forbid_output(line: &str) -> Option<String> {
    parse_name_value_directive(line, "forbid-output")
}

fn parse_aux_build(line: &str) -> Option<String> {
    parse_name_value_directive(line, "aux-build")
}

fn parse_compile_flags(line: &str) -> Option<String> {
    parse_name_value_directive(line, "compile-flags")
}

fn parse_run_flags(line: &str) -> Option<String> {
    parse_name_value_directive(line, "run-flags")
}

fn parse_check_line(line: &str) -> Option<String> {
    parse_name_value_directive(line, "check")
}

fn parse_force_host(line: &str) -> bool {
    parse_name_directive(line, "force-host")
}

fn parse_build_aux_docs(line: &str) -> bool {
    parse_name_directive(line, "build-aux-docs")
}

fn parse_check_stdout(line: &str) -> bool {
    parse_name_directive(line, "check-stdout")
}

fn parse_no_prefer_dynamic(line: &str) -> bool {
    parse_name_directive(line, "no-prefer-dynamic")
}

fn parse_pretty_expanded(line: &str) -> bool {
    parse_name_directive(line, "pretty-expanded")
}

fn parse_pretty_mode(line: &str) -> Option<String> {
    parse_name_value_directive(line, "pretty-mode")
}

fn parse_pretty_compare_only(line: &str) -> bool {
    parse_name_directive(line, "pretty-compare-only")
}

fn parse_exec_env(line: &str) -> Option<(String, String)> {
    parse_name_value_directive(line, "exec-env").map(|nv| {
        // nv is either FOO or FOO=BAR
        let mut strs: Vec<String> = nv
                                      .splitn(2, '=')
                                      .map(str::to_owned)
                                      .collect();

        match strs.len() {
          1 => (strs.pop().unwrap(), "".to_owned()),
          2 => {
              let end = strs.pop().unwrap();
              (strs.pop().unwrap(), end)
          }
          n => panic!("Expected 1 or 2 strings, not {}", n)
        }
    })
}

fn parse_pp_exact(line: &str, testfile: &Path) -> Option<PathBuf> {
    if let Some(s) = parse_name_value_directive(line, "pp-exact") {
        Some(PathBuf::from(&s))
    } else {
        if parse_name_directive(line, "pp-exact") {
            testfile.file_name().map(PathBuf::from)
        } else {
            None
        }
    }
}

fn parse_name_directive(line: &str, directive: &str) -> bool {
    // This 'no-' rule is a quick hack to allow pretty-expanded and no-pretty-expanded to coexist
    line.contains(directive) && !line.contains(&("no-".to_owned() + directive))
}

pub fn parse_name_value_directive(line: &str, directive: &str)
                                  -> Option<String> {
    let keycolon = format!("{}:", directive);
    if let Some(colon) = line.find(&keycolon) {
        let value = line[(colon + keycolon.len()) .. line.len()].to_owned();
        debug!("{}: {}", directive, value);
        Some(value)
    } else {
        None
    }
}

pub fn gdb_version_to_int(version_string: &str) -> isize {
    let error_string = format!(
        "Encountered GDB version string with unexpected format: {}",
        version_string);
    let error_string = error_string;

    let components: Vec<&str> = version_string.trim().split('.').collect();

    if components.len() != 2 {
        panic!("{}", error_string);
    }

    let major: isize = components[0].parse().ok().expect(&error_string);
    let minor: isize = components[1].parse().ok().expect(&error_string);

    return major * 1000 + minor;
}

pub fn lldb_version_to_int(version_string: &str) -> isize {
    let error_string = format!(
        "Encountered LLDB version string with unexpected format: {}",
        version_string);
    let error_string = error_string;
    let major: isize = version_string.parse().ok().expect(&error_string);
    return major;
}
<|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::BindingDeclarations::HTMLTitleElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTitleElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::error::ErrorResult;
use dom::document::Document;
use dom::element::HTMLTitleElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct HTMLTitleElement {
    pub htmlelement: HTMLElement,
}

impl HTMLTitleElementDerived for EventTarget {
    fn is_htmltitleelement(&self) -> bool {
        self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLTitleElementTypeId))
    }
}

impl HTMLTitleElement {
    pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLTitleElement {
        HTMLTitleElement {
            htmlelement: HTMLElement::new_inherited(HTMLTitleElementTypeId, localName, document)
        }
    }

    pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLTitleElement> {
        let element = HTMLTitleElement::new_inherited(localName, document);
        Node::reflect_node(box element, document, HTMLTitleElementBinding::Wrap)
    }
}

pub trait HTMLTitleElementMethods {
    fn Text(&self) -> DOMString;
    fn SetText(&mut self, _text: DOMString) -> ErrorResult;
}

impl<'a> HTMLTitleElementMethods for JSRef<'a, HTMLTitleElement> {
    fn Text(&self) -> DOMString {
        "".to_owned()
    }

    fn SetText(&mut self, _text: DOMString) -> ErrorResult {
        Ok(())
    }
}
<commit_msg>Remove needless '&mut self' from HTMLTitleElementMethods.<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::codegen::BindingDeclarations::HTMLTitleElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTitleElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::error::ErrorResult;
use dom::document::Document;
use dom::element::HTMLTitleElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct HTMLTitleElement {
    pub htmlelement: HTMLElement,
}

impl HTMLTitleElementDerived for EventTarget {
    fn is_htmltitleelement(&self) -> bool {
        self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLTitleElementTypeId))
    }
}

impl HTMLTitleElement {
    pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLTitleElement {
        HTMLTitleElement {
            htmlelement: HTMLElement::new_inherited(HTMLTitleElementTypeId, localName, document)
        }
    }

    pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLTitleElement> {
        let element = HTMLTitleElement::new_inherited(localName, document);
        Node::reflect_node(box element, document, HTMLTitleElementBinding::Wrap)
    }
}

pub trait HTMLTitleElementMethods {
    fn Text(&self) -> DOMString;
    fn SetText(&self, _text: DOMString) -> ErrorResult;
}

impl<'a> HTMLTitleElementMethods for JSRef<'a, HTMLTitleElement> {
    fn Text(&self) -> DOMString {
        "".to_owned()
    }

    fn SetText(&self, _text: DOMString) -> ErrorResult {
        Ok(())
    }
}
<|endoftext|>


<commit_before><commit_msg>Add selection sort<commit_after><|endoftext|>


<commit_before><commit_msg>common-macros: Copy RenameRule from serde<commit_after>//! Code to convert the Rust-styled field/variant (e.g. `my_field`, `MyType`) to the
//! case of the source (e.g. `my-field`, `MY_FIELD`).
//!
//! This is a minimally modified version of the same code [in serde].
//!
//! [serde]: https://github.com/serde-rs/serde/blame/a9f8ea0a1e8ba1206f8c28d96b924606847b85a9/serde_derive/src/internals/case.rs

use std::str::FromStr;

use self::RenameRule::*;

/// The different possible ways to change case of fields in a struct, or variants in an enum.
#[derive(Copy, Clone, PartialEq)]
pub enum RenameRule {
    /// Don't apply a default rename rule.
    None,
    /// Rename direct children to "lowercase" style.
    LowerCase,
    /// Rename direct children to "UPPERCASE" style.
    Uppercase,
    /// Rename direct children to "PascalCase" style, as typically used for
    /// enum variants.
    PascalCase,
    /// Rename direct children to "camelCase" style.
    CamelCase,
    /// Rename direct children to "snake_case" style, as commonly used for
    /// fields.
    SnakeCase,
    /// Rename direct children to "SCREAMING_SNAKE_CASE" style, as commonly
    /// used for constants.
    ScreamingSnakeCase,
    /// Rename direct children to "kebab-case" style.
    KebabCase,
    /// Rename direct children to "SCREAMING-KEBAB-CASE" style.
    ScreamingKebabCase,
}

impl RenameRule {
    /// Apply a renaming rule to an enum variant, returning the version expected in the source.
    pub fn apply_to_variant(&self, variant: &str) -> String {
        match *self {
            None | PascalCase => variant.to_owned(),
            LowerCase => variant.to_ascii_lowercase(),
            Uppercase => variant.to_ascii_uppercase(),
            CamelCase => variant[..1].to_ascii_lowercase() + &variant[1..],
            SnakeCase => {
                let mut snake = String::new();
                for (i, ch) in variant.char_indices() {
                    if i > 0 && ch.is_uppercase() {
                        snake.push('_');
                    }
                    snake.push(ch.to_ascii_lowercase());
                }
                snake
            }
            ScreamingSnakeCase => SnakeCase.apply_to_variant(variant).to_ascii_uppercase(),
            KebabCase => SnakeCase.apply_to_variant(variant).replace('_', "-"),
            ScreamingKebabCase => ScreamingSnakeCase.apply_to_variant(variant).replace('_', "-"),
        }
    }

    /// Apply a renaming rule to a struct field, returning the version expected in the source.
    #[allow(dead_code)]
    pub fn apply_to_field(&self, field: &str) -> String {
        match *self {
            None | LowerCase | SnakeCase => field.to_owned(),
            Uppercase => field.to_ascii_uppercase(),
            PascalCase => {
                let mut pascal = String::new();
                let mut capitalize = true;
                for ch in field.chars() {
                    if ch == '_' {
                        capitalize = true;
                    } else if capitalize {
                        pascal.push(ch.to_ascii_uppercase());
                        capitalize = false;
                    } else {
                        pascal.push(ch);
                    }
                }
                pascal
            }
            CamelCase => {
                let pascal = PascalCase.apply_to_field(field);
                pascal[..1].to_ascii_lowercase() + &pascal[1..]
            }
            ScreamingSnakeCase => field.to_ascii_uppercase(),
            KebabCase => field.replace('_', "-"),
            ScreamingKebabCase => ScreamingSnakeCase.apply_to_field(field).replace('_', "-"),
        }
    }
}

impl FromStr for RenameRule {
    type Err = ();

    fn from_str(rename_all_str: &str) -> Result<Self, Self::Err> {
        match rename_all_str {
            "lowercase" => Ok(LowerCase),
            "UPPERCASE" => Ok(Uppercase),
            "PascalCase" => Ok(PascalCase),
            "camelCase" => Ok(CamelCase),
            "snake_case" => Ok(SnakeCase),
            "SCREAMING_SNAKE_CASE" => Ok(ScreamingSnakeCase),
            "kebab-case" => Ok(KebabCase),
            "SCREAMING-KEBAB-CASE" => Ok(ScreamingKebabCase),
            _ => Err(()),
        }
    }
}

#[test]
fn rename_variants() {
    for &(original, lower, upper, camel, snake, screaming, kebab, screaming_kebab) in &[
        ("Outcome", "outcome", "OUTCOME", "outcome", "outcome", "OUTCOME", "outcome", "OUTCOME"),
        (
            "VeryTasty",
            "verytasty",
            "VERYTASTY",
            "veryTasty",
            "very_tasty",
            "VERY_TASTY",
            "very-tasty",
            "VERY-TASTY",
        ),
        ("A", "a", "A", "a", "a", "A", "a", "A"),
        ("Z42", "z42", "Z42", "z42", "z42", "Z42", "z42", "Z42"),
    ] {
        assert_eq!(None.apply_to_variant(original), original);
        assert_eq!(LowerCase.apply_to_variant(original), lower);
        assert_eq!(Uppercase.apply_to_variant(original), upper);
        assert_eq!(PascalCase.apply_to_variant(original), original);
        assert_eq!(CamelCase.apply_to_variant(original), camel);
        assert_eq!(SnakeCase.apply_to_variant(original), snake);
        assert_eq!(ScreamingSnakeCase.apply_to_variant(original), screaming);
        assert_eq!(KebabCase.apply_to_variant(original), kebab);
        assert_eq!(ScreamingKebabCase.apply_to_variant(original), screaming_kebab);
    }
}

#[test]
fn rename_fields() {
    for &(original, upper, pascal, camel, screaming, kebab, screaming_kebab) in &[
        ("outcome", "OUTCOME", "Outcome", "outcome", "OUTCOME", "outcome", "OUTCOME"),
        (
            "very_tasty",
            "VERY_TASTY",
            "VeryTasty",
            "veryTasty",
            "VERY_TASTY",
            "very-tasty",
            "VERY-TASTY",
        ),
        ("a", "A", "A", "a", "A", "a", "A"),
        ("z42", "Z42", "Z42", "z42", "Z42", "z42", "Z42"),
    ] {
        assert_eq!(None.apply_to_field(original), original);
        assert_eq!(Uppercase.apply_to_field(original), upper);
        assert_eq!(PascalCase.apply_to_field(original), pascal);
        assert_eq!(CamelCase.apply_to_field(original), camel);
        assert_eq!(SnakeCase.apply_to_field(original), original);
        assert_eq!(ScreamingSnakeCase.apply_to_field(original), screaming);
        assert_eq!(KebabCase.apply_to_field(original), kebab);
        assert_eq!(ScreamingKebabCase.apply_to_field(original), screaming_kebab);
    }
}
<|endoftext|>


<commit_before><commit_msg>1-4 done<commit_after><|endoftext|>


<commit_before><commit_msg>update sync logic<commit_after><|endoftext|>


<commit_before><commit_msg>Implement Display and Error for ConfigError.<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test for borrowck errors with multiple closure captures.<commit_after>// Copyright 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.

use std::task;

fn borrow<T>(_: &T) { }

fn different_vars_after_borrows() {
    let x1 = box 1;
    let p1 = &x1;
    let x2 = box 2;
    let p2 = &x2;
    task::spawn(proc() {
        drop(x1); //~ ERROR cannot move `x1` into closure because it is borrowed
        drop(x2); //~ ERROR cannot move `x2` into closure because it is borrowed
    });
    borrow(&*p1);
    borrow(&*p2);
}

fn different_vars_after_moves() {
    let x1 = box 1;
    drop(x1);
    let x2 = box 2;
    drop(x2);
    task::spawn(proc() {
        drop(x1); //~ ERROR capture of moved value: `x1`
        drop(x2); //~ ERROR capture of moved value: `x2`
    });
}

fn same_var_after_borrow() {
    let x = box 1;
    let p = &x;
    task::spawn(proc() {
        drop(x); //~ ERROR cannot move `x` into closure because it is borrowed
        drop(x); //~ ERROR use of moved value: `x`
    });
    borrow(&*p);
}

fn same_var_after_move() {
    let x = box 1;
    drop(x);
    task::spawn(proc() {
        drop(x); //~ ERROR capture of moved value: `x`
        drop(x); //~ ERROR use of moved value: `x`
    });
}

fn main() {
    different_vars_after_borrows();
    different_vars_after_moves();
    same_var_after_borrow();
    same_var_after_move();
}

<|endoftext|>


<commit_before><commit_msg>Added file I/O example<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/.

// We won't use the usual `main` function. We are going to use a different "entry point".
#![no_main]

// We won't use the standard library because it requires OS abstractions like threads and files and
// those are not available in this platform.
#![no_std]
#![feature(alloc)]
#![feature(collections)]

#[macro_use]
extern crate cc3200;
extern crate alloc;
extern crate freertos_rs;
extern crate freertos_alloc;

extern crate smallhttp;

#[macro_use]
extern crate log;

#[macro_use]
extern crate collections;

use cc3200::cc3200::{Board};
use cc3200::simplelink::{SimpleLink, SimpleLinkError};
use cc3200::io::{File, Read, Seek, Write};

use freertos_rs::{Task};

use collections::String;

static VERSION: &'static str = "1.0";

#[derive(Debug)]
pub enum Error {
    SLE(SimpleLinkError),
}

impl From<SimpleLinkError> for Error {
    fn from(err: SimpleLinkError) -> Error {
        Error::SLE(err)
    }
}

macro_rules! ignore {
    ($e:expr) => ({
        match $e {
            Ok(_) => { },
            Err(_) => { },
        }
    })
}

fn fileio_demo() -> Result<(), Error> {

    try!(SimpleLink::start_spawn_task());
    SimpleLink::init_app_variables();
    try!(SimpleLink::start());

    let filename = "myfile.txt";
    let test_string = "Hello world";

    // 1) Remove test file, if any

    ignore!(File::remove(filename));

    // 2) Write test file

    {
        println!("Writing string \"{}\"", test_string);

        let mut file = try!(File::create(filename));
        try!(file.write(test_string.as_bytes()));
    }

    // 3) Get file info

    let info = try!(File::get_info(filename));

    println!("File info:");
    println!("        flags={}", info.flags);
    println!("        current length={}", info.file_length);
    println!("        allocated length={}", info.allocated_length);
    println!("        tokens=({}, {}, {}, {})",
                info.token[0], info.token[1], info.token[2], info.token[3]);

    // 4) Read test file

    let mut file = try!(File::open(filename));

    let mut str = String::new();
    try!(file.read_to_string(&mut str)); // "Hello world"

    println!("Read string \"{}\"", str);

    try!(file.seek(6));
    try!(file.read_to_string(&mut str)); // "world"

    println!("Read string \"{}\" at offset 6", str);

    Ok(())
}

// Conceptually, this is our program "entry point". It's the first thing the microcontroller will
// execute when it (re)boots. (As far as the linker is concerned the entry point must be named
// `start` (by default; it can have a different name). That's why this function is `pub`lic, named
// `start` and is marked as `#[no_mangle]`.)
//
// Returning from this function is undefined because there is nothing to return to! To statically
// forbid returning from this function, we mark it as divergent, hence the `fn() -> !` signature.
#[no_mangle]
pub fn start() -> ! {

    Board::init();

    println!("Welcome to CC3200 File I/O example {}", VERSION);

    let _client = {
        Task::new()
            .name("client")
            .stack_size(2048) // 32-bit words
            .start(|| {
                match fileio_demo() {
                    Ok(())  => { println!("fileio_demo succeeded"); },
                    Err(e)  => { println!("fileio_demo failed: {:?}", e); },
                };
                loop {}
            })
            .unwrap()
    };

    Board::start_scheduler();

    // The only reason start_scheduler should fail is if there wasn't enough
    // heap to initialize the IDLE and timer tasks

    loop {}
}
<|endoftext|>


<commit_before><commit_msg>Add a simple example<commit_after>extern crate escposify;
extern crate tempfile;

use escposify::printer::Printer;
use escposify::device::File;

use tempfile::{NamedTempFile};

fn main() {
    let mut printer = Printer::new(
        File::<NamedTempFile>::from_temp(), None, None);
    let _ = printer
        .font("C")
        .align("lt")
        .style("bu")
        .size(0, 0)
        .text("The quick brown fox jumps over the lazy dog")
        .text("敏捷的棕色狐狸跳过懒狗")
        .barcode("12345678", "EAN8", "", "", 0, 0)
        .feed(1)
        .cut(false)
        .flush();
}
<|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 = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![cfg_attr(not(feature = "clippy"), allow(unknown_lints))]

#![allow(doc_markdown)]

extern crate devicemapper;
extern crate libstratis;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate clap;
#[cfg(feature="dbus_enabled")]
extern crate dbus;
extern crate libc;
extern crate libudev;
extern crate nix;

#[cfg(test)]
extern crate quickcheck;

use std::cell::RefCell;
use std::env;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::io::AsRawFd;
use std::path::PathBuf;
use std::process::exit;
use std::rc::Rc;

use clap::{App, Arg};
use env_logger::LogBuilder;
use libc::pid_t;
use log::{LogLevelFilter, SetLoggerError};
use nix::fcntl::{flock, FlockArg};
use nix::unistd::getpid;

#[cfg(feature="dbus_enabled")]
use dbus::WatchEvent;

use devicemapper::Device;

use libstratis::engine::{Engine, SimEngine, StratEngine};
use libstratis::stratis::{StratisError, StratisResult, VERSION};

const STRATISD_PID_PATH: &str = "/var/run/stratisd.pid";

/// If writing a program error to stderr fails, panic.
fn print_err(err: StratisError) -> () {
    eprintln!("{}", err);
}

/// Configure and initialize the logger.
/// If debug is true, log at debug level. Otherwise read log configuration
/// parameters from the environment if RUST_LOG is set. Otherwise, just
/// accept the default configuration.
fn initialize_log(debug: bool) -> Result<(), SetLoggerError> {
    let mut builder = LogBuilder::new();
    if debug {
        builder.filter(Some("stratisd"), LogLevelFilter::Debug);
        builder.filter(Some("libstratis"), LogLevelFilter::Debug);
    } else {
        if let Ok(s) = env::var("RUST_LOG") {
            builder.parse(&s);
        }
    };

    builder.init()
}

/// Given a udev event check to see if it's an add and if it is return the device node and
/// devicemapper::Device.
fn handle_udev_add(event: &libudev::Event) -> Option<(Device, PathBuf)> {
    if event.event_type() == libudev::EventType::Add {
        let device = event.device();
        return device
                   .devnode()
                   .and_then(|devnode| {
                                 device
                                     .devnum()
                                     .and_then(|devnum| {
                                                   Some((Device::from(devnum),
                                                         PathBuf::from(devnode)))
                                               })
                             });
    }
    None
}

/// To ensure only one instance of stratisd runs at a time, acquire an
/// exclusive lock. Return an error if lock attempt fails.
fn create_pid_file() -> StratisResult<File> {
    let mut f = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open(STRATISD_PID_PATH)?;
    match flock(f.as_raw_fd(), FlockArg::LockExclusiveNonblock) {
        Ok(_) => {
            f.write(format!("{}\n", getpid()).as_bytes())?;
            Ok(f)
        }
        Err(_) => {
            let mut buf = String::new();
            f.read_to_string(&mut buf)?;
            // pidfile is supposed to contain pid of holder. But you never
            // know so be paranoid.
            let pid_str = buf.split_whitespace()
                .next()
                .and_then(|s| s.parse::<pid_t>().ok())
                .map(|pid| format!("{}", pid))
                .unwrap_or_else(|| "<unknown>".into());
            Err(StratisError::Error(format!("Daemon already running with pid: {}", pid_str)))
        }
    }
}

fn run() -> StratisResult<()> {

    // Exit immediately if stratisd is already running
    let _ = create_pid_file()?;

    let matches = App::new("stratis")
        .version(VERSION)
        .about("Stratis storage management")
        .arg(Arg::with_name("debug")
                 .long("debug")
                 .help("Print additional output for debugging"))
        .arg(Arg::with_name("sim")
                 .long("sim")
                 .help("Use simulator engine"))
        .get_matches();

    initialize_log(matches.is_present("debug"))
        .expect("This is the first and only invocation of this method; it must succeed.");

    // We must setup a udev listener before we initialize the
    // engine. It is possible that a device may appear after the engine has read the
    // /dev directory but before it has completed initialization. Unless the udev
    // event has been recorded, the engine will be unaware of the existence of the
    // device.
    // This is especially important since stratisd is required to be able to run
    // during early boot.
    let context = libudev::Context::new()?;
    let mut monitor = libudev::Monitor::new(&context)?;
    monitor.match_subsystem_devtype("block", "disk")?;
    let mut udev = monitor.listen()?;

    let engine: Rc<RefCell<Engine>> = {
        if matches.is_present("sim") {
            info!("Using SimEngine");
            Rc::new(RefCell::new(SimEngine::default()))
        } else {
            info!("Using StratEngine");
            Rc::new(RefCell::new(StratEngine::initialize()?))
        }
    };

    /*
    The file descriptor array indexes are laid out in the following:

    0   == Always udev fd index
    1   == engine index if eventable
    1/2 == Start of dbus client file descriptor(s), 1 if engine is not eventable, else 2
    */
    const FD_INDEX_UDEV: usize = 0;
    const FD_INDEX_ENGINE: usize = 1;

    let mut fds = Vec::new();

    fds.push(libc::pollfd {
                 fd: udev.as_raw_fd(),
                 revents: 0,
                 events: libc::POLLIN,
             });

    let eventable = engine.borrow().get_eventable();

    // The variable _dbus_client_index_start is only used when dbus support is compiled in, thus
    // we denote the value as not needed to compile when dbus support is not included.
    let (engine_eventable, poll_timeout, _dbus_client_index_start) = match eventable {
        Some(ref evt) => {
            fds.push(libc::pollfd {
                         fd: evt.get_pollable_fd(),
                         revents: 0,
                         events: libc::POLLIN,
                     });

            // Don't timeout if eventable, we are event driven
            (true, -1, FD_INDEX_ENGINE + 1)
        }

        // We periodically need to timeout as we are not event driven
        None => (false, 10000, FD_INDEX_ENGINE),
    };

    #[cfg(feature="dbus_enabled")]
    let (mut dbus_conn, mut tree, base_object_path, mut dbus_context) =
        libstratis::dbus_api::connect(Rc::clone(&engine))?;

    loop {
        // Process any udev block events
        if fds[FD_INDEX_UDEV].revents != 0 {
            loop {
                match udev.receive_event() {
                    Some(event) => {
                        if let Some((device, devnode)) = handle_udev_add(&event) {

                            // If block evaluate returns an error we are going to ignore it as
                            // there is nothing we can do for a device we are getting errors with.
                            let pool_uuid = engine
                                .borrow_mut()
                                .block_evaluate(device, devnode)
                                .unwrap_or(None);

                            // We need to pretend that we aren't using the variable _pool_uuid so
                            // that we can conditionally compile out the register_pool when dbus
                            // is not enabled.
                            if let Some(_pool_uuid) = pool_uuid {
                                #[cfg(feature="dbus_enabled")]
                                libstratis::dbus_api::register_pool(&mut dbus_conn,
                                                                    &Rc::clone(&engine),
                                                                    &mut dbus_context,
                                                                    &mut tree,
                                                                    _pool_uuid,
                                                                    &base_object_path)?;
                            }
                        }
                    }
                    None => {
                        break;
                    }
                };
            }
        }

        // Handle engine events, if the engine is eventable
        if engine_eventable {
            if fds[FD_INDEX_ENGINE].revents != 0 {
                fds[FD_INDEX_ENGINE].revents = 0;

                eventable
                    .as_ref()
                    .expect("eventable.is_some()")
                    .clear_event()?;

                engine.borrow_mut().evented()?;
            }
        } else {
            // Unconditionally call evented() if engine has no eventable.
            // This looks like a bad idea, but the only engine that has
            // no eventable is the sim engine, and for that engine, evented()
            // is essentially a no-op.
            engine.borrow_mut().evented()?;
        }

        // Iterate through D-Bus file descriptors (if enabled)
        #[cfg(feature="dbus_enabled")]
        {
            for pfd in fds[_dbus_client_index_start..]
                    .iter()
                    .filter(|pfd| pfd.revents != 0) {
                for item in dbus_conn.watch_handle(pfd.fd, WatchEvent::from_revents(pfd.revents)) {
                    if let Err(r) = libstratis::dbus_api::handle(&dbus_conn,
                                                                 &item,
                                                                 &mut tree,
                                                                 &dbus_context) {
                        print_err(From::from(r));
                    }
                }
            }

            // Refresh list of dbus fds to poll for every time. This can change as
            // D-Bus clients come and go.
            fds.truncate(_dbus_client_index_start);

            fds.extend(dbus_conn.watch_fds().iter().map(|w| w.to_pollfd()));
        }

        let r = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::c_ulong, poll_timeout) };
        assert!(r >= 0);
    }
}

fn main() {
    let error_code = match run() {
        Ok(_) => 0,
        Err(err) => {
            print_err(err);
            1
        }
    };
    exit(error_code);
}
<commit_msg>Tighten up a clippy collapsible-if<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 = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![cfg_attr(not(feature = "clippy"), allow(unknown_lints))]

#![allow(doc_markdown)]

extern crate devicemapper;
extern crate libstratis;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate clap;
#[cfg(feature="dbus_enabled")]
extern crate dbus;
extern crate libc;
extern crate libudev;
extern crate nix;

#[cfg(test)]
extern crate quickcheck;

use std::cell::RefCell;
use std::env;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::io::AsRawFd;
use std::path::PathBuf;
use std::process::exit;
use std::rc::Rc;

use clap::{App, Arg};
use env_logger::LogBuilder;
use libc::pid_t;
use log::{LogLevelFilter, SetLoggerError};
use nix::fcntl::{flock, FlockArg};
use nix::unistd::getpid;

#[cfg(feature="dbus_enabled")]
use dbus::WatchEvent;

use devicemapper::Device;

use libstratis::engine::{Engine, SimEngine, StratEngine};
use libstratis::stratis::{StratisError, StratisResult, VERSION};

const STRATISD_PID_PATH: &str = "/var/run/stratisd.pid";

/// If writing a program error to stderr fails, panic.
fn print_err(err: StratisError) -> () {
    eprintln!("{}", err);
}

/// Configure and initialize the logger.
/// If debug is true, log at debug level. Otherwise read log configuration
/// parameters from the environment if RUST_LOG is set. Otherwise, just
/// accept the default configuration.
fn initialize_log(debug: bool) -> Result<(), SetLoggerError> {
    let mut builder = LogBuilder::new();
    if debug {
        builder.filter(Some("stratisd"), LogLevelFilter::Debug);
        builder.filter(Some("libstratis"), LogLevelFilter::Debug);
    } else if let Ok(s) = env::var("RUST_LOG") {
        builder.parse(&s);
    };

    builder.init()
}

/// Given a udev event check to see if it's an add and if it is return the device node and
/// devicemapper::Device.
fn handle_udev_add(event: &libudev::Event) -> Option<(Device, PathBuf)> {
    if event.event_type() == libudev::EventType::Add {
        let device = event.device();
        return device
                   .devnode()
                   .and_then(|devnode| {
                                 device
                                     .devnum()
                                     .and_then(|devnum| {
                                                   Some((Device::from(devnum),
                                                         PathBuf::from(devnode)))
                                               })
                             });
    }
    None
}

/// To ensure only one instance of stratisd runs at a time, acquire an
/// exclusive lock. Return an error if lock attempt fails.
fn create_pid_file() -> StratisResult<File> {
    let mut f = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open(STRATISD_PID_PATH)?;
    match flock(f.as_raw_fd(), FlockArg::LockExclusiveNonblock) {
        Ok(_) => {
            f.write(format!("{}\n", getpid()).as_bytes())?;
            Ok(f)
        }
        Err(_) => {
            let mut buf = String::new();
            f.read_to_string(&mut buf)?;
            // pidfile is supposed to contain pid of holder. But you never
            // know so be paranoid.
            let pid_str = buf.split_whitespace()
                .next()
                .and_then(|s| s.parse::<pid_t>().ok())
                .map(|pid| format!("{}", pid))
                .unwrap_or_else(|| "<unknown>".into());
            Err(StratisError::Error(format!("Daemon already running with pid: {}", pid_str)))
        }
    }
}

fn run() -> StratisResult<()> {

    // Exit immediately if stratisd is already running
    let _ = create_pid_file()?;

    let matches = App::new("stratis")
        .version(VERSION)
        .about("Stratis storage management")
        .arg(Arg::with_name("debug")
                 .long("debug")
                 .help("Print additional output for debugging"))
        .arg(Arg::with_name("sim")
                 .long("sim")
                 .help("Use simulator engine"))
        .get_matches();

    initialize_log(matches.is_present("debug"))
        .expect("This is the first and only invocation of this method; it must succeed.");

    // We must setup a udev listener before we initialize the
    // engine. It is possible that a device may appear after the engine has read the
    // /dev directory but before it has completed initialization. Unless the udev
    // event has been recorded, the engine will be unaware of the existence of the
    // device.
    // This is especially important since stratisd is required to be able to run
    // during early boot.
    let context = libudev::Context::new()?;
    let mut monitor = libudev::Monitor::new(&context)?;
    monitor.match_subsystem_devtype("block", "disk")?;
    let mut udev = monitor.listen()?;

    let engine: Rc<RefCell<Engine>> = {
        if matches.is_present("sim") {
            info!("Using SimEngine");
            Rc::new(RefCell::new(SimEngine::default()))
        } else {
            info!("Using StratEngine");
            Rc::new(RefCell::new(StratEngine::initialize()?))
        }
    };

    /*
    The file descriptor array indexes are laid out in the following:

    0   == Always udev fd index
    1   == engine index if eventable
    1/2 == Start of dbus client file descriptor(s), 1 if engine is not eventable, else 2
    */
    const FD_INDEX_UDEV: usize = 0;
    const FD_INDEX_ENGINE: usize = 1;

    let mut fds = Vec::new();

    fds.push(libc::pollfd {
                 fd: udev.as_raw_fd(),
                 revents: 0,
                 events: libc::POLLIN,
             });

    let eventable = engine.borrow().get_eventable();

    // The variable _dbus_client_index_start is only used when dbus support is compiled in, thus
    // we denote the value as not needed to compile when dbus support is not included.
    let (engine_eventable, poll_timeout, _dbus_client_index_start) = match eventable {
        Some(ref evt) => {
            fds.push(libc::pollfd {
                         fd: evt.get_pollable_fd(),
                         revents: 0,
                         events: libc::POLLIN,
                     });

            // Don't timeout if eventable, we are event driven
            (true, -1, FD_INDEX_ENGINE + 1)
        }

        // We periodically need to timeout as we are not event driven
        None => (false, 10000, FD_INDEX_ENGINE),
    };

    #[cfg(feature="dbus_enabled")]
    let (mut dbus_conn, mut tree, base_object_path, mut dbus_context) =
        libstratis::dbus_api::connect(Rc::clone(&engine))?;

    loop {
        // Process any udev block events
        if fds[FD_INDEX_UDEV].revents != 0 {
            loop {
                match udev.receive_event() {
                    Some(event) => {
                        if let Some((device, devnode)) = handle_udev_add(&event) {

                            // If block evaluate returns an error we are going to ignore it as
                            // there is nothing we can do for a device we are getting errors with.
                            let pool_uuid = engine
                                .borrow_mut()
                                .block_evaluate(device, devnode)
                                .unwrap_or(None);

                            // We need to pretend that we aren't using the variable _pool_uuid so
                            // that we can conditionally compile out the register_pool when dbus
                            // is not enabled.
                            if let Some(_pool_uuid) = pool_uuid {
                                #[cfg(feature="dbus_enabled")]
                                libstratis::dbus_api::register_pool(&mut dbus_conn,
                                                                    &Rc::clone(&engine),
                                                                    &mut dbus_context,
                                                                    &mut tree,
                                                                    _pool_uuid,
                                                                    &base_object_path)?;
                            }
                        }
                    }
                    None => {
                        break;
                    }
                };
            }
        }

        // Handle engine events, if the engine is eventable
        if engine_eventable {
            if fds[FD_INDEX_ENGINE].revents != 0 {
                fds[FD_INDEX_ENGINE].revents = 0;

                eventable
                    .as_ref()
                    .expect("eventable.is_some()")
                    .clear_event()?;

                engine.borrow_mut().evented()?;
            }
        } else {
            // Unconditionally call evented() if engine has no eventable.
            // This looks like a bad idea, but the only engine that has
            // no eventable is the sim engine, and for that engine, evented()
            // is essentially a no-op.
            engine.borrow_mut().evented()?;
        }

        // Iterate through D-Bus file descriptors (if enabled)
        #[cfg(feature="dbus_enabled")]
        {
            for pfd in fds[_dbus_client_index_start..]
                    .iter()
                    .filter(|pfd| pfd.revents != 0) {
                for item in dbus_conn.watch_handle(pfd.fd, WatchEvent::from_revents(pfd.revents)) {
                    if let Err(r) = libstratis::dbus_api::handle(&dbus_conn,
                                                                 &item,
                                                                 &mut tree,
                                                                 &dbus_context) {
                        print_err(From::from(r));
                    }
                }
            }

            // Refresh list of dbus fds to poll for every time. This can change as
            // D-Bus clients come and go.
            fds.truncate(_dbus_client_index_start);

            fds.extend(dbus_conn.watch_fds().iter().map(|w| w.to_pollfd()));
        }

        let r = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::c_ulong, poll_timeout) };
        assert!(r >= 0);
    }
}

fn main() {
    let error_code = match run() {
        Ok(_) => 0,
        Err(err) => {
            print_err(err);
            1
        }
    };
    exit(error_code);
}
<|endoftext|>


<commit_before><commit_msg>Remove remaining copy of the comment about idtype_t being an enum.<commit_after><|endoftext|>


<commit_before><commit_msg>Custom keybindings example for the library<commit_after>extern crate skim;
use skim::prelude::*;

// No action is actually performed on your filesystem!
// This example only produce friendly print statements!

fn fake_delete_item(item: &str) {
    println!("Deleting item `{}`...", item);
}

fn fake_create_item(item: &str) {
    println!("Creating a new item `{}`...", item);
}

pub fn main() {
    // Note: `accept` is a keyword used define custom actions.
    // For full list of accepted keywords see `parse_event` in `src/event.rs`.
    // `delete` and `create` are arbitrary keywords used for this example.
    let options = SkimOptionsBuilder::default()
        .multi(true)
        .bind(vec!["del:accept(delete)", "ctrl-a:accept(create)"])
        .build()
        .unwrap();

    Skim::run_with(&options, None).map(|out| match out.accept_key.as_ref().map(String::as_str) {
        // Delete each selected item
        Some("delete") => out.selected_items.iter().for_each(|i| fake_delete_item(&i.text())),
        // Create a new item based on the query
        Some("create") => fake_create_item(out.query.as_ref()),
        _ => (),
    });
}
<|endoftext|>


<commit_before><commit_msg>Simple Hello world<commit_after>fn main() {
    println!("Hello World!!");
}
<|endoftext|>


<commit_before><commit_msg>Also set archive mtime.<commit_after><|endoftext|>


<commit_before><commit_msg>Use variable mutable, so we can create an instance<commit_after><|endoftext|>


<commit_before>extern crate gl_generator;
extern crate khronos_api;

use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::Write;
use std::path::Path;
use gl_generator::generators::Generator;

mod textures;

fn main() {
    let dest = env::var("OUT_DIR").unwrap();
    let dest = Path::new(&dest);

    textures::build_texture_file(&mut File::create(&dest.join("textures.rs")).unwrap());

    // There is a `#[derive(Clone)]` line in the bindings that triggers a stack overflow
    // in rustc (https://github.com/rust-lang/rust/issues/26467).
    // Therefore we write the bindings to memory first, then remove this line, and then copy
    // to the file.
    let mut gl_bindings = Vec::new();
    generate_gl_bindings(&mut gl_bindings);
    let gl_bindings = String::from_utf8(gl_bindings).unwrap();
    let gl_bindings = gl_bindings.replace("#[derive(Clone)]", "");
    let mut file_output = File::create(&dest.join("gl_bindings.rs")).unwrap();
    file_output.write_all(&gl_bindings.into_bytes()).unwrap();
}

fn generate_gl_bindings<W>(dest: &mut W) where W: Write {
    let gl_registry = {
        let reader = BufReader::new(khronos_api::GL_XML);
        let ns = gl_generator::registry::Ns::Gl;

        let filter = gl_generator::registry::Filter {
            fallbacks: gl_generator::Fallbacks::None,
            api: gl_generator::registry::Ns::Gl.to_string(),
            extensions: vec![
                "GL_AMD_depth_clamp_separate".to_string(),
                "GL_APPLE_vertex_array_object".to_string(),
                "GL_ARB_bindless_texture".to_string(),
                "GL_ARB_buffer_storage".to_string(),
                "GL_ARB_compute_shader".to_string(),
                "GL_ARB_copy_buffer".to_string(),
                "GL_ARB_debug_output".to_string(),
                "GL_ARB_depth_texture".to_string(),
                "GL_ARB_direct_state_access".to_string(),
                "GL_ARB_draw_buffers".to_string(),
                "GL_ARB_ES2_compatibility".to_string(),
                "GL_ARB_ES3_compatibility".to_string(),
                "GL_ARB_ES3_1_compatibility".to_string(),
                "GL_ARB_ES3_2_compatibility".to_string(),
                "GL_ARB_framebuffer_sRGB".to_string(),
                "GL_ARB_geometry_shader4".to_string(),
                "GL_ARB_gpu_shader_fp64".to_string(),
                "GL_ARB_gpu_shader_int64".to_string(),
                "GL_ARB_invalidate_subdata".to_string(),
                "GL_ARB_multi_draw_indirect".to_string(),
                "GL_ARB_occlusion_query".to_string(),
                "GL_ARB_pixel_buffer_object".to_string(),
                "GL_ARB_robustness".to_string(),
                "GL_ARB_shader_image_load_store".to_string(),
                "GL_ARB_shader_objects".to_string(),
                "GL_ARB_texture_buffer_object".to_string(),
                "GL_ARB_texture_float".to_string(),
                "GL_ARB_texture_multisample".to_string(),
                "GL_ARB_texture_rg".to_string(),
                "GL_ARB_texture_rgb10_a2ui".to_string(),
                "GL_ARB_transform_feedback3".to_string(),
                "GL_ARB_vertex_buffer_object".to_string(),
                "GL_ARB_vertex_shader".to_string(),
                "GL_ATI_draw_buffers".to_string(),
                "GL_ATI_meminfo".to_string(),
                "GL_EXT_debug_marker".to_string(),
                "GL_EXT_direct_state_access".to_string(),
                "GL_EXT_framebuffer_blit".to_string(),
                "GL_EXT_framebuffer_multisample".to_string(),
                "GL_EXT_framebuffer_object".to_string(),
                "GL_EXT_framebuffer_sRGB".to_string(),
                "GL_EXT_gpu_shader4".to_string(),
                "GL_EXT_packed_depth_stencil".to_string(),
                "GL_EXT_provoking_vertex".to_string(),
                "GL_EXT_texture_array".to_string(),
                "GL_EXT_texture_buffer_object".to_string(),
                "GL_EXT_texture_compression_s3tc".to_string(),
                "GL_EXT_texture_filter_anisotropic".to_string(),
                "GL_EXT_texture_integer".to_string(),
                "GL_EXT_texture_sRGB".to_string(),
                "GL_EXT_transform_feedback".to_string(),
                "GL_GREMEDY_string_marker".to_string(),
                "GL_KHR_robustness".to_string(),
                "GL_NVX_gpu_memory_info".to_string(),
                "GL_NV_conditional_render".to_string(),
                "GL_NV_vertex_attrib_integer_64bit".to_string(),
            ],
            version: "4.5".to_string(),
            profile: "compatibility".to_string(),
        };

        gl_generator::registry::Registry::from_xml(reader, ns, Some(filter))
    };

    let gles_registry = {
        let reader = BufReader::new(khronos_api::GL_XML);
        let ns = gl_generator::registry::Ns::Gles2;

        let filter = gl_generator::registry::Filter {
            fallbacks: gl_generator::Fallbacks::None,
            api: gl_generator::registry::Ns::Gles2.to_string(),
            extensions: vec![
                "GL_ANGLE_framebuffer_multisample".to_string(),
                "GL_APPLE_framebuffer_multisample".to_string(),
                "GL_APPLE_sync".to_string(),
                "GL_ARM_rgba8".to_string(),
                "GL_EXT_buffer_storage".to_string(),
                "GL_EXT_disjoint_timer_query".to_string(),
                "GL_EXT_multi_draw_indirect".to_string(),
                "GL_EXT_multisampled_render_to_texture".to_string(),
                "GL_EXT_occlusion_query_boolean".to_string(),
                "GL_EXT_primitive_bounding_box".to_string(),
                "GL_EXT_robustness".to_string(),
                "GL_KHR_debug".to_string(),
                "GL_NV_copy_buffer".to_string(),
                "GL_NV_framebuffer_multisample".to_string(),
                "GL_NV_internalformat_sample_query".to_string(),
                "GL_NV_pixel_buffer_object".to_string(),
                "GL_OES_depth_texture".to_string(),
                "GL_OES_draw_elements_base_vertex".to_string(),
                "GL_OES_packed_depth_stencil".to_string(),
                "GL_OES_primitive_bounding_box".to_string(),
                "GL_OES_rgb8_rgba8".to_string(),
                "GL_OES_texture_buffer".to_string(),
                "GL_OES_texture_npot".to_string(),
                "GL_OES_vertex_array_object".to_string(),
                "GL_OES_vertex_type_10_10_10_2".to_string(),
            ],
            version: "3.2".to_string(),
            profile: "compatibility".to_string(),
        };

        gl_generator::registry::Registry::from_xml(reader, ns, Some(filter))
    };

    gl_generator::StructGenerator.write(&(gl_registry + gles_registry),
                                        gl_generator::registry::Ns::Gl, dest).unwrap();
}
<commit_msg>Use the new build script dependencies system<commit_after>extern crate gl_generator;
extern crate khronos_api;

use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::Write;
use std::path::Path;
use gl_generator::generators::Generator;

mod textures;

fn main() {
    let dest = env::var("OUT_DIR").unwrap();
    let dest = Path::new(&dest);

    textures::build_texture_file(&mut File::create(&dest.join("textures.rs")).unwrap());
    println!("cargo:rerun-if-changed=build/main.rs");

    // There is a `#[derive(Clone)]` line in the bindings that triggers a stack overflow
    // in rustc (https://github.com/rust-lang/rust/issues/26467).
    // Therefore we write the bindings to memory first, then remove this line, and then copy
    // to the file.
    let mut gl_bindings = Vec::new();
    generate_gl_bindings(&mut gl_bindings);
    let gl_bindings = String::from_utf8(gl_bindings).unwrap();
    let gl_bindings = gl_bindings.replace("#[derive(Clone)]", "");
    let mut file_output = File::create(&dest.join("gl_bindings.rs")).unwrap();
    file_output.write_all(&gl_bindings.into_bytes()).unwrap();
}

fn generate_gl_bindings<W>(dest: &mut W) where W: Write {
    let gl_registry = {
        let reader = BufReader::new(khronos_api::GL_XML);
        let ns = gl_generator::registry::Ns::Gl;

        let filter = gl_generator::registry::Filter {
            fallbacks: gl_generator::Fallbacks::None,
            api: gl_generator::registry::Ns::Gl.to_string(),
            extensions: vec![
                "GL_AMD_depth_clamp_separate".to_string(),
                "GL_APPLE_vertex_array_object".to_string(),
                "GL_ARB_bindless_texture".to_string(),
                "GL_ARB_buffer_storage".to_string(),
                "GL_ARB_compute_shader".to_string(),
                "GL_ARB_copy_buffer".to_string(),
                "GL_ARB_debug_output".to_string(),
                "GL_ARB_depth_texture".to_string(),
                "GL_ARB_direct_state_access".to_string(),
                "GL_ARB_draw_buffers".to_string(),
                "GL_ARB_ES2_compatibility".to_string(),
                "GL_ARB_ES3_compatibility".to_string(),
                "GL_ARB_ES3_1_compatibility".to_string(),
                "GL_ARB_ES3_2_compatibility".to_string(),
                "GL_ARB_framebuffer_sRGB".to_string(),
                "GL_ARB_geometry_shader4".to_string(),
                "GL_ARB_gpu_shader_fp64".to_string(),
                "GL_ARB_gpu_shader_int64".to_string(),
                "GL_ARB_invalidate_subdata".to_string(),
                "GL_ARB_multi_draw_indirect".to_string(),
                "GL_ARB_occlusion_query".to_string(),
                "GL_ARB_pixel_buffer_object".to_string(),
                "GL_ARB_robustness".to_string(),
                "GL_ARB_shader_image_load_store".to_string(),
                "GL_ARB_shader_objects".to_string(),
                "GL_ARB_texture_buffer_object".to_string(),
                "GL_ARB_texture_float".to_string(),
                "GL_ARB_texture_multisample".to_string(),
                "GL_ARB_texture_rg".to_string(),
                "GL_ARB_texture_rgb10_a2ui".to_string(),
                "GL_ARB_transform_feedback3".to_string(),
                "GL_ARB_vertex_buffer_object".to_string(),
                "GL_ARB_vertex_shader".to_string(),
                "GL_ATI_draw_buffers".to_string(),
                "GL_ATI_meminfo".to_string(),
                "GL_EXT_debug_marker".to_string(),
                "GL_EXT_direct_state_access".to_string(),
                "GL_EXT_framebuffer_blit".to_string(),
                "GL_EXT_framebuffer_multisample".to_string(),
                "GL_EXT_framebuffer_object".to_string(),
                "GL_EXT_framebuffer_sRGB".to_string(),
                "GL_EXT_gpu_shader4".to_string(),
                "GL_EXT_packed_depth_stencil".to_string(),
                "GL_EXT_provoking_vertex".to_string(),
                "GL_EXT_texture_array".to_string(),
                "GL_EXT_texture_buffer_object".to_string(),
                "GL_EXT_texture_compression_s3tc".to_string(),
                "GL_EXT_texture_filter_anisotropic".to_string(),
                "GL_EXT_texture_integer".to_string(),
                "GL_EXT_texture_sRGB".to_string(),
                "GL_EXT_transform_feedback".to_string(),
                "GL_GREMEDY_string_marker".to_string(),
                "GL_KHR_robustness".to_string(),
                "GL_NVX_gpu_memory_info".to_string(),
                "GL_NV_conditional_render".to_string(),
                "GL_NV_vertex_attrib_integer_64bit".to_string(),
            ],
            version: "4.5".to_string(),
            profile: "compatibility".to_string(),
        };

        gl_generator::registry::Registry::from_xml(reader, ns, Some(filter))
    };

    let gles_registry = {
        let reader = BufReader::new(khronos_api::GL_XML);
        let ns = gl_generator::registry::Ns::Gles2;

        let filter = gl_generator::registry::Filter {
            fallbacks: gl_generator::Fallbacks::None,
            api: gl_generator::registry::Ns::Gles2.to_string(),
            extensions: vec![
                "GL_ANGLE_framebuffer_multisample".to_string(),
                "GL_APPLE_framebuffer_multisample".to_string(),
                "GL_APPLE_sync".to_string(),
                "GL_ARM_rgba8".to_string(),
                "GL_EXT_buffer_storage".to_string(),
                "GL_EXT_disjoint_timer_query".to_string(),
                "GL_EXT_multi_draw_indirect".to_string(),
                "GL_EXT_multisampled_render_to_texture".to_string(),
                "GL_EXT_occlusion_query_boolean".to_string(),
                "GL_EXT_primitive_bounding_box".to_string(),
                "GL_EXT_robustness".to_string(),
                "GL_KHR_debug".to_string(),
                "GL_NV_copy_buffer".to_string(),
                "GL_NV_framebuffer_multisample".to_string(),
                "GL_NV_internalformat_sample_query".to_string(),
                "GL_NV_pixel_buffer_object".to_string(),
                "GL_OES_depth_texture".to_string(),
                "GL_OES_draw_elements_base_vertex".to_string(),
                "GL_OES_packed_depth_stencil".to_string(),
                "GL_OES_primitive_bounding_box".to_string(),
                "GL_OES_rgb8_rgba8".to_string(),
                "GL_OES_texture_buffer".to_string(),
                "GL_OES_texture_npot".to_string(),
                "GL_OES_vertex_array_object".to_string(),
                "GL_OES_vertex_type_10_10_10_2".to_string(),
            ],
            version: "3.2".to_string(),
            profile: "compatibility".to_string(),
        };

        gl_generator::registry::Registry::from_xml(reader, ns, Some(filter))
    };

    gl_generator::StructGenerator.write(&(gl_registry + gles_registry),
                                        gl_generator::registry::Ns::Gl, dest).unwrap();
}
<|endoftext|>