<commit_before><commit_msg>Rust: Problem 8<commit_after>/// # Largest product in a series
/// ## Problem 8
/// The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
/// Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

use std::iter::MultiplicativeIterator;
use std::cmp::max;

fn main() {
  let input = "73167176531330624919225119674426574742355349194934\
               96983520312774506326239578318016984801869478851843\
               85861560789112949495459501737958331952853208805511\
               12540698747158523863050715693290963295227443043557\
               66896648950445244523161731856403098711121722383113\
               62229893423380308135336276614282806444486645238749\
               30358907296290491560440772390713810515859307960866\
               70172427121883998797908792274921901699720888093776\
               65727333001053367881220235421809751254540594752243\
               52584907711670556013604839586446706324415722155397\
               53697817977846174064955149290862569321978468622482\
               83972241375657056057490261407972968652414535100474\
               82166370484403199890008895243450658541227588666881\
               16427171479924442928230863465674813919123162824586\
               17866458359124566529476545682848912883142607690042\
               24219022671055626321111109370544217506941658960408\
               07198403850962455444362981230987879927244284909188\
               84580156166097919133875499200524063689912560717606\
               05886116467109405077541002256983155200055935729725\
               71636269561882670428252483600823257530420752963450".chars();

  let mut nums = input.map(|c| c.to_digit(10).unwrap()).collect::<Vec<uint>>();
  let mut biggest = 0;

  for _ in range(0, nums.len() - 13) {
    biggest = max(biggest, nums.iter().take(13).map(|&n| n).product());
    nums.shift();
  }

  println!("{}", biggest);

}
<|endoftext|>


<commit_before>use redox::*;

use super::FromBytes;

const MZAP_ENT_LEN: usize = 64;
const MZAP_NAME_LEN: usize = MZAP_ENT_LEN - 8 - 4 - 2;

#[repr(u64)]
#[derive(Copy, Clone, Debug)]
pub enum ZapObjectType {
    Micro = (1 << 63) + 3,
    Header = (1 << 63) + 1,
    Leaf = 1 << 63,
}

/// Microzap
#[repr(packed)]
pub struct MZapPhys {
    block_type: ZapObjectType, // ZapObjectType::Micro
    salt: u64,
    norm_flags: u64,
    pad: [u64; 5],
    chunk: [MZapEntPhys; 1],
    // actually variable size depending on block size
}

impl FromBytes for MZapPhys {
    fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() >= mem::size_of::<MZapPhys>() {
            let mzap_phys = unsafe { ptr::read(data.as_ptr() as *const MZapPhys) };
            Some(mzap_phys)
        } else {
            Option::None
        }
    }
}

impl fmt::Debug for MZapPhys {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "MZapPhys {{\nblock_type: {:?},\nsalt: {:X},\nnorm_flags: {:X},\nchunk: [\n",
                    self.block_type, self.salt, self.norm_flags));
        for chunk in &self.chunk {
            try!(write!(f, "{:?}", chunk));
        }
        try!(write!(f, "] }}\n"));
        Ok(())
    }
}

#[repr(packed)]
pub struct MZapEntPhys{
    pub value: u64,
    pub cd: u32,
    pub pad: u16,
    pub name: [u8; MZAP_NAME_LEN],
}

impl fmt::Debug for MZapEntPhys {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "MZapEntPhys {{\nvalue: {:X},\ncd: {:X},\n",
                    self.value, self.cd));
        try!(write!(f, "}}\n"));
        Ok(())
    }
}

/// Fatzap
#[repr(packed)]
pub struct ZapPhys {
    pub block_type: ZapObjectType, // ZapObjectType::Header
    pub magic: u64,
    pub ptr_table: ZapTablePhys,
    pub free_block: u64,
    pub num_leafs: u64,
    pub num_entries: u64,
    pub salt: u64,
    pub pad: [u64; 8181],
    pub leafs: [u64; 8192],
}

#[repr(packed)]
pub struct ZapTablePhys {
     pub block: u64,
     pub num_blocks: u64,
     pub shift: u64,
     pub next_block: u64,
     pub block_copied: u64,
}

const ZAP_LEAF_MAGIC: u32 = 0x2AB1EAF;
const ZAP_LEAF_CHUNKSIZE: usize = 24;

// The amount of space within the chunk available for the array is:
// chunk size - space for type (1) - space for next pointer (2)
const ZAP_LEAF_ARRAY_BYTES: usize = ZAP_LEAF_CHUNKSIZE - 3;

/*pub struct ZapLeafPhys {
    pub header: ZapLeafHeader,
    hash: [u16; ZAP_LEAF_HASH_NUMENTRIES],
    union zap_leaf_chunk {
        entry,
        array,
        free,
    } chunks[ZapLeafChunk; ZAP_LEAF_NUMCHUNKS],
}*/

#[repr(packed)]
pub struct ZapLeafHeader {
    pub block_type: ZapObjectType, // ZapObjectType::Leaf
    pub next: u64,
    pub prefix: u64,
    pub magic: u32,
    pub n_free: u16,
    pub n_entries: u16,
    pub prefix_len: u16,
    pub free_list: u16,
    pad2: [u8; 12],
}

#[repr(packed)]
struct ZapLeafEntry {
    leaf_type: u8,
    int_size: u8,
    next: u16,
    name_chunk: u16,
    name_length: u16,
    value_chunk: u16,
    value_length: u16,
    cd: u16,
    pad: [u8; 2],
    hash: u64,
}

#[repr(packed)]
struct ZapLeafArray {
    leaf_type: u8,
    array: [u8; ZAP_LEAF_ARRAY_BYTES],
    next: u16,
}

#[repr(packed)]
struct ZapLeafFree{
    free_type: u8,
    pad: [u8; ZAP_LEAF_ARRAY_BYTES],
    next: u16,
}
<commit_msg>Show MZapEntPhys::name<commit_after>use redox::*;

use super::FromBytes;

const MZAP_ENT_LEN: usize = 64;
const MZAP_NAME_LEN: usize = MZAP_ENT_LEN - 8 - 4 - 2;

#[repr(u64)]
#[derive(Copy, Clone, Debug)]
pub enum ZapObjectType {
    Micro = (1 << 63) + 3,
    Header = (1 << 63) + 1,
    Leaf = 1 << 63,
}

/// Microzap
#[repr(packed)]
pub struct MZapPhys {
    block_type: ZapObjectType, // ZapObjectType::Micro
    salt: u64,
    norm_flags: u64,
    pad: [u64; 5],
    chunk: [MZapEntPhys; 1],
    // actually variable size depending on block size
}

impl FromBytes for MZapPhys {
    fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() >= mem::size_of::<MZapPhys>() {
            let mzap_phys = unsafe { ptr::read(data.as_ptr() as *const MZapPhys) };
            Some(mzap_phys)
        } else {
            Option::None
        }
    }
}

impl fmt::Debug for MZapPhys {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "MZapPhys {{\nblock_type: {:?},\nsalt: {:X},\nnorm_flags: {:X},\nchunk: [\n",
                    self.block_type, self.salt, self.norm_flags));
        for chunk in &self.chunk {
            try!(write!(f, "{:?}", chunk));
        }
        try!(write!(f, "] }}\n"));
        Ok(())
    }
}

#[repr(packed)]
pub struct MZapEntPhys{
    pub value: u64,
    pub cd: u32,
    pub pad: u16,
    pub name: [u8; MZAP_NAME_LEN],
}

impl fmt::Debug for MZapEntPhys {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "MZapEntPhys {{\nvalue: {:X},\ncd: {:X},\nname: ",
                    self.value, self.cd));
        for i in 0..MZAP_NAME_LEN {
            if self.name[i] == 0 {
                break;
            }
            try!(write!(f, "{}", self.name[i] as char));
        }
        try!(write!(f, "\n}}\n"));
        Ok(())
    }
}

/// Fatzap
#[repr(packed)]
pub struct ZapPhys {
    pub block_type: ZapObjectType, // ZapObjectType::Header
    pub magic: u64,
    pub ptr_table: ZapTablePhys,
    pub free_block: u64,
    pub num_leafs: u64,
    pub num_entries: u64,
    pub salt: u64,
    pub pad: [u64; 8181],
    pub leafs: [u64; 8192],
}

#[repr(packed)]
pub struct ZapTablePhys {
     pub block: u64,
     pub num_blocks: u64,
     pub shift: u64,
     pub next_block: u64,
     pub block_copied: u64,
}

const ZAP_LEAF_MAGIC: u32 = 0x2AB1EAF;
const ZAP_LEAF_CHUNKSIZE: usize = 24;

// The amount of space within the chunk available for the array is:
// chunk size - space for type (1) - space for next pointer (2)
const ZAP_LEAF_ARRAY_BYTES: usize = ZAP_LEAF_CHUNKSIZE - 3;

/*pub struct ZapLeafPhys {
    pub header: ZapLeafHeader,
    hash: [u16; ZAP_LEAF_HASH_NUMENTRIES],
    union zap_leaf_chunk {
        entry,
        array,
        free,
    } chunks[ZapLeafChunk; ZAP_LEAF_NUMCHUNKS],
}*/

#[repr(packed)]
pub struct ZapLeafHeader {
    pub block_type: ZapObjectType, // ZapObjectType::Leaf
    pub next: u64,
    pub prefix: u64,
    pub magic: u32,
    pub n_free: u16,
    pub n_entries: u16,
    pub prefix_len: u16,
    pub free_list: u16,
    pad2: [u8; 12],
}

#[repr(packed)]
struct ZapLeafEntry {
    leaf_type: u8,
    int_size: u8,
    next: u16,
    name_chunk: u16,
    name_length: u16,
    value_chunk: u16,
    value_length: u16,
    cd: u16,
    pad: [u8; 2],
    hash: u64,
}

#[repr(packed)]
struct ZapLeafArray {
    leaf_type: u8,
    array: [u8; ZAP_LEAF_ARRAY_BYTES],
    next: u16,
}

#[repr(packed)]
struct ZapLeafFree{
    free_type: u8,
    pad: [u8; ZAP_LEAF_ARRAY_BYTES],
    next: u16,
}
<|endoftext|>


<commit_before><commit_msg>Create Spa struct. One field down, lots more to go<commit_after>// Storage pool allocator
pub struct Spa {
    name: String, // Pool name
}
<|endoftext|>


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

/// Entry point of thread panic, for details, see std::macros
#[macro_export]
#[allow_internal_unstable]
#[stable(feature = "core", since = "1.6.0")]
macro_rules! panic {
    () => (
        panic!("explicit panic")
    );
    ($msg:expr) => ({
        static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!());
        $crate::panicking::panic(&_MSG_FILE_LINE)
    });
    ($fmt:expr, $($arg:tt)*) => ({
        // The leading _'s are to avoid dead code warnings if this is
        // used inside a dead function. Just `#[allow(dead_code)]` is
        // insufficient, since the user may have
        // `#[forbid(dead_code)]` and which cannot be overridden.
        static _FILE_LINE: (&'static str, u32) = (file!(), line!());
        $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
    });
}

/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// Assertions are always checked in both debug and release builds, and cannot
/// be disabled. See `debug_assert!` for assertions that are not enabled in
/// release builds by default.
///
/// Unsafe code relies on `assert!` to enforce run-time invariants that, if
/// violated could lead to unsafety.
///
/// Other use-cases of `assert!` include
/// [testing](https://doc.rust-lang.org/book/testing.html) and enforcing
/// run-time invariants in safe code (whose violation cannot result in unsafety).
///
/// This macro has a second version, where a custom panic message can be provided.
///
/// # Examples
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// assert!(true);
///
/// fn some_computation() -> bool { true } // a very simple function
///
/// assert!(some_computation());
///
/// // assert with a custom message
/// let x = true;
/// assert!(x, "x wasn't true!");
///
/// let a = 3; let b = 27;
/// assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! assert {
    ($cond:expr) => (
        if !$cond {
            panic!(concat!("assertion failed: ", stringify!($cond)))
        }
    );
    ($cond:expr, $($arg:tt)+) => (
        if !$cond {
            panic!($($arg)+)
        }
    );
}

/// Asserts that two expressions are equal to each other.
///
/// On panic, this macro will print the values of the expressions with their
/// debug representations.
///
/// # Examples
///
/// ```
/// let a = 3;
/// let b = 1 + 2;
/// assert_eq!(a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! assert_eq {
    ($left:expr , $right:expr) => ({
        match (&$left, &$right) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic!("assertion failed: `(left == right)` \
                           (left: `{:?}`, right: `{:?}`)", left_val, right_val)
                }
            }
        }
    });
    ($left:expr , $right:expr, $($arg:tt)*) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic!("assertion failed: `(left == right)` \
                           (left: `{:?}`, right: `{:?}`): {}", left_val, right_val,
                           format_args!($($arg)*))
                }
            }
        }
    });
}

/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// Like `assert!`, this macro also has a second version, where a custom panic
/// message can be provided.
///
/// Unlike `assert!`, `debug_assert!` statements are only enabled in non
/// optimized builds by default. An optimized build will omit all
/// `debug_assert!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert!` useful for checks that are too
/// expensive to be present in a release build but may be helpful during
/// development.
///
/// An unchecked assertion allows a program in an inconsistent state to keep
/// running, which might have unexpected consequences but does not introduce
/// unsafety as long as this only happens in safe code. The performance cost
/// of assertions, is however, not measurable in general. Replacing `assert!`
/// with `debug_assert!` is thus only encouraged after thorough profiling, and
/// more importantly, only in safe code!
///
/// # Examples
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// debug_assert!(true);
///
/// fn some_expensive_computation() -> bool { true } // a very simple function
/// debug_assert!(some_expensive_computation());
///
/// // assert with a custom message
/// let x = true;
/// debug_assert!(x, "x wasn't true!");
///
/// let a = 3; let b = 27;
/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! debug_assert {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
}

/// Asserts that two expressions are equal to each other.
///
/// On panic, this macro will print the values of the expressions with their
/// debug representations.
///
/// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
/// optimized builds by default. An optimized build will omit all
/// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert_eq!` useful for checks that are too
/// expensive to be present in a release build but may be helpful during
/// development.
///
/// # Examples
///
/// ```
/// let a = 3;
/// let b = 1 + 2;
/// debug_assert_eq!(a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! debug_assert_eq {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
}

/// Helper macro for unwrapping `Result` values while returning early with an
/// error if the value of the expression is `Err`. Can only be used in
/// functions that return `Result` because of the early return of `Err` that
/// it provides.
///
/// # Examples
///
/// ```
/// use std::io;
/// use std::fs::File;
/// use std::io::prelude::*;
///
/// fn write_to_file_using_try() -> Result<(), io::Error> {
///     let mut file = try!(File::create("my_best_friends.txt"));
///     try!(file.write_all(b"This is a list of my best friends."));
///     println!("I wrote to the file");
///     Ok(())
/// }
/// // This is equivalent to:
/// fn write_to_file_using_match() -> Result<(), io::Error> {
///     let mut file = try!(File::create("my_best_friends.txt"));
///     match file.write_all(b"This is a list of my best friends.") {
///         Ok(v) => v,
///         Err(e) => return Err(e),
///     }
///     println!("I wrote to the file");
///     Ok(())
/// }
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! try {
    ($expr:expr) => (match $expr {
        $crate::result::Result::Ok(val) => val,
        $crate::result::Result::Err(err) => {
            return $crate::result::Result::Err($crate::convert::From::from(err))
        }
    })
}

/// Use the `format!` syntax to write data into a buffer.
///
/// This macro is typically used with a buffer of `&mut `[`Write`][write].
///
/// See [`std::fmt`][fmt] for more information on format syntax.
///
/// [fmt]: ../std/fmt/index.html
/// [write]: ../std/io/trait.Write.html
///
/// # Examples
///
/// ```
/// use std::io::Write;
///
/// let mut w = Vec::new();
/// write!(&mut w, "test").unwrap();
/// write!(&mut w, "formatted {}", "arguments").unwrap();
///
/// assert_eq!(w, b"testformatted arguments");
/// ```
#[macro_export]
#[stable(feature = "core", since = "1.6.0")]
macro_rules! write {
    ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
}

/// Use the `format!` syntax to write data into a buffer, appending a newline.
/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`)
/// alone (no additional CARRIAGE RETURN (`\r`/`U+000D`).
///
/// This macro is typically used with a buffer of `&mut `[`Write`][write].
///
/// See [`std::fmt`][fmt] for more information on format syntax.
///
/// [fmt]: ../std/fmt/index.html
/// [write]: ../std/io/trait.Write.html
///
/// # Examples
///
/// ```
/// use std::io::Write;
///
/// let mut w = Vec::new();
/// writeln!(&mut w, "test").unwrap();
/// writeln!(&mut w, "formatted {}", "arguments").unwrap();
///
/// assert_eq!(&w[..], "test\nformatted arguments\n".as_bytes());
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! writeln {
    ($dst:expr, $fmt:expr) => (
        write!($dst, concat!($fmt, "\n"))
    );
    ($dst:expr, $fmt:expr, $($arg:tt)*) => (
        write!($dst, concat!($fmt, "\n"), $($arg)*)
    );
}

/// A utility macro for indicating unreachable code.
///
/// This is useful any time that the compiler can't determine that some code is unreachable. For
/// example:
///
/// * Match arms with guard conditions.
/// * Loops that dynamically terminate.
/// * Iterators that dynamically terminate.
///
/// # Panics
///
/// This will always panic.
///
/// # Examples
///
/// Match arms:
///
/// ```
/// # #[allow(dead_code)]
/// fn foo(x: Option<i32>) {
///     match x {
///         Some(n) if n >= 0 => println!("Some(Non-negative)"),
///         Some(n) if n <  0 => println!("Some(Negative)"),
///         Some(_)           => unreachable!(), // compile error if commented out
///         None              => println!("None")
///     }
/// }
/// ```
///
/// Iterators:
///
/// ```
/// # #[allow(dead_code)]
/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
///     for i in 0.. {
///         if 3*i < i { panic!("u32 overflow"); }
///         if x < 3*i { return i-1; }
///     }
///     unreachable!();
/// }
/// ```
#[macro_export]
#[stable(feature = "core", since = "1.6.0")]
macro_rules! unreachable {
    () => ({
        panic!("internal error: entered unreachable code")
    });
    ($msg:expr) => ({
        unreachable!("{}", $msg)
    });
    ($fmt:expr, $($arg:tt)*) => ({
        panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
    });
}

/// A standardized placeholder for marking unfinished code. It panics with the
/// message `"not yet implemented"` when executed.
///
/// This can be useful if you are prototyping and are just looking to have your
/// code typecheck, or if you're implementing a trait that requires multiple
/// methods, and you're only planning on using one of them.
///
/// # Examples
///
/// Here's an example of some in-progress code. We have a trait `Foo`:
///
/// ```
/// trait Foo {
///     fn bar(&self);
///     fn baz(&self);
/// }
/// ```
///
/// We want to implement `Foo` on one of our types, but we also want to work on
/// just `bar()` first. In order for our code to compile, we need to implement
/// `baz()`, so we can use `unimplemented!`:
///
/// ```
/// # trait Foo {
/// #     fn bar(&self);
/// #     fn baz(&self);
/// # }
/// struct MyStruct;
///
/// impl Foo for MyStruct {
///     fn bar(&self) {
///         // implementation goes here
///     }
///
///     fn baz(&self) {
///         // let's not worry about implementing baz() for now
///         unimplemented!();
///     }
/// }
///
/// fn main() {
///     let s = MyStruct;
///     s.bar();
///
///     // we aren't even using baz() yet, so this is fine.
/// }
/// ```
#[macro_export]
#[stable(feature = "core", since = "1.6.0")]
macro_rules! unimplemented {
    () => (panic!("not yet implemented"))
}
<commit_msg>Rollup merge of #35279 - cengizIO:master, r=brson<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/// Entry point of thread panic, for details, see std::macros
#[macro_export]
#[allow_internal_unstable]
#[stable(feature = "core", since = "1.6.0")]
macro_rules! panic {
    () => (
        panic!("explicit panic")
    );
    ($msg:expr) => ({
        static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!());
        $crate::panicking::panic(&_MSG_FILE_LINE)
    });
    ($fmt:expr, $($arg:tt)*) => ({
        // The leading _'s are to avoid dead code warnings if this is
        // used inside a dead function. Just `#[allow(dead_code)]` is
        // insufficient, since the user may have
        // `#[forbid(dead_code)]` and which cannot be overridden.
        static _FILE_LINE: (&'static str, u32) = (file!(), line!());
        $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
    });
}

/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// Assertions are always checked in both debug and release builds, and cannot
/// be disabled. See `debug_assert!` for assertions that are not enabled in
/// release builds by default.
///
/// Unsafe code relies on `assert!` to enforce run-time invariants that, if
/// violated could lead to unsafety.
///
/// Other use-cases of `assert!` include
/// [testing](https://doc.rust-lang.org/book/testing.html) and enforcing
/// run-time invariants in safe code (whose violation cannot result in unsafety).
///
/// This macro has a second version, where a custom panic message can be provided.
///
/// # Examples
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// assert!(true);
///
/// fn some_computation() -> bool { true } // a very simple function
///
/// assert!(some_computation());
///
/// // assert with a custom message
/// let x = true;
/// assert!(x, "x wasn't true!");
///
/// let a = 3; let b = 27;
/// assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! assert {
    ($cond:expr) => (
        if !$cond {
            panic!(concat!("assertion failed: ", stringify!($cond)))
        }
    );
    ($cond:expr, $($arg:tt)+) => (
        if !$cond {
            panic!($($arg)+)
        }
    );
}

/// Asserts that two expressions are equal to each other.
///
/// On panic, this macro will print the values of the expressions with their
/// debug representations.
///
/// # Examples
///
/// ```
/// let a = 3;
/// let b = 1 + 2;
/// assert_eq!(a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! assert_eq {
    ($left:expr , $right:expr) => ({
        match (&$left, &$right) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic!("assertion failed: `(left == right)` \
                           (left: `{:?}`, right: `{:?}`)", left_val, right_val)
                }
            }
        }
    });
    ($left:expr , $right:expr, $($arg:tt)*) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic!("assertion failed: `(left == right)` \
                           (left: `{:?}`, right: `{:?}`): {}", left_val, right_val,
                           format_args!($($arg)*))
                }
            }
        }
    });
}

/// Ensure that a boolean expression is `true` at runtime.
///
/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// Like `assert!`, this macro also has a second version, where a custom panic
/// message can be provided.
///
/// Unlike `assert!`, `debug_assert!` statements are only enabled in non
/// optimized builds by default. An optimized build will omit all
/// `debug_assert!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert!` useful for checks that are too
/// expensive to be present in a release build but may be helpful during
/// development.
///
/// An unchecked assertion allows a program in an inconsistent state to keep
/// running, which might have unexpected consequences but does not introduce
/// unsafety as long as this only happens in safe code. The performance cost
/// of assertions, is however, not measurable in general. Replacing `assert!`
/// with `debug_assert!` is thus only encouraged after thorough profiling, and
/// more importantly, only in safe code!
///
/// # Examples
///
/// ```
/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// debug_assert!(true);
///
/// fn some_expensive_computation() -> bool { true } // a very simple function
/// debug_assert!(some_expensive_computation());
///
/// // assert with a custom message
/// let x = true;
/// debug_assert!(x, "x wasn't true!");
///
/// let a = 3; let b = 27;
/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! debug_assert {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
}

/// Asserts that two expressions are equal to each other.
///
/// On panic, this macro will print the values of the expressions with their
/// debug representations.
///
/// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
/// optimized builds by default. An optimized build will omit all
/// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert_eq!` useful for checks that are too
/// expensive to be present in a release build but may be helpful during
/// development.
///
/// # Examples
///
/// ```
/// let a = 3;
/// let b = 1 + 2;
/// debug_assert_eq!(a, b);
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! debug_assert_eq {
    ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
}

/// Helper macro for unwrapping `Result` values while returning early with an
/// error if the value of the expression is `Err`. Can only be used in
/// functions that return `Result` because of the early return of `Err` that
/// it provides.
///
/// # Examples
///
/// ```
/// use std::io;
/// use std::fs::File;
/// use std::io::prelude::*;
///
/// fn write_to_file_using_try() -> Result<(), io::Error> {
///     let mut file = try!(File::create("my_best_friends.txt"));
///     try!(file.write_all(b"This is a list of my best friends."));
///     println!("I wrote to the file");
///     Ok(())
/// }
/// // This is equivalent to:
/// fn write_to_file_using_match() -> Result<(), io::Error> {
///     let mut file = try!(File::create("my_best_friends.txt"));
///     match file.write_all(b"This is a list of my best friends.") {
///         Ok(v) => v,
///         Err(e) => return Err(e),
///     }
///     println!("I wrote to the file");
///     Ok(())
/// }
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! try {
    ($expr:expr) => (match $expr {
        $crate::result::Result::Ok(val) => val,
        $crate::result::Result::Err(err) => {
            return $crate::result::Result::Err($crate::convert::From::from(err))
        }
    })
}

/// Write formatted data into a buffer
///
/// This macro accepts any value with `write_fmt` method as a writer, a format string, and a list
/// of arguments to format.
///
/// `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] or
/// [`std::io::Write`][io_write] traits. These are sometimes called 'writers'.
///
/// Passed arguments will be formatted according to the specified format string and the resulting
/// string will be passed to the writer.
///
/// See [`std::fmt`][fmt] for more information on format syntax.
///
/// Return value is completely dependent on the 'write_fmt' method.
///
/// Common return values are: [`Result`][enum_result], [`io::Result`][type_result]
///
/// [fmt]: ../std/fmt/index.html
/// [fmt_write]: ../std/fmt/trait.Write.html
/// [io_write]: ../std/io/trait.Write.html
/// [enum_result]: ../std/result/enum.Result.html
/// [type_result]: ../std/io/type.Result.html
///
/// # Examples
///
/// ```
/// use std::io::Write;
///
/// let mut w = Vec::new();
/// write!(&mut w, "test").unwrap();
/// write!(&mut w, "formatted {}", "arguments").unwrap();
///
/// assert_eq!(w, b"testformatted arguments");
/// ```
#[macro_export]
#[stable(feature = "core", since = "1.6.0")]
macro_rules! write {
    ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
}

/// Write formatted data into a buffer, with appending a newline.
///
/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
/// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
///
/// This macro accepts any value with `write_fmt` method as a writer, a format string, and a list
/// of arguments to format.
///
/// `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] or
/// [`std::io::Write`][io_write] traits. These are sometimes called 'writers'.
///
/// Passed arguments will be formatted according to the specified format string and the resulting
/// string will be passed to the writer.
///
/// See [`std::fmt`][fmt] for more information on format syntax.
///
/// Return value is completely dependent on the 'write_fmt' method.
///
/// Common return values are: [`Result`][enum_result], [`io::Result`][type_result]
///
/// [fmt]: ../std/fmt/index.html
/// [fmt_write]: ../std/fmt/trait.Write.html
/// [io_write]: ../std/io/trait.Write.html
/// [enum_result]: ../std/result/enum.Result.html
/// [type_result]: ../std/io/type.Result.html
///
/// # Examples
///
/// ```
/// use std::io::Write;
///
/// let mut w = Vec::new();
/// writeln!(&mut w, "test").unwrap();
/// writeln!(&mut w, "formatted {}", "arguments").unwrap();
///
/// assert_eq!(&w[..], "test\nformatted arguments\n".as_bytes());
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! writeln {
    ($dst:expr, $fmt:expr) => (
        write!($dst, concat!($fmt, "\n"))
    );
    ($dst:expr, $fmt:expr, $($arg:tt)*) => (
        write!($dst, concat!($fmt, "\n"), $($arg)*)
    );
}

/// A utility macro for indicating unreachable code.
///
/// This is useful any time that the compiler can't determine that some code is unreachable. For
/// example:
///
/// * Match arms with guard conditions.
/// * Loops that dynamically terminate.
/// * Iterators that dynamically terminate.
///
/// # Panics
///
/// This will always panic.
///
/// # Examples
///
/// Match arms:
///
/// ```
/// # #[allow(dead_code)]
/// fn foo(x: Option<i32>) {
///     match x {
///         Some(n) if n >= 0 => println!("Some(Non-negative)"),
///         Some(n) if n <  0 => println!("Some(Negative)"),
///         Some(_)           => unreachable!(), // compile error if commented out
///         None              => println!("None")
///     }
/// }
/// ```
///
/// Iterators:
///
/// ```
/// # #[allow(dead_code)]
/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
///     for i in 0.. {
///         if 3*i < i { panic!("u32 overflow"); }
///         if x < 3*i { return i-1; }
///     }
///     unreachable!();
/// }
/// ```
#[macro_export]
#[stable(feature = "core", since = "1.6.0")]
macro_rules! unreachable {
    () => ({
        panic!("internal error: entered unreachable code")
    });
    ($msg:expr) => ({
        unreachable!("{}", $msg)
    });
    ($fmt:expr, $($arg:tt)*) => ({
        panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
    });
}

/// A standardized placeholder for marking unfinished code. It panics with the
/// message `"not yet implemented"` when executed.
///
/// This can be useful if you are prototyping and are just looking to have your
/// code typecheck, or if you're implementing a trait that requires multiple
/// methods, and you're only planning on using one of them.
///
/// # Examples
///
/// Here's an example of some in-progress code. We have a trait `Foo`:
///
/// ```
/// trait Foo {
///     fn bar(&self);
///     fn baz(&self);
/// }
/// ```
///
/// We want to implement `Foo` on one of our types, but we also want to work on
/// just `bar()` first. In order for our code to compile, we need to implement
/// `baz()`, so we can use `unimplemented!`:
///
/// ```
/// # trait Foo {
/// #     fn bar(&self);
/// #     fn baz(&self);
/// # }
/// struct MyStruct;
///
/// impl Foo for MyStruct {
///     fn bar(&self) {
///         // implementation goes here
///     }
///
///     fn baz(&self) {
///         // let's not worry about implementing baz() for now
///         unimplemented!();
///     }
/// }
///
/// fn main() {
///     let s = MyStruct;
///     s.bar();
///
///     // we aren't even using baz() yet, so this is fine.
/// }
/// ```
#[macro_export]
#[stable(feature = "core", since = "1.6.0")]
macro_rules! unimplemented {
    () => (panic!("not yet implemented"))
}
<|endoftext|>


<commit_before><commit_msg>Try to read status byte<commit_after><|endoftext|>


<commit_before><commit_msg>generic structs added<commit_after><|endoftext|>


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

// Regression test for issue #10682
// Nested `proc` usage can't use outer owned data

fn work(_: ~int) {}
fn foo(_: proc()) {}

pub fn main() {
  let a = ~1;
  foo(proc() { foo(proc() { work(a) }) })
}
<|endoftext|>


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

// Regression test for issue #27583. Unclear how useful this will be
// going forward, since the issue in question was EXTREMELY sensitive
// to compiler internals (like the precise numbering of nodes), but
// what the hey.

#![allow(warnings)]

use std::cell::Cell;
use std::marker::PhantomData;

pub trait Delegate<'tcx> { }

pub struct InferCtxt<'a, 'tcx: 'a> {
    x: PhantomData<&'a Cell<&'tcx ()>>
}

pub struct MemCategorizationContext<'t, 'a: 't, 'tcx : 'a> {
    x: &'t InferCtxt<'a, 'tcx>,
}

pub struct ExprUseVisitor<'d, 't, 'a: 't, 'tcx:'a+'d> {
    typer: &'t InferCtxt<'a, 'tcx>,
    mc: MemCategorizationContext<'t, 'a, 'tcx>,
    delegate: &'d mut (Delegate<'tcx>+'d),
}

impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> {
    pub fn new(delegate: &'d mut Delegate<'tcx>,
               typer: &'t InferCtxt<'a, 'tcx>)
               -> ExprUseVisitor<'d,'t,'a,'tcx>
    {
        ExprUseVisitor {
            typer: typer,
            mc: MemCategorizationContext::new(typer),
            delegate: delegate,
        }
    }
}

impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> {
    pub fn new(typer: &'t InferCtxt<'a, 'tcx>) -> MemCategorizationContext<'t, 'a, 'tcx> {
        MemCategorizationContext { x: typer }
    }
}

fn main() { }
<|endoftext|>


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

use std::cell::Cell;
use std::mem::swap;

// Just a grab bag of stuff that you wouldn't want to actually write.

fn strange() -> bool { let _x: bool = return true; }

fn funny() {
    fn f(_x: ()) { }
    f(return);
}

fn what() {
    fn the(x: &Cell<bool>) {
        return while !x.get() { x.set(true); };
    }
    let i = &Cell::new(false);
    let dont = {||the(i)};
    dont();
    assert!((i.get()));
}

fn zombiejesus() {
    loop {
        while (return) {
            if (return) {
                match (return) {
                    1 => {
                        if (return) {
                            return
                        } else {
                            return
                        }
                    }
                    _ => { return }
                };
            } else if (return) {
                return;
            }
        }
        if (return) { break; }
    }
}

fn notsure() {
    let mut _x: isize;
    let mut _y = (_x = 0) == (_x = 0);
    let mut _z = (_x = 0) < (_x = 0);
    let _a = (_x += 0) == (_x = 0);
    let _b = swap(&mut _y, &mut _z) == swap(&mut _y, &mut _z);
}

fn canttouchthis() -> usize {
    fn p() -> bool { true }
    let _a = (assert!((true)) == (assert!(p())));
    let _c = (assert!((p())) == ());
    let _b: bool = (println!("{}", 0) == (return 0));
}

fn angrydome() {
    loop { if break { } }
    let mut i = 0;
    loop { i += 1; if i == 1 { match (continue) { 1 => { }, _ => panic!("wat") } }
      break; }
}

fn evil_lincoln() { let _evil = println!("lincoln"); }

fn dots() {
    assert_eq!(String::from(".................................................."),
               format!("{:?}", .. .. .. .. .. .. .. .. .. .. .. .. ..
                               .. .. .. .. .. .. .. .. .. .. .. ..));
}

fn you_eight() {
    assert_eq!(8, {
        macro_rules! u8 {
            (u8) => {
                mod u8 {
                    pub fn u8<'u8>(u8: &'u8 u8) -> &'u8 u8 {
                        "u8";
                        u8
                    }
                }
            };
        }

        u8!(u8);
        let &u8: &u8 = u8::u8(&8u8);
        u8
    });
}

fn fishy() {
    assert_eq!(String::from("><>"),
               String::<>::from::<>("><>").chars::<>().rev::<>().collect::<String>());
}

pub fn main() {
    strange();
    funny();
    what();
    zombiejesus();
    notsure();
    canttouchthis();
    angrydome();
    evil_lincoln();
    dots();
    you_eight();
    fishy();
}
<commit_msg>add test<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::cell::Cell;
use std::mem::swap;

// Just a grab bag of stuff that you wouldn't want to actually write.

fn strange() -> bool { let _x: bool = return true; }

fn funny() {
    fn f(_x: ()) { }
    f(return);
}

fn what() {
    fn the(x: &Cell<bool>) {
        return while !x.get() { x.set(true); };
    }
    let i = &Cell::new(false);
    let dont = {||the(i)};
    dont();
    assert!((i.get()));
}

fn zombiejesus() {
    loop {
        while (return) {
            if (return) {
                match (return) {
                    1 => {
                        if (return) {
                            return
                        } else {
                            return
                        }
                    }
                    _ => { return }
                };
            } else if (return) {
                return;
            }
        }
        if (return) { break; }
    }
}

fn notsure() {
    let mut _x: isize;
    let mut _y = (_x = 0) == (_x = 0);
    let mut _z = (_x = 0) < (_x = 0);
    let _a = (_x += 0) == (_x = 0);
    let _b = swap(&mut _y, &mut _z) == swap(&mut _y, &mut _z);
}

fn canttouchthis() -> usize {
    fn p() -> bool { true }
    let _a = (assert!((true)) == (assert!(p())));
    let _c = (assert!((p())) == ());
    let _b: bool = (println!("{}", 0) == (return 0));
}

fn angrydome() {
    loop { if break { } }
    let mut i = 0;
    loop { i += 1; if i == 1 { match (continue) { 1 => { }, _ => panic!("wat") } }
      break; }
}

fn evil_lincoln() { let _evil = println!("lincoln"); }

fn dots() {
    assert_eq!(String::from(".................................................."),
               format!("{:?}", .. .. .. .. .. .. .. .. .. .. .. .. ..
                               .. .. .. .. .. .. .. .. .. .. .. ..));
}

fn you_eight() {
    assert_eq!(8, {
        macro_rules! u8 {
            (u8) => {
                mod u8 {
                    pub fn u8<'u8>(u8: &'u8 u8) -> &'u8 u8 {
                        "u8";
                        u8
                    }
                }
            };
        }

        u8!(u8);
        let &u8: &u8 = u8::u8(&8u8);
        u8
    });
}

fn fishy() {
    assert_eq!(String::from("><>"),
               String::<>::from::<>("><>").chars::<>().rev::<>().collect::<String>());
}

fn union() {
    union union<'union> { union: &'union union<'union>, }
}

pub fn main() {
    strange();
    funny();
    what();
    zombiejesus();
    notsure();
    canttouchthis();
    angrydome();
    evil_lincoln();
    dots();
    you_eight();
    fishy();
    union();
}
<|endoftext|>


<commit_before><commit_msg>De-duplicate by journey rid.<commit_after><|endoftext|>


<commit_before><commit_msg>test: Check native main() signature<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.

// Checks the signature of the implicitly generated native main()
// entry point. It must match C's `int main(int, char **)`.

fn main() {
}

// CHECK: define i32 @main(i32, i8**)
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #58725 - jamwt:fix-27949, r=Centril<commit_after>// run-pass
//
// At one time, the `==` operator (and other binary operators) did not
// support subtyping during type checking, and would therefore require
// LHS and RHS to be exactly identical--i.e. to have the same lifetimes.
//
// This was fixed in 1a7fb7dc78439a704f024609ce3dc0beb1386552.

#[derive(Copy, Clone)]
struct Input<'a> {
    foo: &'a u32
}

impl <'a> std::cmp::PartialEq<Input<'a>> for Input<'a> {
    fn eq(&self, other: &Input<'a>) -> bool {
        self.foo == other.foo
    }

    fn ne(&self, other: &Input<'a>) -> bool {
        self.foo != other.foo
    }
}

fn check_equal<'a, 'b>(x: Input<'a>, y: Input<'b>) -> bool {
    // Type checking error due to 'a != 'b prior to 1a7fb7dc78
    x == y
}

fn main() {
    let i = 1u32;
    let j = 1u32;
    let k = 2u32;

    let input_i = Input { foo: &i };
    let input_j = Input { foo: &j };
    let input_k = Input { foo: &k };
    assert!(check_equal(input_i, input_i));
    assert!(check_equal(input_i, input_j));
    assert!(!check_equal(input_i, input_k));
}
<|endoftext|>


<commit_before><commit_msg>Add user interface definition<commit_after>use clap::{Arg, App, SubCommand};

pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
    app
       .arg(Arg::with_name("diaryname")
            .long("diary")
            .short("d")
            .takes_value(true)
            .required(false)
            .help("Use other than default diary"))

        .subcommand(SubCommand::with_name("create")
                   .about("Create a diary entry")
                   .version("0.1")
                   .arg(Arg::with_name("no-edit")
                        .long("no-edit")
                        .short("e")
                        .takes_value(false)
                        .required(false)
                        .help("Do not edit after creating"))
                   )

        .subcommand(SubCommand::with_name("edit")
                   .about("Edit a diary entry")
                   .version("0.1")
                   .arg(Arg::with_name("datetime")
                        .long("datetime")
                        .short("d")
                        .takes_value(true)
                        .required(false)
                        .help("Specify the date and time which entry should be edited. If none is
                        specified, the last entry is edited. If the diary entry does not exist for
                        this time, this fails. Format: YYYY-MM-DDT[HH[:mm[:ss]]]"))
                   )

        .subcommand(SubCommand::with_name("list")
                   .about("List diary entries")
                   .version("0.1"))

        // TODO: Support deleting diary entries
        // .subcommand(SubCommand::with_name("delete")
        //            .about("Delete a diary entry")
        //            .version("0.1")
}

<|endoftext|>


<commit_before>use std::error::Error;
use std::result::Result as RResult;

use toml::{Table, Value};

pub mod error {
    use std::fmt::{Debug, Display, Formatter};
    use std::fmt;
    use std::error::Error;
    use toml;

    #[derive(Clone)]
    pub enum ParserErrorKind {
        TOMLParserErrors,
        MissingMainSection,
        MissingVersionInfo,
    }

    pub struct ParserError {
        kind: ParserErrorKind,
        cause: Option<Box<Error>>,
    }

    impl ParserError {

        pub fn new(k: ParserErrorKind, cause: Option<Box<Error>>) -> ParserError {
            ParserError {
                kind: k,
                cause: cause,
            }
        }

    }

    impl Debug for ParserError {

        fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
            try!(write!(f, "{:?}", self.description()));
            Ok(())
        }

    }

    impl Display for ParserError {

        fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
            try!(write!(f, "{}", self.description()));
            Ok(())
        }

    }

    impl Error for ParserError {

        fn description(&self) -> &str {
            match self.kind {
                ParserErrorKind::TOMLParserErrors   => "Several TOML-Parser-Errors",
                ParserErrorKind::MissingMainSection => "Missing main section",
                ParserErrorKind::MissingVersionInfo => "Missing version information in main section",
            }
        }

        fn cause(&self) -> Option<&Error> {
            self.cause.as_ref().map(|e| &**e)
        }

    }

}

use self::error::ParserErrorKind;
use self::error::ParserError;

/**
 * EntryHeader
 *
 * This is basically a wrapper around toml::Table which provides convenience to the user of the
 * librray.
 */
#[derive(Debug, Clone)]
pub struct EntryHeader {
    toml: Table,
}

pub type Result<V> = RResult<V, error::ParserError>;

/**
 * Wrapper type around file header (TOML) object
 */
impl EntryHeader {

    /**
     * Get a new header object with a already-filled toml table
     */
    pub fn new(toml: Table) -> EntryHeader {
        EntryHeader {
            toml: toml,
        }
    }

    /**
     * Get the table which lives in the background
     */
    pub fn toml(&self) -> &Table {
        &self.toml
    }

    pub fn parse(s: &str) -> Result<EntryHeader> {
        use toml::Parser;

        let mut parser = Parser::new(s);
        parser.parse()
            .ok_or(ParserError::new(ParserErrorKind::TOMLParserErrors, None))
            .and_then(|t| verify_header_consistency(t))
            .map(|t| EntryHeader::new(t))
    }

}

fn verify_header_consistency(t: Table) -> Result<Table> {
    if !has_main_section(&t) {
        Err(ParserError::new(ParserErrorKind::MissingMainSection, None))
    } else if !has_imag_version_in_main_section(&t) {
        Err(ParserError::new(ParserErrorKind::MissingVersionInfo, None))
    } else {
        Ok(t)
    }
}

fn has_main_section(t: &Table) -> bool {
    t.contains_key("imag") &&
        match t.get("imag") {
            Some(&Value::Table(_)) => true,
            Some(_)                => false,
            None                   => false,
        }
}

fn has_imag_version_in_main_section(t: &Table) -> bool {
    use semver::Version;

    match t.get("imag").unwrap() {
        &Value::Table(ref sec) => {
            sec.get("version")
                .and_then(|v| {
                    match v {
                        &Value::String(ref s) => {
                            Some(Version::parse(&s[..]).is_ok())
                        },
                        _                 => Some(false),
                    }
                })
                .unwrap_or(false)
        }
        _                  => false,
    }
}

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

    use toml::Value;

    #[test]
    fn test_imag_section() {
        use super::has_main_section;

        let mut map = BTreeMap::new();
        map.insert("imag".into(), Value::Table(BTreeMap::new()));

        assert!(has_main_section(&map));
    }

    #[test]
    fn test_imag_invalid_section_type() {
        use super::has_main_section;

        let mut map = BTreeMap::new();
        map.insert("imag".into(), Value::Boolean(false));

        assert!(!has_main_section(&map));
    }

    #[test]
    fn test_imag_abscent_main_section() {
        use super::has_main_section;

        let mut map = BTreeMap::new();
        map.insert("not_imag".into(), Value::Boolean(false));

        assert!(!has_main_section(&map));
    }

    #[test]
    fn test_main_section_without_version() {
        use super::has_imag_version_in_main_section;

        let mut map = BTreeMap::new();
        map.insert("imag".into(), Value::Table(BTreeMap::new()));

        assert!(!has_imag_version_in_main_section(&map));
    }

    #[test]
    fn test_main_section_with_version() {
        use super::has_imag_version_in_main_section;

        let mut map = BTreeMap::new();
        let mut sub = BTreeMap::new();
        sub.insert("version".into(), Value::String("0.0.0".into()));
        map.insert("imag".into(), Value::Table(sub));

        assert!(has_imag_version_in_main_section(&map));
    }

    #[test]
    fn test_main_section_with_version_in_wrong_type() {
        use super::has_imag_version_in_main_section;

        let mut map = BTreeMap::new();
        let mut sub = BTreeMap::new();
        sub.insert("version".into(), Value::Boolean(false));
        map.insert("imag".into(), Value::Table(sub));

        assert!(!has_imag_version_in_main_section(&map));
    }

    #[test]
    fn test_verification_good() {
        use super::verify_header_consistency;

        let mut header = BTreeMap::new();
        let sub = {
            let mut sub = BTreeMap::new();
            sub.insert("version".into(), Value::String(String::from("0.0.0")));

            Value::Table(sub)
        };

        header.insert("imag".into(), sub);

        assert!(verify_header_consistency(header).is_ok());
    }

    #[test]
    fn test_verification_invalid_versionstring() {
        use super::verify_header_consistency;

        let mut header = BTreeMap::new();
        let sub = {
            let mut sub = BTreeMap::new();
            sub.insert("version".into(), Value::String(String::from("000")));

            Value::Table(sub)
        };

        header.insert("imag".into(), sub);

        assert!(!verify_header_consistency(header).is_ok());
    }

    #[test]
    fn test_verification_current_version() {
        use version;

        use super::verify_header_consistency;

        let mut header = BTreeMap::new();
        let sub = {
            let mut sub = BTreeMap::new();
            sub.insert("version".into(), Value::String(version!()));

            Value::Table(sub)
        };

        header.insert("imag".into(), sub);

        assert!(verify_header_consistency(header).is_ok());
    }
}

<commit_msg>Dont pass the table to the header object, but generate it in ::new()<commit_after>use std::collections::BTreeMap;
use std::error::Error;
use std::result::Result as RResult;

use toml::{Table, Value};

use self::error::ParserErrorKind;
use self::error::ParserError;

pub mod error {
    use std::fmt::{Debug, Display, Formatter};
    use std::fmt;
    use std::error::Error;
    use toml;

    #[derive(Clone)]
    pub enum ParserErrorKind {
        TOMLParserErrors,
        MissingMainSection,
        MissingVersionInfo,
    }

    pub struct ParserError {
        kind: ParserErrorKind,
        cause: Option<Box<Error>>,
    }

    impl ParserError {

        pub fn new(k: ParserErrorKind, cause: Option<Box<Error>>) -> ParserError {
            ParserError {
                kind: k,
                cause: cause,
            }
        }

    }

    impl Debug for ParserError {

        fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
            try!(write!(f, "{:?}", self.description()));
            Ok(())
        }

    }

    impl Display for ParserError {

        fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
            try!(write!(f, "{}", self.description()));
            Ok(())
        }

    }

    impl Error for ParserError {

        fn description(&self) -> &str {
            match self.kind {
                ParserErrorKind::TOMLParserErrors   => "Several TOML-Parser-Errors",
                ParserErrorKind::MissingMainSection => "Missing main section",
                ParserErrorKind::MissingVersionInfo => "Missing version information in main section",
            }
        }

        fn cause(&self) -> Option<&Error> {
            self.cause.as_ref().map(|e| &**e)
        }

    }

}

/**
 * EntryHeader
 *
 * This is basically a wrapper around toml::Table which provides convenience to the user of the
 * librray.
 */
#[derive(Debug, Clone)]
pub struct EntryHeader {
    toml: Table,
}

pub type Result<V> = RResult<V, error::ParserError>;

/**
 * Wrapper type around file header (TOML) object
 */
impl EntryHeader {

    /**
     * Get a new header object with a already-filled toml table
     *
     * Default header values are inserted into the header object by default.
     */
    pub fn new() -> EntryHeader {
        EntryHeader {
            toml: BTreeMap::new(),
        }
    }

    /**
     * Get the table which lives in the background
     */
    pub fn toml(&self) -> &Table {
        &self.toml
    }

    pub fn parse(s: &str) -> Result<EntryHeader> {
        use toml::Parser;

        let mut parser = Parser::new(s);
        parser.parse()
            .ok_or(ParserError::new(ParserErrorKind::TOMLParserErrors, None))
            .and_then(|t| verify_header_consistency(t))
            .map(|t| {
                EntryHeader {
                    toml: t
                }
            })
    }

}

fn verify_header_consistency(t: Table) -> Result<Table> {
    if !has_main_section(&t) {
        Err(ParserError::new(ParserErrorKind::MissingMainSection, None))
    } else if !has_imag_version_in_main_section(&t) {
        Err(ParserError::new(ParserErrorKind::MissingVersionInfo, None))
    } else {
        Ok(t)
    }
}

fn has_main_section(t: &Table) -> bool {
    t.contains_key("imag") &&
        match t.get("imag") {
            Some(&Value::Table(_)) => true,
            Some(_)                => false,
            None                   => false,
        }
}

fn has_imag_version_in_main_section(t: &Table) -> bool {
    use semver::Version;

    match t.get("imag").unwrap() {
        &Value::Table(ref sec) => {
            sec.get("version")
                .and_then(|v| {
                    match v {
                        &Value::String(ref s) => {
                            Some(Version::parse(&s[..]).is_ok())
                        },
                        _                 => Some(false),
                    }
                })
                .unwrap_or(false)
        }
        _                  => false,
    }
}

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

    use toml::Value;

    #[test]
    fn test_imag_section() {
        use super::has_main_section;

        let mut map = BTreeMap::new();
        map.insert("imag".into(), Value::Table(BTreeMap::new()));

        assert!(has_main_section(&map));
    }

    #[test]
    fn test_imag_invalid_section_type() {
        use super::has_main_section;

        let mut map = BTreeMap::new();
        map.insert("imag".into(), Value::Boolean(false));

        assert!(!has_main_section(&map));
    }

    #[test]
    fn test_imag_abscent_main_section() {
        use super::has_main_section;

        let mut map = BTreeMap::new();
        map.insert("not_imag".into(), Value::Boolean(false));

        assert!(!has_main_section(&map));
    }

    #[test]
    fn test_main_section_without_version() {
        use super::has_imag_version_in_main_section;

        let mut map = BTreeMap::new();
        map.insert("imag".into(), Value::Table(BTreeMap::new()));

        assert!(!has_imag_version_in_main_section(&map));
    }

    #[test]
    fn test_main_section_with_version() {
        use super::has_imag_version_in_main_section;

        let mut map = BTreeMap::new();
        let mut sub = BTreeMap::new();
        sub.insert("version".into(), Value::String("0.0.0".into()));
        map.insert("imag".into(), Value::Table(sub));

        assert!(has_imag_version_in_main_section(&map));
    }

    #[test]
    fn test_main_section_with_version_in_wrong_type() {
        use super::has_imag_version_in_main_section;

        let mut map = BTreeMap::new();
        let mut sub = BTreeMap::new();
        sub.insert("version".into(), Value::Boolean(false));
        map.insert("imag".into(), Value::Table(sub));

        assert!(!has_imag_version_in_main_section(&map));
    }

    #[test]
    fn test_verification_good() {
        use super::verify_header_consistency;

        let mut header = BTreeMap::new();
        let sub = {
            let mut sub = BTreeMap::new();
            sub.insert("version".into(), Value::String(String::from("0.0.0")));

            Value::Table(sub)
        };

        header.insert("imag".into(), sub);

        assert!(verify_header_consistency(header).is_ok());
    }

    #[test]
    fn test_verification_invalid_versionstring() {
        use super::verify_header_consistency;

        let mut header = BTreeMap::new();
        let sub = {
            let mut sub = BTreeMap::new();
            sub.insert("version".into(), Value::String(String::from("000")));

            Value::Table(sub)
        };

        header.insert("imag".into(), sub);

        assert!(!verify_header_consistency(header).is_ok());
    }

    #[test]
    fn test_verification_current_version() {
        use version;

        use super::verify_header_consistency;

        let mut header = BTreeMap::new();
        let sub = {
            let mut sub = BTreeMap::new();
            sub.insert("version".into(), Value::String(version!()));

            Value::Table(sub)
        };

        header.insert("imag".into(), sub);

        assert!(verify_header_consistency(header).is_ok());
    }
}

<|endoftext|>


<commit_before><commit_msg>resolve test case<commit_after>mod x {
    pub fn g() -> uint {14}
}

fn main(){
    // should *not* shadow the module x:
    let x = 9;
    // use it to avoid warnings:
    x+3;
    assert_eq!(x::g(),14);
}
<|endoftext|>


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

pub fn main() {
    assert_eq!([1, 2, 3][..], vec![1, 2, 3][..]);
}
<|endoftext|>


<commit_before><commit_msg>Add solution to problem 20<commit_after>#[macro_use] extern crate libeuler;

extern crate num;
use num::bigint::{BigInt, ToBigInt};
use num::traits::{One, Zero};
/// n! means n × (n − 1) × ... × 3 × 2 × 1
///
/// For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
/// and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
///
/// Find the sum of the digits in the number 100!
fn main() {
    solutions! {
        sol naive {
            let mut sum = 0;
            for c in format!("{}", kinda_fact(100)).chars() {
                let v: i64 = c as i64 - '0' as i64;
                sum += v;
            }

            sum
        }
    }
}

fn kinda_fact(n: i64) -> BigInt {
    let ten = 10.to_bigint().unwrap();
    let nb = n.to_bigint().unwrap();

    match n {
        1 => BigInt::one(),
        n => match nb * kinda_fact(n - 1) {
            ref ret if ret % &ten == BigInt::zero() => ret / &ten,
            ret => ret
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Only print a backtrace the first time the signal handler is called.<commit_after><|endoftext|>


<commit_before><commit_msg>added Rust example<commit_after>
// compile with
// 	rustc --crate-type dylib rustplugin.rs
//          on windows:
//	rustc --crate-type cdylib -C opt-level=3 -C link-args=-s  -C prefer-dynamic rustplugin.rs

use std::os::raw::{c_void,c_char,c_uchar,c_int,c_uint,c_double};

const VOO_PLUGIN_API_VERSION: i32 = 2;

// display pixel data type
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[cfg(target_os = "macos")]
#[repr(C)]
pub struct voo_target_space_t
{
    x: c_uchar,
    r: c_uchar,
    g: c_uchar,
    b: c_uchar,
}
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[cfg(not(target_os = "macos"))]
#[repr(C)]
pub struct voo_target_space_t
{
    b: c_uchar,
    g: c_uchar,
    r: c_uchar,
    x: c_uchar,
}

#[allow(dead_code)]
#[allow(non_camel_case_types)]
pub enum voo_colorSpace_t {
    vooColorSpace_Unknown = -1,
    vooCS_YUV,
    vooCS_XYZ,
    vooCS_YIQ,
    vooCS_RGB,
    vooCS_Gray,
    vooCS_HSV,
    vooCS_YCgCo,
    vooCS_ICtCp
}

#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
pub enum voo_dataArrangement_t {
    vooDataArrangement_Unknown = -1,
    vooDA_planar_420,
    vooDA_planar_422,
    vooDA_planar_444,
    vooDA_planar_410,
    vooDA_planar_411,
    vooDA_uyvy,
    vooDA_yuyv,
    vooDA_yuy2,
    vooDA_nv12,
    vooDA_v210,
    vooDA_interleaved_410,
    vooDA_interleaved_411,
    vooDA_reserved0,
    vooDA_interleaved_422,
    vooDA_interleaved_444,
    vooDA_single,
    vooDA_singleDouble,
    vooDA_singleFloat,
    vooDA_planar_420double,
    vooDA_planar_422double,
    vooDA_planar_444double,
    vooDA_planar_410double,
    vooDA_planar_411double,
    vooDA_planar_420float,
    vooDA_planar_422float,
    vooDA_planar_444float,
    vooDA_planar_410float,
    vooDA_planar_411float,
    vooDA_rgb565,
    vooDA_rgb555,
    vooDA_r210,
    vooDA_v410,
    vooDA_yuv10,
    vooNumDataArrangements
}

#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
pub enum voo_channelOrder_t
{
    vooChannelOrder_Unknown = -1,

    vooCO_c123,
    vooCO_c231,
    vooCO_c312,

    vooCO_c213,
    vooCO_c321,
    vooCO_c132,

    vooCO_c123x,
    vooCO_c231x,
    vooCO_c312x,

    vooCO_c213x,
    vooCO_c321x,
    vooCO_c132x,

    vooNumChannelOrders
}

#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[repr(C)]
pub struct voo_sequence_t {

    pub filename: *const c_char,

    // video resolution
    pub width: c_int,
    pub height: c_int,

    // frames per seconds
    pub fps: c_double,

    // Color space, such as YUV, RGB etc.
    pub colorSpace: voo_colorSpace_t,

    // How the channels are packed or interleaved
    arrangement: voo_dataArrangement_t,

    // The order in which color channels are written
    channel_order: voo_channelOrder_t,

    // size in bytes of a single video frame in native format
    framesize: c_uint,

    // Bits per channel is normally 8 or 10-16 (valid bit depths are 1-16) (if integer)
    bitsPerChannel: c_int,

    // Whether the video shall be played upside down
    b_flipped: c_int,
    // Whether 16bit words shall be byte-swapped
    b_toggle_endian: c_int,
    // Whether the values (if integer) shall be treated as signed integers
    b_signed: c_int,

    reserved: [c_char; 32],

}

// structure vooya gives you in on_load_video( ... ).
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[repr(C)]
pub struct voo_app_info_t {

    // a handle to vooya's current window (what it is, is platform dependent)
    p_handle: *const c_void,

    // to trigger vooya to a reload a frame, use these like:
    //     p_app_info.pf_trigger_reload( app_info.p_reload_cargo )
    // note that this should happen not too often.
    p_reload_cargo: *const c_void,
	pf_trigger_reload: extern fn(p_reload_cargo: *const c_void) -> c_int,

	reserved: [c_char; 32],
}

// Structure you get in per-frame callback functions.
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[repr(C)]
pub struct voo_video_frame_metadata_t {

    // user data you might have provided in voo_describe( ... ) as voo_plugin_t::p_user
    p_user: *const c_void,

    // per-sequence user data you might have provided in voo_plugin_t::on_load_video( ... )
    p_user_video: *const c_void,

    // per-frame user data you might have provided in input_plugin_t::load( ... )
    p_user_frame: *const c_void,

    p_info: *const voo_sequence_t,  // info about the current sequence

    // frame number, beginning at zero
    frame_idx: c_uint,

    flags: c_int,

    reserved: [c_char; 32],

}

#[allow(dead_code)]
#[allow(non_upper_case_globals)]
const VOOPerFrameFlag_YouAlreadyProcessed: i32 = 0x01; // this frame has already been processed by you
#[allow(dead_code)]
#[allow(non_upper_case_globals)]
const VOOPerFrameFlag_IsFromCache:         i32 = 0x02; // this one comes from RGB-display cache
#[allow(dead_code)]
#[allow(non_upper_case_globals)]
const VOOPerFrameFlag_IsDifference:        i32 = 0x04; // this frame is a difference frame

// PLUGIN CALLBACK FUNCTION STRUCT
//
// This struct shall contain user-defined callback functions along with some metadata.
// First the callback types:
#[allow(dead_code)]
#[allow(non_camel_case_types)]
enum vooya_callback_type_t {
    vooCallback_Native,
    vooCallback_RGBOut,
    vooCallback_EOTF,
    vooCallback_Histogram
}

#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[repr(C)]
pub struct vooya_callback_t
{
	// The following strings must be set and be persistent throughout plugin's linkage.
	// uid must not be empty or NULL.
	uid: *const c_char,         // a unique string, e.g. "myplugin.rgb_invert.1",
	                            // at most 63 chars in length, ANSI without any whitespace
	name: *const c_char,        // a user-friendly, descriptive name
	description: *const c_char, // a more in-depth description

    // Functions vooya will call upon user's (de)selection of this callback (optional)
    on_select: unsafe extern fn( p_info: *const voo_sequence_t, p_app_info: *const voo_app_info_t, p_user: *const c_void, pp_user_video: *const *mut c_void ) -> (),
    on_deselect: unsafe extern fn( p_user: *const c_void, p_user_video: *const c_void ) -> (),

    // Flags to signal something to vooya (for future use)
    flags: i32,

    // type determines which callback signature will be called
    e_type: vooya_callback_type_t,

	// actual callback function (required, see below)
	method: *const c_void,

	// For type == vooCallback_RGBOut:
	// Called by vooya for each video frame with rgb data ready to be rendered,
	// i.e. color-converted, range-shifted to 8bit and with EOTF and image
	// adjustments applied. Can be used to feed the data outside of vooya as
	// well as to alter the data right before display.
	// Stride in bytes is equal to width*sizeof(voo_target_space_t).
	//   method shall be:
	// unsafe extern fn( p_data: *mut voo_target_space_t, p_metadata: *const voo_video_frame_metadata_t ) -> (),

	// For type == vooCallback_Native:
	// Called by vooya for each video frame with native data before color
	// conversion to RGB 8bit, and without image adjustments. Can be used to
	// feed the data outside of vooya. Properties like resolution
	// and data format are given beforehand in on_load_video( ... ); you can
	// save them in p_metadata->p_user_video. "p_data" is the image data.
	//   method shall be
	// unsafe extern fn( p_data: *mut c_uchar, p_metadata: *const voo_video_frame_metadata_t ) -> (),

	// For type == vooCallback_EOTF:
	// Called by vooya when a lookup-table for the transfer function is being made.
	// "value" is in the range of 0-1, representing an RGB channel value of input bit
	// depth ("bits"). "p_user" might be provided by you from within voo_describe(...)
	// and can be NULL or any custom data. The call of this function happens before
	// application of brightness, contrast, gamma and exposure user settings.
	//   method shall be:
	// unsafe extern fn( value: c_double, bits: c_int, p_user: *const c_void ) -> c_double,

	// For type == vooCallback_Histogram:
	// Called by vooya for each frame if histogram calculation (and display) is enabled.
	// The three pointers contain the histograms for each channel respectively. Their
	// length is (1<<bit_depth)-1 (floating point data is put into 12bits).
	//   method shall be:
	// unsafe extern fn( p_h1: *const c_uint, p_h2: *const c_uint, p_h3: *const c_uint,
	//                               p_metadata: *const voo_video_frame_metadata_t ) -> (),
}

// INPUT DESCRIPTION STRUCT
//
// Container to provide custom input to vooya from file or from "nowhere".
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[repr(C)]
struct input_plugin_t {

	uid: *const c_char,         // a unique string, e.g. "myplugin.text.input",
	                            // at most 63 chars in length, ANSI without any whitespace
	name: *const c_char,        // a user-friendly, descriptive name (mandatory)
	description: *const c_char, // a more in-depth description

	// If b_fileBased is TRUE, vooya will ask for file suffixes supported by this input,
	// call file_suffixes( ... ), responsible( ... ) and open( ... ), and will include
	// this input in the file open dialog. If b_fileBased is FALSE, an entry for this input
	// will be displayed in the plugins-menu that the user can select as current input.
	// In that case, vooya will call open_nowhere( ... ).
	b_fileBased: i32,

	// Flags to signal something to vooya (for future use)
	flags: i32,

    reserved1: [c_char; 8],

	// If the input is file-based, responsible will be called with the file name and the
	// first sixteen bytes of data, which e.g. might contain magic data. p_user is
	// voo_plugin_t::p_user. If responsible returns TRUE, open will be called.
	// Only if input comes from stdin and "--container [your input UID]" is specified,
	// responsible will not be called, but open( ... ) directly.
	// For stdin, the filename is simply "-".
	//       FIXME: filename not a c_char in Windows
	responsible: unsafe extern fn( filename: *const c_char, sixteen_bytes: *const c_char, p_user: *const c_void ) -> c_int,
	// The global p_user pointer you may have set in voo_describe( ... )
	// is given here as *pp_user_seq, but you can alter it. In that case, subsequent
	// calls to methods of this struct will have the new, per-sequence value. This is
	// important on macOS, where multiple instances of this input may exist.
	open: unsafe extern fn( filename: *const c_char, p_app_info: *const voo_app_info_t, pp_user_seq: *const *mut c_void ) -> c_int,

	// If the input is not based on file input (b_fileBased is FALSE),
	// open_nowhere will be called. The global p_user pointer you may have set in
	// voo_describe( ... ) is given here as *pp_user_seq, but you can alter it.
	// In that case, subsequent calls to methods of this struct will have the new,
	// per-sequence value. This is important on macOS, where multiple instances
	// of this input may exist.
	open_nowhere: unsafe extern fn( p_app_info: *const voo_app_info_t, pp_user_seq: *const *mut c_void ) -> c_int,

	// Called by vooya to get information about the video you provide.
	// You should fill p_info with correct information to make vooya play.
	get_properties: unsafe extern fn( p_info: *const voo_sequence_t, p_user_seq: *const c_void ) -> c_int,

	// Client shall return the number of frames available, or ~0U if no
	// framecount can be given (e.g. stdin).
	framecount: unsafe extern fn( p_user_seq: *const c_void ) -> c_uint,

	// Shall issue a seek by the client plugin to frame number "frame"
	seek: unsafe extern fn( frame: c_uint, p_user_seq: *const c_void ) -> c_int,

	// Load contents of frame number "frame" into p_buffer. p_buffer has a size
	// appropriate to the format given by the client in get_properties( ... ).
	// "pb_skipped" shall be set by the client to FALSE if the p_buffer has been filled
	// with data, or to TRUE if client decided to no reload the frame if e.g. "frame" is
	// repeated. "pp_user_frame" can hold custom data and is later available
	// in voo_video_frame_metadata_t::p_user_frame.
	load: unsafe extern fn( frame: c_uint, p_buffer: *const c_char, pb_skipped: *const c_int, pp_user_frame: *const *mut c_void, p_user_seq: *const c_void ) -> c_int,

	eof: unsafe extern fn( p_user_seq: *const c_void ) -> c_uint,
	good: unsafe extern fn( p_user_seq: *const c_void ) -> c_uint,
	reload: unsafe extern fn( p_user_seq: *const c_void ) -> c_uint,
	close: unsafe extern fn( p_user_seq: *const c_void ) -> (),

	// After open( ... ) or open_nowhere( ... ), this is called.
	// Set pp_err to an appropriate, persistent error message or to NULL.
	error_msg: unsafe extern fn( pp_err: *const *mut c_char, p_user_seq: *const c_void ) -> (),

	// Called by vooya to get supported file extensions. Those are then displayed in
	// the "Open file" dialog. vooya will start with idx=0, then increment idx and
	// call this again as long as you return TRUE. (only called when b_fileBased is true)
	file_suffixes: unsafe extern fn( idx: c_int, pp_suffix: *const *mut c_char, p_user_seq: *const c_void ) -> c_int,

	// Called by vooya to enumerate meta information tags about the video you provide.
	// idx is counting up for each call as long as TRUE is return. Return FALSE to finish the
	// enumeration. "buffer_k" char[64] and shall take a key, "buffer_v" char[1024] and
	// shall take a corresponding value.
	get_meta: unsafe extern fn( idx: c_int, buffer_k: *const c_char, buffer_v: *const c_char, p_user_seq: *const c_void ) -> c_int,

	// vooya gives you a callback that you might call whenever the sequence's number of frames
	// will change. Note that p_vooya_ctx must not be altered and is valid only as long as this input is bound.
//	void (*cb_seq_len_changed)( void (*seq_len_callback)( void *p_vooya_ctx, unsigned int new_len ), void *p_vooya_ctx );
	cb_seq_len_changed: unsafe extern fn( seq_len_callback: unsafe extern fn( p_vooya_ctx: *const c_void, new_len: c_uint ) -> (), p_vooya_ctx: *const c_void ) -> (),

    reserved2: [c_char; 32],
}

// Most important structure, this describes the plugin
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[repr(C)]
pub struct voo_plugin_t
{
	voo_version: c_int, // set this always to VOO_PLUGIN_API_VERSION

	// plugin's main name, user friendly description, copyright notice and version info
	name: *const c_char,
	description: *const c_char,
	copyright: *const c_char,
	version: *const c_char,

	// Flags to signal something to vooya (for future use)
	flags: c_int,

	// any user data that shall be forwarded by vooya into other callback
	// functions ("void *p_user" argument)
	p_user: *const c_void,

	// called by vooya before the plugin is unloaded
	on_unload_plugin: extern fn( p_user: *const c_void ) -> (),

	reserved: [c_char; 48],

	// the plugin's callback functions
	callbacks: [vooya_callback_t; 10],

	// plugin's input capabilities. See input_plugin_t above.
	input: input_plugin_t
}

/*

	-------  actual plugin below -------

*/

const NAME: &'static [u8] = b"vooya Plugin Written in Rust\0";
const DESCR: &'static [u8] = b"Adds funny RGB callback to show Rust binding, hehe.\0";
const COPYRIGHT: &'static [u8] = b"(C) Arion Neddens 2016.\0";
const VERSION: &'static [u8] = b"ver 1.0\0";

const CB_UID: &'static [u8] = b"rust.callback.0\0";
const CB_NAME: &'static [u8] = b"Convert to gray (Rust)\0";
const CB_DESCR: &'static [u8] = b"Fun Function to show Rust bindings.\0";

// Main entry function that every plugin must implement to describe itself on startup.
// The "p_plugin"-structure is provided by vooya and to be filled in the implementation.
// This is the first function to be called and must be implemented.
#[no_mangle]
pub unsafe extern fn voo_describe( p_plugin: *mut voo_plugin_t )
{
	let ref mut p = *p_plugin;

	p.voo_version = VOO_PLUGIN_API_VERSION;
	p.name = NAME.as_ptr() as *const c_char;
	p.description = DESCR.as_ptr() as *const c_char;
	p.copyright = COPYRIGHT.as_ptr() as *const c_char;
	p.version = VERSION.as_ptr() as *const c_char;

	p.callbacks[0].uid = CB_UID.as_ptr() as *const c_char;
	p.callbacks[0].name = CB_NAME.as_ptr() as *const c_char;
	p.callbacks[0].description = CB_DESCR.as_ptr() as *const c_char;
	p.callbacks[0].e_type = vooya_callback_type_t::vooCallback_RGBOut;
	p.callbacks[0].method = twizzle as *const c_void;

}

// our function which does "something" with an rgb buffer.
#[no_mangle]
pub unsafe extern fn twizzle( p_data: *mut voo_target_space_t, p_metadata: *const voo_video_frame_metadata_t )
{
	let ref p_meta = *p_metadata;
	let ref p_seq_info = *(p_meta.p_info);

	if 0 != (p_meta.flags & VOOPerFrameFlag_IsFromCache) {
        return;
	}

    for y in 0..p_seq_info.height {

        for x in 0..p_seq_info.width {

  			let ref mut p: voo_target_space_t = *p_data.offset( (x + p_seq_info.width * y) as isize );
            let luma : i32 = (130 * p.r as i32 + 256 * p.g as i32 + 50 * p.b as i32) >> 8;
			p.r = std::cmp::min( 255, luma ) as u8;
			p.g = std::cmp::min( 255, luma ) as u8;
			p.b = std::cmp::min( 255, luma ) as u8;
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>checkpoint<commit_after>use core::raw::Slice;

use self::syscalls::wait;

#[derive(Clone,Copy)]
struct Chunk {
    inuse: bool,
    slice: Slice<u8>
}

struct App {
    mem: Slice<u8>,
    offset: usize,
    chunks: [Option<Chunk>; 100]
}

static mut app : *mut App = 0 as *mut App;

pub fn _start(mem_start: *mut u8, mem_size: usize) {
    let myapp = unsafe {
        app = mem_start as *mut App;
        &mut *app
    };
    myapp.mem = Slice { data: mem_start, len: mem_size };
    myapp.offset = 0;
    myapp.chunks = [None; 100];

    init();

    loop {
        wait();
    }
}

fn init(){
}

struct Box<T: ?Sized>{ pointer: *mut T }

impl<T> Box<T> {

    fn new(x: T) -> Box<T> {
        use core::mem;
        let myapp = unsafe { &mut *app };
        let size = mem::size_of::<T>();

        // First, see if there is an available chunk of the right size
        for chunk in myapp.chunks.iter_mut() {
            match *chunk {
                Some(mut chunk) => {
                    if !chunk.inuse && chunk.slice.len >= size {
                        chunk.inuse = true;
                        return Box { pointer: chunk.slice.data as *mut T };
                    }
                },
                None => { }
            }
        }

        // No existing chunks match, so allocate a new one
        match myapp.chunks.iter_mut().filter(|c| c.is_none()).next() {
            Some(slot) => {
                let chunk = Chunk {
                    slice: Slice {
                        data: unsafe {
                            myapp.mem.data.offset(myapp.offset as isize)
                        },
                        len: size
                    },
                    inuse: true
                };
                myapp.offset += size;
                *slot = Some(chunk);
                Box{ pointer: chunk.slice.data as *mut T }
            },
            None => {
                panic!("OOM")
            }
        }
    }
}

mod syscalls {

    #[allow(improper_ctypes)]
    extern {
        fn __allow(driver_num: usize, allownum: usize, ptr: *mut (), len: usize) -> isize;
        fn __subscribe(driver_num: usize, subnum: usize, cb: usize) -> isize;
        fn __command(driver_num: usize, cmdnum: usize, arg1: usize) -> isize;
        fn __wait() -> isize;
    }

    pub fn allow(driver_num: usize, allownum: usize, ptr: *mut (), len: usize) -> isize {
        unsafe {
            __allow(driver_num, allownum, ptr, len)
        }
    }

    pub fn command(driver_num: usize, cmdnum: usize, arg1: usize) -> isize {
        unsafe {
            __command(driver_num, cmdnum, arg1)
        }
    }

    pub fn subscribe(driver_num: usize, cmdnum: usize, callback: usize) -> isize {
        unsafe {
            __subscribe(driver_num, cmdnum, callback)
        }
    }

    pub fn wait() -> isize {
        unsafe {
            __wait()
        }
    }
}

mod tmp006 {
    use super::syscalls::{command, subscribe};

    pub fn enable_tmp006() {
        command(2, 0, 0);
    }

    pub fn subscribe_temperature(f: fn(i16)) {
        subscribe(2, 0, f as usize);
    }
}

mod console {
    use super::syscalls::{allow, command, subscribe};

    pub fn putc(c: char) {
        command(0, 0, c as usize);
    }

    pub fn subscribe_read_line(buf: *mut u8, len: usize,
                               f: fn(usize, *mut u8)) -> isize {
        let res =  allow(0, 0, buf as *mut (), len);
        if res < 0 {
            res
        } else {
            subscribe(0, 0, f as usize)
        }
    }

    pub fn subscribe_write_done(f: fn()) -> isize {
        subscribe(0, 1, f as usize)
    }
}

mod gpio {
    use super::syscalls::command;

    pub fn enable_pin(pin: usize) {
        command(1, 0, pin);
    }

    pub fn set_pin(pin: usize) {
        command(1, 2, pin);
    }

    pub fn clear_pin(pin: usize) {
        command(1, 3, pin);
    }

    pub fn toggle_pin(pin: usize) {
        command(1, 4, pin);
    }
}

<|endoftext|>


<commit_before><commit_msg>Don't omit semicolon after assertion<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for issue 36804<commit_after>// check-pass
#![feature(specialization)]

pub struct Cloned<I>(I);

impl<'a, I, T: 'a> Iterator for Cloned<I>
where
    I: Iterator<Item = &'a T>,
    T: Clone,
{
    type Item = T;

    fn next(&mut self) -> Option<T> {
        unimplemented!()
    }
}

impl<'a, I, T: 'a> Iterator for Cloned<I>
where
    I: Iterator<Item = &'a T>,
    T: Copy,
{
    fn count(self) -> usize {
        unimplemented!()
    }
}

fn main() {
    let a = [1,2,3,4];
    Cloned(a.iter()).count();
}
<|endoftext|>


<commit_before>extern crate clap;
#[macro_use] extern crate log;
extern crate semver;
#[macro_use] extern crate version;

extern crate libimagnotes;
extern crate libimagrt;
extern crate libimagentrytag;
extern crate libimagutil;

use std::process::exit;

use libimagrt::edit::Edit;
use libimagrt::runtime::Runtime;
use libimagnotes::note::Note;
use libimagutil::trace::trace_error;

mod ui;
use ui::build_ui;

fn main() {
    let name = "imag-notes";
    let version = &version!()[..];
    let about = "Note taking helper";
    let ui = build_ui(Runtime::get_default_cli_builder(name, version, about));
    let rt = {
        let rt = Runtime::new(ui);
        if rt.is_ok() {
            rt.unwrap()
        } else {
            println!("Could not set up Runtime");
            println!("{:?}", rt.err().unwrap());
            exit(1);
        }
    };

    rt.cli()
        .subcommand_name()
        .map(|name| {
            debug!("Call: {}", name);
            match name {
                "create" => create(&rt),
                "delete" => delete(&rt),
                "edit"   => edit(&rt),
                "list"   => list(&rt),
                _        => {
                    debug!("Unknown command"); // More error handling
                },
            };
        });
}

fn name_from_cli(rt: &Runtime, subcmd: &str) -> String {
    rt.cli().subcommand_matches(subcmd).unwrap().value_of("name").map(String::from).unwrap()
}

fn create(rt: &Runtime) {
    let name = name_from_cli(rt, "create");
    Note::new(rt.store(), name.clone(), String::new())
        .map_err(|e| trace_error(&e))
        .ok();

    if rt.cli().subcommand_matches("create").unwrap().is_present("edit") {
        if !edit_entry(rt, name) {
            exit(1);
        }
    }
}

fn delete(rt: &Runtime) {
    Note::delete(rt.store(), String::from(name_from_cli(rt, "delete")))
        .map_err(|e| trace_error(&e))
        .map(|_| println!("Ok"))
        .ok();
}

fn edit(rt: &Runtime) {
    edit_entry(rt, name_from_cli(rt, "edit"));
}

fn edit_entry(rt: &Runtime, name: String) -> bool {
    let note = Note::retrieve(rt.store(), name);
    if note.is_err() {
        trace_error(&note.err().unwrap());
        warn!("Cannot edit nonexistent Note");
        return false
    }

    let mut note = note.unwrap();
    if let Err(e) = note.edit_content(rt) {
        trace_error(&e);
        warn!("Editing failed");
        return false
    }
    true
}

fn list(rt: &Runtime) {
    use std::cmp::Ordering;

    let iter = Note::all_notes(rt.store());
    if iter.is_err() {
        trace_error(&iter.err().unwrap());
        exit(1);
    }

    let mut iter = iter.unwrap()
        .filter_map(|note| {
            match note {
                Err(e) => {
                    trace_error(&e);
                    None
                },
                Ok(e) => Some(e)
            }
        })
        .collect::<Vec<Note>>();

    iter.sort_by(|note_a, note_b| {
        if let (Ok(a), Ok(b)) = (note_a.get_name(), note_b.get_name()) {
            return a.cmp(&b)
        } else {
            return Ordering::Greater;
        }
    });

    for note in iter {
        note.get_name()
            .map(|name| println!("{}", name))
            .map_err(|e| trace_error(&e))
            .ok();
    }
}

<commit_msg>imag-notes: Replace .err().unwrap() with .unwrap_err()<commit_after>extern crate clap;
#[macro_use] extern crate log;
extern crate semver;
#[macro_use] extern crate version;

extern crate libimagnotes;
extern crate libimagrt;
extern crate libimagentrytag;
extern crate libimagutil;

use std::process::exit;

use libimagrt::edit::Edit;
use libimagrt::runtime::Runtime;
use libimagnotes::note::Note;
use libimagutil::trace::trace_error;

mod ui;
use ui::build_ui;

fn main() {
    let name = "imag-notes";
    let version = &version!()[..];
    let about = "Note taking helper";
    let ui = build_ui(Runtime::get_default_cli_builder(name, version, about));
    let rt = {
        let rt = Runtime::new(ui);
        if rt.is_ok() {
            rt.unwrap()
        } else {
            println!("Could not set up Runtime");
            println!("{:?}", rt.unwrap_err());
            exit(1);
        }
    };

    rt.cli()
        .subcommand_name()
        .map(|name| {
            debug!("Call: {}", name);
            match name {
                "create" => create(&rt),
                "delete" => delete(&rt),
                "edit"   => edit(&rt),
                "list"   => list(&rt),
                _        => {
                    debug!("Unknown command"); // More error handling
                },
            };
        });
}

fn name_from_cli(rt: &Runtime, subcmd: &str) -> String {
    rt.cli().subcommand_matches(subcmd).unwrap().value_of("name").map(String::from).unwrap()
}

fn create(rt: &Runtime) {
    let name = name_from_cli(rt, "create");
    Note::new(rt.store(), name.clone(), String::new())
        .map_err(|e| trace_error(&e))
        .ok();

    if rt.cli().subcommand_matches("create").unwrap().is_present("edit") {
        if !edit_entry(rt, name) {
            exit(1);
        }
    }
}

fn delete(rt: &Runtime) {
    Note::delete(rt.store(), String::from(name_from_cli(rt, "delete")))
        .map_err(|e| trace_error(&e))
        .map(|_| println!("Ok"))
        .ok();
}

fn edit(rt: &Runtime) {
    edit_entry(rt, name_from_cli(rt, "edit"));
}

fn edit_entry(rt: &Runtime, name: String) -> bool {
    let note = Note::retrieve(rt.store(), name);
    if note.is_err() {
        trace_error(&note.unwrap_err());
        warn!("Cannot edit nonexistent Note");
        return false
    }

    let mut note = note.unwrap();
    if let Err(e) = note.edit_content(rt) {
        trace_error(&e);
        warn!("Editing failed");
        return false
    }
    true
}

fn list(rt: &Runtime) {
    use std::cmp::Ordering;

    let iter = Note::all_notes(rt.store());
    if iter.is_err() {
        trace_error(&iter.unwrap_err());
        exit(1);
    }

    let mut iter = iter.unwrap()
        .filter_map(|note| {
            match note {
                Err(e) => {
                    trace_error(&e);
                    None
                },
                Ok(e) => Some(e)
            }
        })
        .collect::<Vec<Note>>();

    iter.sort_by(|note_a, note_b| {
        if let (Ok(a), Ok(b)) = (note_a.get_name(), note_b.get_name()) {
            return a.cmp(&b)
        } else {
            return Ordering::Greater;
        }
    });

    for note in iter {
        note.get_name()
            .map(|name| println!("{}", name))
            .map_err(|e| trace_error(&e))
            .ok();
    }
}

<|endoftext|>


<commit_before><commit_msg>Only need to wait for a single thread to timeout<commit_after><|endoftext|>


<commit_before><commit_msg>more work done on tableau<commit_after><|endoftext|>


<commit_before><commit_msg>Read the headers at index creation.<commit_after><|endoftext|>