<commit_before>use libc::c_int;
use std::num::from_i32;
use std::ptr;
use std::c_str;

use super::{SQLITE_OK, SqliteError, SqliteStep, SqliteResult};
use super::{SQLITE_DONE, SQLITE_ROW};

use ffi;

/// A connection to a sqlite3 database.
pub struct SqliteConnection {
    // not pub so that nothing outside this module
    // interferes with the lifetime
    db: *mut ffi::sqlite3
}

impl Drop for SqliteConnection {
    /// Release resources associated with connection.
    ///
    /// # Failure
    ///
    /// Fails if "the database connection is associated with
    /// unfinalized prepared statements or unfinished sqlite3_backup
    /// objects"[1] which the Rust memory model ensures is impossible
    /// (barring bugs in the use of unsafe blocks in the implementation
    /// of this library).
    ///
    /// [1]: http://www.sqlite.org/c3ref/close.html
    fn drop(&mut self) {
        // sqlite3_close_v2 was not introduced until 2012-09-03 (3.7.14)
        // but we want to build on, e.g. travis, i.e. Ubuntu 12.04.
        // let ok = unsafe { ffi::sqlite3_close_v2(self.db) };
        let ok = unsafe { ffi::sqlite3_close(self.db) };
        assert_eq!(ok, SQLITE_OK as c_int);
    }
}

impl SqliteConnection {
    // Create a new connection to an in-memory database.
    // TODO: explicit access to files
    // TODO: use support _v2 interface with flags
    // TODO: integrate sqlite3_errmsg()
    pub fn new() -> Result<SqliteConnection, SqliteError> {
        let mut db = ptr::mut_null();
        let result = ":memory:".with_c_str({
            |memory|
            unsafe { ffi::sqlite3_open(memory, &mut db) }
        });
        match decode_result(result, "sqlite3_open") {
            Ok(()) => Ok(SqliteConnection { db: db }),
            Err(err) => {
                // "Whether or not an error occurs when it is opened,
                // resources associated with the database connection
                // handle should be released by passing it to
                // sqlite3_close() when it is no longer required."
                unsafe { ffi::sqlite3_close(db) };
                Err(err)
            }
        }
    }

    /// Prepare/compile an SQL statement.
    /// See http://www.sqlite.org/c3ref/prepare.html
    pub fn prepare<'db>(&'db mut self, sql: &str) -> SqliteResult<SqliteStatement<'db>> {
        match self.prepare_with_offset(sql) {
            Ok((cur, _)) => Ok(cur),
            Err(e) => Err(e)
        }
    }

    pub fn prepare_with_offset<'db>(&'db mut self, sql: &str) -> SqliteResult<(SqliteStatement<'db>, uint)> {
        let mut stmt = ptr::mut_null();
        let mut tail = ptr::null();
        let z_sql = sql.as_ptr() as *const ::libc::c_char;
        let n_byte = sql.len() as c_int;
        let r = unsafe { ffi::sqlite3_prepare_v2(self.db, z_sql, n_byte, &mut stmt, &mut tail) };
        match decode_result(r, "sqlite3_prepare_v2") {
            Ok(()) => {
                let offset = tail as uint - z_sql as uint;
                Ok((SqliteStatement { stmt: stmt }, offset))
            },
            Err(code) => Err(code)
        }
    }

}

/// A prepared statement.
pub struct SqliteStatement<'db> {
    stmt: *mut ffi::sqlite3_stmt
}

#[unsafe_destructor]
impl<'db> Drop for SqliteStatement<'db> {
    fn drop(&mut self) {
        unsafe {

            // We ignore the return code from finalize because:

            // "If If the most recent evaluation of statement S
            // failed, then sqlite3_finalize(S) returns the
            // appropriate error codethe most recent evaluation of
            // statement S failed, then sqlite3_finalize(S) returns
            // the appropriate error code"

            // "The sqlite3_finalize(S) routine can be called at any
            // point during the life cycle of prepared statement S"

            ffi::sqlite3_finalize(self.stmt);
        }
    }
}

impl<'db> SqliteStatement<'db> {
    pub fn query(&mut self) -> SqliteResult<SqliteRows> {
        {
            let r = unsafe { ffi::sqlite3_reset(self.stmt) };
            try!(decode_result(r, "sqlite3_reset"))
        }
        Ok(SqliteRows::new(self))
    }
}

/// Results of executing a `prepare()`d statement.
pub struct SqliteRows<'s> {
    statement: &'s mut SqliteStatement<'s>,
}

impl<'s> SqliteRows<'s> {
    pub fn new(statement: &'s mut SqliteStatement) -> SqliteRows<'s> {
        SqliteRows { statement: statement }
    }
}

impl<'s> SqliteRows<'s> {
    /// Iterate over rows resulting from execution of a prepared statement.
    ///
    /// An sqlite "row" only lasts until the next call to `ffi::sqlite3_step()`,
    /// so we need a lifetime constraint. The unfortunate result is that
    ///  `SqliteRows` cannot implement the `Iterator` trait.
    pub fn next<'r>(&'r mut self) -> Option<SqliteResult<SqliteRow<'s, 'r>>> {
        let result = unsafe { ffi::sqlite3_step(self.statement.stmt) };
        match from_i32::<SqliteStep>(result) {
            Some(SQLITE_ROW) => {
                Some(Ok(SqliteRow{ rows: self }))
            },
            Some(SQLITE_DONE) => None,
            None => {
                let err = from_i32::<SqliteError>(result);
                Some(Err(err.unwrap()))
            }
        }
    }
}

/// Access to columns of a row.
pub struct SqliteRow<'s, 'r> {
    rows: &'r mut SqliteRows<'s>
}

impl<'s, 'r> SqliteRow<'s, 'r> {

    // TODO: consider returning Option<uint>
    // "This routine returns 0 if pStmt is an SQL statement that does
    // not return data (for example an UPDATE)."
    pub fn column_count(&self) -> uint {
        let stmt = self.rows.statement.stmt;
        let result = unsafe { ffi::sqlite3_column_count(stmt) };
        result as uint
    }

    // See http://www.sqlite.org/c3ref/column_name.html
    pub fn with_column_name<T>(&mut self, i: uint, default: T, f: |&str| -> T) -> T {
        let stmt = self.rows.statement.stmt;
        let n = i as c_int;
        let result = unsafe { ffi::sqlite3_column_name(stmt, n) };
        if result == ptr::null() { default }
        else {
            let name = unsafe { c_str::CString::new(result, false) };
            match name.as_str() {
                Some(name) => f(name),
                None => default
            }
        }
    }

    pub fn column_int(&self, col: uint) -> i32 {
        let stmt = self.rows.statement.stmt;
        let i_col = col as c_int;
        unsafe { ffi::sqlite3_column_int(stmt, i_col) }
    }
}

#[inline]
pub fn decode_result(result: c_int, context: &str) -> SqliteResult<()> {
    if result == SQLITE_OK as c_int {
        Ok(())
    } else {
        match from_i32::<SqliteError>(result) {
            Some(code) => Err(code),
            None => fail!("{} returned unexpected {:d}", context, result)
        }
    }
}

<commit_msg>tell emacs flycheck where to find the crate root<commit_after>use libc::c_int;
use std::num::from_i32;
use std::ptr;
use std::c_str;

use super::{SQLITE_OK, SqliteError, SqliteStep, SqliteResult};
use super::{SQLITE_DONE, SQLITE_ROW};

use ffi;

/// A connection to a sqlite3 database.
pub struct SqliteConnection {
    // not pub so that nothing outside this module
    // interferes with the lifetime
    db: *mut ffi::sqlite3
}

impl Drop for SqliteConnection {
    /// Release resources associated with connection.
    ///
    /// # Failure
    ///
    /// Fails if "the database connection is associated with
    /// unfinalized prepared statements or unfinished sqlite3_backup
    /// objects"[1] which the Rust memory model ensures is impossible
    /// (barring bugs in the use of unsafe blocks in the implementation
    /// of this library).
    ///
    /// [1]: http://www.sqlite.org/c3ref/close.html
    fn drop(&mut self) {
        // sqlite3_close_v2 was not introduced until 2012-09-03 (3.7.14)
        // but we want to build on, e.g. travis, i.e. Ubuntu 12.04.
        // let ok = unsafe { ffi::sqlite3_close_v2(self.db) };
        let ok = unsafe { ffi::sqlite3_close(self.db) };
        assert_eq!(ok, SQLITE_OK as c_int);
    }
}

impl SqliteConnection {
    // Create a new connection to an in-memory database.
    // TODO: explicit access to files
    // TODO: use support _v2 interface with flags
    // TODO: integrate sqlite3_errmsg()
    pub fn new() -> Result<SqliteConnection, SqliteError> {
        let mut db = ptr::mut_null();
        let result = ":memory:".with_c_str({
            |memory|
            unsafe { ffi::sqlite3_open(memory, &mut db) }
        });
        match decode_result(result, "sqlite3_open") {
            Ok(()) => Ok(SqliteConnection { db: db }),
            Err(err) => {
                // "Whether or not an error occurs when it is opened,
                // resources associated with the database connection
                // handle should be released by passing it to
                // sqlite3_close() when it is no longer required."
                unsafe { ffi::sqlite3_close(db) };
                Err(err)
            }
        }
    }

    /// Prepare/compile an SQL statement.
    /// See http://www.sqlite.org/c3ref/prepare.html
    pub fn prepare<'db>(&'db mut self, sql: &str) -> SqliteResult<SqliteStatement<'db>> {
        match self.prepare_with_offset(sql) {
            Ok((cur, _)) => Ok(cur),
            Err(e) => Err(e)
        }
    }

    pub fn prepare_with_offset<'db>(&'db mut self, sql: &str) -> SqliteResult<(SqliteStatement<'db>, uint)> {
        let mut stmt = ptr::mut_null();
        let mut tail = ptr::null();
        let z_sql = sql.as_ptr() as *const ::libc::c_char;
        let n_byte = sql.len() as c_int;
        let r = unsafe { ffi::sqlite3_prepare_v2(self.db, z_sql, n_byte, &mut stmt, &mut tail) };
        match decode_result(r, "sqlite3_prepare_v2") {
            Ok(()) => {
                let offset = tail as uint - z_sql as uint;
                Ok((SqliteStatement { stmt: stmt }, offset))
            },
            Err(code) => Err(code)
        }
    }

}

/// A prepared statement.
pub struct SqliteStatement<'db> {
    stmt: *mut ffi::sqlite3_stmt
}

#[unsafe_destructor]
impl<'db> Drop for SqliteStatement<'db> {
    fn drop(&mut self) {
        unsafe {

            // We ignore the return code from finalize because:

            // "If If the most recent evaluation of statement S
            // failed, then sqlite3_finalize(S) returns the
            // appropriate error codethe most recent evaluation of
            // statement S failed, then sqlite3_finalize(S) returns
            // the appropriate error code"

            // "The sqlite3_finalize(S) routine can be called at any
            // point during the life cycle of prepared statement S"

            ffi::sqlite3_finalize(self.stmt);
        }
    }
}

impl<'db> SqliteStatement<'db> {
    pub fn query(&mut self) -> SqliteResult<SqliteRows> {
        {
            let r = unsafe { ffi::sqlite3_reset(self.stmt) };
            try!(decode_result(r, "sqlite3_reset"))
        }
        Ok(SqliteRows::new(self))
    }
}

/// Results of executing a `prepare()`d statement.
pub struct SqliteRows<'s> {
    statement: &'s mut SqliteStatement<'s>,
}

impl<'s> SqliteRows<'s> {
    pub fn new(statement: &'s mut SqliteStatement) -> SqliteRows<'s> {
        SqliteRows { statement: statement }
    }
}

impl<'s> SqliteRows<'s> {
    /// Iterate over rows resulting from execution of a prepared statement.
    ///
    /// An sqlite "row" only lasts until the next call to `ffi::sqlite3_step()`,
    /// so we need a lifetime constraint. The unfortunate result is that
    ///  `SqliteRows` cannot implement the `Iterator` trait.
    pub fn next<'r>(&'r mut self) -> Option<SqliteResult<SqliteRow<'s, 'r>>> {
        let result = unsafe { ffi::sqlite3_step(self.statement.stmt) };
        match from_i32::<SqliteStep>(result) {
            Some(SQLITE_ROW) => {
                Some(Ok(SqliteRow{ rows: self }))
            },
            Some(SQLITE_DONE) => None,
            None => {
                let err = from_i32::<SqliteError>(result);
                Some(Err(err.unwrap()))
            }
        }
    }
}

/// Access to columns of a row.
pub struct SqliteRow<'s, 'r> {
    rows: &'r mut SqliteRows<'s>
}

impl<'s, 'r> SqliteRow<'s, 'r> {

    // TODO: consider returning Option<uint>
    // "This routine returns 0 if pStmt is an SQL statement that does
    // not return data (for example an UPDATE)."
    pub fn column_count(&self) -> uint {
        let stmt = self.rows.statement.stmt;
        let result = unsafe { ffi::sqlite3_column_count(stmt) };
        result as uint
    }

    // See http://www.sqlite.org/c3ref/column_name.html
    pub fn with_column_name<T>(&mut self, i: uint, default: T, f: |&str| -> T) -> T {
        let stmt = self.rows.statement.stmt;
        let n = i as c_int;
        let result = unsafe { ffi::sqlite3_column_name(stmt, n) };
        if result == ptr::null() { default }
        else {
            let name = unsafe { c_str::CString::new(result, false) };
            match name.as_str() {
                Some(name) => f(name),
                None => default
            }
        }
    }

    pub fn column_int(&self, col: uint) -> i32 {
        let stmt = self.rows.statement.stmt;
        let i_col = col as c_int;
        unsafe { ffi::sqlite3_column_int(stmt, i_col) }
    }
}

#[inline]
pub fn decode_result(result: c_int, context: &str) -> SqliteResult<()> {
    if result == SQLITE_OK as c_int {
        Ok(())
    } else {
        match from_i32::<SqliteError>(result) {
            Some(code) => Err(code),
            None => fail!("{} returned unexpected {:d}", context, result)
        }
    }
}

// Local Variables:
// flycheck-rust-crate-root: "lib.rs"
// End:
<|endoftext|>


<commit_before><commit_msg>Added a float equality function to allow for a margin of error<commit_after><|endoftext|>


<commit_before><commit_msg>Exit nicely<commit_after><|endoftext|>


<commit_before>use std::env;

fn newmat(x: usize, y: usize) -> Vec<Vec<f64>> {
  let mut r = Vec::new();
  for _ in 0..x {
    let mut c = Vec::new();
    for _ in 0..y { c.push(0_f64); }
    r.push(c);
  }
  r
}

fn matgen(n: usize) -> Vec<Vec<f64>> {
  let mut a = newmat(n, n);
  let tmp = 1_f64 / (n as f64) / (n as f64);
  for i in 0..n {
    for j in 0..n {
      let val = tmp * (i as f64 - j as f64) * (i as f64 + j as f64);
      a[i][j] = val;
    }
  }
  a
}

fn matmul(a: Vec<Vec<f64>>, b: Vec<Vec<f64>>) -> Vec<Vec<f64>> {
  let m = a.len();
  let n = a[0].len();
  let p = b[0].len();

  let mut b2 = newmat(n, p);
  for i in 0..n {
    for j in 0..p {
      b2[j][i] = b[i][j];
    }
  }

  let mut c = newmat(m, p);
  for i in 0..m {
    for j in 0..p {
      let mut s = 0_f64;
      let ref ai = a[i];
      let ref b2j = b2[j];
      for k in 0..n {
        s += ai[k] * b2j[k];
      }
      c[i][j] = s;
    }
  }

  c
}

fn main() {
  let mut n = 100;
  if env::args().len() > 1 {
    let arg1 = env::args().nth(1).unwrap();
    n = ::std::str::FromStr::from_str(&arg1).unwrap();
  }
  n = n / 2 * 2;

  let a = matgen(n);
  let b = matgen(n);
  let c = matmul(a, b);
  print!("{}\n", c[n / 2][n / 2]);
}
<commit_msg>Improve Rust matmul benchmark<commit_after>use std::env;

fn newmat(x: usize, y: usize) -> Vec<Vec<f64>> {
  let mut r = Vec::with_capacity(x);
  for _ in 0..x {
    let mut c = Vec::with_capacity(y);
    for _ in 0..y { c.push(0_f64); }
    r.push(c);
  }
  r
}

fn matgen(n: usize) -> Vec<Vec<f64>> {
  let mut a = newmat(n, n);
  let tmp = 1_f64 / (n as f64) / (n as f64);
  for i in 0..n {
    for j in 0..n {
      let val = tmp * (i as f64 - j as f64) * (i as f64 + j as f64);
      a[i][j] = val;
    }
  }
  a
}

fn matmul(a: Vec<Vec<f64>>, b: Vec<Vec<f64>>) -> Vec<Vec<f64>> {
  let m = a.len();
  let n = a[0].len();
  let p = b[0].len();

  let mut b2 = newmat(n, p);
  for i in 0..n {
    for j in 0..p {
      b2[j][i] = b[i][j];
    }
  }

  let mut c = newmat(m, p);
  for i in 0..m {
    for j in 0..p {
      let mut s = 0_f64;
      let ref ai = a[i];
      let ref b2j = b2[j];
      for k in 0..n {
        s += ai[k] * b2j[k];
      }
      c[i][j] = s;
    }
  }

  c
}

fn main() {
  let mut n = 100;
  if env::args().len() > 1 {
    let arg1 = env::args().nth(1).unwrap();
    n = ::std::str::FromStr::from_str(&arg1).unwrap();
  }
  n = n / 2 * 2;

  let a = matgen(n);
  let b = matgen(n);
  let c = matmul(a, b);
  print!("{}\n", c[n / 2][n / 2]);
}
<|endoftext|>


<commit_before><commit_msg>exit status in prompt now changes depending on exit status of command<commit_after><|endoftext|>


<commit_before><commit_msg>adding site_config method<commit_after><|endoftext|>


<commit_before><commit_msg>Add is_odd function and test for it; ran 'cargo fmt'<commit_after><|endoftext|>


<commit_before>#[macro_use] extern crate clap;
#[macro_use] extern crate log;
#[macro_use] extern crate serde;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate glob;
#[macro_use] extern crate uuid;
#[macro_use] extern crate regex;
#[macro_use] extern crate prettytable;
extern crate url;
extern crate config;

use std::process::exit;

use cli::CliConfig;
use configuration::Configuration;
use runtime::{ImagLogger, Runtime};
use clap::App;
use module::Module;

mod cli;
mod configuration;
mod runtime;
mod module;
mod storage;
mod ui;

use module::bm::BM;

fn main() {
    let yaml = load_yaml!("../etc/cli.yml");
    let app = App::from_yaml(yaml);
    let config = CliConfig::new(app);
    let configuration = Configuration::new(&config);

    let logger = ImagLogger::init(&configuration, &config);
    debug!("Logger created!");

    debug!("CliConfig    : {:?}", &config);
    debug!("Configuration: {:?}", &configuration);

    let rt = Runtime::new(configuration, config);

    debug!("Runtime      : {:?}", &rt);

    if let Some(matches) = rt.config.cli_matches.subcommand_matches("bm") {
        let res = BM::new(&rt).exec(matches.subcommand_matches("bm").unwrap());
        info!("BM exited with {}", res);
    } else {
        info!("No commandline call...")
    }

    info!("Hello, world!");
}
<commit_msg>Fix: Argument for BM::exec()<commit_after>#[macro_use] extern crate clap;
#[macro_use] extern crate log;
#[macro_use] extern crate serde;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate glob;
#[macro_use] extern crate uuid;
#[macro_use] extern crate regex;
#[macro_use] extern crate prettytable;
extern crate url;
extern crate config;

use std::process::exit;

use cli::CliConfig;
use configuration::Configuration;
use runtime::{ImagLogger, Runtime};
use clap::App;
use module::Module;

mod cli;
mod configuration;
mod runtime;
mod module;
mod storage;
mod ui;

use module::bm::BM;

fn main() {
    let yaml = load_yaml!("../etc/cli.yml");
    let app = App::from_yaml(yaml);
    let config = CliConfig::new(app);
    let configuration = Configuration::new(&config);

    let logger = ImagLogger::init(&configuration, &config);
    debug!("Logger created!");

    debug!("CliConfig    : {:?}", &config);
    debug!("Configuration: {:?}", &configuration);

    let rt = Runtime::new(configuration, config);

    debug!("Runtime      : {:?}", &rt);

    if let Some(matches) = rt.config.cli_matches.subcommand_matches("bm") {
        let res = BM::new(&rt).exec(matches);
        info!("BM exited with {}", res);
    } else {
        info!("No commandline call...")
    }

    info!("Hello, world!");
}
<|endoftext|>


<commit_before><commit_msg>every 60s not 10<commit_after><|endoftext|>


<commit_before><commit_msg>testsuite: add tests for derived Eq, TotalEq, Ord, TotalOrd.<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.

#[deriving(Eq, TotalEq, Ord, TotalOrd)]
struct S<T> {
    x: T,
    y: T
}

#[deriving(Eq, TotalEq, Ord, TotalOrd)]
struct TS<T>(T,T);

#[deriving(Eq, TotalEq, Ord, TotalOrd)]
enum E<T> {
    E0,
    E1(T),
    E2(T,T)
}

#[deriving(Eq, TotalEq, Ord, TotalOrd)]
enum ES<T> {
    ES1 { x: T },
    ES2 { x: T, y: T }
}

pub fn main() {
    let s1 = S {x: 1, y: 1}, s2 = S {x: 1, y: 2};
    let ts1 = TS(1, 1), ts2 = TS(1,2);
    let e0 = E0, e11 = E1(1), e12 = E1(2), e21 = E2(1,1), e22 = E2(1, 2);
    let es11 = ES1 {x: 1}, es12 = ES1 {x: 2}, es21 = ES2 {x: 1, y: 1}, es22 = ES2 {x: 1, y: 2};

    test([s1, s2]);
    test([ts1, ts2]);
    test([e0, e11, e12, e21, e22]);
    test([es11, es12, es21, es22]);
}

fn test<T: Eq+TotalEq+Ord+TotalOrd>(ts: &[T]) {
    // compare each element against all other elements. The list
    // should be in sorted order, so that if i < j, then ts[i] <
    // ts[j], etc.
    for ts.eachi |i, t1| {
        for ts.eachi |j, t2| {
            let ord = i.cmp(&j);

            let eq = i == j;
            let lt = i < j, le = i <= j;
            let gt = i > j, ge = i >= j;

            // Eq
            assert_eq!(*t1 == *t2, eq);

            // TotalEq
            assert_eq!(t1.equals(t2), eq);

            // Ord
            assert_eq!(*t1 < *t2, lt);
            assert_eq!(*t1 > *t2, gt);

            assert_eq!(*t1 <= *t2, le);
            assert_eq!(*t1 >= *t2, ge);

            // TotalOrd
            assert_eq!(t1.cmp(t2), ord);
        }
    }
}<|endoftext|>


<commit_before><commit_msg>Update about-text in imag-wiki<commit_after><|endoftext|>


<commit_before><commit_msg>Add whitespace<commit_after><|endoftext|>


<commit_before><commit_msg>short!<commit_after><|endoftext|>


<commit_before><commit_msg>languages/rust/learn-rust/3-chapter/6-code.rs<commit_after><|endoftext|>


<commit_before><commit_msg>JavaっぽくDIする<commit_after>fn main() {
    let foo = FooImpl;
    let bar = Bar::new(&foo);
    let s = bar.get();
    println!("{}", s);
}

trait Foo {
    fn get(&self) -> String;
}

struct Bar<'a> {
    foo: &'a dyn Foo,
}

impl<'a> Bar<'a> {
    fn new(foo: &'a dyn Foo) -> Bar<'a> {
        Bar {
            foo
        }
    }
    fn get(&self) -> String {
        format!("{}bar", self.foo.get())
    }
}

struct FooImpl;

impl Foo for FooImpl {
    fn get(&self) -> String {
        "foo".to_string()
    }
}

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

    struct MockFoo;

    impl Foo for MockFoo {
        fn get(&self) -> String {
            "mock".to_string()
        }
    }

    #[test]
    fn test() {
        let foo = MockFoo;
        let bar = Bar::new(&foo);
        assert_eq!(bar.get(), "mockbar");
    }
}
<|endoftext|>


<commit_before><commit_msg>test: Implement a test for the Drop trait on a generic struct. a=test-only<commit_after>struct S<T> {
    x: T
}

impl<T> S<T> : core::ops::Drop {
    fn finalize() {
        io::println("bye");
    }
}

fn main() {
    let x = S { x: 1 };
}

<|endoftext|>


<commit_before><commit_msg>Rollup merge of #43125 - aochagavia:stable_drop, r=arielb1<commit_after>// Copyright 2017 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.

#![allow(dead_code, unreachable_code)]

use std::cell::RefCell;
use std::rc::Rc;
use std::panic::{self, AssertUnwindSafe, UnwindSafe};

// This struct is used to record the order in which elements are dropped
struct PushOnDrop {
    vec: Rc<RefCell<Vec<u32>>>,
    val: u32
}

impl PushOnDrop {
    fn new(val: u32, vec: Rc<RefCell<Vec<u32>>>) -> PushOnDrop {
        PushOnDrop { vec, val }
    }
}

impl Drop for PushOnDrop {
    fn drop(&mut self) {
        self.vec.borrow_mut().push(self.val)
    }
}

impl UnwindSafe for PushOnDrop { }

// Structs
struct TestStruct {
    x: PushOnDrop,
    y: PushOnDrop,
    z: PushOnDrop
}

// Tuple structs
struct TestTupleStruct(PushOnDrop, PushOnDrop, PushOnDrop);

// Enum variants
enum TestEnum {
    Tuple(PushOnDrop, PushOnDrop, PushOnDrop),
    Struct { x: PushOnDrop, y: PushOnDrop, z: PushOnDrop }
}

fn test_drop_tuple() {
    // Tuple fields are dropped in the same order they are declared
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let test_tuple = (PushOnDrop::new(1, dropped_fields.clone()),
                      PushOnDrop::new(2, dropped_fields.clone()));
    drop(test_tuple);
    assert_eq!(*dropped_fields.borrow(), &[1, 2]);

    // Panic during construction means that fields are treated as local variables
    // Therefore they are dropped in reverse order of initialization
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let cloned = AssertUnwindSafe(dropped_fields.clone());
    panic::catch_unwind(|| {
        (PushOnDrop::new(2, cloned.clone()),
         PushOnDrop::new(1, cloned.clone()),
         panic!("this panic is catched :D"));
    }).err().unwrap();
    assert_eq!(*dropped_fields.borrow(), &[1, 2]);
}

fn test_drop_struct() {
    // Struct fields are dropped in the same order they are declared
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let test_struct = TestStruct {
        x: PushOnDrop::new(1, dropped_fields.clone()),
        y: PushOnDrop::new(2, dropped_fields.clone()),
        z: PushOnDrop::new(3, dropped_fields.clone()),
    };
    drop(test_struct);
    assert_eq!(*dropped_fields.borrow(), &[1, 2, 3]);

    // The same holds for tuple structs
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let test_tuple_struct = TestTupleStruct(PushOnDrop::new(1, dropped_fields.clone()),
                                            PushOnDrop::new(2, dropped_fields.clone()),
                                            PushOnDrop::new(3, dropped_fields.clone()));
    drop(test_tuple_struct);
    assert_eq!(*dropped_fields.borrow(), &[1, 2, 3]);

    // Panic during struct construction means that fields are treated as local variables
    // Therefore they are dropped in reverse order of initialization
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let cloned = AssertUnwindSafe(dropped_fields.clone());
    panic::catch_unwind(|| {
        TestStruct {
            x: PushOnDrop::new(2, cloned.clone()),
            y: PushOnDrop::new(1, cloned.clone()),
            z: panic!("this panic is catched :D")
        };
    }).err().unwrap();
    assert_eq!(*dropped_fields.borrow(), &[1, 2]);

    // Test with different initialization order
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let cloned = AssertUnwindSafe(dropped_fields.clone());
    panic::catch_unwind(|| {
        TestStruct {
            y: PushOnDrop::new(2, cloned.clone()),
            x: PushOnDrop::new(1, cloned.clone()),
            z: panic!("this panic is catched :D")
        };
    }).err().unwrap();
    assert_eq!(*dropped_fields.borrow(), &[1, 2]);

    // The same holds for tuple structs
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let cloned = AssertUnwindSafe(dropped_fields.clone());
    panic::catch_unwind(|| {
        TestTupleStruct(PushOnDrop::new(2, cloned.clone()),
                        PushOnDrop::new(1, cloned.clone()),
                        panic!("this panic is catched :D"));
    }).err().unwrap();
    assert_eq!(*dropped_fields.borrow(), &[1, 2]);
}

fn test_drop_enum() {
    // Enum variants are dropped in the same order they are declared
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let test_struct_enum = TestEnum::Struct {
        x: PushOnDrop::new(1, dropped_fields.clone()),
        y: PushOnDrop::new(2, dropped_fields.clone()),
        z: PushOnDrop::new(3, dropped_fields.clone())
    };
    drop(test_struct_enum);
    assert_eq!(*dropped_fields.borrow(), &[1, 2, 3]);

    // The same holds for tuple enum variants
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let test_tuple_enum = TestEnum::Tuple(PushOnDrop::new(1, dropped_fields.clone()),
                                          PushOnDrop::new(2, dropped_fields.clone()),
                                          PushOnDrop::new(3, dropped_fields.clone()));
    drop(test_tuple_enum);
    assert_eq!(*dropped_fields.borrow(), &[1, 2, 3]);

    // Panic during enum construction means that fields are treated as local variables
    // Therefore they are dropped in reverse order of initialization
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let cloned = AssertUnwindSafe(dropped_fields.clone());
    panic::catch_unwind(|| {
        TestEnum::Struct {
            x: PushOnDrop::new(2, cloned.clone()),
            y: PushOnDrop::new(1, cloned.clone()),
            z: panic!("this panic is catched :D")
        };
    }).err().unwrap();
    assert_eq!(*dropped_fields.borrow(), &[1, 2]);

    // Test with different initialization order
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let cloned = AssertUnwindSafe(dropped_fields.clone());
    panic::catch_unwind(|| {
        TestEnum::Struct {
            y: PushOnDrop::new(2, cloned.clone()),
            x: PushOnDrop::new(1, cloned.clone()),
            z: panic!("this panic is catched :D")
        };
    }).err().unwrap();
    assert_eq!(*dropped_fields.borrow(), &[1, 2]);

    // The same holds for tuple enum variants
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let cloned = AssertUnwindSafe(dropped_fields.clone());
    panic::catch_unwind(|| {
        TestEnum::Tuple(PushOnDrop::new(2, cloned.clone()),
                        PushOnDrop::new(1, cloned.clone()),
                        panic!("this panic is catched :D"));
    }).err().unwrap();
    assert_eq!(*dropped_fields.borrow(), &[1, 2]);
}

fn test_drop_list() {
    // Elements in a Vec are dropped in the same order they are pushed
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let xs = vec![PushOnDrop::new(1, dropped_fields.clone()),
                  PushOnDrop::new(2, dropped_fields.clone()),
                  PushOnDrop::new(3, dropped_fields.clone())];
    drop(xs);
    assert_eq!(*dropped_fields.borrow(), &[1, 2, 3]);

    // The same holds for arrays
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let xs = [PushOnDrop::new(1, dropped_fields.clone()),
              PushOnDrop::new(2, dropped_fields.clone()),
              PushOnDrop::new(3, dropped_fields.clone())];
    drop(xs);
    assert_eq!(*dropped_fields.borrow(), &[1, 2, 3]);

    // Panic during vec construction means that fields are treated as local variables
    // Therefore they are dropped in reverse order of initialization
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let cloned = AssertUnwindSafe(dropped_fields.clone());
    panic::catch_unwind(|| {
        vec![
            PushOnDrop::new(2, cloned.clone()),
            PushOnDrop::new(1, cloned.clone()),
            panic!("this panic is catched :D")
        ];
    }).err().unwrap();
    assert_eq!(*dropped_fields.borrow(), &[1, 2]);

    // The same holds for arrays
    let dropped_fields = Rc::new(RefCell::new(Vec::new()));
    let cloned = AssertUnwindSafe(dropped_fields.clone());
    panic::catch_unwind(|| {
        [
            PushOnDrop::new(2, cloned.clone()),
            PushOnDrop::new(1, cloned.clone()),
            panic!("this panic is catched :D")
        ];
    }).err().unwrap();
    assert_eq!(*dropped_fields.borrow(), &[1, 2]);
}

fn main() {
    test_drop_tuple();
    test_drop_struct();
    test_drop_enum();
    test_drop_list();
}
<|endoftext|>


<commit_before><commit_msg>Remove catch-all case for input sanitization<commit_after><|endoftext|>


<commit_before>use redox::ops::DerefMut;
use redox::string::*;
use redox::vec::Vec;
use redox::boxed::Box;
use redox::fs::file::*;
use redox::io::*;
use redox::console::*;
use redox::env::*;
use redox::to_num::*;

/* Magic Macros { */
static mut application: *mut Application = 0 as *mut Application;

/// Execute a command
macro_rules! exec {
    ($cmd:expr) => ({
        unsafe {
            (*application).on_command(&$cmd.to_string());
        }
    })
}
/* } Magic Macros */

/// A command
pub struct Command {
    pub name: String,
    pub main: Box<Fn(&Vec<String>)>,
}

impl Command {
    /// Return the vector of the commands
    // TODO: Use a more efficient collection instead
    pub fn vec() -> Vec<Self> {
        let mut commands: Vec<Self> = Vec::new();
        commands.push(Command {
            name: "echo".to_string(),
            main: box |args: &Vec<String>| {
                let mut echo = String::new();
                let mut first = true;
                for i in 1..args.len() {
                    if let Some(arg) = args.get(i) {
                        if first {
                            first = false
                        } else {
                            echo = echo + " ";
                        }
                        echo = echo + arg;
                    }
                }
                println!("{}", echo);
            },
        });

        commands.push(Command {
            name: "open".to_string(),
            main: box |args: &Vec<String>| {
                if let Some(arg) = args.get(1) {
                    File::exec(arg);
                }
            },
        });

        commands.push(Command {
            name: "run".to_string(),
            main: box |args: &Vec<String>| {
                if let Some(arg) = args.get(1) {
                    let path = arg.clone();
                    println!("URL: {}", path);

                    let mut commands = String::new();
                    if let Some(mut file) = File::open(&path) {
                        file.read_to_string(&mut commands);
                    }

                    for command in commands.split('\n') {
                        exec!(command);
                    }
                }
            },
        });

        commands.push(Command {
            name: "send".to_string(),
            main: box |args: &Vec<String>| {
                let path;
                match args.get(1) {
                    Some(arg) => path = arg.clone(),
                    None => path = String::new(),
                }
                println!("URL: {}", path);

                if let Some(mut file) = File::open(&path) {
                    let mut string = String::new();
                    for i in 2..args.len() {
                        if let Some(arg) = args.get(i) {
                            if i >= 3 {
                                string.push_str(" ");
                            }
                            string.push_str(arg);
                        }
                    }
                    string.push_str("\r\n\r\n");

                    match file.write(&string.as_bytes()) {
                        Some(size) => println!("Wrote {} bytes", size),
                        None => println!("Failed to write"),
                    }

                    string = String::new();
                    match file.read_to_string(&mut string) {
                        Some(_) => println!("{}", string),
                        None => println!("Failed to read"),
                    }
                }
            },
        });

        commands.push(Command {
            name: "url".to_string(),
            main: box |args: &Vec<String>| {
                let path;
                match args.get(1) {
                    Some(arg) => path = arg.clone(),
                    None => path = String::new(),
                }
                println!("URL: {}", path);

                if let Some(mut file) = File::open(&path) {
                    let mut string = String::new();
                    match file.read_to_string(&mut string) {
                        Some(_) => println!("{}", string),
                        None => println!("Failed to read"),
                    }
                }
            },
        });

        commands.push(Command {
            name: "url_hex".to_string(),
            main: box |args: &Vec<String>| {
                let path;
                match args.get(1) {
                    Some(arg) => path = arg.clone(),
                    None => path = String::new(),
                }
                println!("URL: {}", path);

                if let Some(mut file) = File::open(&path) {
                    let mut vec: Vec<u8> = Vec::new();
                    match file.read_to_end(&mut vec) {
                        Some(_) => {
                            let mut line = "HEX:".to_string();
                            for byte in vec.iter() {
                                line = line + " " + &format!("{:X}", *byte);
                            }
                            println!("{}", line);
                        }
                        None => println!("Failed to read"),
                    }
                }
            },
        });

        commands.push(Command {
            name: "wget".to_string(),
            main: box |args: &Vec<String>| {
                if let Some(host) = args.get(1) {
                    if let Some(req) = args.get(2) {
                        if let Some(mut con) = File::open(&("tcp://".to_string() + host)) {
                            con.write(("GET ".to_string() + req + " HTTP/1.1").as_bytes());

                            let mut res = Vec::new();
                            con.read_to_end(&mut res);

                            if let Some(mut file) = File::open(&req) {
                                file.write(&res);
                            }
                        }
                    } else {
                        println!("No request given");
                    }
                } else {
                    println!("No url given");
                }
            },
        });

        let command_list = commands.iter().fold(String::new(), |l , c| l + " " + &c.name);

        commands.push(Command {
            name: "help".to_string(),
            main: box move |args: &Vec<String>| {
                println!("Commands:{}", command_list);
            },
         });

        commands
    }
}

/// A (env) variable
pub struct Variable {
    pub name: String,
    pub value: String,
}

pub struct Mode {
    value: bool,
}

/// An application
pub struct Application {
    commands: Vec<Command>,
    variables: Vec<Variable>,
    modes: Vec<Mode>,
}

impl Application {
    /// Create a new empty application
    pub fn new() -> Self {
        return Application {
            commands: Command::vec(),
            variables: Vec::new(),
            modes: Vec::new(),
        };
    }

    fn on_command(&mut self, command_string: &String) {
        //Comment
        if command_string.starts_with('#') {
            return;
        }

        //Show variables
        if *command_string == "$" {
            let mut variables = String::new();
            for variable in self.variables.iter() {
                variables = variables + "\n" + &variable.name + "=" + &variable.value;
            }
            println!("{}", variables);
            return;
        }

        //Explode into arguments, replace variables
        let mut args: Vec<String> = Vec::<String>::new();
        for arg in command_string.split(' ') {
            if arg.len() > 0 {
                if arg.starts_with('$') {
                    let name = arg[1 .. arg.len()].to_string();
                    for variable in self.variables.iter() {
                        if variable.name == name {
                            args.push(variable.value.clone());
                            break;
                        }
                    }
                } else {
                    args.push(arg.to_string());
                }
            }
        }

        //Execute commands
        if let Some(cmd) = args.get(0) {
            if cmd == "if" {
                let mut value = false;

                if let Some(left) = args.get(1) {
                    if let Some(cmp) = args.get(2) {
                        if let Some(right) = args.get(3) {
                            if cmp == "==" {
                                value = *left == *right;
                            } else if cmp == "!=" {
                                value = *left != *right;
                            } else if cmp == ">" {
                                value = left.to_num_signed() > right.to_num_signed();
                            } else if cmp == ">=" {
                                value = left.to_num_signed() >= right.to_num_signed();
                            } else if cmp == "<" {
                                value = left.to_num_signed() < right.to_num_signed();
                            } else if cmp == "<=" {
                                value = left.to_num_signed() <= right.to_num_signed();
                            } else {
                                println!("Unknown comparison: {}", cmp);
                            }
                        }
                    }
                }

                self.modes.insert(0, Mode { value: value });
                return;
            }

            if cmd == "else" {
                let mut syntax_error = false;
                match self.modes.get_mut(0) {
                    Some(mode) => mode.value = !mode.value,
                    None => syntax_error = true,
                }
                if syntax_error {
                    println!("Syntax error: else found with no previous if");
                }
                return;
            }

            if cmd == "fi" {
                let mut syntax_error = false;
                if self.modes.len() > 0 {
                    self.modes.remove(0);
                } else {
                    syntax_error = true;
                }
                if syntax_error {
                    println!("Syntax error: fi found with no previous if");
                }
                return;
            }

            for mode in self.modes.iter() {
                if !mode.value {
                    return;
                }
            }

            //Set variables
            if let Some(i) = cmd.find('=') {
                let name = cmd[0 .. i].to_string();
                let mut value = cmd[i + 1 .. cmd.len()].to_string();

                if name.len() == 0 {
                    return;
                }

                for i in 1..args.len() {
                    if let Some(arg) = args.get(i) {
                        value = value + " " + &arg;
                    }
                }

                if value.len() == 0 {
                    let mut remove = -1;
                    for i in 0..self.variables.len() {
                        match self.variables.get(i) {
                            Some(variable) => if variable.name == name {
                                remove = i as isize;
                                break;
                            },
                            None => break,
                        }
                    }

                    if remove >= 0 {
                        self.variables.remove(remove as usize);
                    }
                } else {
                    for variable in self.variables.iter_mut() {
                        if variable.name == name {
                            variable.value = value;
                            return;
                        }
                    }

                    self.variables.push(Variable {
                        name: name,
                        value: value,
                    });
                }
                return;
            }

            //Commands
            for command in self.commands.iter() {
                if &command.name == cmd {
                    (*command.main)(&args);
                    return;
                }
            }

            println!("Unknown command: '{}'", cmd);
        }
    }

    /// Run the application
    pub fn main(&mut self) {
        console_title("Terminal");

        println!("Type help for a command list");
        if let Some(arg) = args().get(1) {
            let command = "run ".to_string() + arg;
            println!("# {}", command);
            self.on_command(&command);
        }

        while let Some(command) = readln!() {
            println!("# {}", command);
            if command.len() > 0 {
                self.on_command(&command);
            }
        }
    }
}

pub fn main() {
    unsafe {
        let mut app = box Application::new();
        application = app.deref_mut();
        app.main();
    }
}
<commit_msg>Add `exit` command to terminal<commit_after>use redox::ops::DerefMut;
use redox::string::*;
use redox::vec::Vec;
use redox::boxed::Box;
use redox::fs::file::*;
use redox::io::*;
use redox::console::*;
use redox::env::*;
use redox::to_num::*;
use redox::syscall;

/* Magic Macros { */
static mut application: *mut Application = 0 as *mut Application;

/// Execute a command
macro_rules! exec {
    ($cmd:expr) => ({
        unsafe {
            (*application).on_command(&$cmd.to_string());
        }
    })
}
/* } Magic Macros */

/// A command
pub struct Command {
    pub name: String,
    pub main: Box<Fn(&Vec<String>)>,
}

impl Command {
    /// Return the vector of the commands
    // TODO: Use a more efficient collection instead
    pub fn vec() -> Vec<Self> {
        let mut commands: Vec<Self> = Vec::new();
        commands.push(Command {
            name: "echo".to_string(),
            main: box |args: &Vec<String>| {
                let mut echo = String::new();
                let mut first = true;
                for i in 1..args.len() {
                    if let Some(arg) = args.get(i) {
                        if first {
                            first = false
                        } else {
                            echo = echo + " ";
                        }
                        echo = echo + arg;
                    }
                }
                println!("{}", echo);
            },
        });

        commands.push(Command {
            name: "open".to_string(),
            main: box |args: &Vec<String>| {
                if let Some(arg) = args.get(1) {
                    File::exec(arg);
                }
            },
        });

        commands.push(Command {
            name: "run".to_string(),
            main: box |args: &Vec<String>| {
                if let Some(arg) = args.get(1) {
                    let path = arg.clone();
                    println!("URL: {}", path);

                    let mut commands = String::new();
                    if let Some(mut file) = File::open(&path) {
                        file.read_to_string(&mut commands);
                    }

                    for command in commands.split('\n') {
                        exec!(command);
                    }
                }
            },
        });

        commands.push(Command {
            name: "send".to_string(),
            main: box |args: &Vec<String>| {
                let path;
                match args.get(1) {
                    Some(arg) => path = arg.clone(),
                    None => path = String::new(),
                }
                println!("URL: {}", path);

                if let Some(mut file) = File::open(&path) {
                    let mut string = String::new();
                    for i in 2..args.len() {
                        if let Some(arg) = args.get(i) {
                            if i >= 3 {
                                string.push_str(" ");
                            }
                            string.push_str(arg);
                        }
                    }
                    string.push_str("\r\n\r\n");

                    match file.write(&string.as_bytes()) {
                        Some(size) => println!("Wrote {} bytes", size),
                        None => println!("Failed to write"),
                    }

                    string = String::new();
                    match file.read_to_string(&mut string) {
                        Some(_) => println!("{}", string),
                        None => println!("Failed to read"),
                    }
                }
            },
        });

        commands.push(Command {
            name: "url".to_string(),
            main: box |args: &Vec<String>| {
                let path;
                match args.get(1) {
                    Some(arg) => path = arg.clone(),
                    None => path = String::new(),
                }
                println!("URL: {}", path);

                if let Some(mut file) = File::open(&path) {
                    let mut string = String::new();
                    match file.read_to_string(&mut string) {
                        Some(_) => println!("{}", string),
                        None => println!("Failed to read"),
                    }
                }
            },
        });

        commands.push(Command {
            name: "url_hex".to_string(),
            main: box |args: &Vec<String>| {
                let path;
                match args.get(1) {
                    Some(arg) => path = arg.clone(),
                    None => path = String::new(),
                }
                println!("URL: {}", path);

                if let Some(mut file) = File::open(&path) {
                    let mut vec: Vec<u8> = Vec::new();
                    match file.read_to_end(&mut vec) {
                        Some(_) => {
                            let mut line = "HEX:".to_string();
                            for byte in vec.iter() {
                                line = line + " " + &format!("{:X}", *byte);
                            }
                            println!("{}", line);
                        }
                        None => println!("Failed to read"),
                    }
                }
            },
        });

        commands.push(Command {
            name: "wget".to_string(),
            main: box |args: &Vec<String>| {
                if let Some(host) = args.get(1) {
                    if let Some(req) = args.get(2) {
                        if let Some(mut con) = File::open(&("tcp://".to_string() + host)) {
                            con.write(("GET ".to_string() + req + " HTTP/1.1").as_bytes());

                            let mut res = Vec::new();
                            con.read_to_end(&mut res);

                            if let Some(mut file) = File::open(&req) {
                                file.write(&res);
                            }
                        }
                    } else {
                        println!("No request given");
                    }
                } else {
                    println!("No url given");
                }
            },
        });

        let command_list = commands.iter().fold(String::new(), |l , c| l + " " + &c.name) + " exit";

        commands.push(Command {
            name: "help".to_string(),
            main: box move |args: &Vec<String>| {
                println!("Commands:{}", command_list);
            },
         });

        commands
    }
}

/// A (env) variable
pub struct Variable {
    pub name: String,
    pub value: String,
}

pub struct Mode {
    value: bool,
}

/// An application
pub struct Application {
    commands: Vec<Command>,
    variables: Vec<Variable>,
    modes: Vec<Mode>,
}

impl Application {
    /// Create a new empty application
    pub fn new() -> Self {
        return Application {
            commands: Command::vec(),
            variables: Vec::new(),
            modes: Vec::new(),
        };
    }

    fn on_command(&mut self, command_string: &String) {
        //Comment
        if command_string.starts_with('#') {
            return;
        }

        //Show variables
        if *command_string == "$" {
            let mut variables = String::new();
            for variable in self.variables.iter() {
                variables = variables + "\n" + &variable.name + "=" + &variable.value;
            }
            println!("{}", variables);
            return;
        }

        //Explode into arguments, replace variables
        let mut args: Vec<String> = Vec::<String>::new();
        for arg in command_string.split(' ') {
            if arg.len() > 0 {
                if arg.starts_with('$') {
                    let name = arg[1 .. arg.len()].to_string();
                    for variable in self.variables.iter() {
                        if variable.name == name {
                            args.push(variable.value.clone());
                            break;
                        }
                    }
                } else {
                    args.push(arg.to_string());
                }
            }
        }

        //Execute commands
        if let Some(cmd) = args.get(0) {
            if cmd == "if" {
                let mut value = false;

                if let Some(left) = args.get(1) {
                    if let Some(cmp) = args.get(2) {
                        if let Some(right) = args.get(3) {
                            if cmp == "==" {
                                value = *left == *right;
                            } else if cmp == "!=" {
                                value = *left != *right;
                            } else if cmp == ">" {
                                value = left.to_num_signed() > right.to_num_signed();
                            } else if cmp == ">=" {
                                value = left.to_num_signed() >= right.to_num_signed();
                            } else if cmp == "<" {
                                value = left.to_num_signed() < right.to_num_signed();
                            } else if cmp == "<=" {
                                value = left.to_num_signed() <= right.to_num_signed();
                            } else {
                                println!("Unknown comparison: {}", cmp);
                            }
                        }
                    }
                }

                self.modes.insert(0, Mode { value: value });
                return;
            }

            if cmd == "else" {
                let mut syntax_error = false;
                match self.modes.get_mut(0) {
                    Some(mode) => mode.value = !mode.value,
                    None => syntax_error = true,
                }
                if syntax_error {
                    println!("Syntax error: else found with no previous if");
                }
                return;
            }

            if cmd == "fi" {
                let mut syntax_error = false;
                if self.modes.len() > 0 {
                    self.modes.remove(0);
                } else {
                    syntax_error = true;
                }
                if syntax_error {
                    println!("Syntax error: fi found with no previous if");
                }
                return;
            }

            for mode in self.modes.iter() {
                if !mode.value {
                    return;
                }
            }

            //Set variables
            if let Some(i) = cmd.find('=') {
                let name = cmd[0 .. i].to_string();
                let mut value = cmd[i + 1 .. cmd.len()].to_string();

                if name.len() == 0 {
                    return;
                }

                for i in 1..args.len() {
                    if let Some(arg) = args.get(i) {
                        value = value + " " + &arg;
                    }
                }

                if value.len() == 0 {
                    let mut remove = -1;
                    for i in 0..self.variables.len() {
                        match self.variables.get(i) {
                            Some(variable) => if variable.name == name {
                                remove = i as isize;
                                break;
                            },
                            None => break,
                        }
                    }

                    if remove >= 0 {
                        self.variables.remove(remove as usize);
                    }
                } else {
                    for variable in self.variables.iter_mut() {
                        if variable.name == name {
                            variable.value = value;
                            return;
                        }
                    }

                    self.variables.push(Variable {
                        name: name,
                        value: value,
                    });
                }
                return;
            }

            //Commands
            for command in self.commands.iter() {
                if &command.name == cmd {
                    (*command.main)(&args);
                    return;
                }
            }

            println!("Unknown command: '{}'", cmd);
        }
    }

    /// Run the application
    pub fn main(&mut self) {
        console_title("Terminal");

        println!("Type help for a command list");
        if let Some(arg) = args().get(1) {
            let command = "run ".to_string() + arg;
            println!("# {}", command);
            self.on_command(&command);
        }

        while let Some(command) = readln!() {
            println!("# {}", command);
            if command == "exit" {
                break;
            } else if command.len() > 0 {
                self.on_command(&command);
            }
        }
    }
}

pub fn main() {
    unsafe {
        let mut app = box Application::new();
        application = app.deref_mut();
        app.main();
    }
}
<|endoftext|>


<commit_before>// This crate is a library
#![crate_type = "lib"]
// The library is named "erty", and its version is 0.1
#![crate_id = "erty#0.1"]

pub fn public_function() {
    println!("called erty's `public_function()`");
}

fn private_function() {
    println!("called erty's `private_function()`");
}

pub fn indirect_access() {
    print!("called erty's `indirect_access()`, that\n> ");

    private_function();
}
<commit_msg>The "crate_id" attribute is deprecated<commit_after>// This crate is a library
#![crate_type = "lib"]
// The library is named "erty"
#![crate_name = "erty"]

pub fn public_function() {
    println!("called erty's `public_function()`");
}

fn private_function() {
    println!("called erty's `private_function()`");
}

pub fn indirect_access() {
    print!("called erty's `indirect_access()`, that\n> ");

    private_function();
}
<|endoftext|>


<commit_before><commit_msg>More doc!<commit_after><|endoftext|>


<commit_before>#![feature(asm)]
#![feature(slice_concat_ext)]

use std::rand;
use std::ptr;
use std::slice::SliceConcatExt;
use std::string::*;
use std::syscall::sys_exit;
use std::thread;

macro_rules! readln {
    () => ({
        let mut buffer = String::new();
        match std::io::stdin().read_line(&mut buffer) {
            Ok(_) => Some(buffer),
            Err(_) => None
        }
    });
}

fn main() {
    println!("Type help for a command list");
    loop {
        print!("# ");
        if let Some(line) = readln!() {
            let args: Vec<String> = line.trim().split(' ').map(|arg| arg.to_string()).collect();

            if let Some(a_command) = args.get(0) {
                let console_commands = ["exit",
                                        "panic",
                                        "ptr_write",
                                        "box_write",
                                        "reboot",
                                        "shutdown",
                                        "clone",
                                        "leak_test",
                                        "test_hm",
                                        "int3"];

                match &a_command[..] {
                    command if command == console_commands[0] => unsafe {
                        sys_exit(0);
                    },
                    command if command == console_commands[1] => panic!("Test panic"),
                    command if command == console_commands[2] => {
                        let a_ptr = rand() as *mut u8;
                        unsafe {
                            ptr::write(a_ptr, rand() as u8);
                        }
                    }
                    command if command == console_commands[3] => {
                        let a_box = Box::new(rand() as u8);
                        unsafe {
                            ptr::write(Box::into_raw(a_box), rand() as u8);
                        }
                    }
                    command if command == console_commands[4] => unsafe {
                        let mut good: u8 = 2;
                        while good & 2 == 2 {
                            asm!("in al, dx" : "={al}"(good) : "{dx}"(0x64) : : "intel", "volatile");
                        }
                        asm!("out dx, al" : : "{dx}"(0x64), "{al}"(0xFE) : : "intel", "volatile");
                        loop {
                            asm!("cli" : : : : "intel", "volatile");
                            asm!("hlt" : : : : "intel", "volatile");
                        }
                    },
                    command if command == console_commands[5] => unsafe {
                        loop {
                            asm!("cli" : : : : "intel", "volatile");
                            asm!("hlt" : : : : "intel", "volatile");
                        }
                    },
                    command if command == console_commands[6] => {
                        let parent_message = "Parent Message";
                        let handle = thread::spawn(move || {
                            println!("Child after spawn: {}", parent_message);
                            return "Child message";
                        });
                        println!("Parent after spawn: {}", parent_message);
                        match handle.join() {
                            Some(child_message) => println!("Parent after join: {}", child_message),
                            None => println!("Failed to join"),
                        }
                    }
                    command if command == console_commands[7] => {
                        let mut stack_it: Vec<Box<u8>> = Vec::new();
                        loop {
                            stack_it.push(Box::new(rand() as u8))
                        }
                    }
                    command if command == console_commands[8] => {
                        ::std::hashmap::test();
                    }
                    command if command == console_commands[9] => unsafe {
                        asm!("int 3" : : : : "intel", "volatile");
                    },
                    _ => println!("Commands: {}", console_commands.join(" ")),
                }
            }
        } else {
            println!("Failed to read line from stdin");
        }
    }
}
<commit_msg>Fix build<commit_after>#![feature(asm)]
#![feature(slice_concat_ext)]

use std::rand;
use std::ptr;
use std::slice::SliceConcatExt;
use std::string::*;
use std::syscall::sys_exit;
use std::thread;

macro_rules! readln {
    () => ({
        let mut buffer = String::new();
        match std::io::stdin().read_line(&mut buffer) {
            Ok(_) => Some(buffer),
            Err(_) => None
        }
    });
}

fn main() {
    println!("Type help for a command list");
    loop {
        print!("# ");
        if let Some(line) = readln!() {
            let args: Vec<String> = line.trim().split(' ').map(|arg| arg.to_string()).collect();

            if let Some(a_command) = args.get(0) {
                let console_commands = ["exit",
                                        "panic",
                                        "ptr_write",
                                        "box_write",
                                        "reboot",
                                        "shutdown",
                                        "clone",
                                        "leak_test",
                                        "test_hm",
                                        "int3"];

                match &a_command[..] {
                    command if command == console_commands[0] => unsafe {
                        sys_exit(0);
                    },
                    command if command == console_commands[1] => panic!("Test panic"),
                    command if command == console_commands[2] => {
                        let a_ptr = rand() as *mut u8;
                        unsafe {
                            ptr::write(a_ptr, rand() as u8);
                        }
                    }
                    command if command == console_commands[3] => {
                        let a_box = Box::new(rand() as u8);
                        unsafe {
                            ptr::write(Box::into_raw(a_box), rand() as u8);
                        }
                    }
                    command if command == console_commands[4] => unsafe {
                        let mut good: u8 = 2;
                        while good & 2 == 2 {
                            asm!("in al, dx" : "={al}"(good) : "{dx}"(0x64) : : "intel", "volatile");
                        }
                        asm!("out dx, al" : : "{dx}"(0x64), "{al}"(0xFE) : : "intel", "volatile");
                        loop {
                            asm!("cli" : : : : "intel", "volatile");
                            asm!("hlt" : : : : "intel", "volatile");
                        }
                    },
                    command if command == console_commands[5] => unsafe {
                        loop {
                            asm!("cli" : : : : "intel", "volatile");
                            asm!("hlt" : : : : "intel", "volatile");
                        }
                    },
                    command if command == console_commands[6] => {
                        let parent_message = "Parent Message";
                        let handle = thread::spawn(move || {
                            println!("Child after spawn: {}", parent_message);
                            return "Child message";
                        });
                        println!("Parent after spawn: {}", parent_message);
                        match handle.join() {
                            Some(child_message) => println!("Parent after join: {}", child_message),
                            None => println!("Failed to join"),
                        }
                    },
                    command if command == console_commands[7] => {
                        let mut stack_it: Vec<Box<u8>> = Vec::new();
                        loop {
                            stack_it.push(Box::new(rand() as u8))
                        }
                    },
                    command if command == console_commands[9] => unsafe {
                        asm!("int 3" : : : : "intel", "volatile");
                    },
                    _ => println!("Commands: {}", console_commands.join(" ")),
                }
            }
        } else {
            println!("Failed to read line from stdin");
        }
    }
}
<|endoftext|>


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

// min-lldb-version: 310

// compile-flags:-g

#![allow(dead_code, unused_variables)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
#![feature(static_mutex)]

// This test makes sure that the compiler doesn't crash when trying to assign
// debug locations to const-expressions.

use std::cell::UnsafeCell;

const CONSTANT: u64 = 3 + 4;

struct Struct {
    a: isize,
    b: usize,
}
const STRUCT: Struct = Struct { a: 1, b: 2 };

struct TupleStruct(u32);
const TUPLE_STRUCT: TupleStruct = TupleStruct(4);

enum Enum {
    Variant1(char),
    Variant2 { a: u8 },
    Variant3
}

const VARIANT1: Enum = Enum::Variant1('v');
const VARIANT2: Enum = Enum::Variant2 { a: 2 };
const VARIANT3: Enum = Enum::Variant3;

const STRING: &'static str = "String";

const VEC: [u32; 8] = [0; 8];

const NESTED: (Struct, TupleStruct) = (STRUCT, TUPLE_STRUCT);

const UNSAFE_CELL: UnsafeCell<bool> = UnsafeCell::new(false);

fn main() {
    let mut _constant = CONSTANT;
    let mut _struct = STRUCT;
    let mut _tuple_struct = TUPLE_STRUCT;
    let mut _variant1 = VARIANT1;
    let mut _variant2 = VARIANT2;
    let mut _variant3 = VARIANT3;
    let mut _string = STRING;
    let mut _vec = VEC;
    let mut _nested = NESTED;
    let mut _unsafe_cell = UNSAFE_CELL;
}
<commit_msg>Fix test/debuginfo<commit_after>// Copyright 2013-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.

// min-lldb-version: 310

// compile-flags:-g

#![allow(dead_code, unused_variables)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]

// This test makes sure that the compiler doesn't crash when trying to assign
// debug locations to const-expressions.

use std::cell::UnsafeCell;

const CONSTANT: u64 = 3 + 4;

struct Struct {
    a: isize,
    b: usize,
}
const STRUCT: Struct = Struct { a: 1, b: 2 };

struct TupleStruct(u32);
const TUPLE_STRUCT: TupleStruct = TupleStruct(4);

enum Enum {
    Variant1(char),
    Variant2 { a: u8 },
    Variant3
}

const VARIANT1: Enum = Enum::Variant1('v');
const VARIANT2: Enum = Enum::Variant2 { a: 2 };
const VARIANT3: Enum = Enum::Variant3;

const STRING: &'static str = "String";

const VEC: [u32; 8] = [0; 8];

const NESTED: (Struct, TupleStruct) = (STRUCT, TUPLE_STRUCT);

const UNSAFE_CELL: UnsafeCell<bool> = UnsafeCell::new(false);

fn main() {
    let mut _constant = CONSTANT;
    let mut _struct = STRUCT;
    let mut _tuple_struct = TUPLE_STRUCT;
    let mut _variant1 = VARIANT1;
    let mut _variant2 = VARIANT2;
    let mut _variant3 = VARIANT3;
    let mut _string = STRING;
    let mut _vec = VEC;
    let mut _nested = NESTED;
    let mut _unsafe_cell = UNSAFE_CELL;
}
<|endoftext|>


<commit_before><commit_msg>Add hmac and hmac key derivation methods<commit_after><|endoftext|>


<commit_before><commit_msg>FEAT(currency): Update Currency<commit_after><|endoftext|>


<commit_before><commit_msg>last will updated.<commit_after><|endoftext|>


<commit_before>// xfail-pretty

// 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.

extern mod std;

use std::bitv;
use core::io::{ReaderUtil, WriterUtil};
use core::io;

// Computes a single solution to a given 9x9 sudoku
//
// Call with "-" to read input sudoku from stdin
//
// The expected line-based format is:
//
// 9,9
// <row>,<column>,<color>
// ...
//
// Row and column are 0-based (i.e. <= 8) and color is 1-based (>=1,<=9).
// A color of 0 indicates an empty field.
//
// If called without arguments, sudoku solves a built-in example sudoku
//

// internal type of sudoku grids
type grid = ~[~[u8]];

// exported type of sudoku grids
pub enum grid_t { grid_ctor(grid), }

// read a sudoku problem from file f
pub fn read_grid(f: @io::Reader) -> grid_t {
    fail_unless!(f.read_line() == ~"9,9"); /* assert first line is exactly "9,9" */

    let mut g = vec::from_fn(10u, {|_i|
        vec::from_elem(10u, 0 as u8)
    });
    while !f.eof() {
        let comps = str::split_char(str::trim(f.read_line()), ',');
        if vec::len(comps) >= 3u {
            let row     = uint::from_str(comps[0]).get() as u8;
            let col     = uint::from_str(comps[1]).get() as u8;
            g[row][col] = uint::from_str(comps[2]).get() as u8;
        }
    }
    return grid_ctor(g);
}

// solve sudoku grid
pub fn solve_grid(g: grid_t) {
    fn next_color(mut g: grid, row: u8, col: u8, start_color: u8) -> bool {
        if start_color < 10u8 {
            // colors not yet used
            let mut avail = bitv::Bitv::new(10u, false);
            for u8::range(start_color, 10u8) |color| {
                avail.set(color as uint, true);
            }

            // drop colors already in use in neighbourhood
            drop_colors(copy g, copy avail, row, col);

            // find first remaining color that is available
            for uint::range(1u, 10u) |i| {
                if avail.get(i) {
                    g[row][col] = i as u8;
                    return true;
                }
            };
        }
        g[row][col] = 0u8;
        return false;
    }

    // find colors available in neighbourhood of (row, col)
    fn drop_colors(g: grid, avail: bitv::Bitv, row: u8, col: u8) {
        fn drop_color(g: grid, mut colors: bitv::Bitv, row: u8, col: u8) {
            let color = g[row][col];
            if color != 0u8 { colors.set(color as uint, false); }
        }

        let it = |a,b| drop_color(copy g, copy avail, a, b);

        for u8::range(0u8, 9u8) |idx| {
            it(idx, col); /* check same column fields */
            it(row, idx); /* check same row fields */
        }

        // check same block fields
        let row0 = (row / 3u8) * 3u8;
        let col0 = (col / 3u8) * 3u8;
        for u8::range(row0, row0 + 3u8) |alt_row| {
            for u8::range(col0, col0 + 3u8) |alt_col| { it(alt_row, alt_col); }
        }
    }

    let mut work: ~[(u8, u8)] = ~[]; /* queue of uncolored fields */
    for u8::range(0u8, 9u8) |row| {
        for u8::range(0u8, 9u8) |col| {
            let color = (*g)[row][col];
            if color == 0u8 { work += ~[(row, col)]; }
        }
    }

    let mut ptr = 0u;
    let end = vec::len(work);
    while (ptr < end) {
        let (row, col) = work[ptr];
        // is there another color to try?
        if next_color(copy *g, row, col, (*g)[row][col] + (1 as u8)) {
            //  yes: advance work list
            ptr = ptr + 1u;
        } else {
            // no: redo this field aft recoloring pred; unless there is none
            if ptr == 0u { fail!(~"No solution found for this sudoku"); }
            ptr = ptr - 1u;
        }
    }
}

pub fn write_grid(f: @io::Writer, g: grid_t) {
    for u8::range(0u8, 9u8) |row| {
        f.write_str(fmt!("%u", (*g)[row][0] as uint));
        for u8::range(1u8, 9u8) |col| {
            f.write_str(fmt!(" %u", (*g)[row][col] as uint));
        }
        f.write_char('\n');
     }
}

fn main() {
    let args = os::args();
    let grid = if vec::len(args) == 1u {
        // FIXME create sudoku inline since nested vec consts dont work yet
        // (#3733)
        let mut g = vec::from_fn(10u, |_i| {
            vec::from_elem(10u, 0 as u8)
        });
        g[0][1] = 4u8;
        g[0][3] = 6u8;
        g[0][7] = 3u8;
        g[0][8] = 2u8;
        g[1][2] = 8u8;
        g[1][4] = 2u8;
        g[2][0] = 7u8;
        g[2][3] = 8u8;
        g[3][3] = 5u8;
        g[4][1] = 5u8;
        g[4][5] = 3u8;
        g[4][6] = 6u8;
        g[5][0] = 6u8;
        g[5][1] = 8u8;
        g[5][7] = 9u8;
        g[6][1] = 9u8;
        g[6][2] = 5u8;
        g[6][5] = 6u8;
        g[6][7] = 7u8;
        g[7][4] = 4u8;
        g[7][7] = 6u8;
        g[8][0] = 4u8;
        g[8][5] = 7u8;
        g[8][6] = 2u8;
        g[8][8] = 3u8;
        grid_ctor(g)
    } else {
        read_grid(io::stdin())
    };
    solve_grid(copy grid);
    write_grid(io::stdout(), grid);
}

<commit_msg>Refactored sudoku benchmark to use traits and added some tests<commit_after>// xfail-pretty

// 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.

extern mod std;

use core::io::{ReaderUtil, WriterUtil};
use core::io;
use core::unstable::intrinsics::cttz16;

// Computes a single solution to a given 9x9 sudoku
//
// Call with "-" to read input sudoku from stdin
//
// The expected line-based format is:
//
// 9,9
// <row>,<column>,<color>
// ...
//
// Row and column are 0-based (i.e. <= 8) and color is 1-based (>=1,<=9).
// A color of 0 indicates an empty field.
//
// If called without arguments, sudoku solves a built-in example sudoku
//

// internal type of sudoku grids
type grid = ~[~[u8]];

struct Sudoku {
    grid: grid
}

pub impl Sudoku {
    static pub fn new(g: grid) -> Sudoku {
        return Sudoku { grid: g }
    }

    static pub fn from_vec(vec: &[[u8 * 9] * 9]) -> Sudoku {
        let mut g = do vec::from_fn(9u) |i| {
            do vec::from_fn(9u) |j| { vec[i][j] }
        };
        return Sudoku::new(g)
    }

    pub fn equal(&self, other: &Sudoku) -> bool {
        for u8::range(0u8, 9u8) |row| {
            for u8::range(0u8, 9u8) |col| {
                if self.grid[row][col] != other.grid[row][col] {
                    return false;
                }
            }
        }
        return true;
    }

    static pub fn read(reader: @io::Reader) -> Sudoku {
        fail_unless!(reader.read_line() == ~"9,9"); /* assert first line is exactly "9,9" */

        let mut g = vec::from_fn(10u, { |_i| ~[0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8] });
        while !reader.eof() {
            let comps = str::split_char(str::trim(reader.read_line()), ',');
            if vec::len(comps) == 3u {
                let row     = uint::from_str(comps[0]).get() as u8;
                let col     = uint::from_str(comps[1]).get() as u8;
                g[row][col] = uint::from_str(comps[2]).get() as u8;
            }
            else {
                fail!(~"Invalid sudoku file");
            }
        }
        return Sudoku::new(g)
    }

    pub fn write(&self, writer: @io::Writer) {
        for u8::range(0u8, 9u8) |row| {
            writer.write_str(fmt!("%u", self.grid[row][0] as uint));
            for u8::range(1u8, 9u8) |col| {
                writer.write_str(fmt!(" %u", self.grid[row][col] as uint));
            }
            writer.write_char('\n');
         }
    }

    // solve sudoku grid
    pub fn solve(&mut self) {
        let mut work: ~[(u8, u8)] = ~[]; /* queue of uncolored fields */
        for u8::range(0u8, 9u8) |row| {
            for u8::range(0u8, 9u8) |col| {
                let color = self.grid[row][col];
                if color == 0u8 { work += ~[(row, col)]; }
            }
        }

        let mut ptr = 0u;
        let end = vec::len(work);
        while (ptr < end) {
            let (row, col) = work[ptr];
            // is there another color to try?
            if self.next_color(row, col, self.grid[row][col] + (1 as u8)) {
                //  yes: advance work list
                ptr = ptr + 1u;
            } else {
                // no: redo this field aft recoloring pred; unless there is none
                if ptr == 0u { fail!(~"No solution found for this sudoku"); }
                ptr = ptr - 1u;
            }
        }
    }

    fn next_color(&mut self, row: u8, col: u8, start_color: u8) -> bool {
        if start_color < 10u8 {
            // colors not yet used
            let mut avail = ~Colors::new(start_color);

            // drop colors already in use in neighbourhood
            self.drop_colors(avail, row, col);

            // find first remaining color that is available
            let next = avail.next();
            self.grid[row][col] = next;
            return 0u8 != next;
        }
        self.grid[row][col] = 0u8;
        return false;
    }

    // find colors available in neighbourhood of (row, col)
    fn drop_colors(&mut self, avail: &mut Colors, row: u8, col: u8) {
        for u8::range(0u8, 9u8) |idx| {
            avail.remove(self.grid[idx][col]); /* check same column fields */
            avail.remove(self.grid[row][idx]); /* check same row fields */
        }

        // check same block fields
        let row0 = (row / 3u8) * 3u8;
        let col0 = (col / 3u8) * 3u8;
        for u8::range(row0, row0 + 3u8) |alt_row| {
            for u8::range(col0, col0 + 3u8) |alt_col| { avail.remove(self.grid[alt_row][alt_col]); }
        }
    }
}

// Stores available colors as simple bitfield, bit 0 is always unset
struct Colors(u16);

const heads: u16 = (1u16 << 10) - 1; /* bits 9..0 */

impl Colors {
    static fn new(start_color: u8) -> Colors {
        // Sets bits 9..start_color
        let tails = !0u16 << start_color;
        return Colors(heads & tails);
    }

    fn next(&self) -> u8 {
        let val = **self & heads;
        if (0u16 == val) {
            return 0u8;
        }
        else
        {
            return cttz16(val as i16) as u8;
        }
    }

    fn remove(&mut self, color: u8) {
        if color != 0u8 {
            let val  = **self;
            let mask = !(1u16 << color);
            *self    = Colors(val & mask);
        }
    }
}

const default_sudoku: [[u8 * 9] * 9] = [
         /* 0    1    2    3    4    5    6    7    8    */
  /* 0 */  [0u8, 4u8, 0u8, 6u8, 0u8, 0u8, 0u8, 3u8, 2u8],
  /* 1 */  [0u8, 0u8, 8u8, 0u8, 2u8, 0u8, 0u8, 0u8, 0u8],
  /* 2 */  [7u8, 0u8, 0u8, 8u8, 0u8, 0u8, 0u8, 0u8, 0u8],
  /* 3 */  [0u8, 0u8, 0u8, 5u8, 0u8, 0u8, 0u8, 0u8, 0u8],
  /* 4 */  [0u8, 5u8, 0u8, 0u8, 0u8, 3u8, 6u8, 0u8, 0u8],
  /* 5 */  [6u8, 8u8, 0u8, 0u8, 0u8, 0u8, 0u8, 9u8, 0u8],
  /* 6 */  [0u8, 9u8, 5u8, 0u8, 0u8, 6u8, 0u8, 7u8, 0u8],
  /* 7 */  [0u8, 0u8, 0u8, 0u8, 4u8, 0u8, 0u8, 6u8, 0u8],
  /* 8 */  [4u8, 0u8, 0u8, 0u8, 0u8, 7u8, 2u8, 0u8, 3u8]
];

#[cfg(test)]
const default_solution: [[u8 * 9] * 9] = [
         /* 0    1    2    3    4    5    6    7    8    */
  /* 0 */  [1u8, 4u8, 9u8, 6u8, 7u8, 5u8, 8u8, 3u8, 2u8],
  /* 1 */  [5u8, 3u8, 8u8, 1u8, 2u8, 9u8, 7u8, 4u8, 6u8],
  /* 2 */  [7u8, 2u8, 6u8, 8u8, 3u8, 4u8, 1u8, 5u8, 9u8],
  /* 3 */  [9u8, 1u8, 4u8, 5u8, 6u8, 8u8, 3u8, 2u8, 7u8],
  /* 4 */  [2u8, 5u8, 7u8, 4u8, 9u8, 3u8, 6u8, 1u8, 8u8],
  /* 5 */  [6u8, 8u8, 3u8, 7u8, 1u8, 2u8, 5u8, 9u8, 4u8],
  /* 6 */  [3u8, 9u8, 5u8, 2u8, 8u8, 6u8, 4u8, 7u8, 1u8],
  /* 7 */  [8u8, 7u8, 2u8, 3u8, 4u8, 1u8, 9u8, 6u8, 5u8],
  /* 8 */  [4u8, 6u8, 1u8, 9u8, 5u8, 7u8, 2u8, 8u8, 3u8]
];

#[test]
fn colors_new_works() {
    fail_unless!(*Colors::new(1) == 1022u16);
    fail_unless!(*Colors::new(2) == 1020u16);
    fail_unless!(*Colors::new(3) == 1016u16);
    fail_unless!(*Colors::new(4) == 1008u16);
    fail_unless!(*Colors::new(5) == 992u16);
    fail_unless!(*Colors::new(6) == 960u16);
    fail_unless!(*Colors::new(7) == 896u16);
    fail_unless!(*Colors::new(8) == 768u16);
    fail_unless!(*Colors::new(9) == 512u16);
}

#[test]
fn colors_next_works() {
    fail_unless!(Colors(0).next() == 0u8);
    fail_unless!(Colors(2).next() == 1u8);
    fail_unless!(Colors(4).next() == 2u8);
    fail_unless!(Colors(8).next() == 3u8);
    fail_unless!(Colors(16).next() == 4u8);
    fail_unless!(Colors(32).next() == 5u8);
    fail_unless!(Colors(64).next() == 6u8);
    fail_unless!(Colors(128).next() == 7u8);
    fail_unless!(Colors(256).next() == 8u8);
    fail_unless!(Colors(512).next() == 9u8);
    fail_unless!(Colors(1024).next() == 0u8);
}

#[test]
fn colors_remove_works() {
    // GIVEN
    let mut colors = Colors::new(1);

    // WHEN
    colors.remove(1);

    // THEN
    fail_unless!(colors.next() == 2u8);
}

#[test]
fn check_default_sudoku_solution() {
    // GIVEN
    let mut sudoku = Sudoku::from_vec(&default_sudoku);
    let solution   = Sudoku::from_vec(&default_solution);

    // WHEN
    sudoku.solve();

    // THEN
    fail_unless!(sudoku.equal(&solution));
}

fn main() {
    let args        = os::args();
    let use_default = vec::len(args) == 1u;
    let mut sudoku = if use_default {
        Sudoku::from_vec(&default_sudoku)
    } else {
        Sudoku::read(io::stdin())
    };
    sudoku.solve();
    sudoku.write(io::stdout());
}

<|endoftext|>


<commit_before>import core::*;

import str;
import std::rope::*;
import option;
import uint;
import vec;

//Utility function, used for sanity check
fn rope_to_string(r: rope) -> str {
    alt(r) {
      node::empty. { ret "" }
      node::content(x) {
        let str = @mutable "";
        fn aux(str: @mutable str, node: @node::node) {
            alt(*node) {
              node::leaf(x) {
                *str += str::substr(*x.content, x.byte_offset, x.byte_len);
              }
              node::concat(x) {
                aux(str, x.left);
                aux(str, x.right);
              }
            }
        }
        aux(str, x);
        ret *str
      }
    }
}

#[test]
fn trivial() {
    assert char_len(empty()) == 0u;
    assert byte_len(empty()) == 0u;
}

#[test]
fn of_string1() {
    let sample = @"0123456789ABCDE";
    let r      = of_str(sample);

    assert char_len(r) == str::char_len(*sample);
    assert rope_to_string(r) == *sample;
}

#[test]
fn of_string2() {
    let buf = @ mutable "1234567890";
    let i = 0;
    while i < 10 { *buf = *buf + *buf; i+=1;}
    let sample = @*buf;
    let r      = of_str(sample);
    assert char_len(r) == str::char_len(*sample);
    assert rope_to_string(r) == *sample;

    let string_iter = 0u;
    let string_len  = str::byte_len(*sample);
    let rope_iter   = iterator::char::start(r);
    let equal       = true;
    let pos         = 0u;
    while equal {
        alt(node::char_iterator::next(rope_iter)) {
          option::none. {
            if string_iter < string_len {
                equal = false;
            } break; }
          option::some(c) {
            let {ch, next} = str::char_range_at(*sample, string_iter);
            string_iter = next;
            if ch != c { equal = false; break; }
          }
        }
        pos += 1u;
    }

    assert equal;
}

#[test]
fn iter1() {
    let buf = @ mutable "1234567890";
    let i = 0;
    while i < 10 { *buf = *buf + *buf; i+=1;}
    let sample = @*buf;
    let r      = of_str(sample);

    let len = 0u;
    let it  = iterator::char::start(r);
    while true {
        alt(node::char_iterator::next(it)) {
          option::none. { break; }
          option::some(_) { len += 1u; }
        }
    }

    assert len == str::char_len(*sample);
}

#[test]
fn bal1() {
    let init = @ "1234567890";
    let buf  = @ mutable * init;
    let i = 0;
    while i < 16 { *buf = *buf + *buf; i+=1;}
    let sample = @*buf;
    let r1     = of_str(sample);
    let r2     = of_str(init);
    i = 0;
    while i < 16 { r2 = append_rope(r2, r2); i+= 1;}

    assert eq(r1, r2);
    let r3 = bal(r2);
    assert char_len(r1) == char_len(r3);

    assert eq(r1, r3);
}

#[test]
fn char_at1() {
    //Generate a large rope
    let r = of_str(@ "123456789");
    uint::range(0u, 10u){|_i|
        r = append_rope(r, r);
    }

    //Copy it in the slowest possible way
    let r2 = empty();
    uint::range(0u, char_len(r)){|i|
        r2 = append_char(r2, char_at(r, i));
    }
    assert eq(r, r2);

    let r3 = empty();
    uint::range(0u, char_len(r)){|i|
        r3 = prepend_char(r3, char_at(r, char_len(r) - i - 1u));
    }
    assert eq(r, r3);

    //Additional sanity checks
    let balr = bal(r);
    let bal2 = bal(r2);
    let bal3 = bal(r3);
    assert eq(r, balr);
    assert eq(r, bal2);
    assert eq(r, bal3);
    assert eq(r2, r3);
    assert eq(bal2, bal3);
}

#[test]
fn concat1() {
    //Generate a reasonable rope
    let chunk = of_str(@ "123456789");
    let r = empty();
    uint::range(0u, 10u){|_i|
        r = append_rope(r, chunk);
    }

    //Same rope, obtained with rope::concat
    let r2 = concat(vec::init_elt(chunk, 10u));

    assert eq(r, r2);
}<commit_msg>test: Simplify rope::bal1. Closes #1424<commit_after>import core::*;

import str;
import std::rope::*;
import option;
import uint;
import vec;

//Utility function, used for sanity check
fn rope_to_string(r: rope) -> str {
    alt(r) {
      node::empty. { ret "" }
      node::content(x) {
        let str = @mutable "";
        fn aux(str: @mutable str, node: @node::node) {
            alt(*node) {
              node::leaf(x) {
                *str += str::substr(*x.content, x.byte_offset, x.byte_len);
              }
              node::concat(x) {
                aux(str, x.left);
                aux(str, x.right);
              }
            }
        }
        aux(str, x);
        ret *str
      }
    }
}

#[test]
fn trivial() {
    assert char_len(empty()) == 0u;
    assert byte_len(empty()) == 0u;
}

#[test]
fn of_string1() {
    let sample = @"0123456789ABCDE";
    let r      = of_str(sample);

    assert char_len(r) == str::char_len(*sample);
    assert rope_to_string(r) == *sample;
}

#[test]
fn of_string2() {
    let buf = @ mutable "1234567890";
    let i = 0;
    while i < 10 { *buf = *buf + *buf; i+=1;}
    let sample = @*buf;
    let r      = of_str(sample);
    assert char_len(r) == str::char_len(*sample);
    assert rope_to_string(r) == *sample;

    let string_iter = 0u;
    let string_len  = str::byte_len(*sample);
    let rope_iter   = iterator::char::start(r);
    let equal       = true;
    let pos         = 0u;
    while equal {
        alt(node::char_iterator::next(rope_iter)) {
          option::none. {
            if string_iter < string_len {
                equal = false;
            } break; }
          option::some(c) {
            let {ch, next} = str::char_range_at(*sample, string_iter);
            string_iter = next;
            if ch != c { equal = false; break; }
          }
        }
        pos += 1u;
    }

    assert equal;
}

#[test]
fn iter1() {
    let buf = @ mutable "1234567890";
    let i = 0;
    while i < 10 { *buf = *buf + *buf; i+=1;}
    let sample = @*buf;
    let r      = of_str(sample);

    let len = 0u;
    let it  = iterator::char::start(r);
    while true {
        alt(node::char_iterator::next(it)) {
          option::none. { break; }
          option::some(_) { len += 1u; }
        }
    }

    assert len == str::char_len(*sample);
}

#[test]
fn bal1() {
    let init = @ "1234567890";
    let buf  = @ mutable * init;
    let i = 0;
    while i < 8 { *buf = *buf + *buf; i+=1;}
    let sample = @*buf;
    let r1     = of_str(sample);
    let r2     = of_str(init);
    i = 0;
    while i < 8 { r2 = append_rope(r2, r2); i+= 1;}

    assert eq(r1, r2);
    let r3 = bal(r2);
    assert char_len(r1) == char_len(r3);

    assert eq(r1, r3);
}

#[test]
fn char_at1() {
    //Generate a large rope
    let r = of_str(@ "123456789");
    uint::range(0u, 10u){|_i|
        r = append_rope(r, r);
    }

    //Copy it in the slowest possible way
    let r2 = empty();
    uint::range(0u, char_len(r)){|i|
        r2 = append_char(r2, char_at(r, i));
    }
    assert eq(r, r2);

    let r3 = empty();
    uint::range(0u, char_len(r)){|i|
        r3 = prepend_char(r3, char_at(r, char_len(r) - i - 1u));
    }
    assert eq(r, r3);

    //Additional sanity checks
    let balr = bal(r);
    let bal2 = bal(r2);
    let bal3 = bal(r3);
    assert eq(r, balr);
    assert eq(r, bal2);
    assert eq(r, bal3);
    assert eq(r2, r3);
    assert eq(bal2, bal3);
}

#[test]
fn concat1() {
    //Generate a reasonable rope
    let chunk = of_str(@ "123456789");
    let r = empty();
    uint::range(0u, 10u){|_i|
        r = append_rope(r, chunk);
    }

    //Same rope, obtained with rope::concat
    let r2 = concat(vec::init_elt(chunk, 10u));

    assert eq(r, r2);
}<|endoftext|>


<commit_before><commit_msg>writing to file<commit_after>use std::io::File;

fn main(){
  let mut file = File::create(&Path::new("test.txt"));
  file.write(bytes!("pewpewpew\n"));
}
<|endoftext|>


<commit_before><commit_msg>bring in the file<commit_after>use std;
use capnp;
use zmq;

fn slice_cast<'a, T, V>(s : &'a [T]) -> &'a [V] {
    unsafe {
        std::mem::transmute(
            std::raw::Slice {data : s.as_ptr(),
                             len : s.len() * std::mem::size_of::<T>() / std::mem::size_of::<V>()  })
    }
}

pub fn frames_to_segments<'a>(frames : &'a [zmq::Message] ) -> Vec<&'a [capnp::common::Word]> {

    let mut result : Vec<&'a [capnp::common::Word]> = Vec::new();

    for frame in frames.iter() {
        unsafe {
            let slice = frame.with_bytes(|v|
                    std::raw::Slice { data : v.as_ptr(),
                                      len : v.len() / 8 });

            // TODO check whether bytes are aligned on a word boundary.
            // If not, copy them into a new buffer. Who will own that buffer?

            result.push(std::mem::transmute(slice));
        }
    }

    return result;
}

pub fn recv(socket : &mut zmq::Socket) -> Result<Vec<zmq::Message>, zmq::Error> {
    let mut frames = Vec::new();
    loop {
        match socket.recv_msg(0) {
            Ok(m) => frames.push(m),
            Err(e) => return Err(e)
        }
        match socket.get_rcvmore() {
            Ok(true) => (),
            Ok(false) => return Ok(frames),
            Err(e) => return Err(e)
        }
    }
}

pub fn send<U:capnp::message::MessageBuilder>(
    socket : &mut zmq::Socket, message : & U)
                  -> Result<(), zmq::Error>{

    message.get_segments_for_output(|segments| {
            for ii in range(0, segments.len()) {
                let flags = if ii == segments.len() - 1 { 0 } else { zmq::SNDMORE };
                match socket.send(slice_cast(segments[ii]), flags) {
                    Ok(_) => {}
                    Err(_) => {fail!();} // XXX
                }
            }
        });

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Implement Serialize and Deserialize for JoinRule.<commit_after><|endoftext|>


<commit_before><commit_msg>Unimplemented move hotfix<commit_after><|endoftext|>


<commit_before><commit_msg>added a world tick method<commit_after><|endoftext|>


<commit_before><commit_msg>Collecting metrics _might_ block.<commit_after><|endoftext|>


<commit_before><commit_msg> rookie mistake: forgot the file<commit_after>use std::convert::From;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ExampleResult(Result<(), ()>);

impl ExampleResult {
    pub fn res(&self) -> Result<(), ()> {
        self.0
    }

    pub fn is_err(&self) -> bool { self.0.is_err() }
    pub fn is_ok(&self) -> bool { self.0.is_ok() }

    pub fn or<T: Into<ExampleResult>>(self, other: T) -> ExampleResult {
        match self.0 {
            Ok(_) => other.into(),
            Err(_) => self
        }
    }
}

pub static SUCCESS_RES : ExampleResult = ExampleResult(Ok(()));
pub static FAILED_RES : ExampleResult = ExampleResult(Err(()));

impl From<()> for ExampleResult {
    fn from(_other: ()) -> ExampleResult {
        SUCCESS_RES
    }
}

impl From<bool> for ExampleResult {
    fn from(other: bool) -> ExampleResult {
        if other {
            SUCCESS_RES
        } else {
            FAILED_RES
        }
    }
}

impl<T1,T2> From<Result<T1,T2>> for ExampleResult {
    fn from(other: Result<T1,T2>) -> ExampleResult {
        if other.is_ok() {
            SUCCESS_RES
        } else {
            FAILED_RES
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Fixes for clear<commit_after><|endoftext|>


<commit_before><commit_msg>Add result module<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::result::Result as RResult;

use error::AnnotationError;

pub type Result<T> = RResult<T, AnnotationError>;

<|endoftext|>


<commit_before><commit_msg>feat(*): add helper functions to get year month interval and date time interval<commit_after><|endoftext|>


<commit_before><commit_msg>Suck it up and just duplicate the strings for now<commit_after><|endoftext|>


<commit_before><commit_msg>Tidy up the correlation between texture objects with their combined image sampler uniforms<commit_after><|endoftext|>


<commit_before><commit_msg>entrance placement<commit_after><|endoftext|>


<commit_before><commit_msg>Added comment.<commit_after><|endoftext|>


<commit_before><commit_msg>replace service<commit_after><|endoftext|>


<commit_before><commit_msg>Update build.rs (#553) \n Nightly is required for compiling (#534)<commit_after><|endoftext|>


<commit_before><commit_msg>Change sql select queries to prepared statements.<commit_after><|endoftext|>


<commit_before><commit_msg>add 2.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the stream example.<commit_after><|endoftext|>