<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 lint;
use metadata::cstore::CStore;
use metadata::filesearch;
use session::search_paths::PathKind;
use util::nodemap::NodeMap;

use regex::Regex;

use syntax::ast::NodeId;
use syntax::codemap::Span;
use syntax::diagnostic::{self, Emitter};
use syntax::diagnostics;
use syntax::feature_gate;
use syntax::parse;
use syntax::parse::token;
use syntax::parse::ParseSess;
use syntax::{ast, codemap};

use rustc_back::target::Target;

use std::os;
use std::cell::{Cell, RefCell};

pub mod config;
pub mod search_paths;

// Represents the data associated with a compilation
// session for a single crate.
pub struct Session {
    pub target: config::Config,
    pub host: Target,
    pub opts: config::Options,
    pub cstore: CStore,
    pub parse_sess: ParseSess,
    // For a library crate, this is always none
    pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
    pub entry_type: Cell<Option<config::EntryFnType>>,
    pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
    pub default_sysroot: Option<Path>,
    // The name of the root source file of the crate, in the local file system. The path is always
    // expected to be absolute. `None` means that there is no source file.
    pub local_crate_source_file: Option<Path>,
    pub working_dir: Path,
    pub lint_store: RefCell<lint::LintStore>,
    pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
    pub crate_types: RefCell<Vec<config::CrateType>>,
    pub crate_metadata: RefCell<Vec<String>>,
    pub features: RefCell<feature_gate::Features>,

    /// The maximum recursion limit for potentially infinitely recursive
    /// operations such as auto-dereference and monomorphization.
    pub recursion_limit: Cell<uint>,

    pub can_print_warnings: bool
}

impl Session {
    pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
        self.diagnostic().span_fatal(sp, msg)
    }
    pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! {
        self.diagnostic().span_fatal_with_code(sp, msg, code)
    }
    pub fn fatal(&self, msg: &str) -> ! {
        self.diagnostic().handler().fatal(msg)
    }
    pub fn span_err(&self, sp: Span, msg: &str) {
        // Conditions for enabling multi-line errors:
        if !msg.contains("mismatched types") &&
           !msg.contains("type mismatch resolving") &&
           !msg.contains("if and else have incompatible types") &&
           !msg.contains("if may be missing an else clause") &&
           !msg.contains("match arms have incompatible types") &&
           !msg.contains("structure constructor specifies a structure of type") {
            return self.diagnostic().span_err(sp, msg);
        }

        let first  = Regex::new(r"[( ]expected").unwrap();
        let second = Regex::new(r" found").unwrap();
        let third  = Regex::new(
                     r"\((values differ|lifetime|cyclic type of infinite size)").unwrap();

        let mut new_msg = String::new();
        let mut head = 0u;

        // Insert `\n` before expected and found.
        for (pos1, pos2) in first.find_iter(msg).zip(
                            second.find_iter(msg)) {
            new_msg = new_msg +
            // A `(` may be preceded by a space and it should be trimmed
                      msg[head..pos1.0].trim_right() + // prefix
                      "\n" +                           // insert before first
                      &msg[pos1.0..pos1.1] +           // insert what first matched
                      &msg[pos1.1..pos2.0] +           // between matches
                      "\n   " +                        // insert before second
            //           123
            // `expected` is 3 char longer than `found`. To align the types, `found` gets
            // 3 spaces prepended.
                      &msg[pos2.0..pos2.1];            // insert what second matched

            head = pos2.1;
        }

        let mut tail = &msg[head..];
        // Insert `\n` before any remaining messages which match.
        for pos in third.find_iter(tail).take(1) {
            // The end of the message may just be wrapped in `()` without `expected`/`found`.
            // Push this also to a new line and add the final tail after.
            new_msg = new_msg +
            // `(` is usually preceded by a space and should be trimmed.
                      tail[..pos.0].trim_right() + // prefix
                      "\n" +                       // insert before paren
                      &tail[pos.0..];              // append the tail

            tail = "";
        }

        new_msg.push_str(tail);
        self.diagnostic().span_err(sp, &new_msg[])
    }
    pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
        self.diagnostic().span_err_with_code(sp, msg, code)
    }
    pub fn err(&self, msg: &str) {
        self.diagnostic().handler().err(msg)
    }
    pub fn err_count(&self) -> uint {
        self.diagnostic().handler().err_count()
    }
    pub fn has_errors(&self) -> bool {
        self.diagnostic().handler().has_errors()
    }
    pub fn abort_if_errors(&self) {
        self.diagnostic().handler().abort_if_errors()
    }
    pub fn span_warn(&self, sp: Span, msg: &str) {
        if self.can_print_warnings {
            self.diagnostic().span_warn(sp, msg)
        }
    }
    pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
        if self.can_print_warnings {
            self.diagnostic().span_warn_with_code(sp, msg, code)
        }
    }
    pub fn warn(&self, msg: &str) {
        if self.can_print_warnings {
            self.diagnostic().handler().warn(msg)
        }
    }
    pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
        match opt_sp {
            Some(sp) => self.span_warn(sp, msg),
            None => self.warn(msg),
        }
    }
    pub fn span_note(&self, sp: Span, msg: &str) {
        self.diagnostic().span_note(sp, msg)
    }
    pub fn span_end_note(&self, sp: Span, msg: &str) {
        self.diagnostic().span_end_note(sp, msg)
    }
    pub fn span_help(&self, sp: Span, msg: &str) {
        self.diagnostic().span_help(sp, msg)
    }
    pub fn fileline_note(&self, sp: Span, msg: &str) {
        self.diagnostic().fileline_note(sp, msg)
    }
    pub fn fileline_help(&self, sp: Span, msg: &str) {
        self.diagnostic().fileline_help(sp, msg)
    }
    pub fn note(&self, msg: &str) {
        self.diagnostic().handler().note(msg)
    }
    pub fn help(&self, msg: &str) {
        self.diagnostic().handler().note(msg)
    }
    pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
        match opt_sp {
            Some(sp) => self.span_bug(sp, msg),
            None => self.bug(msg),
        }
    }
    pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
        self.diagnostic().span_bug(sp, msg)
    }
    pub fn bug(&self, msg: &str) -> ! {
        self.diagnostic().handler().bug(msg)
    }
    pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
        self.diagnostic().span_unimpl(sp, msg)
    }
    pub fn unimpl(&self, msg: &str) -> ! {
        self.diagnostic().handler().unimpl(msg)
    }
    pub fn add_lint(&self,
                    lint: &'static lint::Lint,
                    id: ast::NodeId,
                    sp: Span,
                    msg: String) {
        let lint_id = lint::LintId::of(lint);
        let mut lints = self.lints.borrow_mut();
        match lints.get_mut(&id) {
            Some(arr) => { arr.push((lint_id, sp, msg)); return; }
            None => {}
        }
        lints.insert(id, vec!((lint_id, sp, msg)));
    }
    pub fn next_node_id(&self) -> ast::NodeId {
        self.parse_sess.next_node_id()
    }
    pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
        self.parse_sess.reserve_node_ids(count)
    }
    pub fn diagnostic<'a>(&'a self) -> &'a diagnostic::SpanHandler {
        &self.parse_sess.span_diagnostic
    }
    pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
        &self.parse_sess.span_diagnostic.cm
    }
    // This exists to help with refactoring to eliminate impossible
    // cases later on
    pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
        self.span_bug(sp,
                      &format!("impossible case reached: {}", msg)[]);
    }
    pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
    pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
    pub fn count_llvm_insns(&self) -> bool {
        self.opts.debugging_opts.count_llvm_insns
    }
    pub fn count_type_sizes(&self) -> bool {
        self.opts.debugging_opts.count_type_sizes
    }
    pub fn time_llvm_passes(&self) -> bool {
        self.opts.debugging_opts.time_llvm_passes
    }
    pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
    pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
    pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
    pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
    pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
    pub fn print_llvm_passes(&self) -> bool {
        self.opts.debugging_opts.print_llvm_passes
    }
    pub fn lto(&self) -> bool {
        self.opts.cg.lto
    }
    pub fn no_landing_pads(&self) -> bool {
        self.opts.debugging_opts.no_landing_pads
    }
    pub fn unstable_options(&self) -> bool {
        self.opts.debugging_opts.unstable_options
    }
    pub fn print_enum_sizes(&self) -> bool {
        self.opts.debugging_opts.print_enum_sizes
    }
    pub fn sysroot<'a>(&'a self) -> &'a Path {
        match self.opts.maybe_sysroot {
            Some (ref sysroot) => sysroot,
            None => self.default_sysroot.as_ref()
                        .expect("missing sysroot and default_sysroot in Session")
        }
    }
    pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
        filesearch::FileSearch::new(self.sysroot(),
                                    &self.opts.target_triple[],
                                    &self.opts.search_paths,
                                    kind)
    }
    pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
        filesearch::FileSearch::new(
            self.sysroot(),
            config::host_triple(),
            &self.opts.search_paths,
            kind)
    }
}

pub fn build_session(sopts: config::Options,
                     local_crate_source_file: Option<Path>,
                     registry: diagnostics::registry::Registry)
                     -> Session {
    let codemap = codemap::CodeMap::new();
    let diagnostic_handler =
        diagnostic::default_handler(sopts.color, Some(registry));
    let span_diagnostic_handler =
        diagnostic::mk_span_handler(diagnostic_handler, codemap);

    build_session_(sopts, local_crate_source_file, span_diagnostic_handler)
}

pub fn build_session_(sopts: config::Options,
                      local_crate_source_file: Option<Path>,
                      span_diagnostic: diagnostic::SpanHandler)
                      -> Session {
    let host = match Target::search(config::host_triple()) {
        Ok(t) => t,
        Err(e) => {
            span_diagnostic.handler()
                .fatal((format!("Error loading host specification: {}", e)).as_slice());
    }
    };
    let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
    let p_s = parse::new_parse_sess_special_handler(span_diagnostic);
    let default_sysroot = match sopts.maybe_sysroot {
        Some(_) => None,
        None => Some(filesearch::get_or_default_sysroot())
    };

    // Make the path absolute, if necessary
    let local_crate_source_file = local_crate_source_file.map(|path|
        if path.is_absolute() {
            path.clone()
        } else {
            os::getcwd().unwrap().join(&path)
        }
    );

    let can_print_warnings = sopts.lint_opts
        .iter()
        .filter(|&&(ref key, _)| *key == "warnings")
        .map(|&(_, ref level)| *level != lint::Allow)
        .last()
        .unwrap_or(true);

    let sess = Session {
        target: target_cfg,
        host: host,
        opts: sopts,
        cstore: CStore::new(token::get_ident_interner()),
        parse_sess: p_s,
        // For a library crate, this is always none
        entry_fn: RefCell::new(None),
        entry_type: Cell::new(None),
        plugin_registrar_fn: Cell::new(None),
        default_sysroot: default_sysroot,
        local_crate_source_file: local_crate_source_file,
        working_dir: os::getcwd().unwrap(),
        lint_store: RefCell::new(lint::LintStore::new()),
        lints: RefCell::new(NodeMap()),
        crate_types: RefCell::new(Vec::new()),
        crate_metadata: RefCell::new(Vec::new()),
        features: RefCell::new(feature_gate::Features::new()),
        recursion_limit: Cell::new(64),
        can_print_warnings: can_print_warnings
    };

    sess.lint_store.borrow_mut().register_builtin(Some(&sess));
    sess
}

// Seems out of place, but it uses session, so I'm putting it here
pub fn expect<T, M>(sess: &Session, opt: Option<T>, msg: M) -> T where
    M: FnOnce() -> String,
{
    diagnostic::expect(sess.diagnostic(), opt, msg)
}

pub fn early_error(msg: &str) -> ! {
    let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
    emitter.emit(None, msg, None, diagnostic::Fatal);
    panic!(diagnostic::FatalError);
}

pub fn early_warn(msg: &str) {
    let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
    emitter.emit(None, msg, None, diagnostic::Warning);
}
<commit_msg>Make multiline errors work with codes<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 lint;
use metadata::cstore::CStore;
use metadata::filesearch;
use session::search_paths::PathKind;
use util::nodemap::NodeMap;

use regex::Regex;

use syntax::ast::NodeId;
use syntax::codemap::Span;
use syntax::diagnostic::{self, Emitter};
use syntax::diagnostics;
use syntax::feature_gate;
use syntax::parse;
use syntax::parse::token;
use syntax::parse::ParseSess;
use syntax::{ast, codemap};

use rustc_back::target::Target;

use std::os;
use std::cell::{Cell, RefCell};

pub mod config;
pub mod search_paths;

// Represents the data associated with a compilation
// session for a single crate.
pub struct Session {
    pub target: config::Config,
    pub host: Target,
    pub opts: config::Options,
    pub cstore: CStore,
    pub parse_sess: ParseSess,
    // For a library crate, this is always none
    pub entry_fn: RefCell<Option<(NodeId, codemap::Span)>>,
    pub entry_type: Cell<Option<config::EntryFnType>>,
    pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
    pub default_sysroot: Option<Path>,
    // The name of the root source file of the crate, in the local file system. The path is always
    // expected to be absolute. `None` means that there is no source file.
    pub local_crate_source_file: Option<Path>,
    pub working_dir: Path,
    pub lint_store: RefCell<lint::LintStore>,
    pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
    pub crate_types: RefCell<Vec<config::CrateType>>,
    pub crate_metadata: RefCell<Vec<String>>,
    pub features: RefCell<feature_gate::Features>,

    /// The maximum recursion limit for potentially infinitely recursive
    /// operations such as auto-dereference and monomorphization.
    pub recursion_limit: Cell<uint>,

    pub can_print_warnings: bool
}

impl Session {
    pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
        self.diagnostic().span_fatal(sp, msg)
    }
    pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! {
        self.diagnostic().span_fatal_with_code(sp, msg, code)
    }
    pub fn fatal(&self, msg: &str) -> ! {
        self.diagnostic().handler().fatal(msg)
    }
    pub fn span_err(&self, sp: Span, msg: &str) {
        match split_msg_into_multilines(msg) {
            Some(msg) => self.diagnostic().span_err(sp, &msg[]),
            None => self.diagnostic().span_err(sp, msg)
        }
    }
    pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
        match split_msg_into_multilines(msg) {
            Some(msg) => self.diagnostic().span_err_with_code(sp, &msg[], code),
            None => self.diagnostic().span_err_with_code(sp, msg, code)
        }
    }
    pub fn err(&self, msg: &str) {
        self.diagnostic().handler().err(msg)
    }
    pub fn err_count(&self) -> uint {
        self.diagnostic().handler().err_count()
    }
    pub fn has_errors(&self) -> bool {
        self.diagnostic().handler().has_errors()
    }
    pub fn abort_if_errors(&self) {
        self.diagnostic().handler().abort_if_errors()
    }
    pub fn span_warn(&self, sp: Span, msg: &str) {
        if self.can_print_warnings {
            self.diagnostic().span_warn(sp, msg)
        }
    }
    pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
        if self.can_print_warnings {
            self.diagnostic().span_warn_with_code(sp, msg, code)
        }
    }
    pub fn warn(&self, msg: &str) {
        if self.can_print_warnings {
            self.diagnostic().handler().warn(msg)
        }
    }
    pub fn opt_span_warn(&self, opt_sp: Option<Span>, msg: &str) {
        match opt_sp {
            Some(sp) => self.span_warn(sp, msg),
            None => self.warn(msg),
        }
    }
    pub fn span_note(&self, sp: Span, msg: &str) {
        self.diagnostic().span_note(sp, msg)
    }
    pub fn span_end_note(&self, sp: Span, msg: &str) {
        self.diagnostic().span_end_note(sp, msg)
    }
    pub fn span_help(&self, sp: Span, msg: &str) {
        self.diagnostic().span_help(sp, msg)
    }
    pub fn fileline_note(&self, sp: Span, msg: &str) {
        self.diagnostic().fileline_note(sp, msg)
    }
    pub fn fileline_help(&self, sp: Span, msg: &str) {
        self.diagnostic().fileline_help(sp, msg)
    }
    pub fn note(&self, msg: &str) {
        self.diagnostic().handler().note(msg)
    }
    pub fn help(&self, msg: &str) {
        self.diagnostic().handler().note(msg)
    }
    pub fn opt_span_bug(&self, opt_sp: Option<Span>, msg: &str) -> ! {
        match opt_sp {
            Some(sp) => self.span_bug(sp, msg),
            None => self.bug(msg),
        }
    }
    pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
        self.diagnostic().span_bug(sp, msg)
    }
    pub fn bug(&self, msg: &str) -> ! {
        self.diagnostic().handler().bug(msg)
    }
    pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
        self.diagnostic().span_unimpl(sp, msg)
    }
    pub fn unimpl(&self, msg: &str) -> ! {
        self.diagnostic().handler().unimpl(msg)
    }
    pub fn add_lint(&self,
                    lint: &'static lint::Lint,
                    id: ast::NodeId,
                    sp: Span,
                    msg: String) {
        let lint_id = lint::LintId::of(lint);
        let mut lints = self.lints.borrow_mut();
        match lints.get_mut(&id) {
            Some(arr) => { arr.push((lint_id, sp, msg)); return; }
            None => {}
        }
        lints.insert(id, vec!((lint_id, sp, msg)));
    }
    pub fn next_node_id(&self) -> ast::NodeId {
        self.parse_sess.next_node_id()
    }
    pub fn reserve_node_ids(&self, count: ast::NodeId) -> ast::NodeId {
        self.parse_sess.reserve_node_ids(count)
    }
    pub fn diagnostic<'a>(&'a self) -> &'a diagnostic::SpanHandler {
        &self.parse_sess.span_diagnostic
    }
    pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
        &self.parse_sess.span_diagnostic.cm
    }
    // This exists to help with refactoring to eliminate impossible
    // cases later on
    pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
        self.span_bug(sp,
                      &format!("impossible case reached: {}", msg)[]);
    }
    pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
    pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
    pub fn count_llvm_insns(&self) -> bool {
        self.opts.debugging_opts.count_llvm_insns
    }
    pub fn count_type_sizes(&self) -> bool {
        self.opts.debugging_opts.count_type_sizes
    }
    pub fn time_llvm_passes(&self) -> bool {
        self.opts.debugging_opts.time_llvm_passes
    }
    pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
    pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
    pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
    pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
    pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
    pub fn print_llvm_passes(&self) -> bool {
        self.opts.debugging_opts.print_llvm_passes
    }
    pub fn lto(&self) -> bool {
        self.opts.cg.lto
    }
    pub fn no_landing_pads(&self) -> bool {
        self.opts.debugging_opts.no_landing_pads
    }
    pub fn unstable_options(&self) -> bool {
        self.opts.debugging_opts.unstable_options
    }
    pub fn print_enum_sizes(&self) -> bool {
        self.opts.debugging_opts.print_enum_sizes
    }
    pub fn sysroot<'a>(&'a self) -> &'a Path {
        match self.opts.maybe_sysroot {
            Some (ref sysroot) => sysroot,
            None => self.default_sysroot.as_ref()
                        .expect("missing sysroot and default_sysroot in Session")
        }
    }
    pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
        filesearch::FileSearch::new(self.sysroot(),
                                    &self.opts.target_triple[],
                                    &self.opts.search_paths,
                                    kind)
    }
    pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
        filesearch::FileSearch::new(
            self.sysroot(),
            config::host_triple(),
            &self.opts.search_paths,
            kind)
    }
}

fn split_msg_into_multilines(msg: &str) -> Option<String> {
    // Conditions for enabling multi-line errors:
    if !msg.contains("mismatched types") &&
        !msg.contains("type mismatch resolving") &&
        !msg.contains("if and else have incompatible types") &&
        !msg.contains("if may be missing an else clause") &&
        !msg.contains("match arms have incompatible types") &&
        !msg.contains("structure constructor specifies a structure of type") {
            return None
    }

    let first  = Regex::new(r"[( ]expected").unwrap();
    let second = Regex::new(r" found").unwrap();
    let third  = Regex::new(
        r"\((values differ|lifetime|cyclic type of infinite size)").unwrap();

    let mut new_msg = String::new();
    let mut head = 0u;

    // Insert `\n` before expected and found.
    for (pos1, pos2) in first.find_iter(msg).zip(
        second.find_iter(msg)) {
        new_msg = new_msg +
            // A `(` may be preceded by a space and it should be trimmed
            msg[head..pos1.0].trim_right() + // prefix
            "\n" +                           // insert before first
            &msg[pos1.0..pos1.1] +           // insert what first matched
            &msg[pos1.1..pos2.0] +           // between matches
            "\n   " +                        // insert before second
            //           123
            // `expected` is 3 char longer than `found`. To align the types, `found` gets
            // 3 spaces prepended.
            &msg[pos2.0..pos2.1];            // insert what second matched

        head = pos2.1;
    }

    let mut tail = &msg[head..];
    // Insert `\n` before any remaining messages which match.
    for pos in third.find_iter(tail).take(1) {
        // The end of the message may just be wrapped in `()` without `expected`/`found`.
        // Push this also to a new line and add the final tail after.
        new_msg = new_msg +
            // `(` is usually preceded by a space and should be trimmed.
            tail[..pos.0].trim_right() + // prefix
            "\n" +                       // insert before paren
            &tail[pos.0..];              // append the tail

        tail = "";
    }

    new_msg.push_str(tail);

    return Some(new_msg)
}

pub fn build_session(sopts: config::Options,
                     local_crate_source_file: Option<Path>,
                     registry: diagnostics::registry::Registry)
                     -> Session {
    let codemap = codemap::CodeMap::new();
    let diagnostic_handler =
        diagnostic::default_handler(sopts.color, Some(registry));
    let span_diagnostic_handler =
        diagnostic::mk_span_handler(diagnostic_handler, codemap);

    build_session_(sopts, local_crate_source_file, span_diagnostic_handler)
}

pub fn build_session_(sopts: config::Options,
                      local_crate_source_file: Option<Path>,
                      span_diagnostic: diagnostic::SpanHandler)
                      -> Session {
    let host = match Target::search(config::host_triple()) {
        Ok(t) => t,
        Err(e) => {
            span_diagnostic.handler()
                .fatal((format!("Error loading host specification: {}", e)).as_slice());
    }
    };
    let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
    let p_s = parse::new_parse_sess_special_handler(span_diagnostic);
    let default_sysroot = match sopts.maybe_sysroot {
        Some(_) => None,
        None => Some(filesearch::get_or_default_sysroot())
    };

    // Make the path absolute, if necessary
    let local_crate_source_file = local_crate_source_file.map(|path|
        if path.is_absolute() {
            path.clone()
        } else {
            os::getcwd().unwrap().join(&path)
        }
    );

    let can_print_warnings = sopts.lint_opts
        .iter()
        .filter(|&&(ref key, _)| *key == "warnings")
        .map(|&(_, ref level)| *level != lint::Allow)
        .last()
        .unwrap_or(true);

    let sess = Session {
        target: target_cfg,
        host: host,
        opts: sopts,
        cstore: CStore::new(token::get_ident_interner()),
        parse_sess: p_s,
        // For a library crate, this is always none
        entry_fn: RefCell::new(None),
        entry_type: Cell::new(None),
        plugin_registrar_fn: Cell::new(None),
        default_sysroot: default_sysroot,
        local_crate_source_file: local_crate_source_file,
        working_dir: os::getcwd().unwrap(),
        lint_store: RefCell::new(lint::LintStore::new()),
        lints: RefCell::new(NodeMap()),
        crate_types: RefCell::new(Vec::new()),
        crate_metadata: RefCell::new(Vec::new()),
        features: RefCell::new(feature_gate::Features::new()),
        recursion_limit: Cell::new(64),
        can_print_warnings: can_print_warnings
    };

    sess.lint_store.borrow_mut().register_builtin(Some(&sess));
    sess
}

// Seems out of place, but it uses session, so I'm putting it here
pub fn expect<T, M>(sess: &Session, opt: Option<T>, msg: M) -> T where
    M: FnOnce() -> String,
{
    diagnostic::expect(sess.diagnostic(), opt, msg)
}

pub fn early_error(msg: &str) -> ! {
    let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
    emitter.emit(None, msg, None, diagnostic::Fatal);
    panic!(diagnostic::FatalError);
}

pub fn early_warn(msg: &str) {
    let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
    emitter.emit(None, msg, None, diagnostic::Warning);
}
<|endoftext|>


<commit_before><commit_msg>Add read from file<commit_after><|endoftext|>


<commit_before><commit_msg>removes unnecessary mutability<commit_after><|endoftext|>


<commit_before><commit_msg>adding mod escaping<commit_after>// mod escaping

const ESCAPE_CHARS: [(char, &'static str); 11] = [('\\', "\\\\"),
                                                  (' ', "\\s"),
                                                  ('/', "\\/"),
                                                  ('|', "\\p"),
                                                  (7 as char, "\\a"),
                                                  (8 as char, "\\b"),
                                                  (9 as char, "\\t"),
                                                  (10 as char, "\\n"),
                                                  (11 as char, "\\v"),
                                                  (12 as char, "\\f"),
                                                  (13 as char, "\\r")];

/// escapes all chars described in the server query manual
/// # Example
/// ```
/// use sqlib::escaping::escape;
///
/// let unescaped = "hello world/|\\".to_string();
/// let escaped = "hello\\sworld\\/\\p\\\\".to_string();
///
/// let s = escape(&unescaped);
///
/// assert_eq!(s, escaped);
/// ```
pub fn escape(s: &str) -> String {
    let mut new_string = s.to_string();
    for &(from, to) in ESCAPE_CHARS.iter() {
        new_string = new_string.replace(from, to);
    }
    new_string
}

/// unescapes all chars described in the server query manual
/// # Example
/// ```
/// use sqlib::escaping::unescape;
///
/// let unescaped = "hello world/|\\".to_string();
/// let escaped = "hello\\sworld\\/\\p\\\\".to_string();
///
/// let s = unescape(&escaped);
///
/// assert_eq!(s, unescaped);
/// ```
pub fn unescape(s: &str) -> String {
    let mut new_string = s.to_string();
    for &(to, from) in ESCAPE_CHARS.iter() {
        new_string = new_string.replace(from, &to.to_string());
    }
    new_string
}
<|endoftext|>


<commit_before><commit_msg>solve me second<commit_after>use std::io;
use std::io::prelude::*;

fn add(a: u32, b: u32) -> u32 {
    a + b
}

fn main() {
    let stdin = io::stdin();

    let count: usize = stdin.lock().lines() //iterator over lines in stdin
        .next().unwrap().unwrap() //finally it's a string
        .trim().parse().unwrap(); //and then parsing count value...But we don't need it :) lol

    for line in stdin.lock().lines() {
        let line: String = line.unwrap();
        let v: Vec<&str> = line.trim().split(' ').collect();
        let a: u32 = v[0].parse().unwrap();
        let b: u32 = v[1].parse().unwrap();
        println!("{}", add(a, b));
    }
}<|endoftext|>


<commit_before><commit_msg>init commit, finished product?<commit_after>#![crate_type = "lib"]
#![crate_name = "currency"]

use std::cmp::PartialEq;
use std::cmp::PartialOrd;
use std::cmp::Ordering;

use std::ops::Add;
use std::ops::Sub;
use std::ops::Mul;
use std::ops::Div;

use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result;

use std::marker::Copy;

/// Represents currency through an optional symbol and amount of coin.
///
/// Each 100 coins results in a banknote. (100 is formatted as 1.00)
/// The currency will be formatted as such:
///     Currency('$', 432) ==> "$4.32"
pub struct Currency(pub Option<char>, pub i64);

impl Currency {
    /// Creates a blank Currency as Currency(None, 0)
    fn new() -> Currency {
        Currency(None, 0)
    }

    /// Parses a string literal and turns it into a currency.
    ///
    /// Parsing ignores spaces and commas, only taking note of the digits and
    /// leading sign.
    ///
    /// # Examples
    /// Currency::from_string("$4.32") -> Currency(Some('$'), 432)
    /// Currency::from_string("424.44") -> Currency(None, 42444)
    /// Currency::from_string("@12") -> Currency(Some('@'), 1200)
    ///
    /// # Failures
    /// Fails to take note of the floating points position.
    /// Currency::from_string("$42.012) -> Currency(Some('$'), 42012)
    /// Currency::from_string("42.") -> Currency(None, 42)
    ///
    /// # Panics
    /// Panics if a number fails to be parsed; this only occurs if the string
    /// argument has no numbers in it.
    ///
    /// # Safety
    /// If a decimal point is intended to be marked, always use '.'
    /// A "European style" ',' will be ignored.
    /// String::from_string("€4.32") instead of String::from_string("€4,32")
    fn from_string(s: &str) -> Currency {
        // Try to find the sign
        let mut sign = None;
        let mut unicode: u8 = s.chars().next().unwrap() as u8;
        // If the first character is not a letter
        if unicode <= 0x30 || unicode >= 0x39 {
            sign = Some(unicode as char);
        }

        // Find the numbers
        let mut should_multiply = true; // May later change if a '.' is specified
        let mut coin_str = String::new();
        for c in s.chars() {
            unicode = c as u8;
            // Only pay attention to numbers
            if unicode >= 0x30 && unicode <= 0x39 {
                coin_str = coin_str + &c.to_string();
            }
            // If coins are explicitly specified (via a '.'), then we shouldn't
            // multiply at the end
            if unicode == 0x2E {
                should_multiply = false;
            }
        }
        // Parse out the resulting number
        let mut coin: i64 = coin_str.parse()
            .ok()
            .expect("Failed to convert string to currency");

        if should_multiply {
            coin *= 100;
        }

        // Return result
        Currency(sign, coin)
    }
}

/// Overloads the '==' operator for Currency objects.
///
/// # Panics
/// Panics if the two comparators are different types of currency, as denoted by
/// the Currency's symbol.
impl PartialEq<Currency> for Currency {
    fn eq(&self, rhs: &Currency) -> bool {
        self.0 == rhs.0 && self.1 == rhs.1
    }

    fn ne(&self, rhs: &Currency) -> bool {
        self.0 != rhs.0 || self.1 != rhs.1
    }
}

/// Overloads the order operators for Currency objects.
///
/// These operators include '<', '<=', '>', and '>='.
///
/// # Panics
/// Panics if the two comparators are different types of currency, as denoted by
/// the Currency's symbol.
impl PartialOrd<Currency> for Currency {
    fn partial_cmp(&self, rhs: &Currency) -> Option<Ordering> {
        if self.0 == rhs.0 {
            if self < rhs { return Some(Ordering::Less) }
            if self == rhs { return Some(Ordering::Equal) }
            if self > rhs { return Some(Ordering::Greater) }
        }
        None
    }

    // TODO: sign checking here
    fn lt(&self, rhs: &Currency) -> bool {
        self.1 < rhs.1
    }
    fn le(&self, rhs: &Currency) -> bool {
        self < rhs || self == rhs
    }
    fn gt(&self, rhs: &Currency) -> bool {
        self.1 > rhs.1
    }
    fn ge(&self, rhs: &Currency) -> bool {
        self > rhs || self == rhs
    }
}

/// Overloads the '+' operator for Currency objects.
///
/// # Panics
/// Panics if the two addends are different types of currency, as denoted by the
/// Currency's symbol.
impl Add for Currency {
    type Output = Currency;

    fn add(self, rhs: Currency) -> Currency {
        if self.0 == rhs.0 {
            Currency(self.0, self.1 + rhs.1)
        } else {
            panic!("Cannot do arithmetic on two different types of currency!");
        }
    }
}

/// Overloads the '-' operator for Currency objects.
///
/// # Panics
/// Panics if the minuend and subtrahend are two different types of currency,
/// as denoted by the Currency's symbol.
impl Sub for Currency {
    type Output = Currency;

    fn sub(self, rhs: Currency) -> Currency {
        if self.0 == rhs.0 {
            Currency(self.0, self.1 - rhs.1)
        } else {
            panic!("Cannot do arithmetic on two different types of currency!");
        }
    }
}

/// Overloads the '*' operator for Currency objects.
///
/// Allows a Currency to be multiplied by an i64.
impl Mul<i64> for Currency {
    type Output = Currency;

    fn mul(self, rhs: i64) -> Currency {
        Currency(self.0, self.1 * rhs)
    }
}

/// Overloads the '*' operator for i64.
///
/// Allows an i64 to be multiplied by a Currency.
/// Completes the commutative property for i64 multiplied by Currency.
impl Mul<Currency> for i64 {
    type Output = Currency;

    fn mul(self, rhs: Currency) -> Currency {
        Currency(rhs.0, rhs.1 * self)
    }
}

/// Overloads the '/' operator for Currency objects.
///
/// Allows a Currency to be divided by an i64.
impl Div<i64> for Currency {
    type Output = Currency;

    fn div(self, rhs: i64) -> Currency {
        Currency(self.0, self.1 / rhs)
    }
}

/// Allows Currencies to be displayed as Strings
///
/// # Examples
/// Currency(Some('$'), 1210).to_string() == "$12.10"
/// Currency(None, 1210.to_string() == "12.10"
impl Display for Currency {
    fn fmt(&self, f: &mut Formatter) -> Result {
        let decimal = (self.1 / 100).to_string()
            + &('.').to_string()
            + &(self.1 % 100).to_string();
        match self.0 {
            Some(c) => write!(f, "{}{}", c, decimal),
            None    => write!(f, "{}", decimal),
        }
    }
}

/// Allows Currencies to be copied, rather than using move semantics.
impl Copy for Currency { }
impl Clone for Currency {
    fn clone(&self) -> Currency {
        *self
    }
}

#[test]
fn eq_works() {
    let a = Currency(Some('$'), 1210);
    let b = Currency(Some('$'), 1210);
    let c = Currency(Some('$'), 1251);

    assert!(a == b);
    assert!(b == b);
    assert!(b == a);
    assert!(a != c);
}

#[test]
fn ord_works() {
    let a = Currency(Some('$'), 1210);
    let b = Currency(Some('$'), 1211);
    let c = Currency(Some('$'), 1311);
    let d = Currency(Some('$'), 1210);

    assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
    assert_eq!(a.partial_cmp(&c), Some(Ordering::Less));
    assert_eq!(a.partial_cmp(&d), Some(Ordering::Equal));
    assert_eq!(c.partial_cmp(&a), Some(Ordering::Greater));

    assert!(a < b);
    assert!(a < c);
    assert!(a <= a);
    assert!(a <= c);
    assert!(b > a);
    assert!(c > a);
    assert!(a >= a);
    assert!(c >= a);
}

#[test]
fn arithmetic_works() {
    let x = Currency(Some('$'), 1206);
    let y = Currency(Some('$'), 1143);

    assert!(x + y == Currency(Some('$'), 2349)
         && y + x == Currency(Some('$'), 2349));
    assert!(x - y == Currency(Some('$'), 63));
    assert!(y - x == Currency(Some('$'), -63));
    assert!(x * 2 == Currency(Some('$'), 2412)
         && 2 * x == Currency(Some('$'), 2412));
    assert!(x / 2 == Currency(Some('$'), 603));
}

#[test]
fn parse_works() {
    let a = Currency(Some('$'), 1210);
    let b = Currency::from_string("$12.10");
    assert!(a == b);

    let c = Currency(Some('$'), 1200);
    let d = Currency::from_string("$12");
    assert!(c == d);
}

#[test]
fn display_works() {
    assert!(Currency(Some('$'), 1210).to_string() == "$12.10");
    assert!(Currency(None, 1210).to_string() == "12.10");
}
<|endoftext|>


<commit_before><commit_msg>Fix: Allow to pass only UUIDs and automatically add "todo/" prefix<commit_after><|endoftext|>


<commit_before><commit_msg>SPOP call key_updated<commit_after><|endoftext|>


<commit_before><commit_msg>Euler243 in Rust<commit_after>const N: usize = 100;
const T: f64 = 15499.0/94744.0;

fn sieve(n: usize) -> Vec<usize> {
    let mut is_prime = Vec::with_capacity(n+1);
    is_prime.push(false); // 0
    is_prime.push(false); // 1
    for _i in 1..n { is_prime.push(true); /* for now */ }
    for i in 2..=(n/2) {
        if is_prime[i] {
            let mut j = i * 2;
            while j <= n {
              is_prime[j] = false;
              j += i;
            }
        }
    }
    is_prime.iter().enumerate().filter(|(_, b)| **b).map(|(c, _)| c).collect::<Vec<usize>>()
}

fn main() {
  let primes = sieve(N);
  eprintln!("Calculated {} prime(s) up to {}", primes.len(), N);
  let mut n = 1;
  'denom: for i in &primes {
      n *= i;
      eprintln!("Trying n={}...", n);
      let mut c = 0;
      'frac: for j in 1..n {
          for p in &primes {
              if *p > i/2 { break; }
              if j % p == 0 && n % p == 0 { continue 'frac; }
          }
          c += 1;
          let ratio = (c as f64) / ((n - 1) as f64);
          if ratio > T { continue 'denom; }
      }
      let ratio = (c as f64) / ((i - 1) as f64);
      if ratio < T {
          eprintln!("{}: {} / {} == {}", i, c, i - 1, ratio);
          break;
      }
  }
}
<|endoftext|>


<commit_before>// aux-build:impl_privacy_xc_1.rs

extern mod impl_privacy_xc_1;

fn main() {
    let fish = impl_privacy_xc_1::Fish { x: 1 };
    fish.swim();
}

<commit_msg>xfail-fast run-pass/impl-privacy-xc-1.rs<commit_after>// aux-build:impl_privacy_xc_1.rs
// xfail-fast

extern mod impl_privacy_xc_1;

fn main() {
    let fish = impl_privacy_xc_1::Fish { x: 1 };
    fish.swim();
}

<|endoftext|>


<commit_before>//! Client Requests
use std::io::{BufferedWriter, IoResult};

use url::Url;

use method::{mod, Get, Post, Delete, Put, Patch, Head, Options};
use header::Headers;
use header::common::{mod, Host};
use net::{NetworkStream, NetworkConnector, HttpStream, Fresh, Streaming};
use http::{HttpWriter, ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter, LINE_ENDING};
use version;
use {HttpResult, HttpUriError};
use client::Response;

/// A client request to a remote server.
pub struct Request<W> {
    /// The target URI for this request.
    pub url: Url,

    /// The HTTP version of this request.
    pub version: version::HttpVersion,

    body: HttpWriter<BufferedWriter<Box<NetworkStream + Send>>>,
    headers: Headers,
    method: method::Method,
}

impl<W> Request<W> {
    /// Read the Request headers.
    #[inline]
    pub fn headers(&self) -> &Headers { &self.headers }

    /// Read the Request method.
    #[inline]
    pub fn method(&self) -> method::Method { self.method.clone() }
}

impl Request<Fresh> {
    /// Create a new client request.
    pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
        Request::with_stream::<HttpStream>(method, url)
    }

    /// Create a new client request with a specific underlying NetworkStream.
    pub fn with_stream<S: NetworkConnector>(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
        debug!("{} {}", method, url);
        let host = match url.serialize_host() {
            Some(host) => host,
            None => return Err(HttpUriError)
        };
        debug!("host={}", host);
        let port = match url.port_or_default() {
            Some(port) => port,
            None => return Err(HttpUriError)
        };
        debug!("port={}", port);

        let stream: S = try_io!(NetworkConnector::connect((host[], port), url.scheme.as_slice()));
        let stream = ThroughWriter(BufferedWriter::new(box stream as Box<NetworkStream + Send>));

        let mut headers = Headers::new();
        headers.set(Host {
            hostname: host,
            port: Some(port),
        });

        Ok(Request {
            method: method,
            headers: headers,
            url: url,
            version: version::Http11,
            body: stream
        })
    }

    /// Create a new GET request.
    #[inline]
    pub fn get(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Get, url) }

    /// Create a new POST request.
    #[inline]
    pub fn post(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Post, url) }

    /// Create a new DELETE request.
    #[inline]
    pub fn delete(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Delete, url) }

    /// Create a new PUT request.
    #[inline]
    pub fn put(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Put, url) }

    /// Create a new PATCH request.
    #[inline]
    pub fn patch(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Patch, url) }

    /// Create a new HEAD request.
    #[inline]
    pub fn head(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Head, url) }

    /// Create a new OPTIONS request.
    #[inline]
    pub fn options(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Options, url) }

    /// Consume a Fresh Request, writing the headers and method,
    /// returning a Streaming Request.
    pub fn start(mut self) -> HttpResult<Request<Streaming>> {
        let mut uri = self.url.serialize_path().unwrap();
        //TODO: this needs a test
        if let Some(ref q) = self.url.query {
            uri.push('?');
            uri.push_str(q[]);
        }

        debug!("writing head: {} {} {}", self.method, uri, self.version);
        try_io!(write!(self.body, "{} {} {}", self.method, uri, self.version))
        try_io!(self.body.write(LINE_ENDING));

        let stream = match self.method {
            Get | Head => {
                EmptyWriter(self.body.unwrap())
            },
            _ => {
                let mut chunked = true;
                let mut len = 0;

                match self.headers.get::<common::ContentLength>() {
                    Some(cl) => {
                        chunked = false;
                        len = cl.len();
                    },
                    None => ()
                };

                // cant do in match above, thanks borrowck
                if chunked {
                    let encodings = match self.headers.get_mut::<common::TransferEncoding>() {
                        Some(&common::TransferEncoding(ref mut encodings)) => {
                            //TODO: check if chunked is already in encodings. use HashSet?
                            encodings.push(common::transfer_encoding::Chunked);
                            false
                        },
                        None => true
                    };

                    if encodings {
                        self.headers.set::<common::TransferEncoding>(
                            common::TransferEncoding(vec![common::transfer_encoding::Chunked]))
                    }
                }

                debug!("headers [\n{}]", self.headers);
                try_io!(write!(self.body, "{}", self.headers));

                try_io!(self.body.write(LINE_ENDING));

                if chunked {
                    ChunkedWriter(self.body.unwrap())
                } else {
                    SizedWriter(self.body.unwrap(), len)
                }
            }
        };

        Ok(Request {
            method: self.method,
            headers: self.headers,
            url: self.url,
            version: self.version,
            body: stream
        })
    }

    /// Get a mutable reference to the Request headers.
    #[inline]
    pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }
}

impl Request<Streaming> {
    /// Completes writing the request, and returns a response to read from.
    ///
    /// Consumes the Request.
    pub fn send(self) -> HttpResult<Response> {
        let raw = try_io!(self.body.end()).unwrap();
        Response::new(raw)
    }
}

impl Writer for Request<Streaming> {
    #[inline]
    fn write(&mut self, msg: &[u8]) -> IoResult<()> {
        self.body.write(msg)
    }

    #[inline]
    fn flush(&mut self) -> IoResult<()> {
        self.body.flush()
    }
}

#[cfg(test)]
mod tests {
    use std::boxed::BoxAny;
    use std::str::from_utf8;
    use url::Url;
    use method::{Get, Head};
    use mock::MockStream;
    use super::Request;

    #[test]
    fn test_get_empty_body() {
        let req = Request::with_stream::<MockStream>(
            Get, Url::parse("http://example.dom").unwrap()
        ).unwrap();
        let req = req.start().unwrap();
        let stream = *req.body.end().unwrap().unwrap().downcast::<MockStream>().unwrap();
        let bytes = stream.write.unwrap();
        let s = from_utf8(bytes[]).unwrap();
        assert!(!s.contains("Content-Length:"));
        assert!(!s.contains("Transfer-Encoding:"));
    }

    #[test]
    fn test_head_empty_body() {
        let req = Request::with_stream::<MockStream>(
            Head, Url::parse("http://example.dom").unwrap()
        ).unwrap();
        let req = req.start().unwrap();
        let stream = *req.body.end().unwrap().unwrap().downcast::<MockStream>().unwrap();
        let bytes = stream.write.unwrap();
        let s = from_utf8(bytes[]).unwrap();
        assert!(!s.contains("Content-Length:"));
        assert!(!s.contains("Transfer-Encoding:"));
    }
}
<commit_msg>fix Get and Head requests that weren't writing headers<commit_after>//! Client Requests
use std::io::{BufferedWriter, IoResult};

use url::Url;

use method::{mod, Get, Post, Delete, Put, Patch, Head, Options};
use header::Headers;
use header::common::{mod, Host};
use net::{NetworkStream, NetworkConnector, HttpStream, Fresh, Streaming};
use http::{HttpWriter, ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter, LINE_ENDING};
use version;
use {HttpResult, HttpUriError};
use client::Response;

/// A client request to a remote server.
pub struct Request<W> {
    /// The target URI for this request.
    pub url: Url,

    /// The HTTP version of this request.
    pub version: version::HttpVersion,

    body: HttpWriter<BufferedWriter<Box<NetworkStream + Send>>>,
    headers: Headers,
    method: method::Method,
}

impl<W> Request<W> {
    /// Read the Request headers.
    #[inline]
    pub fn headers(&self) -> &Headers { &self.headers }

    /// Read the Request method.
    #[inline]
    pub fn method(&self) -> method::Method { self.method.clone() }
}

impl Request<Fresh> {
    /// Create a new client request.
    pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
        Request::with_stream::<HttpStream>(method, url)
    }

    /// Create a new client request with a specific underlying NetworkStream.
    pub fn with_stream<S: NetworkConnector>(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
        debug!("{} {}", method, url);
        let host = match url.serialize_host() {
            Some(host) => host,
            None => return Err(HttpUriError)
        };
        debug!("host={}", host);
        let port = match url.port_or_default() {
            Some(port) => port,
            None => return Err(HttpUriError)
        };
        debug!("port={}", port);

        let stream: S = try_io!(NetworkConnector::connect((host[], port), url.scheme.as_slice()));
        let stream = ThroughWriter(BufferedWriter::new(box stream as Box<NetworkStream + Send>));

        let mut headers = Headers::new();
        headers.set(Host {
            hostname: host,
            port: Some(port),
        });

        Ok(Request {
            method: method,
            headers: headers,
            url: url,
            version: version::Http11,
            body: stream
        })
    }

    /// Create a new GET request.
    #[inline]
    pub fn get(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Get, url) }

    /// Create a new POST request.
    #[inline]
    pub fn post(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Post, url) }

    /// Create a new DELETE request.
    #[inline]
    pub fn delete(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Delete, url) }

    /// Create a new PUT request.
    #[inline]
    pub fn put(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Put, url) }

    /// Create a new PATCH request.
    #[inline]
    pub fn patch(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Patch, url) }

    /// Create a new HEAD request.
    #[inline]
    pub fn head(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Head, url) }

    /// Create a new OPTIONS request.
    #[inline]
    pub fn options(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Options, url) }

    /// Consume a Fresh Request, writing the headers and method,
    /// returning a Streaming Request.
    pub fn start(mut self) -> HttpResult<Request<Streaming>> {
        let mut uri = self.url.serialize_path().unwrap();
        //TODO: this needs a test
        if let Some(ref q) = self.url.query {
            uri.push('?');
            uri.push_str(q[]);
        }

        debug!("writing head: {} {} {}", self.method, uri, self.version);
        try_io!(write!(self.body, "{} {} {}", self.method, uri, self.version))
        try_io!(self.body.write(LINE_ENDING));

        let stream = match self.method {
            Get | Head => {
                debug!("headers [\n{}]", self.headers);
                try_io!(write!(self.body, "{}", self.headers));
                try_io!(self.body.write(LINE_ENDING));
                EmptyWriter(self.body.unwrap())
            },
            _ => {
                let mut chunked = true;
                let mut len = 0;

                match self.headers.get::<common::ContentLength>() {
                    Some(cl) => {
                        chunked = false;
                        len = cl.len();
                    },
                    None => ()
                };

                // cant do in match above, thanks borrowck
                if chunked {
                    let encodings = match self.headers.get_mut::<common::TransferEncoding>() {
                        Some(&common::TransferEncoding(ref mut encodings)) => {
                            //TODO: check if chunked is already in encodings. use HashSet?
                            encodings.push(common::transfer_encoding::Chunked);
                            false
                        },
                        None => true
                    };

                    if encodings {
                        self.headers.set::<common::TransferEncoding>(
                            common::TransferEncoding(vec![common::transfer_encoding::Chunked]))
                    }
                }

                debug!("headers [\n{}]", self.headers);
                try_io!(write!(self.body, "{}", self.headers));
                try_io!(self.body.write(LINE_ENDING));

                if chunked {
                    ChunkedWriter(self.body.unwrap())
                } else {
                    SizedWriter(self.body.unwrap(), len)
                }
            }
        };

        Ok(Request {
            method: self.method,
            headers: self.headers,
            url: self.url,
            version: self.version,
            body: stream
        })
    }

    /// Get a mutable reference to the Request headers.
    #[inline]
    pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }
}

impl Request<Streaming> {
    /// Completes writing the request, and returns a response to read from.
    ///
    /// Consumes the Request.
    pub fn send(self) -> HttpResult<Response> {
        let raw = try_io!(self.body.end()).unwrap();
        Response::new(raw)
    }
}

impl Writer for Request<Streaming> {
    #[inline]
    fn write(&mut self, msg: &[u8]) -> IoResult<()> {
        self.body.write(msg)
    }

    #[inline]
    fn flush(&mut self) -> IoResult<()> {
        self.body.flush()
    }
}

#[cfg(test)]
mod tests {
    use std::boxed::BoxAny;
    use std::str::from_utf8;
    use url::Url;
    use method::{Get, Head};
    use mock::MockStream;
    use super::Request;

    #[test]
    fn test_get_empty_body() {
        let req = Request::with_stream::<MockStream>(
            Get, Url::parse("http://example.dom").unwrap()
        ).unwrap();
        let req = req.start().unwrap();
        let stream = *req.body.end().unwrap().unwrap().downcast::<MockStream>().unwrap();
        let bytes = stream.write.unwrap();
        let s = from_utf8(bytes[]).unwrap();
        assert!(!s.contains("Content-Length:"));
        assert!(!s.contains("Transfer-Encoding:"));
    }

    #[test]
    fn test_head_empty_body() {
        let req = Request::with_stream::<MockStream>(
            Head, Url::parse("http://example.dom").unwrap()
        ).unwrap();
        let req = req.start().unwrap();
        let stream = *req.body.end().unwrap().unwrap().downcast::<MockStream>().unwrap();
        let bytes = stream.write.unwrap();
        let s = from_utf8(bytes[]).unwrap();
        assert!(!s.contains("Content-Length:"));
        assert!(!s.contains("Transfer-Encoding:"));
    }
}
<|endoftext|>


<commit_before><commit_msg>faster??<commit_after><|endoftext|>


<commit_before><commit_msg>striptags tests added<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #132<commit_after>//! Problem 132 (https://projecteuler.net/problem=132)
//!
//! # 解析
//!
//! ```math
//! R(k) = (10^k - 1) / 9
//! ```
//!
//! 素数 `p` が `R(k)` の因数の場合、以下が成立する。
//!
//! ```math
//! (10^k - 1) / 9 \equiv 0 (mod p)
//! => 10^k - 1 \equiv 0 (mod 9p)
//! => 10^k \qeuiv 1 (mod 9p)
//! ```
//!
//! # 解法
//!
//! 冪剰余 (Modular exponation) を求める。

#[crate_id = "prob0132"];
#[crate_type = "rlib"];

extern mod math;

use std::num;
use std::iter::AdditiveIterator;
use math::prime::Prime;

pub static EXPECTED_ANSWER: &'static str = "843296";

fn mod_pow(mut base: uint, mut exp: uint, modulo: uint) -> uint {
    let mut result = 1;

    while exp > 0 {
        if exp.is_odd() {
            result = (result * base) % modulo;
        }
        exp >>= 1;
        base = (base * base) % modulo;
    }
    result
}

pub fn solve() -> ~str {
    Prime::new().iter()
        .filter(|&p| mod_pow(10, num::pow(10u, 9), 9 * p) == 1)
        .take(40)
        .sum()
        .to_str()
}

#[cfg(test)]
mod test {
    use std::num;

    #[test]
    fn mod_pow() {
        for b in range(1u, 10) {
            for e in range(0u, 5) {
                for r in range(10u, 100) {
                    assert_eq!(num::pow(b, e) % r, super::mod_pow(b, e, r));
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test case for labeled break in const assignment<commit_after>// Using labeled break in a while loop has caused an illegal instruction being
// generated, and an ICE later.
//
// See https://github.com/rust-lang/rust/issues/51350 for more information.

const CRASH: () = 'a: while break 'a {};

fn main() {
    println!("{:?}", CRASH);
}
<|endoftext|>


<commit_before><commit_msg>lib definition added<commit_after><|endoftext|>


<commit_before><commit_msg>case_id takes the address of Channel<commit_after><|endoftext|>


<commit_before><commit_msg>Rewrite list_todos() to be able to read ids from stdin<commit_after><|endoftext|>


<commit_before>use std::io;

use futures::{Future, Poll, Task};

use {ReadTask, WriteTask};

/// A future which will copy all data from a reader into a writer.
///
/// Created by the `copy` function, this future will resolve to the number of
/// bytes copied or an error if one happens.
pub struct Copy<R, W> {
    reader: R,
    read_ready: bool,
    read_done: bool,
    writer: W,
    write_ready: bool,
    flush_done: bool,
    pos: usize,
    cap: usize,
    amt: u64,
    buf: [u8; 2048],
}

/// Creates a future which represents copying all the bytes from one object to
/// another.
///
/// The returned future will copy all the bytes read from `reader` into the
/// `writer` specified. This future will only complete once the `reader` has hit
/// EOF and all bytes have been written to and flushed from the `writer`
/// provided.
///
/// On success the number of bytes is returned and the `reader` and `writer` are
/// consumed. On error the error is returned and the I/O objects are consumed as
/// well.
pub fn copy<R, W>(reader: R, writer: W) -> Copy<R, W>
    where R: ReadTask,
          W: WriteTask,
{
    Copy {
        reader: reader,
        read_ready: true,
        read_done: false,
        writer: writer,
        write_ready: true,
        flush_done: false,
        amt: 0,
        pos: 0,
        cap: 0,
        buf: [0; 2048],
    }
}

impl<R, W> Future for Copy<R, W>
    where R: ReadTask,
          W: WriteTask,
{
    type Item = u64;
    type Error = io::Error;

    fn poll(&mut self, task: &mut Task) -> Poll<u64, io::Error> {
        loop {
            // If our buffer is empty, then we need to read some data to
            // continue.
            if !self.read_done && self.pos == self.cap {
                if !self.read_ready {
                    debug!("copy waiting for read");
                    match try_poll!(self.reader.poll(task)) {
                        Ok(Some(ref r)) if r.is_read() => self.read_ready = true,
                        Ok(_) => return Poll::NotReady,
                        Err(e) => return Poll::Err(e),
                    }
                }
                match self.reader.read(task, &mut self.buf) {
                    Ok(0) => {
                        debug!("copy at eof");
                        self.read_done = true;
                    }
                    Ok(i) => {
                        debug!("read {} bytes", i);
                        self.pos = 0;
                        self.cap = i;
                    }
                    Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                        debug!("read is gone");
                        self.read_ready = false;
                        return Poll::NotReady
                    }
                    Err(e) => return Poll::Err(e),
                }
            }

            // Now that our buffer has some data, let's write it out!
            while self.pos < self.cap || (self.read_done && !self.flush_done) {
                if !self.write_ready {
                    debug!("copy waiting for write");
                    match try_poll!(self.writer.poll(task)) {
                        Ok(Some(ref r)) if r.is_write() => self.write_ready = true,
                        Ok(_) => return Poll::NotReady,
                        Err(e) => return Poll::Err(e),
                    }
                }
                if self.pos == self.cap {
                    match self.writer.flush(task) {
                        Ok(()) => {
                            debug!("flush done");
                            self.flush_done = true;
                        }
                        Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                            debug!("waiting for another flush");
                            return Poll::NotReady
                        }
                        Err(e) => return Poll::Err(e),
                    }
                    break
                }
                match self.writer.write(task, &self.buf[self.pos..self.cap]) {
                    Ok(i) => {
                        debug!("wrote {} bytes", i);
                        self.pos += i;
                        self.amt += i as u64;
                    }
                    Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                        debug!("write no longer ready");
                        self.write_ready = false;
                        return Poll::NotReady
                    }
                    Err(e) => return Poll::Err(e),
                }
            }

            if self.read_done && self.flush_done {
                return Poll::Ok(self.amt)
            }
        }
    }

    fn schedule(&mut self, task: &mut Task) {
        if self.read_ready && self.write_ready {
            task.notify();
        }
        if !self.read_ready && !self.read_done {
            self.reader.schedule(task);
        }
        if !self.write_ready && !self.flush_done {
            self.writer.schedule(task);
        }
    }
}
<commit_msg>Put the Copy buffer on the heap<commit_after>use std::io;

use futures::{Future, Poll, Task};

use {ReadTask, WriteTask};

/// A future which will copy all data from a reader into a writer.
///
/// Created by the `copy` function, this future will resolve to the number of
/// bytes copied or an error if one happens.
pub struct Copy<R, W> {
    reader: R,
    read_ready: bool,
    read_done: bool,
    writer: W,
    write_ready: bool,
    flush_done: bool,
    pos: usize,
    cap: usize,
    amt: u64,
    buf: Box<[u8]>,
}

/// Creates a future which represents copying all the bytes from one object to
/// another.
///
/// The returned future will copy all the bytes read from `reader` into the
/// `writer` specified. This future will only complete once the `reader` has hit
/// EOF and all bytes have been written to and flushed from the `writer`
/// provided.
///
/// On success the number of bytes is returned and the `reader` and `writer` are
/// consumed. On error the error is returned and the I/O objects are consumed as
/// well.
pub fn copy<R, W>(reader: R, writer: W) -> Copy<R, W>
    where R: ReadTask,
          W: WriteTask,
{
    Copy {
        reader: reader,
        read_ready: true,
        read_done: false,
        writer: writer,
        write_ready: true,
        flush_done: false,
        amt: 0,
        pos: 0,
        cap: 0,
        buf: Box::new([0; 2048]),
    }
}

impl<R, W> Future for Copy<R, W>
    where R: ReadTask,
          W: WriteTask,
{
    type Item = u64;
    type Error = io::Error;

    fn poll(&mut self, task: &mut Task) -> Poll<u64, io::Error> {
        loop {
            // If our buffer is empty, then we need to read some data to
            // continue.
            if !self.read_done && self.pos == self.cap {
                if !self.read_ready {
                    debug!("copy waiting for read");
                    match try_poll!(self.reader.poll(task)) {
                        Ok(Some(ref r)) if r.is_read() => self.read_ready = true,
                        Ok(_) => return Poll::NotReady,
                        Err(e) => return Poll::Err(e),
                    }
                }
                match self.reader.read(task, &mut self.buf) {
                    Ok(0) => {
                        debug!("copy at eof");
                        self.read_done = true;
                    }
                    Ok(i) => {
                        debug!("read {} bytes", i);
                        self.pos = 0;
                        self.cap = i;
                    }
                    Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                        debug!("read is gone");
                        self.read_ready = false;
                        return Poll::NotReady
                    }
                    Err(e) => return Poll::Err(e),
                }
            }

            // Now that our buffer has some data, let's write it out!
            while self.pos < self.cap || (self.read_done && !self.flush_done) {
                if !self.write_ready {
                    debug!("copy waiting for write");
                    match try_poll!(self.writer.poll(task)) {
                        Ok(Some(ref r)) if r.is_write() => self.write_ready = true,
                        Ok(_) => return Poll::NotReady,
                        Err(e) => return Poll::Err(e),
                    }
                }
                if self.pos == self.cap {
                    match self.writer.flush(task) {
                        Ok(()) => {
                            debug!("flush done");
                            self.flush_done = true;
                        }
                        Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                            debug!("waiting for another flush");
                            return Poll::NotReady
                        }
                        Err(e) => return Poll::Err(e),
                    }
                    break
                }
                match self.writer.write(task, &self.buf[self.pos..self.cap]) {
                    Ok(i) => {
                        debug!("wrote {} bytes", i);
                        self.pos += i;
                        self.amt += i as u64;
                    }
                    Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                        debug!("write no longer ready");
                        self.write_ready = false;
                        return Poll::NotReady
                    }
                    Err(e) => return Poll::Err(e),
                }
            }

            if self.read_done && self.flush_done {
                return Poll::Ok(self.amt)
            }
        }
    }

    fn schedule(&mut self, task: &mut Task) {
        if self.read_ready && self.write_ready {
            task.notify();
        }
        if !self.read_ready && !self.read_done {
            self.reader.schedule(task);
        }
        if !self.write_ready && !self.flush_done {
            self.writer.schedule(task);
        }
    }
}
<|endoftext|>


<commit_before>use std::ffi::OsString;
use std::fs::OpenOptions;
use std::io;
use std::io::BufWriter;
use std::io::Stderr;
use std::io::Stdin;
use std::io::Stdout;
use std::io::Write;
use std::path::PathBuf;
use structopt::StructOpt;
use super::Error;
use super::Result;

enum Context {
    /// The path is absolute (has root).
    Absolute,
    /// The `interactive` option is present.
    Interactive,
}

#[derive(Debug, StructOpt)]
#[structopt(about = "Securely erase files (single-pass).")]
struct Options {
    /// Do not overwrite any files (verbose).
    #[structopt(short = "d", long = "dry-run")]
    dry_run: bool,

    /// Prompt before overwriting each file.
    #[structopt(short = "i", long = "interactive")]
    interactive: bool,

    /// Recursively descend into directories.
    #[structopt(short = "r", long = "recursive")]
    recursive: bool,

    /// Suppress all interaction.
    #[structopt(short = "s", long = "suppress")]
    suppress: bool,

    /// Explain what's being done.
    #[structopt(short = "V", long = "verbose")]
    verbose: bool,

    /// Show this message.
    #[structopt(short = "h", long = "help")]
    help: bool,

    /// Show the version.
    #[structopt(short = "v", long = "version")]
    version: bool,

    /// The paths to be accessed by the tool.
    #[structopt(name = "PATHS", parse(from_str))]
    paths: Vec<PathBuf>,
}

pub struct Zero {
    options: Options,
    stderr: Stderr,
    stdout: Stdout,
    stdin: Stdin,
}

impl Zero {
    /// Constructs this program from an iterable of arguments.
    pub fn from_iter<I>(iter: I) -> Result<Self>
    where
        Self: Sized,
        I: IntoIterator,
        I::Item: Into<OsString> + Clone,
    {
        return Ok(
            Self {
                options: Options::from_iter_safe(iter)?,
                stderr: io::stderr(),
                stdout: io::stdout(),
                stdin: io::stdin(),
            }
        );
    }

    /// Replaces the standard error stream for this program.
    pub fn stderr(&mut self, stderr: Stderr) -> &mut Self {
        self.stderr = stderr;
        return self;
    }

    /// Replaces the standard output stream for this program.
    pub fn stdout(&mut self, stdout: Stdout) -> &mut Self {
        self.stdout = stdout;
        return self;
    }

    /// Replaces the standard input stream for this program.
    pub fn stdin(&mut self, stdin: Stdin) -> &mut Self {
        self.stdin = stdin;
        return self;
    }

    /// Runs this program and writes all errors.
    pub fn run(&mut self) -> Result<()> {
        match self.run_inner() {
            Ok(val) => {
                return Ok(val);
            },
            Err(err) => {
                writeln!(self.stderr, "Error: {}", err)?;
                return Err(err);
            },
        }
    }

    /// Runs this program.
    fn run_inner(&mut self) -> Result<()> {
        // Write the help or version message
        if self.options.help {
            return self.help();
        }
        if self.options.version {
            return self.version();
        }

        // Check for conflicting options
        self.validate()?;

        // Loop through the paths
        self.overwrite()?;
        return Ok(());
    }

    /// Checks for conflicts in the options.
    fn validate(&self) -> Result<()> {
        return if self.options.interactive && self.options.suppress {
            Err(Error::Conflict)
        } else {
            Ok(())
        };
    }

    /// Writes the help message to the standard error stream.
    fn help(&mut self) -> Result<()> {
        Options::clap().write_help(&mut self.stderr)?;
        writeln!(self.stderr, "")?;
        return Ok(());
    }

    /// Writes the version message to the standard error stream.
    fn version(&mut self) -> Result<()> {
        Options::clap().write_version(&mut self.stderr)?;
        writeln!(self.stderr, "")?;
        return Ok(());
    }

    /// Authorizes directory and file access by prompting the user and reading
    /// from the standard input stream.
    fn auth(&mut self, path: &PathBuf, context: Context) -> Result<bool> {
        // Determine the appropriate prompt
        let prompt = match context {
            Context::Absolute => "is absolute",
            Context::Interactive => "will be overwritten",
        };

        let mut input = String::new();
        loop {
            // Prompt the user and normalize the input
            write!(self.stderr, "{:#?} {} - continue? [y/n] ", path, prompt)?;
            self.stdin.read_line(&mut input)?;

            // The response must be `y` or `n`
            match input.trim().to_lowercase().as_str() {
                "n" => {
                    if self.options.verbose {
                        writeln!(self.stderr, "Skipped.")?;
                    }
                    return Ok(false);
                },
                "y" => {
                    return Ok(true);
                },
                _ => {
                    input.clear();
                },
            }
        }
    }

    /// Overwrites all paths provided by the user. Authorization may be
    /// requested if the `suppress` option is not present.
    fn overwrite(&mut self) -> Result<()> {
        for path in self.options.paths.to_owned() {
            if !self.options.suppress && path.has_root() {
                // Authorize absolute paths (optional)
                if let Ok(false) = self.auth(&path, Context::Absolute) {
                    continue;
                }
            }

            if path.is_file() {
                // The path is a valid file
                self.overwrite_file(&path)?;
            } else if path.is_dir() {
                // The path is a valid directory
                if let Err(err) = self.overwrite_dir(&path) {
                    writeln!(self.stderr, "Error: Cannot access {:#?}: {}", path, err)?;
                }
            } else {
                // The path could not be accessed
                writeln!(self.stderr, "Error: Cannot access {:#?}", path)?;
            }
        }
        return Ok(());
    }

    /// Overwrites all files in the given directory. If the `recursive` option
    /// is present, all files under the given directory will overwritten.
    fn overwrite_dir(&mut self, path: &PathBuf) -> Result<()> {
        for entry in path.read_dir()? {
            let path = entry?.path();

            // Recurse if the entry is a directory (optional)
            if self.options.recursive && path.is_dir() {
                self.overwrite_dir(&path)?;
            } else if path.is_file() {
                self.overwrite_file(&path)?;
            }
        }
        return Ok(());
    }

    /// Overwrites the given file and writes all errors.
    fn overwrite_file(&mut self, path: &PathBuf) -> Result<()> {
        if let Err(err) = self.overwrite_file_inner(path) {
            writeln!(self.stderr, "Error: Cannot overwrite {:#?}: {}", path, err)?;
        }
        return Ok(());
    }

    /// Overwrites the given file. Authorization may be requested and
    /// additional information may be written if the `interactive` and
    /// `verbose` options are present. The file will not be overwritten
    /// during a `dry-run`.
    fn overwrite_file_inner(&mut self, path: &PathBuf) -> Result<()> {
        if self.options.interactive {
            // Authorize every file (optional)
            if let Ok(false) = self.auth(&path, Context::Interactive) {
                return Ok(());
            }
        }
        let metadata = path.metadata()?;

        if !self.options.dry_run {
            // Open the file and wrap it in a buffer
            let mut file = OpenOptions::new().write(true).open(path)?;
            let mut buf = BufWriter::new(file);

            // Overwrite the file
            for _ in 0..metadata.len() {
                buf.write(&[0])?;
            }

            // Flush the buffer to the disk
            file = buf.into_inner()?;
            file.sync_all()?;

            if self.options.verbose {
                // Write the results (optional)
                writeln!(self.stdout, "{:#?}: {} byte(s) overwritten.", path, metadata.len())?;
            }
        } else {
            // Perform a dry run (optional)
            writeln!(self.stdout, "{:#?}: {} byte(s) will be overwritten.", path, metadata.len())?;
        }
        return Ok(());
    }
}
<commit_msg>Refactored code<commit_after>use std::ffi::OsString;
use std::fs::OpenOptions;
use std::io;
use std::io::BufWriter;
use std::io::Stderr;
use std::io::Stdin;
use std::io::Stdout;
use std::io::Write;
use std::path::PathBuf;
use structopt::StructOpt;
use super::Error;
use super::Result;

enum Context {
    /// The path is absolute (has root).
    Absolute,
    /// The `interactive` option is present.
    Interactive,
}

#[derive(Debug, StructOpt)]
#[structopt(about = "Securely erase files (single-pass).")]
struct Options {
    /// Do not overwrite any files (verbose).
    #[structopt(short = "d", long = "dry-run")]
    dry_run: bool,

    /// Prompt before overwriting each file.
    #[structopt(short = "i", long = "interactive")]
    interactive: bool,

    /// Recursively descend into directories.
    #[structopt(short = "r", long = "recursive")]
    recursive: bool,

    /// Suppress all interaction.
    #[structopt(short = "s", long = "suppress")]
    suppress: bool,

    /// Explain what's being done.
    #[structopt(short = "V", long = "verbose")]
    verbose: bool,

    /// Show this message.
    #[structopt(short = "h", long = "help")]
    help: bool,

    /// Show the version.
    #[structopt(short = "v", long = "version")]
    version: bool,

    /// The paths to be accessed by the tool.
    #[structopt(name = "PATHS", parse(from_str))]
    paths: Vec<PathBuf>,
}

pub struct Zero {
    options: Options,
    stderr: Stderr,
    stdout: Stdout,
    stdin: Stdin,
}

impl Zero {
    /// Constructs this program from an iterable of arguments.
    pub fn from_iter<I>(iter: I) -> Result<Self>
    where
        Self: Sized,
        I: IntoIterator,
        I::Item: Into<OsString> + Clone,
    {
        return Ok(
            Self {
                options: Options::from_iter_safe(iter)?,
                stderr: io::stderr(),
                stdout: io::stdout(),
                stdin: io::stdin(),
            }
        );
    }

    /// Replaces the standard error stream for this program.
    pub fn stderr(&mut self, stderr: Stderr) -> &mut Self {
        self.stderr = stderr;
        return self;
    }

    /// Replaces the standard output stream for this program.
    pub fn stdout(&mut self, stdout: Stdout) -> &mut Self {
        self.stdout = stdout;
        return self;
    }

    /// Replaces the standard input stream for this program.
    pub fn stdin(&mut self, stdin: Stdin) -> &mut Self {
        self.stdin = stdin;
        return self;
    }

    /// Runs this program and writes all errors.
    pub fn run(&mut self) -> Result<()> {
        match self.run_inner() {
            Ok(val) => {
                return Ok(val);
            },
            Err(err) => {
                writeln!(self.stderr, "Error: {}", err)?;
                return Err(err);
            },
        }
    }

    /// Runs this program.
    fn run_inner(&mut self) -> Result<()> {
        // Write the help or version message
        if self.options.help {
            return self.help();
        }
        if self.options.version {
            return self.version();
        }

        // Check for conflicting options
        self.validate()?;

        // Loop through the paths
        return self.overwrite();
    }

    /// Checks for conflicts in the options.
    fn validate(&self) -> Result<()> {
        return if self.options.interactive && self.options.suppress {
            Err(Error::Conflict)
        } else {
            Ok(())
        };
    }

    /// Writes the help message to the standard error stream.
    fn help(&mut self) -> Result<()> {
        Options::clap().write_help(&mut self.stderr)?;
        writeln!(self.stderr, "")?;
        return Ok(());
    }

    /// Writes the version message to the standard error stream.
    fn version(&mut self) -> Result<()> {
        Options::clap().write_version(&mut self.stderr)?;
        writeln!(self.stderr, "")?;
        return Ok(());
    }

    /// Authorizes directory and file access by prompting the user and reading
    /// from the standard input stream.
    fn auth(&mut self, path: &PathBuf, context: Context) -> Result<bool> {
        // Determine the appropriate prompt
        let prompt = match context {
            Context::Absolute => "is absolute",
            Context::Interactive => "will be overwritten",
        };

        let mut input = String::new();
        loop {
            // Prompt the user and normalize the input
            write!(self.stderr, r#""{}" {} - continue? [y/n] "#, path.display(), prompt)?;
            self.stdin.read_line(&mut input)?;

            // The response must be `y` or `n`
            match input.trim().to_lowercase().as_str() {
                "n" => {
                    if self.options.verbose {
                        writeln!(self.stderr, "Skipped.")?;
                    }
                    return Ok(false);
                },
                "y" => {
                    return Ok(true);
                },
                _ => {
                    input.clear();
                },
            }
        }
    }

    /// Overwrites all paths provided by the user. Authorization may be
    /// requested if the `suppress` option is not present.
    fn overwrite(&mut self) -> Result<()> {
        for path in self.options.paths.to_owned() {
            if !self.options.suppress && path.has_root() {
                // Authorize absolute paths (optional)
                if let Ok(false) = self.auth(&path, Context::Absolute) {
                    continue;
                }
            }

            if path.is_file() {
                // The path is a file
                self.overwrite_file(&path)?;
            } else {
                // Try the path as a directory
                self.overwrite_dir(&path)?;
            }
        }
        return Ok(());
    }

    /// Overwrites all files in the given directory and writes all errors.
    fn overwrite_dir(&mut self, path: &PathBuf) -> Result<()> {
        return if let Err(err) = self.overwrite_dir_inner(path) {
            self.write_error("Cannot access", path, &err)
        } else {
            Ok(())
        };
    }

    /// Overwrites all files in the given directory. If the `recursive` option
    /// is present, all files under the given directory will overwritten.
    fn overwrite_dir_inner(&mut self, path: &PathBuf) -> Result<()> {
        for entry in path.read_dir()? {
            let path = entry?.path();

            // Recurse if the entry is a directory (optional)
            if self.options.recursive && path.is_dir() {
                self.overwrite_dir(&path)?;
            } else if path.is_file() {
                self.overwrite_file(&path)?;
            }
        }
        return Ok(());
    }

    /// Overwrites the given file and writes all errors.
    fn overwrite_file(&mut self, path: &PathBuf) -> Result<()> {
        return if let Err(err) = self.overwrite_file_inner(path) {
            self.write_error("Cannot overwrite", path, &err)
        } else {
            Ok(())
        };
    }

    /// Overwrites the given file. Authorization may be requested and
    /// additional information may be written if the `interactive` and
    /// `verbose` options are present. The file will not be overwritten
    /// during a `dry-run`.
    fn overwrite_file_inner(&mut self, path: &PathBuf) -> Result<()> {
        if self.options.interactive {
            // Authorize every file (optional)
            if let Ok(false) = self.auth(path, Context::Interactive) {
                return Ok(());
            }
        }
        let metadata = path.metadata()?;

        if !self.options.dry_run {
            // Open the file and wrap it in a buffer
            let mut file = OpenOptions::new().write(true).open(path)?;
            let mut buf = BufWriter::new(file);

            // Overwrite the file
            for _ in 0..metadata.len() {
                buf.write(&[0])?;
            }

            // Flush the buffer to the disk
            file = buf.into_inner()?;
            file.sync_all()?;

            if self.options.verbose {
                // Write the results (optional)
                self.write_result("overwritten", path, metadata.len())?;
            }
        } else {
            // Perform a dry run (optional)
            self.write_result("will be overwritten", path, metadata.len())?;
        }
        return Ok(());
    }

    /// Writes a path related error to the standard error stream.
    fn write_error(&mut self, msg: &str, path: &PathBuf, err: &Error) -> Result<()> {
        writeln!(self.stderr, r#"Error: {} "{}": {}"#, msg, path.display(), err)?;
        return Ok(());
    }

    /// Writes the result of an operation to the standard output stream.
    fn write_result(&mut self, msg: &str, path: &PathBuf, len: u64) -> Result<()> {
        writeln!(self.stdout, r#""{}": {} byte(s) {}."#, path.display(), len, msg)?;
        return Ok(());
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove unused lifetime<commit_after><|endoftext|>


<commit_before>// FIXME: Replace these examples with executable tests
//! Traits related to relationships between multiple tables.
//!
//! **Note: This feature is under active development, and we are seeking feedback on the APIs that
//! have been released. Please feel free to open issues, or join [our chat][gitter] to provide
//! feedback.**
//!
//! [gitter]: https://gitter.im/diesel-rs/diesel
//!
//! Note: This guide is written assuming the usage of `diesel_codegen` or `diesel_codegen_syntex`.
//! If you are using [`custom_derive`] instead, you will need to replace `#[belongs_to(Foo)]` with
//! `#[derive(BelongsTo(Foo, foreign_key = foo_id))]` and `#[has_many(bars)]` with
//! `#[derive(HasMany(bars, foreign_key = bar_id))]`.
//!
//! Associations in Diesel are bidirectional, but primarily focus on the child-to-parent
//! relationship. You can declare an association between two records with `#[has_many]` and
//! `#[belongs_to]`.
//!
//! ```ignore
//! #[derive(Identifiable, Queryable)]
//! #[has_many(posts)]
//! pub struct User {
//!     id: i32,
//!     name: String,
//! }
//!
//! #[derive(Identifiable, Queryable)]
//! #[belongs_to(User)]
//! pub struct Post {
//!     id: i32,
//!     user_id: i32,
//!     title: String,
//! }
//! ```
//!
//! `#[has_many]` shoudld be passed the name of the table that the children will be loaded from,
//! while `#[belongs_to]` is given the name of the struct that represents the parent. Both types
//! must implement the [`Identifiable`][identifiable] trait.
//!
//! [Identifiable]: associations/trait.Identifiable.html
//!
//! `#[has_many]` actually has no behavior on its own. It only enables joining between the two
//! tables. If you are only accessing data through the [`belonging_to`][belonging-to] method, you
//! only need to define the `#[belongs_to]` side.
//!
//! Once the associations are defined, you can join between the two tables using the
//! [`inner_join`][inner-join] or [`left_outer_join`][left-outer-join].
//!
//! [inner-join]: query_source/trait.Table.html#method.inner_join
//! [left-outer-join]: query_source/trait.Table.html#method.left_outer_join
//!
//! ```ignore
//! let data: Vec<(User, Post)> = users::table.inner_join(posts::table).load(&connection);
//! ```
//!
//! Note: Due to language limitations, only two tables can be joined per query. This will change in
//! the future.
//!
//! Typically however, queries are loaded in multiple queries. For most datasets, the reduced
//! amount of duplicated information sent over the wire saves more than the the extra round trip
//! costs us. You can load the children for a single parent using the
//! [`belonging_to`][belonging-to]
//!
//! [belonging-to]: prelude/trait.BelongingToDsl.html#tymethod.belonging_to
//!
//! ```ignore
//! let user = try!(users::find(1).first(&connection));
//! let posts = Post::belonging_to(&user).load(&connection);
//! ```
//!
//! If you're coming from most other ORMs, you'll notice that this design is quite different from
//! most, where you would have an instance method on the parent, or have the children stored
//! somewhere on the posts. This design leads to many problems, including N+1 query bugs, and
//! runtime errors when accessing an association that isn't there.
//!
//! In Diesel, data and its associations are considered to be separate. If you want to pass around
//! a user and all of its posts, that type is `(User, Vec<Post>)`.
//!
//! Next lets look at how to load the children for more than one parent record.
//! [`belonging_to`][belonging-to] can be used to load the data, but we'll also need to group it
//! with its parents. For this we use an additional method [`grouped_by`][grouped-by]
//!
//! [grouped-by]: associations/trait.GroupedBy.html#tymethod.grouped_by
//!
//! ```ignore
//! fn first_twenty_users_and_their_posts(conn: &PgConnection) -> QueryResult<Vec<(User, Vec<Post>)>> {
//!     let users = try!(users::limit(20).load::<User>(&conn));
//!     let posts = try!(Post::belonging_to(&users).load::<Post>());
//!     let grouped_posts = posts.grouped_by(&users);
//!     users.into_iter().zip(grouped_posts).collect()
//! }
//! ```
//!
//! [`grouped_by`][grouped-by] takes a `Vec<Child>` and a `Vec<Parent>` and returns a
//! `Vec<Vec<Child>>` where the index of the children matches the index of the parent the belong
//! to. Or to put it simply, it returns them in an order ready to be `zip`ed with the parents. You
//! can do this multiple times. For example, if you wanted to load the comments for all the posts
//! as well, you could do this:
//!
//! ```ignore
//! let posts = try!(Post::belonging_to(&users).load::<Post>());
//! let comments = try!(Comment::belonging_to(&posts).load::<Comment>());
//! let comments = comments.grouped_by(&posts);
//! let posts_and_comments = posts.into_iter().zip(comments).grouped_by(&users);
//! users.into_iter().zip(posts_and_comments).collect()
//! ```
//!
//! And that's it. This module will be expanded in the future with more complex joins, and ability
//! to define "through" associations. However, the goal is to provide simple building blocks which
//! can be used to construct the complex behavior applications need.
mod belongs_to;

use std::hash::Hash;

use query_dsl::FindDsl;
use query_source::Table;

pub use self::belongs_to::{BelongsTo, GroupedBy};

pub trait Identifiable {
    type Id: Hash + Eq + Copy;
    type Table: Table + FindDsl<Self::Id>;

    fn table() -> Self::Table;
    fn id(&self) -> Self::Id;
}
<commit_msg>Typos and respond to feedback on the docs<commit_after>// FIXME: Replace these examples with executable tests
//! Traits related to relationships between multiple tables.
//!
//! **Note: This feature is under active development, and we are seeking feedback on the APIs that
//! have been released. Please feel free to [open issues][open-issue], or join [our chat][gitter]
//! to provide feedback.**
//!
//! [open-issue]: https://github.com/diesel-rs/diesel/issues/new
//! [gitter]: https://gitter.im/diesel-rs/diesel
//!
//! Note: This guide is written assuming the usage of `diesel_codegen` or `diesel_codegen_syntex`.
//! If you are using [`custom_derive`][custom-derive] instead, you will need to replace
//! `#[belongs_to(Foo)]` with `#[derive(BelongsTo(Foo, foreign_key = foo_id))]` and
//! `#[has_many(bars)]` with `#[derive(HasMany(bars, foreign_key = bar_id))]`.
//!
//! Associations in Diesel are bidirectional, but primarily focus on the child-to-parent
//! relationship. You can declare an association between two records with `#[has_many]` and
//! `#[belongs_to]`.
//!
//! ```ignore
//! #[derive(Identifiable, Queryable)]
//! #[has_many(posts)]
//! pub struct User {
//!     id: i32,
//!     name: String,
//! }
//!
//! #[derive(Identifiable, Queryable)]
//! #[belongs_to(User)]
//! pub struct Post {
//!     id: i32,
//!     user_id: i32,
//!     title: String,
//! }
//! ```
//!
//! `#[has_many]` should be passed the name of the table that the children will be loaded from,
//! while `#[belongs_to]` is given the name of the struct that represents the parent. Both types
//! must implement the [`Identifiable`][identifiable] trait.
//!
//! [Identifiable]: associations/trait.Identifiable.html
//!
//! `#[has_many]` actually has no behavior on its own. It only enables joining between the two
//! tables. If you are only accessing data through the [`belonging_to`][belonging-to] method, you
//! only need to define the `#[belongs_to]` side.
//!
//! Once the associations are defined, you can join between the two tables using the
//! [`inner_join`][inner-join] or [`left_outer_join`][left-outer-join].
//!
//! [inner-join]: query_source/trait.Table.html#method.inner_join
//! [left-outer-join]: query_source/trait.Table.html#method.left_outer_join
//!
//! ```ignore
//! let data: Vec<(User, Post)> = users::table.inner_join(posts::table).load(&connection);
//! ```
//!
//! Note: Due to language limitations, only two tables can be joined per query. This will change in
//! the future.
//!
//! Typically however, queries are loaded in multiple queries. For most datasets, the reduced
//! amount of duplicated information sent over the wire saves more time than the extra round trip
//! costs us. You can load the children for a single parent using the
//! [`belonging_to`][belonging-to]
//!
//! [belonging-to]: prelude/trait.BelongingToDsl.html#tymethod.belonging_to
//!
//! ```ignore
//! let user = try!(users::find(1).first(&connection));
//! let posts = Post::belonging_to(&user).load(&connection);
//! ```
//!
//! If you're coming from other ORMs, you'll notice that this design is quite different from most.
//! There you would have an instance method on the parent, or have the children stored somewhere on
//! the posts. This design leads to many problems, including [N+1 query
//! bugs][load-your-entire-database-into-memory-lol], and runtime errors when accessing an
//! association that isn't there.
//!
//! [load-your-entire-database-into-memory-lol]: http://stackoverflow.com/q/97197/1254484
//!
//! In Diesel, data and its associations are considered to be separate. If you want to pass around
//! a user and all of its posts, that type is `(User, Vec<Post>)`.
//!
//! Next lets look at how to load the children for more than one parent record.
//! [`belonging_to`][belonging-to] can be used to load the data, but we'll also need to group it
//! with its parents. For this we use an additional method [`grouped_by`][grouped-by]
//!
//! [grouped-by]: associations/trait.GroupedBy.html#tymethod.grouped_by
//!
//! ```ignore
//! fn first_twenty_users_and_their_posts(conn: &PgConnection) -> QueryResult<Vec<(User, Vec<Post>)>> {
//!     let users = try!(users::limit(20).load::<User>(conn));
//!     let posts = try!(Post::belonging_to(&users).load::<Post>(conn));
//!     let grouped_posts = posts.grouped_by(&users);
//!     users.into_iter().zip(grouped_posts).collect()
//! }
//! ```
//!
//! [`grouped_by`][grouped-by] takes a `Vec<Child>` and a `Vec<Parent>` and returns a
//! `Vec<Vec<Child>>` where the index of the children matches the index of the parent they belong
//! to. Or to put it another way, it returns them in an order ready to be `zip`ed with the parents. You
//! can do this multiple times. For example, if you wanted to load the comments for all the posts
//! as well, you could do this: (explicit type annotations have been added for documentation
//! purposes)
//!
//! ```ignore
//! let posts: Vec<Post> = try!(Post::belonging_to(&users).load());
//! let comments: Vec<Comment> = try!(Comment::belonging_to(&posts).load());
//! let comments: Vec<Vec<Comment>> = comments.grouped_by(&posts);
//! let posts_and_comments: Vec<Vec<(Post, Vec<Comment>)>> = posts.into_iter().zip(comments).grouped_by(&users);
//! let result: Vec<(User, Vec<(Post, Vec<Comment>)>)> = users.into_iter().zip(posts_and_comments).collect();
//! ```
//!
//! And that's it. This module will be expanded in the future with more complex joins, and the
//! ability to define "through" associations (e.g. load all the comments left on any posts written
//! by a user in a single query). However, the goal is to provide simple building blocks which can
//! be used to construct the complex behavior applications need.
mod belongs_to;

use std::hash::Hash;

use query_dsl::FindDsl;
use query_source::Table;

pub use self::belongs_to::{BelongsTo, GroupedBy};

pub trait Identifiable {
    type Id: Hash + Eq + Copy;
    type Table: Table + FindDsl<Self::Id>;

    fn table() -> Self::Table;
    fn id(&self) -> Self::Id;
}
<|endoftext|>


<commit_before><commit_msg>Format alu...() test to pass rustfmt (part 2: name change)<commit_after><|endoftext|>