<commit_before>import std::term;
import io::writer_util;
import codemap::span;

export emitter, emit;
export level, fatal, error, warning, note;
export span_handler, handler, mk_span_handler, mk_handler;
export codemap_span_handler, codemap_handler;
export ice_msg;
export expect;

type emitter = fn@(cmsp: option<(codemap::codemap, span)>,
                   msg: ~str, lvl: level);

iface span_handler {
    fn span_fatal(sp: span, msg: ~str) -> !;
    fn span_err(sp: span, msg: ~str);
    fn span_warn(sp: span, msg: ~str);
    fn span_note(sp: span, msg: ~str);
    fn span_bug(sp: span, msg: ~str) -> !;
    fn span_unimpl(sp: span, msg: ~str) -> !;
    fn handler() -> handler;
}

iface handler {
    fn fatal(msg: ~str) -> !;
    fn err(msg: ~str);
    fn bump_err_count();
    fn has_errors() -> bool;
    fn abort_if_errors();
    fn warn(msg: ~str);
    fn note(msg: ~str);
    fn bug(msg: ~str) -> !;
    fn unimpl(msg: ~str) -> !;
    fn emit(cmsp: option<(codemap::codemap, span)>, msg: ~str, lvl: level);
}

type handler_t = @{
    mut err_count: uint,
    emit: emitter
};

type codemap_t = @{
    handler: handler,
    cm: codemap::codemap
};

impl codemap_span_handler of span_handler for codemap_t {
    fn span_fatal(sp: span, msg: ~str) -> ! {
        self.handler.emit(some((self.cm, sp)), msg, fatal);
        fail;
    }
    fn span_err(sp: span, msg: ~str) {
        self.handler.emit(some((self.cm, sp)), msg, error);
        self.handler.bump_err_count();
    }
    fn span_warn(sp: span, msg: ~str) {
        self.handler.emit(some((self.cm, sp)), msg, warning);
    }
    fn span_note(sp: span, msg: ~str) {
        self.handler.emit(some((self.cm, sp)), msg, note);
    }
    fn span_bug(sp: span, msg: ~str) -> ! {
        self.span_fatal(sp, ice_msg(msg));
    }
    fn span_unimpl(sp: span, msg: ~str) -> ! {
        self.span_bug(sp, ~"unimplemented " + msg);
    }
    fn handler() -> handler {
        self.handler
    }
}

impl codemap_handler of handler for handler_t {
    fn fatal(msg: ~str) -> ! {
        self.emit(none, msg, fatal);
        fail;
    }
    fn err(msg: ~str) {
        self.emit(none, msg, error);
        self.bump_err_count();
    }
    fn bump_err_count() {
        self.err_count += 1u;
    }
    fn has_errors() -> bool { self.err_count > 0u }
    fn abort_if_errors() {
        let s;
        alt self.err_count {
          0u { ret; }
          1u { s = ~"aborting due to previous error"; }
          _  { s = #fmt["aborting due to %u previous errors",
                        self.err_count]; }
        }
        self.fatal(s);
    }
    fn warn(msg: ~str) {
        self.emit(none, msg, warning);
    }
    fn note(msg: ~str) {
        self.emit(none, msg, note);
    }
    fn bug(msg: ~str) -> ! {
        self.fatal(ice_msg(msg));
    }
    fn unimpl(msg: ~str) -> ! { self.bug(~"unimplemented " + msg); }
    fn emit(cmsp: option<(codemap::codemap, span)>, msg: ~str, lvl: level) {
        self.emit(cmsp, msg, lvl);
    }
}

fn ice_msg(msg: ~str) -> ~str {
    #fmt["internal compiler error: %s", msg]
}

fn mk_span_handler(handler: handler, cm: codemap::codemap) -> span_handler {
    @{ handler: handler, cm: cm } as span_handler
}

fn mk_handler(emitter: option<emitter>) -> handler {

    let emit = alt emitter {
      some(e) { e }
      none {
        let f = fn@(cmsp: option<(codemap::codemap, span)>,
            msg: ~str, t: level) {
            emit(cmsp, msg, t);
        };
        f
      }
    };

    @{
        mut err_count: 0u,
        emit: emit
    } as handler
}

enum level {
    fatal,
    error,
    warning,
    note,
}

fn diagnosticstr(lvl: level) -> ~str {
    alt lvl {
      fatal { ~"error" }
      error { ~"error" }
      warning { ~"warning" }
      note { ~"note" }
    }
}

fn diagnosticcolor(lvl: level) -> u8 {
    alt lvl {
      fatal { term::color_bright_red }
      error { term::color_bright_red }
      warning { term::color_bright_yellow }
      note { term::color_bright_green }
    }
}

fn print_diagnostic(topic: ~str, lvl: level, msg: ~str) {
    if str::is_not_empty(topic) {
        io::stderr().write_str(#fmt["%s ", topic]);
    }
    if term::color_supported() {
        term::fg(io::stderr(), diagnosticcolor(lvl));
    }
    io::stderr().write_str(#fmt["%s:", diagnosticstr(lvl)]);
    if term::color_supported() {
        term::reset(io::stderr());
    }
    io::stderr().write_str(#fmt[" %s\n", msg]);
}

fn emit(cmsp: option<(codemap::codemap, span)>,
        msg: ~str, lvl: level) {
    alt cmsp {
      some((cm, sp)) {
        let sp = codemap::adjust_span(cm,sp);
        let ss = codemap::span_to_str(sp, cm);
        let lines = codemap::span_to_lines(sp, cm);
        print_diagnostic(ss, lvl, msg);
        highlight_lines(cm, sp, lines);
        print_macro_backtrace(cm, sp);
      }
      none {
        print_diagnostic(~"", lvl, msg);
      }
    }
}

fn highlight_lines(cm: codemap::codemap, sp: span,
                   lines: @codemap::file_lines) {

    let fm = lines.file;

    // arbitrarily only print up to six lines of the error
    let max_lines = 6u;
    let mut elided = false;
    let mut display_lines = /* FIXME (#2543) */ copy lines.lines;
    if vec::len(display_lines) > max_lines {
        display_lines = vec::slice(display_lines, 0u, max_lines);
        elided = true;
    }
    // Print the offending lines
    for display_lines.each |line| {
        io::stderr().write_str(#fmt["%s:%u ", fm.name, line + 1u]);
        let s = codemap::get_line(fm, line as int) + ~"\n";
        io::stderr().write_str(s);
    }
    if elided {
        let last_line = display_lines[vec::len(display_lines) - 1u];
        let s = #fmt["%s:%u ", fm.name, last_line + 1u];
        let mut indent = str::len(s);
        let mut out = ~"";
        while indent > 0u { out += ~" "; indent -= 1u; }
        out += ~"...\n";
        io::stderr().write_str(out);
    }

    // If there's one line at fault we can easily point to the problem
    if vec::len(lines.lines) == 1u {
        let lo = codemap::lookup_char_pos(cm, sp.lo);
        let mut digits = 0u;
        let mut num = (lines.lines[0] + 1u) / 10u;

        // how many digits must be indent past?
        while num > 0u { num /= 10u; digits += 1u; }

        // indent past |name:## | and the 0-offset column location
        let mut left = str::len(fm.name) + digits + lo.col + 3u;
        let mut s = ~"";
        while left > 0u { str::push_char(s, ' '); left -= 1u; }

        s += ~"^";
        let hi = codemap::lookup_char_pos(cm, sp.hi);
        if hi.col != lo.col {
            // the ^ already takes up one space
            let mut width = hi.col - lo.col - 1u;
            while width > 0u { str::push_char(s, '~'); width -= 1u; }
        }
        io::stderr().write_str(s + ~"\n");
    }
}

fn print_macro_backtrace(cm: codemap::codemap, sp: span) {
    do option::iter (sp.expn_info) |ei| {
        let ss = option::map_default(ei.callie.span, @~"",
                                     |span| @codemap::span_to_str(span, cm));
        print_diagnostic(*ss, note,
                         #fmt("in expansion of #%s", ei.callie.name));
        let ss = codemap::span_to_str(ei.call_site, cm);
        print_diagnostic(ss, note, ~"expansion site");
        print_macro_backtrace(cm, ei.call_site);
    }
}

fn expect<T: copy>(diag: span_handler,
                   opt: option<T>, msg: fn() -> ~str) -> T {
    alt opt {
       some(t) { t }
       none { diag.handler().bug(msg()); }
    }
}
<commit_msg>diagnostic: only print color if output is for the screen<commit_after>import std::term;
import io::writer_util;
import codemap::span;

export emitter, emit;
export level, fatal, error, warning, note;
export span_handler, handler, mk_span_handler, mk_handler;
export codemap_span_handler, codemap_handler;
export ice_msg;
export expect;

type emitter = fn@(cmsp: option<(codemap::codemap, span)>,
                   msg: ~str, lvl: level);

iface span_handler {
    fn span_fatal(sp: span, msg: ~str) -> !;
    fn span_err(sp: span, msg: ~str);
    fn span_warn(sp: span, msg: ~str);
    fn span_note(sp: span, msg: ~str);
    fn span_bug(sp: span, msg: ~str) -> !;
    fn span_unimpl(sp: span, msg: ~str) -> !;
    fn handler() -> handler;
}

iface handler {
    fn fatal(msg: ~str) -> !;
    fn err(msg: ~str);
    fn bump_err_count();
    fn has_errors() -> bool;
    fn abort_if_errors();
    fn warn(msg: ~str);
    fn note(msg: ~str);
    fn bug(msg: ~str) -> !;
    fn unimpl(msg: ~str) -> !;
    fn emit(cmsp: option<(codemap::codemap, span)>, msg: ~str, lvl: level);
}

type handler_t = @{
    mut err_count: uint,
    emit: emitter
};

type codemap_t = @{
    handler: handler,
    cm: codemap::codemap
};

impl codemap_span_handler of span_handler for codemap_t {
    fn span_fatal(sp: span, msg: ~str) -> ! {
        self.handler.emit(some((self.cm, sp)), msg, fatal);
        fail;
    }
    fn span_err(sp: span, msg: ~str) {
        self.handler.emit(some((self.cm, sp)), msg, error);
        self.handler.bump_err_count();
    }
    fn span_warn(sp: span, msg: ~str) {
        self.handler.emit(some((self.cm, sp)), msg, warning);
    }
    fn span_note(sp: span, msg: ~str) {
        self.handler.emit(some((self.cm, sp)), msg, note);
    }
    fn span_bug(sp: span, msg: ~str) -> ! {
        self.span_fatal(sp, ice_msg(msg));
    }
    fn span_unimpl(sp: span, msg: ~str) -> ! {
        self.span_bug(sp, ~"unimplemented " + msg);
    }
    fn handler() -> handler {
        self.handler
    }
}

impl codemap_handler of handler for handler_t {
    fn fatal(msg: ~str) -> ! {
        self.emit(none, msg, fatal);
        fail;
    }
    fn err(msg: ~str) {
        self.emit(none, msg, error);
        self.bump_err_count();
    }
    fn bump_err_count() {
        self.err_count += 1u;
    }
    fn has_errors() -> bool { self.err_count > 0u }
    fn abort_if_errors() {
        let s;
        alt self.err_count {
          0u { ret; }
          1u { s = ~"aborting due to previous error"; }
          _  { s = #fmt["aborting due to %u previous errors",
                        self.err_count]; }
        }
        self.fatal(s);
    }
    fn warn(msg: ~str) {
        self.emit(none, msg, warning);
    }
    fn note(msg: ~str) {
        self.emit(none, msg, note);
    }
    fn bug(msg: ~str) -> ! {
        self.fatal(ice_msg(msg));
    }
    fn unimpl(msg: ~str) -> ! { self.bug(~"unimplemented " + msg); }
    fn emit(cmsp: option<(codemap::codemap, span)>, msg: ~str, lvl: level) {
        self.emit(cmsp, msg, lvl);
    }
}

fn ice_msg(msg: ~str) -> ~str {
    #fmt["internal compiler error: %s", msg]
}

fn mk_span_handler(handler: handler, cm: codemap::codemap) -> span_handler {
    @{ handler: handler, cm: cm } as span_handler
}

fn mk_handler(emitter: option<emitter>) -> handler {

    let emit = alt emitter {
      some(e) { e }
      none {
        let f = fn@(cmsp: option<(codemap::codemap, span)>,
            msg: ~str, t: level) {
            emit(cmsp, msg, t);
        };
        f
      }
    };

    @{
        mut err_count: 0u,
        emit: emit
    } as handler
}

enum level {
    fatal,
    error,
    warning,
    note,
}

fn diagnosticstr(lvl: level) -> ~str {
    alt lvl {
      fatal { ~"error" }
      error { ~"error" }
      warning { ~"warning" }
      note { ~"note" }
    }
}

fn diagnosticcolor(lvl: level) -> u8 {
    alt lvl {
      fatal { term::color_bright_red }
      error { term::color_bright_red }
      warning { term::color_bright_yellow }
      note { term::color_bright_green }
    }
}

fn print_diagnostic(topic: ~str, lvl: level, msg: ~str) {
    let use_color = term::color_supported() &&
        io::stderr().get_type() == io::screen;
    if str::is_not_empty(topic) {
        io::stderr().write_str(#fmt["%s ", topic]);
    }
    if use_color {
        term::fg(io::stderr(), diagnosticcolor(lvl));
    }
    io::stderr().write_str(#fmt["%s:", diagnosticstr(lvl)]);
    if use_color {
        term::reset(io::stderr());
    }
    io::stderr().write_str(#fmt[" %s\n", msg]);
}

fn emit(cmsp: option<(codemap::codemap, span)>,
        msg: ~str, lvl: level) {
    alt cmsp {
      some((cm, sp)) {
        let sp = codemap::adjust_span(cm,sp);
        let ss = codemap::span_to_str(sp, cm);
        let lines = codemap::span_to_lines(sp, cm);
        print_diagnostic(ss, lvl, msg);
        highlight_lines(cm, sp, lines);
        print_macro_backtrace(cm, sp);
      }
      none {
        print_diagnostic(~"", lvl, msg);
      }
    }
}

fn highlight_lines(cm: codemap::codemap, sp: span,
                   lines: @codemap::file_lines) {

    let fm = lines.file;

    // arbitrarily only print up to six lines of the error
    let max_lines = 6u;
    let mut elided = false;
    let mut display_lines = /* FIXME (#2543) */ copy lines.lines;
    if vec::len(display_lines) > max_lines {
        display_lines = vec::slice(display_lines, 0u, max_lines);
        elided = true;
    }
    // Print the offending lines
    for display_lines.each |line| {
        io::stderr().write_str(#fmt["%s:%u ", fm.name, line + 1u]);
        let s = codemap::get_line(fm, line as int) + ~"\n";
        io::stderr().write_str(s);
    }
    if elided {
        let last_line = display_lines[vec::len(display_lines) - 1u];
        let s = #fmt["%s:%u ", fm.name, last_line + 1u];
        let mut indent = str::len(s);
        let mut out = ~"";
        while indent > 0u { out += ~" "; indent -= 1u; }
        out += ~"...\n";
        io::stderr().write_str(out);
    }

    // If there's one line at fault we can easily point to the problem
    if vec::len(lines.lines) == 1u {
        let lo = codemap::lookup_char_pos(cm, sp.lo);
        let mut digits = 0u;
        let mut num = (lines.lines[0] + 1u) / 10u;

        // how many digits must be indent past?
        while num > 0u { num /= 10u; digits += 1u; }

        // indent past |name:## | and the 0-offset column location
        let mut left = str::len(fm.name) + digits + lo.col + 3u;
        let mut s = ~"";
        while left > 0u { str::push_char(s, ' '); left -= 1u; }

        s += ~"^";
        let hi = codemap::lookup_char_pos(cm, sp.hi);
        if hi.col != lo.col {
            // the ^ already takes up one space
            let mut width = hi.col - lo.col - 1u;
            while width > 0u { str::push_char(s, '~'); width -= 1u; }
        }
        io::stderr().write_str(s + ~"\n");
    }
}

fn print_macro_backtrace(cm: codemap::codemap, sp: span) {
    do option::iter (sp.expn_info) |ei| {
        let ss = option::map_default(ei.callie.span, @~"",
                                     |span| @codemap::span_to_str(span, cm));
        print_diagnostic(*ss, note,
                         #fmt("in expansion of #%s", ei.callie.name));
        let ss = codemap::span_to_str(ei.call_site, cm);
        print_diagnostic(ss, note, ~"expansion site");
        print_macro_backtrace(cm, ei.call_site);
    }
}

fn expect<T: copy>(diag: span_handler,
                   opt: option<T>, msg: fn() -> ~str) -> T {
    alt opt {
       some(t) { t }
       none { diag.handler().bug(msg()); }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add evaluate tests<commit_after>extern crate robin_core;

mod eval_expr_tests {
    use robin_core::ast::Expression;
    use robin_core::to_javascript::ToJavaScript;
    use robin_core::error::{Error, ErrorLevel, ErrorKind};

    #[test]
    fn if_with_no_args_should_return_an_err() {
        let expr = Expression::FuncCall("if".to_string(), vec![]);

        let err =  Err(Error(ErrorLevel::Error, ErrorKind::TooFewArguments, "Too few Arguments applied for if"));

        assert_eq!(expr.eval(), err)
    }

    #[test]
    fn if_with_no_expression_after_condition_should_return_an_err() {
        let expr = Expression::FuncCall("if".to_string(), vec![Box::new(Expression::Boolean(true))]);

        let err = Err(Error(ErrorLevel::Error, ErrorKind::TooFewArguments, "No expression applied for condition"));

        assert_eq!(expr.eval(), err)
    }

    #[test]
    fn if_with_only_one_branch_should_return_an_func() {
        let expr = Expression::FuncCall("if".to_string(), vec![Box::new(Expression::Boolean(true)), Box::new(Expression::Number(1.0))]);

        assert_eq!(expr.eval(), Ok(String::from("(if (true) { 1 })")))
    }

    #[test]
    fn if_with_else_branch_should_return_a_func() {
        let expr = Expression::FuncCall("if".to_string(),
                                           vec![Box::new(Expression::Boolean(true)),
                                                Box::new(Expression::Number(1.0)),
                                                Box::new(Expression::Number(1.0))]);

        assert_eq!(expr.eval(), Ok(String::from("(if (true) { 1 } else { 1 })")))
    }
}<|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::fs::{File, OpenOptions, create_dir_all, remove_file, copy, rename};
use std::io::{Seek, SeekFrom, Read};
use std::path::{Path, PathBuf};

use error::{StoreError as SE, StoreErrorKind as SEK};
use error::ResultExt;

use super::FileAbstraction;
use super::FileAbstractionInstance;
use super::Drain;
use store::Entry;
use storeid::StoreId;
use file_abstraction::iter::PathIterator;

#[derive(Debug)]
pub enum FSFileAbstractionInstance {
    Absent(PathBuf),
    File(File, PathBuf)
}

impl FileAbstractionInstance for FSFileAbstractionInstance {

    /**
     * Get the content behind this file
     */
    fn get_file_content(&mut self, id: StoreId) -> Result<Entry, SE> {
        debug!("Getting lazy file: {:?}", self);
        let (file, path) = match *self {
            FSFileAbstractionInstance::File(ref mut f, _) => return {
                // We seek to the beginning of the file since we expect each
                // access to the file to be in a different context
                try!(f.seek(SeekFrom::Start(0))
                    .chain_err(|| SEK::FileNotSeeked));

                let mut s = String::new();
                f.read_to_string(&mut s)
                    .chain_err(|| SEK::IoError)
                    .map(|_| s)
                    .and_then(|s| Entry::from_str(id, &s))
            },
            FSFileAbstractionInstance::Absent(ref p) =>
                (try!(open_file(p).chain_err(|| SEK::FileNotFound)), p.clone()),
        };
        *self = FSFileAbstractionInstance::File(file, path);
        if let FSFileAbstractionInstance::File(ref mut f, _) = *self {
            let mut s = String::new();
            f.read_to_string(&mut s)
                .chain_err(|| SEK::IoError)
                .map(|_| s)
                .and_then(|s| Entry::from_str(id, &s))
        } else {
            unreachable!()
        }
    }

    /**
     * Write the content of this file
     */
    fn write_file_content(&mut self, buf: &Entry) -> Result<(), SE> {
        use std::io::Write;

        let buf = buf.to_str().into_bytes();

        let (file, path) = match *self {
            FSFileAbstractionInstance::File(ref mut f, _) => return {
                // We seek to the beginning of the file since we expect each
                // access to the file to be in a different context
                try!(f.seek(SeekFrom::Start(0))
                    .chain_err(|| SEK::FileNotCreated));

                try!(f.set_len(buf.len() as u64).chain_err(|| SEK::FileNotWritten));

                f.write_all(&buf).chain_err(|| SEK::FileNotWritten)
            },
            FSFileAbstractionInstance::Absent(ref p) =>
                (try!(create_file(p).chain_err(|| SEK::FileNotCreated)), p.clone()),
        };
        *self = FSFileAbstractionInstance::File(file, path);
        if let FSFileAbstractionInstance::File(ref mut f, _) = *self {
            return f.write_all(&buf).chain_err(|| SEK::FileNotWritten);
        }
        unreachable!();
    }
}

/// `FSFileAbstraction` state type
///
/// A lazy file is either absent, but a path to it is available, or it is present.
#[derive(Debug)]
pub struct FSFileAbstraction {
}

impl FSFileAbstraction {
    pub fn new() -> FSFileAbstraction {
        FSFileAbstraction { }
    }
}

impl FileAbstraction for FSFileAbstraction {

    fn remove_file(&self, path: &PathBuf) -> Result<(), SE> {
        remove_file(path).chain_err(|| SEK::FileNotRemoved)
    }

    fn copy(&self, from: &PathBuf, to: &PathBuf) -> Result<(), SE> {
        copy(from, to).chain_err(|| SEK::FileNotCopied).map(|_| ())
    }

    fn rename(&self, from: &PathBuf, to: &PathBuf) -> Result<(), SE> {
        rename(from, to).chain_err(|| SEK::FileNotRenamed)
    }

    fn create_dir_all(&self, path: &PathBuf) -> Result<(), SE> {
        create_dir_all(path).chain_err(|| SEK::DirNotCreated)
    }

    fn exists(&self, path: &PathBuf) -> Result<bool, SE> {
        Ok(path.exists())
    }

    fn new_instance(&self, p: PathBuf) -> Box<FileAbstractionInstance> {
        Box::new(FSFileAbstractionInstance::Absent(p))
    }

    /// We return nothing from the FS here.
    fn drain(&self) -> Result<Drain, SE> {
        Ok(Drain::empty())
    }

    /// FileAbstraction::fill implementation that consumes the Drain and writes everything to the
    /// filesystem
    fn fill(&mut self, mut d: Drain) -> Result<(), SE> {
        d.iter()
            .fold(Ok(()), |acc, (path, element)| {
                acc.and_then(|_| self.new_instance(path).write_file_content(&element))
            })
    }

    fn pathes_recursively(&self, basepath: PathBuf) -> Result<PathIterator, SE> {
        use walkdir::WalkDir;

        let i : Result<Vec<PathBuf>, SE> = WalkDir::new(basepath)
            .into_iter()
            .map(|r| {
                r.map(|e| PathBuf::from(e.path()))
                    .chain_err(|| SE::from_kind(SEK::FileError))
            })
            .fold(Ok(vec![]), |acc, e| {
                acc.and_then(move |mut a| {
                    a.push(try!(e));
                    Ok(a)
                })
            });
        Ok(PathIterator::new(Box::new(try!(i).into_iter())))
    }
}

fn open_file<A: AsRef<Path>>(p: A) -> ::std::io::Result<File> {
    OpenOptions::new().write(true).read(true).open(p)
}

fn create_file<A: AsRef<Path>>(p: A) -> ::std::io::Result<File> {
    if let Some(parent) = p.as_ref().parent() {
        debug!("Implicitely creating directory: {:?}", parent);
        if let Err(e) = create_dir_all(parent) {
            return Err(e);
        }
    }
    OpenOptions::new().write(true).read(true).create(true).open(p)
}

<commit_msg>Fix Walkdir depth<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::fs::{File, OpenOptions, create_dir_all, remove_file, copy, rename};
use std::io::{Seek, SeekFrom, Read};
use std::path::{Path, PathBuf};

use error::{StoreError as SE, StoreErrorKind as SEK};
use error::ResultExt;

use super::FileAbstraction;
use super::FileAbstractionInstance;
use super::Drain;
use store::Entry;
use storeid::StoreId;
use file_abstraction::iter::PathIterator;

#[derive(Debug)]
pub enum FSFileAbstractionInstance {
    Absent(PathBuf),
    File(File, PathBuf)
}

impl FileAbstractionInstance for FSFileAbstractionInstance {

    /**
     * Get the content behind this file
     */
    fn get_file_content(&mut self, id: StoreId) -> Result<Entry, SE> {
        debug!("Getting lazy file: {:?}", self);
        let (file, path) = match *self {
            FSFileAbstractionInstance::File(ref mut f, _) => return {
                // We seek to the beginning of the file since we expect each
                // access to the file to be in a different context
                try!(f.seek(SeekFrom::Start(0))
                    .chain_err(|| SEK::FileNotSeeked));

                let mut s = String::new();
                f.read_to_string(&mut s)
                    .chain_err(|| SEK::IoError)
                    .map(|_| s)
                    .and_then(|s| Entry::from_str(id, &s))
            },
            FSFileAbstractionInstance::Absent(ref p) =>
                (try!(open_file(p).chain_err(|| SEK::FileNotFound)), p.clone()),
        };
        *self = FSFileAbstractionInstance::File(file, path);
        if let FSFileAbstractionInstance::File(ref mut f, _) = *self {
            let mut s = String::new();
            f.read_to_string(&mut s)
                .chain_err(|| SEK::IoError)
                .map(|_| s)
                .and_then(|s| Entry::from_str(id, &s))
        } else {
            unreachable!()
        }
    }

    /**
     * Write the content of this file
     */
    fn write_file_content(&mut self, buf: &Entry) -> Result<(), SE> {
        use std::io::Write;

        let buf = buf.to_str().into_bytes();

        let (file, path) = match *self {
            FSFileAbstractionInstance::File(ref mut f, _) => return {
                // We seek to the beginning of the file since we expect each
                // access to the file to be in a different context
                try!(f.seek(SeekFrom::Start(0))
                    .chain_err(|| SEK::FileNotCreated));

                try!(f.set_len(buf.len() as u64).chain_err(|| SEK::FileNotWritten));

                f.write_all(&buf).chain_err(|| SEK::FileNotWritten)
            },
            FSFileAbstractionInstance::Absent(ref p) =>
                (try!(create_file(p).chain_err(|| SEK::FileNotCreated)), p.clone()),
        };
        *self = FSFileAbstractionInstance::File(file, path);
        if let FSFileAbstractionInstance::File(ref mut f, _) = *self {
            return f.write_all(&buf).chain_err(|| SEK::FileNotWritten);
        }
        unreachable!();
    }
}

/// `FSFileAbstraction` state type
///
/// A lazy file is either absent, but a path to it is available, or it is present.
#[derive(Debug)]
pub struct FSFileAbstraction {
}

impl FSFileAbstraction {
    pub fn new() -> FSFileAbstraction {
        FSFileAbstraction { }
    }
}

impl FileAbstraction for FSFileAbstraction {

    fn remove_file(&self, path: &PathBuf) -> Result<(), SE> {
        remove_file(path).chain_err(|| SEK::FileNotRemoved)
    }

    fn copy(&self, from: &PathBuf, to: &PathBuf) -> Result<(), SE> {
        copy(from, to).chain_err(|| SEK::FileNotCopied).map(|_| ())
    }

    fn rename(&self, from: &PathBuf, to: &PathBuf) -> Result<(), SE> {
        rename(from, to).chain_err(|| SEK::FileNotRenamed)
    }

    fn create_dir_all(&self, path: &PathBuf) -> Result<(), SE> {
        create_dir_all(path).chain_err(|| SEK::DirNotCreated)
    }

    fn exists(&self, path: &PathBuf) -> Result<bool, SE> {
        Ok(path.exists())
    }

    fn new_instance(&self, p: PathBuf) -> Box<FileAbstractionInstance> {
        Box::new(FSFileAbstractionInstance::Absent(p))
    }

    /// We return nothing from the FS here.
    fn drain(&self) -> Result<Drain, SE> {
        Ok(Drain::empty())
    }

    /// FileAbstraction::fill implementation that consumes the Drain and writes everything to the
    /// filesystem
    fn fill(&mut self, mut d: Drain) -> Result<(), SE> {
        d.iter()
            .fold(Ok(()), |acc, (path, element)| {
                acc.and_then(|_| self.new_instance(path).write_file_content(&element))
            })
    }

    fn pathes_recursively(&self, basepath: PathBuf) -> Result<PathIterator, SE> {
        use walkdir::WalkDir;

        let i : Result<Vec<PathBuf>, SE> = WalkDir::new(basepath)
            .min_depth(1)
            .into_iter()
            .map(|r| {
                r.map(|e| PathBuf::from(e.path()))
                    .chain_err(|| SE::from_kind(SEK::FileError))
            })
            .fold(Ok(vec![]), |acc, e| {
                acc.and_then(move |mut a| {
                    a.push(try!(e));
                    Ok(a)
                })
            });
        Ok(PathIterator::new(Box::new(try!(i).into_iter())))
    }
}

fn open_file<A: AsRef<Path>>(p: A) -> ::std::io::Result<File> {
    OpenOptions::new().write(true).read(true).open(p)
}

fn create_file<A: AsRef<Path>>(p: A) -> ::std::io::Result<File> {
    if let Some(parent) = p.as_ref().parent() {
        debug!("Implicitely creating directory: {:?}", parent);
        if let Err(e) = create_dir_all(parent) {
            return Err(e);
        }
    }
    OpenOptions::new().write(true).read(true).create(true).open(p)
}

<|endoftext|>


<commit_before><commit_msg>Add test for #6155<commit_after>// Copyright 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.

// Issue #6155

fn first((value, _): (int, float)) -> int { value }

fn main() {
    let y = first ((1,2,3)); //~ ERROR expected a tuple with 2 elements but found one with 3 elements
}
<|endoftext|>


<commit_before><commit_msg>Make Iter a tuple-struct<commit_after><|endoftext|>


<commit_before>#![cfg(any(target_arch="x86", target_arch="x86_64"))]

#![feature(const_fn)]
#![feature(asm)]
#![feature(associated_consts)]
#![no_std]
#![cfg_attr(test, allow(unused_features))]

#[macro_use]
extern crate bitflags;

#[macro_use]
extern crate raw_cpuid;

#[cfg(feature = "performance-counter")]
#[macro_use]
extern crate phf;

#[cfg(target_arch="x86")]
pub mod bits32;
#[cfg(target_arch="x86_64")]
pub mod bits64;
pub mod shared;

mod std {
    pub use core::fmt;
    pub use core::ops;
    pub use core::option;
}
<commit_msg>Add `::current` module for whichever of `bits{32,64}` is active<commit_after>#![cfg(any(target_arch="x86", target_arch="x86_64"))]

#![feature(const_fn)]
#![feature(asm)]
#![feature(associated_consts)]
#![no_std]
#![cfg_attr(test, allow(unused_features))]

#[macro_use]
extern crate bitflags;

#[macro_use]
extern crate raw_cpuid;

#[cfg(feature = "performance-counter")]
#[macro_use]
extern crate phf;

#[cfg(target_arch="x86")]
pub mod bits32;
#[cfg(target_arch="x86_64")]
pub mod bits64;
pub mod shared;

pub mod current {
  #[cfg(target_arch="x86")]
  pub use bits32::*;
  #[cfg(target_arch="x86_64")]
  pub use bits64::*;
}

mod std {
    pub use core::fmt;
    pub use core::ops;
    pub use core::option;
}
<|endoftext|>


<commit_before><commit_msg>Inline methods<commit_after><|endoftext|>


<commit_before>#![crate_name = "input"]
#![deny(missing_doc)]
#![feature(globs)]
#![feature(struct_variant)]

//! A flexible structure for user interactions
//! to be used in window frameworks and widgets libraries.

pub mod keyboard;
pub mod mouse;

/// Models input events.
#[deriving(Clone)]
pub enum InputEvent {
    /// Pressed a keyboard key.
    KeyPress {
        /// Keyboard key.
        pub key: keyboard::Key,
    },
    /// Released a keyboard key.
    KeyRelease {
        /// Keyboard key.
        pub key: keyboard::Key,
    },
    /// Pressed a mouse button.
    MousePress {
        /// Mouse button.
        pub button: mouse::Button,
    },
    /// Released a mouse button.
    MouseRelease {
        /// Mouse button.
        pub button: mouse::Button,
    },
    /// Moved mouse cursor.
    MouseMove {
        /// x in window coordinates.
        pub x: f64,
        /// y in window coordinates.
        pub y: f64,
        /// x in drawing coordinates.
        pub draw_x: f64,
        /// y in drawing coordinates.
        pub draw_y: f64,
    },
    /// Moved mouse relative, not bounded by cursor.
    MouseRelativeMove {
        /// Delta x in window coordinates.
        pub dx: f64,
        /// Delta y in window coordinates.
        pub dy: f64,
        /// Delta x in drawing coordinates.
        pub draw_dx: f64,
        /// Delta y in drawing coordinates.
        pub draw_dy: f64,
    },
    /// Scrolled mouse.
    MouseScroll {
        /// Delta x in undefined coordinates.
        pub dx: f64,
        /// Delta y in undefined coordinates.
        pub dy: f64,
    },
}

<commit_msg>New simplified design<commit_after>#![crate_name = "input"]
#![deny(missing_doc)]
#![feature(globs)]
#![feature(struct_variant)]

//! A flexible structure for user interactions
//! to be used in window frameworks and widgets libraries.

pub mod keyboard;
pub mod mouse;

/// Models different kinds of buttons.
#[deriving(Clone)]
pub enum Button {
    /// A keyboard button.
    Keyboard(keyboard::Key),
    /// A mouse button.
    Mouse(mouse::Button),
}

/// Models different kinds of motion.
#[deriving(Clone)]
pub enum Motion {
    /// x and y in window coordinates.
    MouseCursor(f64, f64),
    /// x and y in relative coordinates.
    MouseRelative(f64, f64),
    /// x and y in scroll ticks.
    MouseScroll(f64, f64),
}

/// Models input events.
#[deriving(Clone)]
pub enum InputEvent {
    /// Pressed a button.
    Press(Button),
    /// Released a button.
    Release(Button),
    /// Moved mouse cursor.
    Move(Motion),
    /// Text (usually from keyboard).
    Text(String),
}

<|endoftext|>


<commit_before><commit_msg>Formatting<commit_after><|endoftext|>


<commit_before><commit_msg>fixed output bug<commit_after><|endoftext|>


<commit_before><commit_msg>Add const generics tests for supertraits + dyn traits.<commit_after>// check-pass
// revisions: full min

#![cfg_attr(full, feature(const_generics))]
#![cfg_attr(full, allow(incomplete_features))]
#![cfg_attr(min, feature(min_const_generics))]

trait Foo<const N: usize> {}
trait Bar<const N: usize> : Foo<N> {}
trait Baz: Foo<3> {}

struct FooType<const N: usize> {}
struct BarType<const N: usize> {}
struct BazType {}

impl<const N: usize> Foo<N> for FooType<N> {}
impl<const N: usize> Foo<N> for BarType<N> {}
impl<const N: usize> Bar<N> for BarType<N> {}
impl Foo<3> for BazType {}
impl Baz for BazType {}

trait Foz {}
trait Boz: Foo<3> + Foz {}
trait Bok<const N: usize>: Foo<N> + Foz {}

struct FozType {}
struct BozType {}
struct BokType<const N: usize> {}

impl Foz for FozType {}

impl Foz for BozType {}
impl Foo<3> for BozType {}
impl Boz for BozType {}

impl<const N: usize> Foz for BokType<N> {}
impl<const N: usize> Foo<N> for BokType<N> {}
impl<const N: usize> Bok<N> for BokType<N> {}

fn a<const N: usize>(x: &dyn Foo<N>) {}
fn b(x: &dyn Foo<3>) {}

fn main() {
    let foo = FooType::<3> {};
    a(&foo); b(&foo);

    let bar = BarType::<3> {};
    a(&bar); b(&bar);

    let baz = BazType {};
    a(&baz); b(&baz);

    let boz = BozType {};
    a(&boz); b(&boz);

    let bok = BokType::<3> {};
    a(&bok); b(&bok);
}
<|endoftext|>


<commit_before><commit_msg>Roughly Implement LDR<commit_after><|endoftext|>


<commit_before><commit_msg>Fixes after refactoring<commit_after><|endoftext|>


<commit_before><commit_msg>WIP: handshake to service<commit_after><|endoftext|>


<commit_before><commit_msg>Add rust code for minesweeper case<commit_after>#[inline]
fn neighbors(x: usize, y: usize, width: usize, height: usize) -> Vec<(usize, usize)> {
    let mut result = Vec::new();

    if x != 0 && y != 0 {
        result.push((x - 1, y - 1));
    }

    if x != width - 1 && y != height - 1 {
        result.push((x + 1, y + 1));
    }

    if x != 0 && y != height - 1 {
        result.push((x - 1, y + 1));
    }

    if y != 0 && x != width - 1 {
        result.push((x + 1, y - 1));
    }

    if x != 0 {
        result.push((x - 1, y));
    }

    if y != 0 {
        result.push((x, y - 1));
    }

    if x != width - 1 {
        result.push((x + 1, y));
    }

    if y != height - 1 {
        result.push((x, y + 1));
    }

    result
}

pub fn annotate(text: &[&str]) -> Vec<String> {
    let height = text.len();
    if height == 0 {
        return Vec::new();
    }

    let width = text[0].len();
    if width == 0 {
        return vec![String::new()];
    }

    let mut v = Vec::new();

    for i in text {
        v.push(i.chars().collect::<Vec<_>>());
    }

    let mut result = Vec::new();

    for (y, vec) in v.iter().enumerate() {
        let mut s = String::new();

        for (x, &c) in vec.iter().enumerate() {
            if c == '*' {
                s.push('*');

                continue;
            }

            let r = neighbors(x, y, width, height)
                .iter()
                .filter(|&&(m, n)| v[n][m] == '*')
                .count();
            if r != 0 {
                s.push((r as u8 + b'0') as char);
            } else {
                s.push(' ');
            }
        }

        result.push(s);
    }

    result
}
<|endoftext|>


<commit_before>use std::ops::DerefMut;

use runtime::Runtime;
use error::RuntimeError;
use error::RuntimeErrorKind;

use libimagstore::store::FileLockEntry;
use libimagstore::store::Entry;

use libimagerror::into::IntoError;

pub type EditResult<T> = Result<T, RuntimeError>;

pub trait Edit {
    fn edit_content(&mut self, rt: &Runtime) -> EditResult<()>;
}

impl Edit for String {

    fn edit_content(&mut self, rt: &Runtime) -> EditResult<()> {
        edit_in_tmpfile(rt, self).map(|_| ())
    }

}

impl Edit for Entry {

    fn edit_content(&mut self, rt: &Runtime) -> EditResult<()> {
        edit_in_tmpfile(rt, self.get_content_mut())
            .map(|_| ())
    }

}

impl<'a> Edit for FileLockEntry<'a> {

    fn edit_content(&mut self, rt: &Runtime) -> EditResult<()> {
        self.deref_mut().edit_content(rt)
    }

}

pub fn edit_in_tmpfile(rt: &Runtime, s: &mut String) -> EditResult<()> {
    use tempfile::NamedTempFile;
    use std::io::Seek;
    use std::io::Read;
    use std::io::SeekFrom;
    use std::io::Write;

    let file      = try!(NamedTempFile::new());
    let file_path = file.path();
    let mut file  = try!(file.reopen());

    try!(file.write_all(&s.clone().into_bytes()[..]));
    try!(file.sync_data());

    if let Some(mut editor) = rt.editor() {
        let exit_status = editor.arg(file_path).status();

        match exit_status.map(|s| s.success()).map_err(Box::new) {
            Ok(true)  => {
                file.sync_data()
                    .and_then(|_| file.seek(SeekFrom::Start(0)))
                    .and_then(|_| {
                        let mut new_s = String::new();
                        let res = file.read_to_string(&mut new_s);
                        *s = new_s;
                        res
                    })
                    .map(|_| ())
                    .map_err(Box::new)
                    .map_err(|e| RuntimeErrorKind::IOError.into_error_with_cause(e))
            },
            Ok(false) => Err(RuntimeErrorKind::ProcessExitFailure.into()),
            Err(e)    => Err(RuntimeErrorKind::IOError.into_error_with_cause(e)),
        }
    } else {
        Err(RuntimeErrorKind::Instantiate.into())
    }
}
<commit_msg>Rewrite error module<commit_after>use std::ops::DerefMut;

use libimagerror::into::IntoError;
use libimagrt::runtime::Runtime;
use libimagstore::store::Entry;
use libimagstore::store::FileLockEntry;

use result::Result;
use error::EditErrorKind;
use error::MapErrInto;

pub trait Edit {
    fn edit_content(&mut self, rt: &Runtime) -> Result<()>;
}

impl Edit for String {

    fn edit_content(&mut self, rt: &Runtime) -> Result<()> {
        edit_in_tmpfile(rt, self).map(|_| ())
    }

}

impl Edit for Entry {

    fn edit_content(&mut self, rt: &Runtime) -> Result<()> {
        edit_in_tmpfile(rt, self.get_content_mut())
            .map(|_| ())
    }

}

impl<'a> Edit for FileLockEntry<'a> {

    fn edit_content(&mut self, rt: &Runtime) -> Result<()> {
        self.deref_mut().edit_content(rt)
    }

}

pub fn edit_in_tmpfile(rt: &Runtime, s: &mut String) -> Result<()> {
    use tempfile::NamedTempFile;
    use std::io::Seek;
    use std::io::Read;
    use std::io::SeekFrom;
    use std::io::Write;

    let file      = try!(NamedTempFile::new().map_err_into(EditErrorKind::IOError));
    let file_path = file.path();
    let mut file  = try!(file.reopen().map_err_into(EditErrorKind::IOError));

    try!(file.write_all(&s.clone().into_bytes()[..]).map_err_into(EditErrorKind::IOError));
    try!(file.sync_data().map_err_into(EditErrorKind::IOError));

    if let Some(mut editor) = rt.editor() {
        let exit_status = editor.arg(file_path).status();

        match exit_status.map(|s| s.success()).map_err(Box::new) {
            Ok(true)  => {
                file.sync_data()
                    .and_then(|_| file.seek(SeekFrom::Start(0)))
                    .and_then(|_| {
                        let mut new_s = String::new();
                        let res = file.read_to_string(&mut new_s);
                        *s = new_s;
                        res
                    })
                    .map(|_| ())
                    .map_err_into(EditErrorKind::IOError)
            },
            Ok(false) => Err(EditErrorKind::ProcessExitFailure.into()),
            Err(e)    => Err(EditErrorKind::IOError.into_error_with_cause(e)),
        }
    } else {
        Err(EditErrorKind::InstantiateError.into())
    }
}
<|endoftext|>


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

pub fn to_closure<A:Durable + Copy>(x: A) -> @fn() -> A {
    let result: @fn() -> A = || copy x;
    result
}
<commit_msg>test: Replace Durable with 'static<commit_after>// Copyright 2012 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.

pub fn to_closure<A:'static + Copy>(x: A) -> @fn() -> A {
    let result: @fn() -> A = || copy x;
    result
}
<|endoftext|>


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

//! Runtime calls emitted by the compiler.

use c_str::ToCStr;

#[cold]
#[lang="fail_"]
pub fn fail_(expr: *u8, file: *u8, line: uint) -> ! {
    ::rt::begin_unwind_raw(expr, file, line);
}

#[cold]
#[lang="fail_bounds_check"]
pub fn fail_bounds_check(file: *u8, line: uint, index: uint, len: uint) -> ! {
    let msg = format!("index out of bounds: the len is {} but the index is {}",
                      len as uint, index as uint);
    msg.with_c_str(|buf| fail_(buf as *u8, file, line))
}

#[lang="malloc"]
#[inline]
pub unsafe fn local_malloc(drop_glue: fn(*mut u8), size: uint, align: uint) -> *u8 {
    ::rt::local_heap::local_malloc(drop_glue, size, align)
}

// NB: Calls to free CANNOT be allowed to fail, as throwing an exception from
// inside a landing pad may corrupt the state of the exception handler. If a
// problem occurs, call exit instead.
#[lang="free"]
#[inline]
pub unsafe fn local_free(ptr: *u8) {
    ::rt::local_heap::local_free(ptr);
}
<commit_msg>auto merge of #12357 : chromatic/rust/gh_11976_fail_bounds_check_str, r=alexcrichton<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.

//! Runtime calls emitted by the compiler.

use c_str::CString;
use libc::c_char;
use cast;
use option::Some;

#[cold]
#[lang="fail_"]
pub fn fail_(expr: *u8, file: *u8, line: uint) -> ! {
    ::rt::begin_unwind_raw(expr, file, line);
}

#[cold]
#[lang="fail_bounds_check"]
pub fn fail_bounds_check(file: *u8, line: uint, index: uint, len: uint) -> ! {
    let msg = format!("index out of bounds: the len is {} but the index is {}",
                      len as uint, index as uint);

    let file_str = match unsafe { CString::new(file as *c_char, false) }.as_str() {
        // This transmute is safe because `file` is always stored in rodata.
        Some(s) => unsafe { cast::transmute::<&str, &'static str>(s) },
        None    => "file wasn't UTF-8 safe"
    };

    ::rt::begin_unwind(msg, file_str, line)
}

#[lang="malloc"]
#[inline]
pub unsafe fn local_malloc(drop_glue: fn(*mut u8), size: uint, align: uint) -> *u8 {
    ::rt::local_heap::local_malloc(drop_glue, size, align)
}

// NB: Calls to free CANNOT be allowed to fail, as throwing an exception from
// inside a landing pad may corrupt the state of the exception handler. If a
// problem occurs, call exit instead.
#[lang="free"]
#[inline]
pub unsafe fn local_free(ptr: *u8) {
    ::rt::local_heap::local_free(ptr);
}
<|endoftext|>


<commit_before><commit_msg>Add a test for mismatched types when comparing functions<commit_after>// xfail-stage0
// error-pattern:expected fn() but found fn(int)

fn main() {
  fn f() {}
  fn g(int i) {}
  auto x = f == g;
}<|endoftext|>


<commit_before><commit_msg>object identification<commit_after><|endoftext|>


<commit_before>use cocoa;

export QuartzNativeFont, with_test_native_font, create;

import libc::size_t;
import ptr::null;
import unsafe::reinterpret_cast;
import glyph::GlyphIndex;
import cocoa::cg::{
    CGDataProviderRef,
    CGFontRef
};
import cocoa::cg::cg::{
    CGDataProviderCreateWithData,
    CGDataProviderRelease,
    CGFontCreateWithDataProvider,
    CGFontRelease
};

mod coretext {

    type CTFontRef = *u8;
    type UniChar = libc::c_ushort;
    type CGGlyph = libc::c_ushort;
    type CFIndex = libc::c_long;

    type CTFontOrientation = u32;
    const kCTFontDefaultOrientation: CTFontOrientation = 0;
    const kCTFontHorizontalOrientation: CTFontOrientation = 1;
    const kCTFontVerticalOrientation: CTFontOrientation = 2;

    type CGFloat = libc::c_double;

    struct CGSize {
        width: CGFloat;
        height: CGFloat;
    }

    type CGAffineTransform = ();
    type CTFontDescriptorRef = *u8;

    #[nolink]
    #[link_args = "-framework ApplicationServices"]
    extern mod coretext {
        fn CTFontCreateWithGraphicsFont(graphicsFont: CGFontRef, size: CGFloat, matrix: *CGAffineTransform, attributes: CTFontDescriptorRef) -> CTFontRef;
        fn CTFontGetGlyphsForCharacters(font: CTFontRef, characters: *UniChar, glyphs: *CGGlyph, count: CFIndex) -> bool;
        fn CTFontGetAdvancesForGlyphs(font: CTFontRef, orientation: CTFontOrientation, glyphs: *CGGlyph, advances: *CGSize, count: CFIndex) -> libc::c_double;
        fn CFRelease(font: CTFontRef);
    }
}

struct QuartzNativeFont/& {
    let fontprov: CGDataProviderRef;
    let cgfont: CGFontRef;

    new (fontprov: CGDataProviderRef, cgfont: CGFontRef) {
        assert fontprov.is_not_null();
        assert cgfont.is_not_null();

        self.fontprov = fontprov;
        self.cgfont = cgfont;
    }

    drop {
        assert self.cgfont.is_not_null();
        assert self.fontprov.is_not_null();

        CGFontRelease(self.cgfont);
        CGDataProviderRelease(self.fontprov);
    }

    fn glyph_index(codepoint: char) -> Option<GlyphIndex> {

        import coretext::{UniChar, CGGlyph, CFIndex};
        import coretext::coretext::{CFRelease, CTFontGetGlyphsForCharacters};

        let ctfont = ctfont_from_cgfont(self.cgfont);
        assert ctfont.is_not_null();
        let characters: ~[UniChar] = ~[codepoint as UniChar];
        let glyphs: ~[mut CGGlyph] = ~[mut 0 as CGGlyph];
        let count: CFIndex = 1;

        let result = do vec::as_buf(characters) |character_buf, _l| {
            do vec::as_buf(glyphs) |glyph_buf, _l| {
                CTFontGetGlyphsForCharacters(ctfont, character_buf, glyph_buf, count)
            }
        };

        assert result != false; // FIXME: error handling

        CFRelease(ctfont);

        assert glyphs[0] != 0; // FIXME: error handling
        return Some(glyphs[0] as GlyphIndex);
    }

    // FIXME: What unit is this returning? Let's have a custom type
    fn glyph_h_advance(glyph: GlyphIndex) -> Option<int> {
        import coretext::{CGGlyph, kCTFontDefaultOrientation};
        import coretext::coretext::{CFRelease, CTFontGetAdvancesForGlyphs};

        let ctfont = ctfont_from_cgfont(self.cgfont);
        assert ctfont.is_not_null();
        let glyphs = ~[glyph as CGGlyph];
        let advance = do vec::as_buf(glyphs) |glyph_buf, _l| {
            CTFontGetAdvancesForGlyphs(ctfont, kCTFontDefaultOrientation, glyph_buf, null(), 1)
        };

        CFRelease(ctfont);

        return Some(advance as int);
    }
}

fn ctfont_from_cgfont(+cgfont: CGFontRef) -> coretext::CTFontRef unsafe {
    import coretext::CGFloat;
    import coretext::coretext::CTFontCreateWithGraphicsFont;

    assert cgfont.is_not_null();
    CTFontCreateWithGraphicsFont(cgfont, 21f as CGFloat, null(), null())
}

fn create(buf: &~[u8]) -> Result<QuartzNativeFont, ()> {
    let fontprov = vec::as_buf(*buf, |cbuf, len| {
        CGDataProviderCreateWithData(
            null(),
            unsafe { reinterpret_cast(&cbuf) },
            len as size_t,
            null())
    });
    // FIXME: Error handling
    assert fontprov.is_not_null();
    let cgfont = CGFontCreateWithDataProvider(fontprov);
    // FIXME: Error handling
    assert cgfont.is_not_null();

    return Ok(QuartzNativeFont(fontprov, cgfont));
}

fn with_test_native_font(f: fn@(nf: &NativeFont)) {
    import font::test_font_bin;
    import unwrap_result = result::unwrap;

    let buf = test_font_bin();
    let res = create(&buf);
    let font = unwrap_result(res);
    f(&font);
}
<commit_msg>Handle when glyphs don't exist on mac<commit_after>use cocoa;

export QuartzNativeFont, with_test_native_font, create;

import libc::size_t;
import ptr::null;
import unsafe::reinterpret_cast;
import glyph::GlyphIndex;
import cocoa::cg::{
    CGDataProviderRef,
    CGFontRef
};
import cocoa::cg::cg::{
    CGDataProviderCreateWithData,
    CGDataProviderRelease,
    CGFontCreateWithDataProvider,
    CGFontRelease
};

mod coretext {

    type CTFontRef = *u8;
    type UniChar = libc::c_ushort;
    type CGGlyph = libc::c_ushort;
    type CFIndex = libc::c_long;

    type CTFontOrientation = u32;
    const kCTFontDefaultOrientation: CTFontOrientation = 0;
    const kCTFontHorizontalOrientation: CTFontOrientation = 1;
    const kCTFontVerticalOrientation: CTFontOrientation = 2;

    type CGFloat = libc::c_double;

    struct CGSize {
        width: CGFloat;
        height: CGFloat;
    }

    type CGAffineTransform = ();
    type CTFontDescriptorRef = *u8;

    #[nolink]
    #[link_args = "-framework ApplicationServices"]
    extern mod coretext {
        fn CTFontCreateWithGraphicsFont(graphicsFont: CGFontRef, size: CGFloat, matrix: *CGAffineTransform, attributes: CTFontDescriptorRef) -> CTFontRef;
        fn CTFontGetGlyphsForCharacters(font: CTFontRef, characters: *UniChar, glyphs: *CGGlyph, count: CFIndex) -> bool;
        fn CTFontGetAdvancesForGlyphs(font: CTFontRef, orientation: CTFontOrientation, glyphs: *CGGlyph, advances: *CGSize, count: CFIndex) -> libc::c_double;
        fn CFRelease(font: CTFontRef);
    }
}

struct QuartzNativeFont/& {
    let fontprov: CGDataProviderRef;
    let cgfont: CGFontRef;

    new (fontprov: CGDataProviderRef, cgfont: CGFontRef) {
        assert fontprov.is_not_null();
        assert cgfont.is_not_null();

        self.fontprov = fontprov;
        self.cgfont = cgfont;
    }

    drop {
        assert self.cgfont.is_not_null();
        assert self.fontprov.is_not_null();

        CGFontRelease(self.cgfont);
        CGDataProviderRelease(self.fontprov);
    }

    fn glyph_index(codepoint: char) -> Option<GlyphIndex> {

        import coretext::{UniChar, CGGlyph, CFIndex};
        import coretext::coretext::{CFRelease, CTFontGetGlyphsForCharacters};

        let ctfont = ctfont_from_cgfont(self.cgfont);
        assert ctfont.is_not_null();
        let characters: ~[UniChar] = ~[codepoint as UniChar];
        let glyphs: ~[mut CGGlyph] = ~[mut 0 as CGGlyph];
        let count: CFIndex = 1;

        let result = do vec::as_buf(characters) |character_buf, _l| {
            do vec::as_buf(glyphs) |glyph_buf, _l| {
                CTFontGetGlyphsForCharacters(ctfont, character_buf, glyph_buf, count)
            }
        };

        if !result {
            // No glyph for this character
            return None;
        }

        CFRelease(ctfont);

        assert glyphs[0] != 0; // FIXME: error handling
        return Some(glyphs[0] as GlyphIndex);
    }

    // FIXME: What unit is this returning? Let's have a custom type
    fn glyph_h_advance(glyph: GlyphIndex) -> Option<int> {
        import coretext::{CGGlyph, kCTFontDefaultOrientation};
        import coretext::coretext::{CFRelease, CTFontGetAdvancesForGlyphs};

        let ctfont = ctfont_from_cgfont(self.cgfont);
        assert ctfont.is_not_null();
        let glyphs = ~[glyph as CGGlyph];
        let advance = do vec::as_buf(glyphs) |glyph_buf, _l| {
            CTFontGetAdvancesForGlyphs(ctfont, kCTFontDefaultOrientation, glyph_buf, null(), 1)
        };

        CFRelease(ctfont);

        return Some(advance as int);
    }
}

fn ctfont_from_cgfont(+cgfont: CGFontRef) -> coretext::CTFontRef unsafe {
    import coretext::CGFloat;
    import coretext::coretext::CTFontCreateWithGraphicsFont;

    assert cgfont.is_not_null();
    CTFontCreateWithGraphicsFont(cgfont, 21f as CGFloat, null(), null())
}

fn create(buf: &~[u8]) -> Result<QuartzNativeFont, ()> {
    let fontprov = vec::as_buf(*buf, |cbuf, len| {
        CGDataProviderCreateWithData(
            null(),
            unsafe { reinterpret_cast(&cbuf) },
            len as size_t,
            null())
    });
    // FIXME: Error handling
    assert fontprov.is_not_null();
    let cgfont = CGFontCreateWithDataProvider(fontprov);
    // FIXME: Error handling
    assert cgfont.is_not_null();

    return Ok(QuartzNativeFont(fontprov, cgfont));
}

fn with_test_native_font(f: fn@(nf: &NativeFont)) {
    import font::test_font_bin;
    import unwrap_result = result::unwrap;

    let buf = test_font_bin();
    let res = create(&buf);
    let font = unwrap_result(res);
    f(&font);
}
<|endoftext|>


<commit_before><commit_msg>Swap comment<commit_after><|endoftext|>


<commit_before><commit_msg>Add extra arc_wake<commit_after>// edition:2018

use std::sync::Arc;
use std::task::{
    Waker, RawWaker, RawWakerVTable,
};

macro_rules! waker_vtable {
    ($ty:ident) => {
        &RawWakerVTable::new(
            clone_arc_raw::<$ty>,
            wake_arc_raw::<$ty>,
            wake_by_ref_arc_raw::<$ty>,
            drop_arc_raw::<$ty>,
        )
    };
}

pub trait ArcWake {
    fn wake(self: Arc<Self>);

    fn wake_by_ref(arc_self: &Arc<Self>) {
        arc_self.clone().wake()
    }

    fn into_waker(wake: Arc<Self>) -> Waker where Self: Sized
    {
        let ptr = Arc::into_raw(wake) as *const ();

        unsafe {
            Waker::from_raw(RawWaker::new(ptr, waker_vtable!(Self)))
        }
    }
}

unsafe fn increase_refcount<T: ArcWake>(data: *const ()) {
    // Retain Arc by creating a copy
    let arc: Arc<T> = Arc::from_raw(data as *const T);
    let arc_clone = arc.clone();
    // Forget the Arcs again, so that the refcount isn't decrased
    let _ = Arc::into_raw(arc);
    let _ = Arc::into_raw(arc_clone);
}

unsafe fn clone_arc_raw<T: ArcWake>(data: *const ()) -> RawWaker {
    increase_refcount::<T>(data);
    RawWaker::new(data, waker_vtable!(T))
}

unsafe fn drop_arc_raw<T: ArcWake>(data: *const ()) {
    // Drop Arc
    let _: Arc<T> = Arc::from_raw(data as *const T);
}

unsafe fn wake_arc_raw<T: ArcWake>(data: *const ()) {
    let arc: Arc<T> = Arc::from_raw(data as *const T);
    ArcWake::wake(arc);
}

unsafe fn wake_by_ref_arc_raw<T: ArcWake>(data: *const ()) {
    let arc: Arc<T> = Arc::from_raw(data as *const T);
    ArcWake::wake_by_ref(&arc);
    let _ = Arc::into_raw(arc);
}
<|endoftext|>


<commit_before>use std::collections::BTreeMap;
use rustc_serialize::Decodable;
use rustc_serialize::base64::{
    FromBase64,
    ToBase64,
};
use rustc_serialize::json::{
    self,
    Decoder,
    Json,
};
use Component;
use error::Error;
use BASE_CONFIG;

#[derive(Debug, Default, PartialEq)]
pub struct Claims {
    pub reg: Registered,
    pub private: BTreeMap<String, Json>,
}

#[derive(Debug, Default, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Registered {
    pub iss: Option<String>,
    pub sub: Option<String>,
    pub aud: Option<String>,
    pub exp: Option<u64>,
    pub nbf: Option<u64>,
    pub iat: Option<u64>,
    pub jti: Option<String>,
}

/// JWT Claims. Registered claims are directly accessible via the `Registered`
/// struct embedded, while private fields are a map that contains `Json`
/// values.
impl Claims {
    pub fn new(reg: Registered) -> Claims {
        Claims {
            reg: reg,
            private: BTreeMap::new(),
        }
    }
}

impl Component for Claims {
    fn from_base64(raw: &str) -> Result<Claims, Error> {
        let data = try!(raw.from_base64());
        let s = try!(String::from_utf8(data));
        let tree = match try!(Json::from_str(&*s)) {
            Json::Object(x) => x,
            _ => return Err(Error::Format),
        };

        const FIELDS: [&'static str; 7] = [
            "iss", "sub", "aud",
            "exp", "nbf", "iat",
            "jti",
        ];

        let (reg, pri): (BTreeMap<_, _>, BTreeMap<_, _>) = tree.into_iter()
            .partition(|&(ref key, _)| {
                FIELDS.iter().any(|f| f == key)
            });

        let mut decoder = Decoder::new(Json::Object(reg));
        let reg_claims: Registered = try!(Decodable::decode(&mut decoder));

        Ok(Claims{
            reg: reg_claims,
            private: pri,
        })
    }

    fn to_base64(&self) -> Result<String, Error> {
        // Extremely inefficient
        let s = try!(json::encode(&self.reg));
        let mut tree = match try!(Json::from_str(&*s)) {
            Json::Object(x) => x,
            _ => return Err(Error::Format),
        };

        tree.extend(self.private.clone());

        let s = try!(json::encode(&tree));
        let enc = (&*s).as_bytes().to_base64(BASE_CONFIG);
        Ok(enc)
    }
}

#[cfg(test)]
mod tests {
    use std::default::Default;
    use claims::Claims;

    #[test]
    fn from_base64() {
        let enc = "ew0KICAiaXNzIjogIm1pa2t5YW5nLmNvbSIsDQogICJleHAiOiAxMzAyMzE5MTAwLA0KICAibmFtZSI6ICJNaWNoYWVsIFlhbmciLA0KICAiYWRtaW4iOiB0cnVlDQp9";
        let claims = Claims::from_base64(enc).unwrap();

        assert_eq!(claims.reg.iss.unwrap(), "mikkyang.com");
        assert_eq!(claims.reg.exp.unwrap(), 1302319100);
    }

    #[test]
    fn roundtrip() {
        let mut claims: Claims = Default::default();
        claims.reg.iss = Some("mikkyang.com".into());
        claims.reg.exp = Some(1302319100);
        let enc = claims.to_base64().unwrap();
        assert_eq!(claims, Claims::from_base64(&*enc).unwrap());
    }
}
<commit_msg>Fix tests<commit_after>use std::collections::BTreeMap;
use rustc_serialize::Decodable;
use rustc_serialize::base64::{
    FromBase64,
    ToBase64,
};
use rustc_serialize::json::{
    self,
    Decoder,
    Json,
};
use Component;
use error::Error;
use BASE_CONFIG;

#[derive(Debug, Default, PartialEq)]
pub struct Claims {
    pub reg: Registered,
    pub private: BTreeMap<String, Json>,
}

#[derive(Debug, Default, PartialEq, RustcDecodable, RustcEncodable)]
pub struct Registered {
    pub iss: Option<String>,
    pub sub: Option<String>,
    pub aud: Option<String>,
    pub exp: Option<u64>,
    pub nbf: Option<u64>,
    pub iat: Option<u64>,
    pub jti: Option<String>,
}

/// JWT Claims. Registered claims are directly accessible via the `Registered`
/// struct embedded, while private fields are a map that contains `Json`
/// values.
impl Claims {
    pub fn new(reg: Registered) -> Claims {
        Claims {
            reg: reg,
            private: BTreeMap::new(),
        }
    }
}

impl Component for Claims {
    fn from_base64(raw: &str) -> Result<Claims, Error> {
        let data = try!(raw.from_base64());
        let s = try!(String::from_utf8(data));
        let tree = match try!(Json::from_str(&*s)) {
            Json::Object(x) => x,
            _ => return Err(Error::Format),
        };

        const FIELDS: [&'static str; 7] = [
            "iss", "sub", "aud",
            "exp", "nbf", "iat",
            "jti",
        ];

        let (reg, pri): (BTreeMap<_, _>, BTreeMap<_, _>) = tree.into_iter()
            .partition(|&(ref key, _)| {
                FIELDS.iter().any(|f| f == key)
            });

        let mut decoder = Decoder::new(Json::Object(reg));
        let reg_claims: Registered = try!(Decodable::decode(&mut decoder));

        Ok(Claims{
            reg: reg_claims,
            private: pri,
        })
    }

    fn to_base64(&self) -> Result<String, Error> {
        // Extremely inefficient
        let s = try!(json::encode(&self.reg));
        let mut tree = match try!(Json::from_str(&*s)) {
            Json::Object(x) => x,
            _ => return Err(Error::Format),
        };

        tree.extend(self.private.clone());

        let s = try!(json::encode(&tree));
        let enc = (&*s).as_bytes().to_base64(BASE_CONFIG);
        Ok(enc)
    }
}

#[cfg(test)]
mod tests {
    use std::default::Default;
    use claims::Claims;
    use Component;

    #[test]
    fn from_base64() {
        let enc = "ew0KICAiaXNzIjogIm1pa2t5YW5nLmNvbSIsDQogICJleHAiOiAxMzAyMzE5MTAwLA0KICAibmFtZSI6ICJNaWNoYWVsIFlhbmciLA0KICAiYWRtaW4iOiB0cnVlDQp9";
        let claims = Claims::from_base64(enc).unwrap();

        assert_eq!(claims.reg.iss.unwrap(), "mikkyang.com");
        assert_eq!(claims.reg.exp.unwrap(), 1302319100);
    }

    #[test]
    fn roundtrip() {
        let mut claims: Claims = Default::default();
        claims.reg.iss = Some("mikkyang.com".into());
        claims.reg.exp = Some(1302319100);
        let enc = claims.to_base64().unwrap();
        assert_eq!(claims, Claims::from_base64(&*enc).unwrap());
    }
}
<|endoftext|>


<commit_before><commit_msg>feat(geektime_algo): add 38 divide and conquer<commit_after>fn merge_sort_count(mut nums: Vec<i32>) -> i32 {
    let mut count = 0;
    let n = nums.len() - 1;
    merge_sort(&mut nums, 0, n, &mut count);
    count
}

fn merge_sort(nums: &mut Vec<i32>, low: usize, high: usize, count: &mut i32) {
    if low >= high { return; }

    let middle = low + ((high - low) >> 1);
    merge_sort(nums, low, middle, count);
    merge_sort(nums, middle+1, high, count);

    merge(nums, low, middle, high, count);
}

fn merge(nums:   &mut Vec<i32>,
         low:    usize,
         middle: usize,
         high:   usize,
         count:  &mut i32) {
    let mut i = low;
    let mut j = middle + 1;
    let mut tmp = vec![];

    while i <= middle && j <= high {
        if nums[i] <= nums[j] {
            tmp.push(nums[i]);
            i += 1;
        } else {
            // count += &(middle - i + 1);
            *count += (middle - i + 1) as i32;
            tmp.push(nums[j]);
            j += 1;
        }
    }

    while i <= middle {
        tmp.push(nums[i]);
        i += 1;
    }

    while j <= high {
        tmp.push(nums[j]);
        j += 1;
    }

   for i in 0..=(high-low) {
       nums[low+1] = tmp[i];
   }
}
fn main() {
    let nums = vec![1, 5, 6, 2, 3, 4];
    let m = merge_sort_count(nums);
    println!("{:?}", m);
}
<|endoftext|>


<commit_before><commit_msg>Finish converting tests to render to texture<commit_after><|endoftext|>


<commit_before>//! Macros for the linear algebra modules.

/// The `matrix!` macro enables easy construction of small matrices.
///
/// This is particularly useful when writing tests involving matrices.
/// Note that the macro is just a convenient wrapper around the Matrix
/// constructors, and as a result the matrix is still allocated on the
/// heap.
///
/// Rows are separated by semi-colons, while commas separate the columns.
/// Users of MATLAB will find this style familiar. If the dimensions
/// don't match, the macro will fail to compile.
///
/// # Examples
///
/// ```
/// #[macro_use]
/// extern crate rulinalg;
///
/// # fn main() {
/// // Construct a 3x3 matrix of f64
/// let mat = matrix!(1.0, 2.0, 3.0;
///                   4.0, 5.0, 6.0;
///                   7.0, 8.0, 9.0);
/// # }
/// ```
///
/// To construct matrices of other types, specify the type by
/// the usual Rust syntax:
///
/// ```
/// # #[macro_use]
/// # extern crate rulinalg;
/// # fn main() {
/// use rulinalg::matrix::Matrix;
///
/// // Construct a 2x3 matrix of f32
/// let mat: Matrix<f32> = matrix!(1.0, 2.0, 3.0;
///                                4.0, 5.0, 6.0);
/// // Or
/// let mat = matrix!(1.0, 2.0, 3.0;
///                   4.0, 5.0, 6.0f32);
/// # }
/// ```
///
#[macro_export]
macro_rules! matrix {
    ($( $( $x: expr ),*);*) => {
        {
            use $crate::matrix::Matrix;
            let data_as_nested_array = [ $( [ $($x),* ] ),* ];
            let rows = data_as_nested_array.len();
            let cols = data_as_nested_array[0].len();
            let data_as_flat_array: Vec<_> = data_as_nested_array.into_iter()
                .flat_map(|row| row.into_iter())
                .cloned()
                .collect();
            Matrix::new(rows, cols, data_as_flat_array)
        }
    }
}

#[cfg(test)]
mod tests {
    use matrix::slice::BaseMatrix;

    #[test]
    fn matrix_macro() {
        {
            // An arbitrary rectangular matrix
            let mat = matrix!(1, 2, 3;
                              4, 5, 6);
            assert_eq!(2, mat.rows());
            assert_eq!(3, mat.cols());
            assert_eq!(&vec![1, 2, 3, 4, 5, 6], mat.data());
        }

        {
            // A single row
            let mat = matrix!(1, 2, 3);
            assert_eq!(1, mat.rows());
            assert_eq!(3, mat.cols());
            assert_eq!(&vec![1, 2, 3], mat.data());
        }

        {
            // A single element
            let mat = matrix!(1);
            assert_eq!(1, mat.rows());
            assert_eq!(1, mat.cols());
            assert_eq!(&vec![1], mat.data());
        }

        {
            // A floating point matrix
            let mat = matrix!(1.0, 2.0, 3.0;
                              4.0, 5.0, 6.0;
                              7.0, 8.0, 9.0);
            let ref expected_data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];
            assert_eq!(3, mat.rows());
            assert_eq!(3, mat.cols());
            assert_eq!(expected_data, mat.data());
        }
    }

}
<commit_msg>Enable matrix! to construct empty matrix (#65)<commit_after>//! Macros for the linear algebra modules.

/// The `matrix!` macro enables easy construction of small matrices.
///
/// This is particularly useful when writing tests involving matrices.
/// Note that the macro is just a convenient wrapper around the Matrix
/// constructors, and as a result the matrix is still allocated on the
/// heap.
///
/// Rows are separated by semi-colons, while commas separate the columns.
/// Users of MATLAB will find this style familiar. If the dimensions
/// don't match, the macro will fail to compile.
///
/// # Examples
///
/// ```
/// #[macro_use]
/// extern crate rulinalg;
///
/// # fn main() {
/// // Construct a 3x3 matrix of f64
/// let mat = matrix!(1.0, 2.0, 3.0;
///                   4.0, 5.0, 6.0;
///                   7.0, 8.0, 9.0);
/// # }
/// ```
///
/// To construct matrices of other types, specify the type by
/// the usual Rust syntax:
///
/// ```
/// # #[macro_use]
/// # extern crate rulinalg;
/// # fn main() {
/// use rulinalg::matrix::Matrix;
///
/// // Construct a 2x3 matrix of f32
/// let mat: Matrix<f32> = matrix!(1.0, 2.0, 3.0;
///                                4.0, 5.0, 6.0);
/// // Or
/// let mat = matrix!(1.0, 2.0, 3.0;
///                   4.0, 5.0, 6.0f32);
/// # }
/// ```
///
#[macro_export]
macro_rules! matrix {
    () => {
        {
            // Handle the case when called with no arguments, i.e. matrix![]
            use $crate::matrix::Matrix;
            Matrix::new(0, 0, vec![])
        }
    };
    ($( $( $x: expr ),*);*) => {
        {
            use $crate::matrix::Matrix;
            let data_as_nested_array = [ $( [ $($x),* ] ),* ];
            let rows = data_as_nested_array.len();
            let cols = data_as_nested_array[0].len();
            let data_as_flat_array: Vec<_> = data_as_nested_array.into_iter()
                .flat_map(|row| row.into_iter())
                .cloned()
                .collect();
            Matrix::new(rows, cols, data_as_flat_array)
        }
    }
}

#[cfg(test)]
mod tests {
    use matrix::slice::BaseMatrix;
    use matrix::Matrix;

    #[test]
    fn matrix_macro() {
        {
            // An arbitrary rectangular matrix
            let mat = matrix!(1, 2, 3;
                              4, 5, 6);
            assert_eq!(2, mat.rows());
            assert_eq!(3, mat.cols());
            assert_eq!(&vec![1, 2, 3, 4, 5, 6], mat.data());
        }

        {
            // A single row
            let mat = matrix!(1, 2, 3);
            assert_eq!(1, mat.rows());
            assert_eq!(3, mat.cols());
            assert_eq!(&vec![1, 2, 3], mat.data());
        }

        {
            // A single element
            let mat = matrix!(1);
            assert_eq!(1, mat.rows());
            assert_eq!(1, mat.cols());
            assert_eq!(&vec![1], mat.data());
        }

        {
            // A floating point matrix
            let mat = matrix!(1.0, 2.0, 3.0;
                              4.0, 5.0, 6.0;
                              7.0, 8.0, 9.0);
            let ref expected_data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];
            assert_eq!(3, mat.rows());
            assert_eq!(3, mat.cols());
            assert_eq!(expected_data, mat.data());
        }
    }

    #[test]
    fn matrix_macro_empty_mat() {
        let mat: Matrix<f64> = matrix![];

        assert_eq!(0, mat.rows());
        assert_eq!(0, mat.cols());
    }

}
<|endoftext|>


<commit_before><commit_msg>added the example for real<commit_after>extern crate phant;

use phant::Phant;

fn main() {

    // Create a phant object for sparkfun's publically writable repository
    let mut phant = Phant::new("data.sparkfun.com", "Jxyjr7DmxwTD5dG1D1Kv", "gzgnB4VazkIg7GN1g1qA");

    // Add one key/value pair of data.  The keys need to be same
    phant.add("brewTemp", "posting from the rust library @ github.com/freiguy1/phant-rust");

    println!("------ url paste-able into a browser -------\n{}\n", phant.get_url());

    match phant.push() {
        Ok(result) => println!("------- result -------\n{}", result),
        Err(e) => println!("-------- error --------\n{}", e)
    }

}
<|endoftext|>


<commit_before><commit_msg>Add ISO-8601 calendar conversion functions<commit_after>static EPOCH_LEN: int = 146097;
static MONTHDAY: [int, ..12] = [
    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
];

/// Convert an ISO 8601 date to a chronological Julian day.
pub fn to_cjd(year: int, month: int, day: int) -> int {
    let y = year - 2000;
    let mut a = y % 400;
    let mut b = y / 400;
    if a < 0 {
        a += 400;
        b -= 1;
    }
    let mut leap = 1 + a / 4 - a / 100;
    if month <= 2 && (a % 4) == 0 && ((a % 100) != 0 || a == 0) {
        leap -= 1;
    }
    146097 * b + 365 * a + MONTHDAY[(month - 1) as uint] + day - 1 + leap
}

/// Convert a chronological Julian day to an ISO 8601 date.
pub fn from_cjd(cjd: int) -> (int, int, int) {
    let mut t1 = cjd / EPOCH_LEN;
    let mut d = cjd % EPOCH_LEN;
    if d < 0 {
        t1 -= 1;
        d += EPOCH_LEN;
    }
    let y = t1 * 400 + 2000;

    let t2 = (d - 1) / 36524;
    let d = (d - 1) % 36524;
    let y = y + t2 * 100;

    let t3 = (d + 1) / 1461;
    let d = (d + 1) % 1461;
    let y = y + t3 * 4;

    let t4 = (d - 1) / 365;
    let d = (d - 1) % 365;
    let y = y + t4;

    let mut m = d / 29 + 1;
    if m > 12 || (m > 1 && d < MONTHDAY[(m - 1) as uint]) {
        m -= 1;
    }

    let mut d = d - MONTHDAY[(m - 1) as uint] + 1;
    if t4 == 0 && (t3 != 0 || t2 == 0) && m <= 2 {
        d += 1;
        if d == 32 {
            m = 2;
            d = 1;
        }
    }

    (y, m, d)
}

#[test]
fn cjd_point() {
    fn test(cjd: int, y: int, m: int, d: int) {
        let out_cjd = to_cjd(y, m, d);
        if out_cjd != cjd {
            fail!("{:04d}-{:02d}-{:02d}: expected {}, got {}",
                  y, m, d, cjd, out_cjd);
        }

        let (y2, m2, d2) = from_cjd(cjd);
        if y != y2 || m != m2 || d != d2 {
            fail!("{}: expected {:04d}-{:02d}-{:02d}, got {:04d}-{:02d}-{:02d}",
                  cjd, y, m, d, y2, m2, d2);
        }
    }

    test(0, 2000, 1, 1);
    test(1, 2000, 1, 2);
    test(-1, 1999, 12, 31);
    test(146097, 2400, 1, 1);
    test(-146097, 1600, 1, 1);
}

#[test]
fn cjd_range() {
    static MONTHS: [int, ..12] = [
        31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    ];

    fn test_range(start: int, end: int) {
        let mut y = start;
        let mut m = 1;
        let mut d = 1;
        let mut last_cjd = to_cjd(y, m, d) - 1;
        while y < end {
            let cjd = to_cjd(y, m, d);
            if cjd != last_cjd + 1 {
                fail!("Nonconsecutive date.");
            }
            last_cjd = cjd;
            let (y2, m2, d2) = from_cjd(cjd);
            if y != y2 || m != m2 || d != d2 {
                fail!("Bad conversion: {:04d}-{:02d}-{:02d} to {} to {:04d}-{:02d}-{:02d}",
                      y, m, d, cjd, y2, m2, d2);
            }
            d += 1;
            if d > MONTHS[(m - 1) as uint] {
                let is_leap = m == 2 && d == 29 && (y % 4) == 0 &&
                              ((y % 100) != 0 || (y % 400) == 0);
                if !is_leap {
                    m += 1;
                    d = 1;
                    if m >= 13 {
                        m = 1;
                        y += 1;
                    }
                }
            }
        }
    }

    test_range(1596, 2404);
}
<|endoftext|>


<commit_before>// Copyright 2015 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 prelude::*;
use fmt::{self, Write, FlagV1};

struct PadAdapter<'a, 'b: 'a> {
    fmt: &'a mut fmt::Formatter<'b>,
    on_newline: bool,
}

impl<'a, 'b: 'a> PadAdapter<'a, 'b> {
    fn new(fmt: &'a mut fmt::Formatter<'b>) -> PadAdapter<'a, 'b> {
        PadAdapter {
            fmt: fmt,
            on_newline: false,
        }
    }
}

impl<'a, 'b: 'a> fmt::Write for PadAdapter<'a, 'b> {
    fn write_str(&mut self, mut s: &str) -> fmt::Result {
        while !s.is_empty() {
            if self.on_newline {
                try!(self.fmt.write_str("    "));
            }

            let split = match s.find('\n') {
                Some(pos) => {
                    self.on_newline = true;
                    pos + 1
                }
                None => {
                    self.on_newline = false;
                    s.len()
                }
            };
            try!(self.fmt.write_str(&s[..split]));
            s = &s[split..];
        }

        Ok(())
    }
}

/// A struct to help with `fmt::Debug` implementations.
///
/// Constructed by the `Formatter::debug_struct` method.
#[must_use]
pub struct DebugStruct<'a, 'b: 'a> {
    fmt: &'a mut fmt::Formatter<'b>,
    result: fmt::Result,
    has_fields: bool,
}

pub fn debug_struct_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str)
                                -> DebugStruct<'a, 'b> {
    let result = fmt.write_str(name);
    DebugStruct {
        fmt: fmt,
        result: result,
        has_fields: false,
    }
}

impl<'a, 'b: 'a> DebugStruct<'a, 'b> {
    /// Adds a new field to the generated struct output.
    #[unstable(feature = "core", reason = "method was just created")]
    #[inline]
    pub fn field(mut self, name: &str, value: &fmt::Debug) -> DebugStruct<'a, 'b> {
        self.field_inner(name, value);
        self
    }

    #[inline(never)]
    fn field_inner(&mut self, name: &str, value: &fmt::Debug) {
        self.result = self.result.and_then(|_| {
            let prefix = if self.has_fields {
                ","
            } else {
                " {"
            };

            if self.is_pretty() {
                let mut writer = PadAdapter::new(self.fmt);
                fmt::write(&mut writer, format_args!("{}\n{}: {:#?}", prefix, name, value))
            } else {
                write!(self.fmt, "{} {}: {:?}", prefix, name, value)
            }
        });

        self.has_fields = true;
    }

    /// Consumes the `DebugStruct`, finishing output and returning any error
    /// encountered.
    #[unstable(feature = "core", reason = "method was just created")]
    #[inline]
    pub fn finish(mut self) -> fmt::Result {
        self.finish_inner();
        self.result
    }

    #[inline(never)]
    fn finish_inner(&mut self) {
        if self.has_fields {
            self.result = self.result.and_then(|_| {
                if self.is_pretty() {
                    self.fmt.write_str("\n}")
                } else {
                    self.fmt.write_str(" }")
                }
            });
        }
    }

    fn is_pretty(&self) -> bool {
        self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
    }
}

/// A struct to help with `fmt::Debug` implementations.
///
/// Constructed by the `Formatter::debug_tuple` method.
#[must_use]
pub struct DebugTuple<'a, 'b: 'a> {
    fmt: &'a mut fmt::Formatter<'b>,
    result: fmt::Result,
    has_fields: bool,
}

pub fn debug_tuple_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str) -> DebugTuple<'a, 'b> {
    let result = fmt.write_str(name);
    DebugTuple {
        fmt: fmt,
        result: result,
        has_fields: false,
    }
}

impl<'a, 'b: 'a> DebugTuple<'a, 'b> {
    /// Adds a new field to the generated tuple struct output.
    #[unstable(feature = "core", reason = "method was just created")]
    #[inline]
    pub fn field(mut self, value: &fmt::Debug) -> DebugTuple<'a, 'b> {
        self.field_inner(value);
        self
    }

    #[inline(never)]
    fn field_inner(&mut self, value: &fmt::Debug) {
        self.result = self.result.and_then(|_| {
            let (prefix, space) = if self.has_fields {
                (",", " ")
            } else {
                ("(", "")
            };

            if self.is_pretty() {
                let mut writer = PadAdapter::new(self.fmt);
                fmt::write(&mut writer, format_args!("{}\n{:#?}", prefix, value))
            } else {
                write!(self.fmt, "{}{}{:?}", prefix, space, value)
            }
        });

        self.has_fields = true;
    }

    /// Consumes the `DebugTuple`, finishing output and returning any error
    /// encountered.
    #[unstable(feature = "core", reason = "method was just created")]
    #[inline]
    pub fn finish(mut self) -> fmt::Result {
        self.finish_inner();
        self.result
    }

    #[inline(never)]
    fn finish_inner(&mut self) {
        if self.has_fields {
            self.result = self.result.and_then(|_| {
                if self.is_pretty() {
                    self.fmt.write_str("\n)")
                } else {
                    self.fmt.write_str(")")
                }
            });
        }
    }

    fn is_pretty(&self) -> bool {
        self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
    }
}

/// A struct to help with `fmt::Debug` implementations.
///
/// Constructed by the `Formatter::debug_set` method.
#[must_use]
pub struct DebugSet<'a, 'b: 'a> {
    fmt: &'a mut fmt::Formatter<'b>,
    result: fmt::Result,
    has_fields: bool,
}

pub fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str) -> DebugSet<'a, 'b> {
    let result = write!(fmt, "{} {{", name);
    DebugSet {
        fmt: fmt,
        result: result,
        has_fields: false,
    }
}

impl<'a, 'b: 'a> DebugSet<'a, 'b> {
    /// Adds a new entry to the set output.
    #[unstable(feature = "core", reason = "method was just created")]
    #[inline]
    pub fn entry(mut self, entry: &fmt::Debug) -> DebugSet<'a, 'b> {
        self.entry_inner(entry);
        self
    }

    #[inline(never)]
    fn entry_inner(&mut self, entry: &fmt::Debug) {
        self.result = self.result.and_then(|_| {
            let prefix = if self.has_fields {
                ","
            } else {
                ""
            };

            if self.is_pretty() {
                let mut writer = PadAdapter::new(self.fmt);
                fmt::write(&mut writer, format_args!("{}\n{:#?}", prefix, entry))
            } else {
                write!(self.fmt, "{} {:?}", prefix, entry)
            }
        });

        self.has_fields = true;
    }

    /// Consumes the `DebugSet`, finishing output and returning any error
    /// encountered.
    #[unstable(feature = "core", reason = "method was just created")]
    #[inline]
    pub fn finish(mut self) -> fmt::Result {
        self.finish_inner();
        self.result
    }

    #[inline(never)]
    fn finish_inner(&mut self) {
        self.result = self.result.and_then(|_| {
            let end = match (self.has_fields, self.is_pretty()) {
                (false, _) => "}",
                (true, false) => " }",
                (true, true) => "\n}",
            };
            self.fmt.write_str(end)
        });
    }

    fn is_pretty(&self) -> bool {
        self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
    }
}

/// A struct to help with `fmt::Debug` implementations.
///
/// Constructed by the `Formatter::debug_map` method.
#[must_use]
pub struct DebugMap<'a, 'b: 'a> {
    fmt: &'a mut fmt::Formatter<'b>,
    result: fmt::Result,
    has_fields: bool,
}

pub fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str) -> DebugMap<'a, 'b> {
    let result = write!(fmt, "{} {{", name);
    DebugMap {
        fmt: fmt,
        result: result,
        has_fields: false,
    }
}

impl<'a, 'b: 'a> DebugMap<'a, 'b> {
    /// Adds a new entry to the map output.
    #[unstable(feature = "core", reason = "method was just created")]
    #[inline]
    pub fn entry(mut self, key: &fmt::Debug, value: &fmt::Debug) -> DebugMap<'a, 'b> {
        self.entry_inner(key, value);
        self
    }

    #[inline(never)]
    fn entry_inner(&mut self, key: &fmt::Debug, value: &fmt::Debug) {
        self.result = self.result.and_then(|_| {
            let prefix = if self.has_fields {
                ","
            } else {
                ""
            };

            if self.is_pretty() {
                let mut writer = PadAdapter::new(self.fmt);
                fmt::write(&mut writer, format_args!("{}\n{:#?}: {:#?}", prefix, key, value))
            } else {
                write!(self.fmt, "{} {:?}: {:?}", prefix, key, value)
            }
        });

        self.has_fields = true;
    }

    /// Consumes the `DebugMap`, finishing output and returning any error
    /// encountered.
    #[unstable(feature = "core", reason = "method was just created")]
    #[inline]
    pub fn finish(mut self) -> fmt::Result {
        self.finish_inner();
        self.result
    }

    #[inline(never)]
    fn finish_inner(&mut self) {
        self.result = self.result.and_then(|_| {
            let end = match (self.has_fields, self.is_pretty()) {
                (false, _) => "}",
                (true, false) => " }",
                (true, true) => "\n}",
            };
            self.fmt.write_str(end)
        });
    }

    fn is_pretty(&self) -> bool {
        self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
    }
}
<commit_msg>Remove inline silliness from debug builders<commit_after>// Copyright 2015 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 prelude::*;
use fmt::{self, Write, FlagV1};

struct PadAdapter<'a, 'b: 'a> {
    fmt: &'a mut fmt::Formatter<'b>,
    on_newline: bool,
}

impl<'a, 'b: 'a> PadAdapter<'a, 'b> {
    fn new(fmt: &'a mut fmt::Formatter<'b>) -> PadAdapter<'a, 'b> {
        PadAdapter {
            fmt: fmt,
            on_newline: false,
        }
    }
}

impl<'a, 'b: 'a> fmt::Write for PadAdapter<'a, 'b> {
    fn write_str(&mut self, mut s: &str) -> fmt::Result {
        while !s.is_empty() {
            if self.on_newline {
                try!(self.fmt.write_str("    "));
            }

            let split = match s.find('\n') {
                Some(pos) => {
                    self.on_newline = true;
                    pos + 1
                }
                None => {
                    self.on_newline = false;
                    s.len()
                }
            };
            try!(self.fmt.write_str(&s[..split]));
            s = &s[split..];
        }

        Ok(())
    }
}

/// A struct to help with `fmt::Debug` implementations.
///
/// Constructed by the `Formatter::debug_struct` method.
#[must_use]
pub struct DebugStruct<'a, 'b: 'a> {
    fmt: &'a mut fmt::Formatter<'b>,
    result: fmt::Result,
    has_fields: bool,
}

pub fn debug_struct_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str)
                                -> DebugStruct<'a, 'b> {
    let result = fmt.write_str(name);
    DebugStruct {
        fmt: fmt,
        result: result,
        has_fields: false,
    }
}

impl<'a, 'b: 'a> DebugStruct<'a, 'b> {
    /// Adds a new field to the generated struct output.
    #[unstable(feature = "core", reason = "method was just created")]
    pub fn field(mut self, name: &str, value: &fmt::Debug) -> DebugStruct<'a, 'b> {
        self.result = self.result.and_then(|_| {
            let prefix = if self.has_fields {
                ","
            } else {
                " {"
            };

            if self.is_pretty() {
                let mut writer = PadAdapter::new(self.fmt);
                fmt::write(&mut writer, format_args!("{}\n{}: {:#?}", prefix, name, value))
            } else {
                write!(self.fmt, "{} {}: {:?}", prefix, name, value)
            }
        });

        self.has_fields = true;
        self
    }

    /// Consumes the `DebugStruct`, finishing output and returning any error
    /// encountered.
    #[unstable(feature = "core", reason = "method was just created")]
    pub fn finish(mut self) -> fmt::Result {
        if self.has_fields {
            self.result = self.result.and_then(|_| {
                if self.is_pretty() {
                    self.fmt.write_str("\n}")
                } else {
                    self.fmt.write_str(" }")
                }
            });
        }
        self.result
    }

    fn is_pretty(&self) -> bool {
        self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
    }
}

/// A struct to help with `fmt::Debug` implementations.
///
/// Constructed by the `Formatter::debug_tuple` method.
#[must_use]
pub struct DebugTuple<'a, 'b: 'a> {
    fmt: &'a mut fmt::Formatter<'b>,
    result: fmt::Result,
    has_fields: bool,
}

pub fn debug_tuple_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str) -> DebugTuple<'a, 'b> {
    let result = fmt.write_str(name);
    DebugTuple {
        fmt: fmt,
        result: result,
        has_fields: false,
    }
}

impl<'a, 'b: 'a> DebugTuple<'a, 'b> {
    /// Adds a new field to the generated tuple struct output.
    #[unstable(feature = "core", reason = "method was just created")]
    pub fn field(mut self, value: &fmt::Debug) -> DebugTuple<'a, 'b> {
        self.result = self.result.and_then(|_| {
            let (prefix, space) = if self.has_fields {
                (",", " ")
            } else {
                ("(", "")
            };

            if self.is_pretty() {
                let mut writer = PadAdapter::new(self.fmt);
                fmt::write(&mut writer, format_args!("{}\n{:#?}", prefix, value))
            } else {
                write!(self.fmt, "{}{}{:?}", prefix, space, value)
            }
        });

        self.has_fields = true;
        self
    }

    /// Consumes the `DebugTuple`, finishing output and returning any error
    /// encountered.
    #[unstable(feature = "core", reason = "method was just created")]
    pub fn finish(mut self) -> fmt::Result {
        if self.has_fields {
            self.result = self.result.and_then(|_| {
                if self.is_pretty() {
                    self.fmt.write_str("\n)")
                } else {
                    self.fmt.write_str(")")
                }
            });
        }
        self.result
    }

    fn is_pretty(&self) -> bool {
        self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
    }
}

/// A struct to help with `fmt::Debug` implementations.
///
/// Constructed by the `Formatter::debug_set` method.
#[must_use]
pub struct DebugSet<'a, 'b: 'a> {
    fmt: &'a mut fmt::Formatter<'b>,
    result: fmt::Result,
    has_fields: bool,
}

pub fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str) -> DebugSet<'a, 'b> {
    let result = write!(fmt, "{} {{", name);
    DebugSet {
        fmt: fmt,
        result: result,
        has_fields: false,
    }
}

impl<'a, 'b: 'a> DebugSet<'a, 'b> {
    /// Adds a new entry to the set output.
    #[unstable(feature = "core", reason = "method was just created")]
    pub fn entry(mut self, entry: &fmt::Debug) -> DebugSet<'a, 'b> {
        self.result = self.result.and_then(|_| {
            let prefix = if self.has_fields {
                ","
            } else {
                ""
            };

            if self.is_pretty() {
                let mut writer = PadAdapter::new(self.fmt);
                fmt::write(&mut writer, format_args!("{}\n{:#?}", prefix, entry))
            } else {
                write!(self.fmt, "{} {:?}", prefix, entry)
            }
        });

        self.has_fields = true;
        self
    }

    /// Consumes the `DebugSet`, finishing output and returning any error
    /// encountered.
    #[unstable(feature = "core", reason = "method was just created")]
    pub fn finish(mut self) -> fmt::Result {
        self.result.and_then(|_| {
            let end = match (self.has_fields, self.is_pretty()) {
                (false, _) => "}",
                (true, false) => " }",
                (true, true) => "\n}",
            };
            self.fmt.write_str(end)
        })
    }

    fn is_pretty(&self) -> bool {
        self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
    }
}

/// A struct to help with `fmt::Debug` implementations.
///
/// Constructed by the `Formatter::debug_map` method.
#[must_use]
pub struct DebugMap<'a, 'b: 'a> {
    fmt: &'a mut fmt::Formatter<'b>,
    result: fmt::Result,
    has_fields: bool,
}

pub fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str) -> DebugMap<'a, 'b> {
    let result = write!(fmt, "{} {{", name);
    DebugMap {
        fmt: fmt,
        result: result,
        has_fields: false,
    }
}

impl<'a, 'b: 'a> DebugMap<'a, 'b> {
    /// Adds a new entry to the map output.
    #[unstable(feature = "core", reason = "method was just created")]
    pub fn entry(mut self, key: &fmt::Debug, value: &fmt::Debug) -> DebugMap<'a, 'b> {
        self.result = self.result.and_then(|_| {
            let prefix = if self.has_fields {
                ","
            } else {
                ""
            };

            if self.is_pretty() {
                let mut writer = PadAdapter::new(self.fmt);
                fmt::write(&mut writer, format_args!("{}\n{:#?}: {:#?}", prefix, key, value))
            } else {
                write!(self.fmt, "{} {:?}: {:?}", prefix, key, value)
            }
        });

        self.has_fields = true;

        self
    }

    /// Consumes the `DebugMap`, finishing output and returning any error
    /// encountered.
    #[unstable(feature = "core", reason = "method was just created")]
    pub fn finish(mut self) -> fmt::Result {
        self.result.and_then(|_| {
            let end = match (self.has_fields, self.is_pretty()) {
                (false, _) => "}",
                (true, false) => " }",
                (true, true) => "\n}",
            };
            self.fmt.write_str(end)
        })
    }

    fn is_pretty(&self) -> bool {
        self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
    }
}
<|endoftext|>