<commit_before>use super::{VirtualAddress, PhysicalAddress, Page, PAGE_SIZE, ENTRY_COUNT};
use super::table::P4;
use super::entry::{PRESENT, HUGE_PAGE};
use memory::Frame;

pub fn translate(virtual_address: VirtualAddress) -> Option<PhysicalAddress> {
    let page = Page::containing_address(virtual_address);
    let offset = virtual_address % PAGE_SIZE;

    let p4 = unsafe { &*P4 };

    let huge_page = || {
        p4.next_table(page.p4_index())
          .and_then(|p3| {
              // 1GiB page?
              if p3[page.p3_index()].flags().contains(HUGE_PAGE | PRESENT) {
                  let start_frame_number = p3[page.p3_index()].pointed_frame().number;
                  // address must be 1GiB aligned
                  assert!(start_frame_number % (ENTRY_COUNT * ENTRY_COUNT) == 0);
                  return Some(start_frame_number + page.p2_index() * ENTRY_COUNT + page.p1_index());
              }
              if let Some(p2) = p3.next_table(page.p3_index()) {
                  // 2MiB page?
                  if p2[page.p2_index()].flags().contains(HUGE_PAGE | PRESENT) {
                      let start_frame_number = p2[page.p2_index()].pointed_frame().number;
                      // address must be 2MiB aligned
                      assert!(start_frame_number % ENTRY_COUNT == 0);
                      return Some(start_frame_number + page.p1_index());
                  }
              }
              None
          })
          .map(|start_frame_number| Frame { number: start_frame_number })
    };

    p4.next_table(page.p4_index())
      .and_then(|p3| p3.next_table(page.p3_index()))
      .and_then(|p2| p2.next_table(page.p2_index()))
      .map(|p1| p1[page.p1_index()].pointed_frame())
      .or_else(huge_page)
      .map(|frame| frame.number * PAGE_SIZE + offset)
}
<commit_msg>Split translate into `translate_page` and rest<commit_after>use super::{VirtualAddress, PhysicalAddress, Page, PAGE_SIZE, ENTRY_COUNT};
use super::table::P4;
use super::entry::{PRESENT, HUGE_PAGE};
use memory::Frame;

pub fn translate(virtual_address: VirtualAddress) -> Option<PhysicalAddress> {
    let offset = virtual_address % PAGE_SIZE;
    translate_page(Page::containing_address(virtual_address))
        .map(|frame| frame.number * PAGE_SIZE + offset)
}

fn translate_page(page: Page) -> Option<Frame> {
    let p4 = unsafe { &*P4 };

    let huge_page = || {
        p4.next_table(page.p4_index())
          .and_then(|p3| {
              // 1GiB page?
              if p3[page.p3_index()].flags().contains(HUGE_PAGE | PRESENT) {
                  let start_frame_number = p3[page.p3_index()].pointed_frame().number;
                  // address must be 1GiB aligned
                  assert!(start_frame_number % (ENTRY_COUNT * ENTRY_COUNT) == 0);
                  return Some(start_frame_number + page.p2_index() * ENTRY_COUNT + page.p1_index());
              }
              if let Some(p2) = p3.next_table(page.p3_index()) {
                  // 2MiB page?
                  if p2[page.p2_index()].flags().contains(HUGE_PAGE | PRESENT) {
                      let start_frame_number = p2[page.p2_index()].pointed_frame().number;
                      // address must be 2MiB aligned
                      assert!(start_frame_number % ENTRY_COUNT == 0);
                      return Some(start_frame_number + page.p1_index());
                  }
              }
              None
          })
          .map(|start_frame_number| Frame { number: start_frame_number })
    };

    p4.next_table(page.p4_index())
      .and_then(|p3| p3.next_table(page.p3_index()))
      .and_then(|p2| p2.next_table(page.p2_index()))
      .map(|p1| p1[page.p1_index()].pointed_frame())
      .or_else(huge_page)
}
<|endoftext|>


<commit_before>#![allow(dead_code)]
use std::ops::{Deref, DerefMut};

use uuid::Uuid;
use rustwlc::WlcView;

use ::layout::{Tree, Layout, TreeError};

type TestTreeResult = Result<UnitTestTree, TreeError>;

/// A tree that has some utility methods to aid in creating unit tests.
#[derive(Debug)]
pub struct UnitTestTree(Tree);

#[allow(dead_code)]
impl UnitTestTree {
    pub fn new() -> Self {
        UnitTestTree (
            Tree::new()
        )
    }

    /// Attempts to add an output to the tree.
    pub fn add_new_output(mut self) -> TestTreeResult {
        let fake_output = WlcView::root().as_output();
        self.0.add_output(fake_output)?;
        Ok(self)
    }

    /// Switches to a workspace, which is the default workspace
    /// for all the subsequent operations.
    ///
    /// NOTE If you don't add anything to this workspace, it will be
    /// removed if you switch to another one.
    pub fn add_workspace(mut self, name: &str) -> TestTreeResult {
        self.0.switch_to_workspace(name)?;
        assert_eq!(self.0.current_workspace()?, name);
        Ok(self)
    }

    /// Sets the active container to the given layout.
    pub fn set_layout(mut self, layout: Layout) -> TestTreeResult {
        self.0.set_active_layout(layout)?;
        Ok(self)
    }

    /// Adds a view, and sets it as the active container
    pub fn add_new_view(mut self) -> TestTreeResult {
        let fake_view = WlcView::root();
        self.0.add_view(fake_view)?;
        Ok(self)
    }

    /// Focuses on the `Container` associated with the UUID.
    ///
    /// If the container is floating, it is not set to be the active container,
    /// per the spec.
    pub fn focus_on(mut self, id: Uuid) -> TestTreeResult {
        self.0.focus(id)?;
        Ok(self)
    }
}

impl Deref for UnitTestTree {
    type Target = Tree;

    fn deref(&self) -> &Tree {
        &self.0
    }
}

impl DerefMut for UnitTestTree {
    fn deref_mut(&mut self) -> &mut Tree {
        &mut self.0
    }
}

/// Makes a very basic tree. This is sufficient for basic tests.
/// There is only one output,
/// Two workspaces,
/// First workspace has a single view in the root container,
/// second workspace has a container with two views in it
/// (the container is a child of the root container).
///
/// The active container is the only view in the first workspace
pub fn basic_tree() -> UnitTestTree {
    UnitTestTree::new()
        .add_new_output().unwrap()
        .add_workspace("1").unwrap()
        .add_new_view().unwrap()
        .add_workspace("2").unwrap()
        .add_new_view().unwrap()
        .set_layout(Layout::Horizontal).unwrap()
        .add_new_view().unwrap()
        .add_workspace("1").unwrap()
}

<commit_msg>Further clarified the error<commit_after>#![allow(dead_code)]
use std::ops::{Deref, DerefMut};

use uuid::Uuid;
use rustwlc::WlcView;

use ::layout::{Tree, Layout, TreeError};

type TestTreeResult = Result<UnitTestTree, TreeError>;

/// A tree that has some utility methods to aid in creating unit tests.
#[derive(Debug)]
pub struct UnitTestTree(Tree);

#[allow(dead_code)]
impl UnitTestTree {
    pub fn new() -> Self {
        UnitTestTree (
            Tree::new()
        )
    }

    /// Attempts to add an output to the tree.
    pub fn add_new_output(mut self) -> TestTreeResult {
        let fake_output = WlcView::root().as_output();
        self.0.add_output(fake_output)?;
        Ok(self)
    }

    /// Switches to a workspace, which is the default workspace
    /// for all the subsequent operations.
    ///
    /// NOTE If you don't add anything to this workspace, it will be
    /// removed if you switch to another one.
    pub fn add_workspace(mut self, name: &str) -> TestTreeResult {
        self.0.switch_to_workspace(name)?;
        {
            let cur_workspace_name = self.0.current_workspace()
                .expect("After switching workspace, not focused on a container");
            assert_eq!(cur_workspace_name, name);
        }
        Ok(self)
    }

    /// Sets the active container to the given layout.
    pub fn set_layout(mut self, layout: Layout) -> TestTreeResult {
        self.0.set_active_layout(layout)?;
        Ok(self)
    }

    /// Adds a view, and sets it as the active container
    pub fn add_new_view(mut self) -> TestTreeResult {
        let fake_view = WlcView::root();
        self.0.add_view(fake_view)?;
        Ok(self)
    }

    /// Focuses on the `Container` associated with the UUID.
    ///
    /// If the container is floating, it is not set to be the active container,
    /// per the spec.
    pub fn focus_on(mut self, id: Uuid) -> TestTreeResult {
        self.0.focus(id)?;
        Ok(self)
    }
}

impl Deref for UnitTestTree {
    type Target = Tree;

    fn deref(&self) -> &Tree {
        &self.0
    }
}

impl DerefMut for UnitTestTree {
    fn deref_mut(&mut self) -> &mut Tree {
        &mut self.0
    }
}

/// Makes a very basic tree. This is sufficient for basic tests.
/// There is only one output,
/// Two workspaces,
/// First workspace has a single view in the root container,
/// second workspace has a container with two views in it
/// (the container is a child of the root container).
///
/// The active container is the only view in the first workspace
pub fn basic_tree() -> UnitTestTree {
    UnitTestTree::new()
        .add_new_output().unwrap()
        .add_workspace("1").unwrap()
        .add_new_view().unwrap()
        .add_workspace("2").unwrap()
        .add_new_view().unwrap()
        .set_layout(Layout::Horizontal).unwrap()
        .add_new_view().unwrap()
        .add_workspace("1").unwrap()
}

<|endoftext|>


<commit_before>// TODO: Move into grammar

use std::io::{self, Write};

use super::Status;
use crate as ion_shell;
use crate::{shell::variables::Variables, types, Shell};
use builtins_proc::builtin;

fn print_list(vars: &Variables<'_>) {
    let stdout = io::stdout();
    let stdout = &mut stdout.lock();

    for (key, value) in vars.aliases() {
        writeln!(stdout, "{} = {}", key, value).unwrap();
    }
}

enum Binding {
    InvalidKey(types::Str),
    ListEntries,
    KeyOnly(types::Str),
    KeyValue(types::Str, types::Str),
}

/// Parses alias as a `(key, value)` tuple.
fn parse_alias(args: &str) -> Binding {
    // Write all the arguments into a single `String`
    let mut char_iter = args.chars();

    // Find the key and advance the iterator until the equals operator is found.
    let mut key = "".to_owned();
    let mut found_key = false;

    // Scans through characters until the key is found, then continues to scan until
    // the equals operator is found.
    while let Some(character) = char_iter.next() {
        match character {
            ' ' if key.is_empty() => (),
            ' ' => found_key = true,
            '=' => {
                found_key = true;
                break;
            }
            _ if !found_key => key.push(character),
            _ => (),
        }
    }

    let key: types::Str = key.into();

    if !found_key && key.is_empty() {
        Binding::ListEntries
    } else {
        let value: String = char_iter.skip_while(|&x| x == ' ').collect();
        if value.is_empty() {
            Binding::KeyOnly(key)
        } else if Variables::is_valid_variable_name(&key) {
            Binding::KeyValue(key, value.into())
        } else {
            Binding::InvalidKey(key)
        }
    }
}

/// The `alias` command will define an alias for another command, and thus may be used as a
/// command itself.
pub fn builtin_alias(args: &[types::Str], shell: &mut Shell<'_>) -> Status {
    match parse_alias(&args[1..].join(" ")) {
        Binding::InvalidKey(key) => {
            return Status::error(format!("ion: alias name, '{}', is invalid", key));
        }
        Binding::KeyValue(key, value) => {
            shell.variables_mut().set(&key, types::Alias(value));
        }
        Binding::ListEntries => print_list(shell.variables()),
        Binding::KeyOnly(key) => {
            return Status::error(format!("ion: please provide value for alias '{}'", key));
        }
    }
    Status::SUCCESS
}

/// Dropping an alias will erase it from the shell.
pub fn builtin_unalias(args: &[types::Str], shell: &mut Shell<'_>) -> Status {
    if args.len() <= 1 {
        return Status::error("ion: you must specify an alias name".to_string());
    }
    for alias in args.iter().skip(1) {
        if shell.variables_mut().remove(alias.as_ref()).is_none() {
            return Status::error(format!("ion: undefined alias: {}", alias));
        }
    }
    Status::SUCCESS
}

#[builtin(
    desc = "delete some variables or arrays",
    man = "
SYNOPSIS
    drop VARIABLES...

DESCRIPTION
    Deletes the variables given to it as arguments. The variables name must be supplied.
    Instead of '$x' use 'x'.
"
)]
/// Dropping a variable will erase it from the shell.
pub fn drop(args: &[types::Str], shell: &mut Shell<'_>) -> Status {
    if args.len() <= 1 {
        return Status::error("ion: you must specify a variable name".to_string());
    }

    for variable in args.iter().skip(1) {
        if shell.variables_mut().remove(variable.as_ref()).is_none() {
            return Status::error(format!("ion: undefined variable: {}", variable));
        }
    }

    Status::SUCCESS
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::expansion::Expander;

    fn vec_string(args: &[&str]) -> Vec<types::Str> { args.iter().map(|s| (*s).into()).collect() }

    // TODO: Rewrite tests now that let is part of the grammar.
    // #[test]
    // fn let_and_expand_a_variable() {
    //     let mut shell = Shell::default();
    //     let dir_stack = new_dir_stack();
    //     let_(&mut variables, vec!["let", "FOO", "=", "BAR"]);
    // let expanded = expand_string("$FOO", &variables, &dir_stack,
    // false).join("");     assert_eq!("BAR", &expanded);
    // }
    //
    // #[test]
    // fn let_fails_if_no_value() {
    //     let mut shell = Shell::default();
    //     let return_status = let_(&mut variables, vec!["let", "FOO"]);
    //     assert_eq!(FAILURE, return_status);
    // }
    //
    // #[test]
    // fn let_checks_variable_name() {
    //     let mut shell = Shell::default();
    // let return_status = let_(&mut variables, vec!["let", ",;!:", "=",
    // "FOO"]);     assert_eq!(FAILURE, return_status);
    // }

    #[test]
    fn drop_deletes_variable() {
        let mut shell = Shell::default();
        shell.variables_mut().set("FOO", "BAR");
        let return_status = builtin_drop(&vec_string(&["drop", "FOO"]), &mut shell);
        assert!(return_status.is_success());
        assert!(shell.expand_string("$FOO").is_err());
    }

    #[test]
    fn drop_fails_with_no_arguments() {
        let mut shell = Shell::default();
        let return_status = builtin_drop(&vec_string(&["drop"]), &mut shell);
        assert!(return_status.is_failure());
    }

    #[test]
    fn drop_fails_with_undefined_variable() {
        let mut shell = Shell::default();
        let return_status = builtin_drop(&vec_string(&["drop", "FOO"]), &mut shell);
        assert!(return_status.is_failure());
    }

    #[test]
    fn drop_deletes_array() {
        let mut shell = Shell::default();
        shell.variables_mut().set("FOO", types_rs::array!["BAR"]);
        let return_status = builtin_drop(&vec_string(&["drop", "FOO"]), &mut shell);
        assert_eq!(Status::SUCCESS, return_status);
        assert!(shell.expand_string("@FOO").is_err());
    }

    #[test]
    fn drop_array_fails_with_no_arguments() {
        let mut shell = Shell::default();
        let return_status = builtin_drop(&vec_string(&["drop"]), &mut shell);
        assert!(return_status.is_failure());
    }

    #[test]
    fn drop_array_fails_with_undefined_array() {
        let mut shell = Shell::default();
        let return_status = builtin_drop(&vec_string(&["drop", "FOO"]), &mut shell);
        assert!(return_status.is_failure());
    }
}
<commit_msg>feat: allow use of empty 'alias' (print if exists)<commit_after>// TODO: Move into grammar

use std::io::{self, Write};

use super::Status;
use crate as ion_shell;
use crate::{shell::variables::Variables, types, Shell};
use builtins_proc::builtin;

fn print_list(vars: &Variables<'_>) {
    let stdout = io::stdout();
    let stdout = &mut stdout.lock();

    for (key, value) in vars.aliases() {
        writeln!(stdout, "{} = {}", key, value).unwrap();
    }
}

enum Binding {
    InvalidKey(types::Str),
    ListEntries,
    KeyOnly(types::Str),
    KeyValue(types::Str, types::Str),
}

/// Parses alias as a `(key, value)` tuple.
fn parse_alias(args: &str) -> Binding {
    // Write all the arguments into a single `String`
    let mut char_iter = args.chars();

    // Find the key and advance the iterator until the equals operator is found.
    let mut key = "".to_owned();
    let mut found_key = false;

    // Scans through characters until the key is found, then continues to scan until
    // the equals operator is found.
    while let Some(character) = char_iter.next() {
        match character {
            ' ' if key.is_empty() => (),
            ' ' => found_key = true,
            '=' => {
                found_key = true;
                break;
            }
            _ if !found_key => key.push(character),
            _ => (),
        }
    }

    let key: types::Str = key.into();

    if !found_key && key.is_empty() {
        Binding::ListEntries
    } else {
        let value: String = char_iter.skip_while(|&x| x == ' ').collect();
        if value.is_empty() {
            Binding::KeyOnly(key)
        } else if Variables::is_valid_variable_name(&key) {
            Binding::KeyValue(key, value.into())
        } else {
            Binding::InvalidKey(key)
        }
    }
}

/// The `alias` command will define an alias for another command, and thus may be used as a
/// command itself.
pub fn builtin_alias(args: &[types::Str], shell: &mut Shell<'_>) -> Status {
    match parse_alias(&args[1..].join(" ")) {
        Binding::InvalidKey(key) => {
            return Status::error(format!("ion: alias name, '{}', is invalid", key));
        }
        Binding::KeyValue(key, value) => {
            shell.variables_mut().set(&key, types::Alias(value));
        }
        Binding::ListEntries => print_list(shell.variables()),
        Binding::KeyOnly(key) => {
            if let Some(alias) = shell.variables().get(&key) {
                println!("alias {}='{}'", key, alias);
            } else {
                return Status::error(format!("ion: alias '{}' not found", key));
            }
        }
    }
    Status::SUCCESS
}

/// Dropping an alias will erase it from the shell.
pub fn builtin_unalias(args: &[types::Str], shell: &mut Shell<'_>) -> Status {
    if args.len() <= 1 {
        return Status::error("ion: you must specify an alias name".to_string());
    }
    for alias in args.iter().skip(1) {
        if shell.variables_mut().remove(alias.as_ref()).is_none() {
            return Status::error(format!("ion: undefined alias: {}", alias));
        }
    }
    Status::SUCCESS
}

#[builtin(
    desc = "delete some variables or arrays",
    man = "
SYNOPSIS
    drop VARIABLES...

DESCRIPTION
    Deletes the variables given to it as arguments. The variables name must be supplied.
    Instead of '$x' use 'x'.
"
)]
/// Dropping a variable will erase it from the shell.
pub fn drop(args: &[types::Str], shell: &mut Shell<'_>) -> Status {
    if args.len() <= 1 {
        return Status::error("ion: you must specify a variable name".to_string());
    }

    for variable in args.iter().skip(1) {
        if shell.variables_mut().remove(variable.as_ref()).is_none() {
            return Status::error(format!("ion: undefined variable: {}", variable));
        }
    }

    Status::SUCCESS
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::expansion::Expander;

    fn vec_string(args: &[&str]) -> Vec<types::Str> { args.iter().map(|s| (*s).into()).collect() }

    // TODO: Rewrite tests now that let is part of the grammar.
    // #[test]
    // fn let_and_expand_a_variable() {
    //     let mut shell = Shell::default();
    //     let dir_stack = new_dir_stack();
    //     let_(&mut variables, vec!["let", "FOO", "=", "BAR"]);
    // let expanded = expand_string("$FOO", &variables, &dir_stack,
    // false).join("");     assert_eq!("BAR", &expanded);
    // }
    //
    // #[test]
    // fn let_fails_if_no_value() {
    //     let mut shell = Shell::default();
    //     let return_status = let_(&mut variables, vec!["let", "FOO"]);
    //     assert_eq!(FAILURE, return_status);
    // }
    //
    // #[test]
    // fn let_checks_variable_name() {
    //     let mut shell = Shell::default();
    // let return_status = let_(&mut variables, vec!["let", ",;!:", "=",
    // "FOO"]);     assert_eq!(FAILURE, return_status);
    // }

    #[test]
    fn drop_deletes_variable() {
        let mut shell = Shell::default();
        shell.variables_mut().set("FOO", "BAR");
        let return_status = builtin_drop(&vec_string(&["drop", "FOO"]), &mut shell);
        assert!(return_status.is_success());
        assert!(shell.expand_string("$FOO").is_err());
    }

    #[test]
    fn drop_fails_with_no_arguments() {
        let mut shell = Shell::default();
        let return_status = builtin_drop(&vec_string(&["drop"]), &mut shell);
        assert!(return_status.is_failure());
    }

    #[test]
    fn drop_fails_with_undefined_variable() {
        let mut shell = Shell::default();
        let return_status = builtin_drop(&vec_string(&["drop", "FOO"]), &mut shell);
        assert!(return_status.is_failure());
    }

    #[test]
    fn drop_deletes_array() {
        let mut shell = Shell::default();
        shell.variables_mut().set("FOO", types_rs::array!["BAR"]);
        let return_status = builtin_drop(&vec_string(&["drop", "FOO"]), &mut shell);
        assert_eq!(Status::SUCCESS, return_status);
        assert!(shell.expand_string("@FOO").is_err());
    }

    #[test]
    fn drop_array_fails_with_no_arguments() {
        let mut shell = Shell::default();
        let return_status = builtin_drop(&vec_string(&["drop"]), &mut shell);
        assert!(return_status.is_failure());
    }

    #[test]
    fn drop_array_fails_with_undefined_array() {
        let mut shell = Shell::default();
        let return_status = builtin_drop(&vec_string(&["drop", "FOO"]), &mut shell);
        assert!(return_status.is_failure());
    }
}
<|endoftext|>


<commit_before>// Copyright 2021 The Propverify authors
//
// 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.

/////////////////////////////////////////////////////////////////
// FFI wrapper for SeaHorn symbolic execution tool
/////////////////////////////////////////////////////////////////

use std::default::Default;
use core::panic::PanicInfo;

pub use crate::traits::*;

extern {
    fn __VERIFIER_error() -> !;
    fn __VERIFIER_assume(pred: i32);
}

#[no_mangle]
fn spanic(_info: &PanicInfo) -> ! {
    abort();
}

/// Reject the current execution with a verification failure.
///
/// In almost all circumstances, `report_error` should
/// be used instead because it generates an error message.
pub fn abort() -> ! {
    unsafe { __VERIFIER_error(); }
}

/// Assume that condition `cond` is true
///
/// Any paths found must satisfy this assumption.
pub fn assume(pred: bool) {
    if ! pred {
        unsafe { __VERIFIER_assume(0); }
    }
}

/// Reject the current execution path with a verification success.
/// This is equivalent to `assume(false)`
/// and the opposite of `report_error(...)`.
///
/// Typical usage is in generating symbolic values when the value
/// does not meet some criteria.
pub fn reject() -> ! {
    assume(false);
    panic!("Unreachable, should have been rejected!");
}

/// Detect whether the program is being run symbolically in KLEE
/// or being replayed using the kleeRuntest runtime.
///
/// This is used to decide whether to display the values of
/// variables that may be either symbolic or concrete.
pub fn is_replay() -> bool {
    panic!("SeaHorn doesn't support replay.")
}

/// Reject the current execution with a verification failure
/// and an error message.
pub fn report_error(message: &str) -> ! {
    // Mimic the format of klee_report_error
    // (We don't use klee_report_error because it is not
    // supported by the kleeRuntest library.)
    eprintln!("SEAHORN: ERROR:{}", message);
    abort();
}

/// Declare that failure is the expected behaviour
pub fn expect_raw(msg: &str) {
    eprintln!("VERIFIER_EXPECT: {}", msg)
}

/// Declare that failure is the expected behaviour
pub fn expect(msg: Option<&str>) {
    match msg {
        None => eprintln!("VERIFIER_EXPECT: should_panic"),
        Some(msg) => eprintln!("VERIFIER_EXPECT: should_panic(expected = \"{}\")", msg)
    }
}

macro_rules! make_nondet {
    ($typ:ty, $ext:ident, $v:expr) => {
        extern { fn $ext() -> $typ; }
        impl VerifierNonDet for $typ {
            fn verifier_nondet(self) -> Self {
                unsafe { $ext() }
            }
        }
    };
}

make_nondet!(u8, __VERIFIER_nondet_u8, 0);
make_nondet!(u16, __VERIFIER_nondet_u16, 0);
make_nondet!(u32, __VERIFIER_nondet_u32, 0);
make_nondet!(u64, __VERIFIER_nondet_u64, 0);
// make_nondet!(u128, __VERIFIER_nondet_u128, 0);
make_nondet!(usize, __VERIFIER_nondet_usize, 0);

make_nondet!(i8, __VERIFIER_nondet_i8, 0);
make_nondet!(i16, __VERIFIER_nondet_i16, 0);
make_nondet!(i32, __VERIFIER_nondet_i32, 0);
make_nondet!(i64, __VERIFIER_nondet_i64, 0);
// make_nondet!(i128, __VERIFIER_nondet_i128, 0);
make_nondet!(isize, __VERIFIER_nondet_isize, 0);

make_nondet!(f32, __VERIFIER_nondet_f32, 0.0);
make_nondet!(f64, __VERIFIER_nondet_f63, 0.0);

impl VerifierNonDet for bool {
    fn verifier_nondet(self) -> Self {
        let c = u8::verifier_nondet(0u8);
        assume(c == 0 || c == 1);
        c == 1
    }
}

impl <T: VerifierNonDet + Default> AbstractValue for T {
    fn abstract_value() -> Self {
        Self::verifier_nondet(Self::default())
    }
}

impl <T: VerifierNonDet + Default> Symbolic for T {
    fn symbolic(_desc: &'static str) -> Self {
        Self::verifier_nondet(Self::default())
    }
}

#[macro_export]
macro_rules! assert {
    ($cond:expr,) => { $crate::assert!($cond) };
    ($cond:expr) => { $crate::assert!($cond, "assertion failed: {}", stringify!($cond)) };
    ($cond:expr, $($arg:tt)+) => {{
        if ! $cond {
            let message = format!($($arg)+);
            eprintln!("VERIFIER: panicked at '{}', {}:{}:{}",
                      message,
                      std::file!(), std::line!(), std::column!());
            $crate::abort();
        }
    }}
}

#[macro_export]
macro_rules! assert_eq {
    ($left:expr, $right:expr) => {{
        let left = $left;
        let right = $right;
        $crate::assert!(
            left == right,
            "assertion failed: `(left == right)` \
             \n  left: `{:?}`,\n right: `{:?}`",
            left,
            right)
    }};
    ($left:expr, $right:expr, $fmt:tt $($arg:tt)*) => {{
        let left = $left;
        let right = $right;
        $crate::assert!(
            left == right,
            concat!(
                "assertion failed: `(left == right)` \
                 \n  left: `{:?}`, \n right: `{:?}`: ", $fmt),
            left, right $($arg)*);
    }};
}

#[macro_export]
macro_rules! assert_ne {
    ($left:expr, $right:expr) => {{
        let left = $left;
        let right = $right;
        $crate::assert!(
            left != right,
            "assertion failed: `(left != right)` \
             \n  left: `{:?}`,\n right: `{:?}`",
            left,
            right)
    }};
    ($left:expr, $right:expr, $fmt:tt $($arg:tt)*) => {{
        let left = $left;
        let right = $right;
        $crate::assert!(
            left != right,
            concat!(
                "assertion failed: `(left != right)` \
                 \n  left: `{:?}`, \n right: `{:?}`: ", $fmt),
            left, right $($arg)*);
    }};
}

/////////////////////////////////////////////////////////////////
// End
/////////////////////////////////////////////////////////////////
<commit_msg>Fix Seahorn nondet for f64, u128 and i128<commit_after>// Copyright 2021 The Propverify authors
//
// 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.

/////////////////////////////////////////////////////////////////
// FFI wrapper for SeaHorn symbolic execution tool
/////////////////////////////////////////////////////////////////

use core::panic::PanicInfo;
use std::default::Default;
use std::convert::TryInto;

pub use crate::traits::*;

extern {
    fn __VERIFIER_error() -> !;
    fn __VERIFIER_assume(pred: i32);
}

#[no_mangle]
fn spanic(_info: &PanicInfo) -> ! {
    abort();
}

/// Reject the current execution with a verification failure.
///
/// In almost all circumstances, `report_error` should
/// be used instead because it generates an error message.
pub fn abort() -> ! {
    unsafe { __VERIFIER_error(); }
}

/// Assume that condition `cond` is true
///
/// Any paths found must satisfy this assumption.
pub fn assume(pred: bool) {
    if ! pred {
        unsafe { __VERIFIER_assume(0); }
    }
}

/// Reject the current execution path with a verification success.
/// This is equivalent to `assume(false)`
/// and the opposite of `report_error(...)`.
///
/// Typical usage is in generating symbolic values when the value
/// does not meet some criteria.
pub fn reject() -> ! {
    assume(false);
    panic!("Unreachable, should have been rejected!");
}

/// Detect whether the program is being run symbolically in KLEE
/// or being replayed using the kleeRuntest runtime.
///
/// This is used to decide whether to display the values of
/// variables that may be either symbolic or concrete.
pub fn is_replay() -> bool {
    // panic!("SeaHorn doesn't support replay.")
    false
}

/// Reject the current execution with a verification failure
/// and an error message.
pub fn report_error(message: &str) -> ! {
    // Mimic the format of klee_report_error
    // (We don't use klee_report_error because it is not
    // supported by the kleeRuntest library.)
    eprintln!("SEAHORN: ERROR:{}", message);
    abort();
}

/// Declare that failure is the expected behaviour
pub fn expect_raw(msg: &str) {
    eprintln!("VERIFIER_EXPECT: {}", msg)
}

/// Declare that failure is the expected behaviour
pub fn expect(msg: Option<&str>) {
    match msg {
        None => eprintln!("VERIFIER_EXPECT: should_panic"),
        Some(msg) => eprintln!("VERIFIER_EXPECT: should_panic(expected = \"{}\")", msg)
    }
}

macro_rules! make_nondet {
    ($typ:ty, $ext:ident, $v:expr) => {
        extern { fn $ext() -> $typ; }
        impl VerifierNonDet for $typ {
            fn verifier_nondet(self) -> Self {
                unsafe { $ext() }
            }
        }
    };
}

make_nondet!(u8, __VERIFIER_nondet_u8, 0);
make_nondet!(u16, __VERIFIER_nondet_u16, 0);
make_nondet!(u32, __VERIFIER_nondet_u32, 0);
make_nondet!(u64, __VERIFIER_nondet_u64, 0);
make_nondet!(usize, __VERIFIER_nondet_usize, 0);

make_nondet!(i8, __VERIFIER_nondet_i8, 0);
make_nondet!(i16, __VERIFIER_nondet_i16, 0);
make_nondet!(i32, __VERIFIER_nondet_i32, 0);
make_nondet!(i64, __VERIFIER_nondet_i64, 0);
make_nondet!(isize, __VERIFIER_nondet_isize, 0);

make_nondet!(f32, __VERIFIER_nondet_f32, 0.0);
make_nondet!(f64, __VERIFIER_nondet_f64, 0.0);

macro_rules! make_nondet_ne_bytes {
    ($typ:ty) => {
        impl VerifierNonDet for $typ {
            fn verifier_nondet(self) -> Self {
                let mut bytes = vec![0u8; std::mem::size_of::<$typ>()];
                for i in 0..bytes.len() {
                    unsafe { bytes[i] = __VERIFIER_nondet_u8(); }
                }
                Self::from_ne_bytes(bytes[..].try_into().unwrap())
            }
        }
    };
}

make_nondet_ne_bytes!(u128);
make_nondet_ne_bytes!(i128);

impl VerifierNonDet for bool {
    fn verifier_nondet(self) -> Self {
        let c = u8::verifier_nondet(0u8);
        assume(c == 0 || c == 1);
        c == 1
    }
}

impl <T: VerifierNonDet + Default> AbstractValue for T {
    fn abstract_value() -> Self {
        Self::verifier_nondet(Self::default())
    }
}

impl <T: VerifierNonDet + Default> Symbolic for T {
    fn symbolic(_desc: &'static str) -> Self {
        Self::verifier_nondet(Self::default())
    }
}

#[macro_export]
macro_rules! assert {
    ($cond:expr,) => { $crate::assert!($cond) };
    ($cond:expr) => { $crate::assert!($cond, "assertion failed: {}", stringify!($cond)) };
    ($cond:expr, $($arg:tt)+) => {{
        if ! $cond {
            let message = format!($($arg)+);
            eprintln!("VERIFIER: panicked at '{}', {}:{}:{}",
                      message,
                      std::file!(), std::line!(), std::column!());
            $crate::abort();
        }
    }}
}

#[macro_export]
macro_rules! assert_eq {
    ($left:expr, $right:expr) => {{
        let left = $left;
        let right = $right;
        $crate::assert!(
            left == right,
            "assertion failed: `(left == right)` \
             \n  left: `{:?}`,\n right: `{:?}`",
            left,
            right)
    }};
    ($left:expr, $right:expr, $fmt:tt $($arg:tt)*) => {{
        let left = $left;
        let right = $right;
        $crate::assert!(
            left == right,
            concat!(
                "assertion failed: `(left == right)` \
                 \n  left: `{:?}`, \n right: `{:?}`: ", $fmt),
            left, right $($arg)*);
    }};
}

#[macro_export]
macro_rules! assert_ne {
    ($left:expr, $right:expr) => {{
        let left = $left;
        let right = $right;
        $crate::assert!(
            left != right,
            "assertion failed: `(left != right)` \
             \n  left: `{:?}`,\n right: `{:?}`",
            left,
            right)
    }};
    ($left:expr, $right:expr, $fmt:tt $($arg:tt)*) => {{
        let left = $left;
        let right = $right;
        $crate::assert!(
            left != right,
            concat!(
                "assertion failed: `(left != right)` \
                 \n  left: `{:?}`, \n right: `{:?}`: ", $fmt),
            left, right $($arg)*);
    }};
}

/////////////////////////////////////////////////////////////////
// End
/////////////////////////////////////////////////////////////////
<|endoftext|>


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

//! Unix-specific extensions to general I/O primitives

#![stable(feature = "rust1", since = "1.0.0")]

use fs;
use net;
use os::raw;
use sys;
use sys_common::{self, AsInner, FromInner, IntoInner};

/// Raw file descriptors.
#[stable(feature = "rust1", since = "1.0.0")]
pub type RawFd = raw::c_int;

/// A trait to extract the raw unix file descriptor from an underlying
/// object.
///
/// This is only available on unix platforms and must be imported in order
/// to call the method. Windows platforms have a corresponding `AsRawHandle`
/// and `AsRawSocket` set of traits.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRawFd {
    /// Extracts the raw file descriptor.
    ///
    /// This method does **not** pass ownership of the raw file descriptor
    /// to the caller. The descriptor is only guaranteed to be valid while
    /// the original object has not yet been destroyed.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_raw_fd(&self) -> RawFd;
}

/// A trait to express the ability to construct an object from a raw file
/// descriptor.
#[stable(feature = "from_raw_os", since = "1.1.0")]
pub trait FromRawFd {
    /// Constructs a new instance of `Self` from the given raw file
    /// descriptor.
    ///
    /// This function **consumes ownership** of the specified file
    /// descriptor. The returned object will take responsibility for closing
    /// it when the object goes out of scope.
    ///
    /// This function is also unsafe as the primitives currently returned
    /// have the contract that they are the sole owner of the file
    /// descriptor they are wrapping. Usage of this function could
    /// accidentally allow violating this contract which can cause memory
    /// unsafety in code that relies on it being true.
    #[stable(feature = "from_raw_os", since = "1.1.0")]
    unsafe fn from_raw_fd(fd: RawFd) -> Self;
}

/// A trait to express the ability to consume an object and acquire ownership of
/// its raw file descriptor.
#[stable(feature = "into_raw_os", since = "1.4.0")]
pub trait IntoRawFd {
    /// Consumes this object, returning the raw underlying file descriptor.
    ///
    /// This function **transfers ownership** of the underlying file descriptor
    /// to the caller. Callers are then the unique owners of the file descriptor
    /// and must close the descriptor once it's no longer needed.
    #[stable(feature = "into_raw_os", since = "1.4.0")]
    fn into_raw_fd(self) -> RawFd;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for RawFd {
    fn as_raw_fd(&self) -> RawFd {
        *self
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for fs::File {
    fn as_raw_fd(&self) -> RawFd {
        self.as_inner().fd().raw()
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for fs::File {
    unsafe fn from_raw_fd(fd: RawFd) -> fs::File {
        fs::File::from_inner(sys::fs::File::from_inner(fd))
    }
}

#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for RawFd {
    fn into_raw_fd(self) -> RawFd {
        self
    }
}

#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for fs::File {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_fd().into_raw()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::TcpStream {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::TcpListener {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::UdpSocket {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}

#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::TcpStream {
    unsafe fn from_raw_fd(fd: RawFd) -> net::TcpStream {
        let socket = sys::net::Socket::from_inner(fd);
        net::TcpStream::from_inner(sys_common::net::TcpStream::from_inner(socket))
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::TcpListener {
    unsafe fn from_raw_fd(fd: RawFd) -> net::TcpListener {
        let socket = sys::net::Socket::from_inner(fd);
        net::TcpListener::from_inner(sys_common::net::TcpListener::from_inner(socket))
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::UdpSocket {
    unsafe fn from_raw_fd(fd: RawFd) -> net::UdpSocket {
        let socket = sys::net::Socket::from_inner(fd);
        net::UdpSocket::from_inner(sys_common::net::UdpSocket::from_inner(socket))
    }
}

#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::TcpStream {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::TcpListener {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::UdpSocket {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
<commit_msg>Rollup merge of #41035 - jmesmon:revert-bad-raw-fd-impls, r=aturon<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.

//! Unix-specific extensions to general I/O primitives

#![stable(feature = "rust1", since = "1.0.0")]

use fs;
use net;
use os::raw;
use sys;
use sys_common::{self, AsInner, FromInner, IntoInner};

/// Raw file descriptors.
#[stable(feature = "rust1", since = "1.0.0")]
pub type RawFd = raw::c_int;

/// A trait to extract the raw unix file descriptor from an underlying
/// object.
///
/// This is only available on unix platforms and must be imported in order
/// to call the method. Windows platforms have a corresponding `AsRawHandle`
/// and `AsRawSocket` set of traits.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRawFd {
    /// Extracts the raw file descriptor.
    ///
    /// This method does **not** pass ownership of the raw file descriptor
    /// to the caller. The descriptor is only guaranteed to be valid while
    /// the original object has not yet been destroyed.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_raw_fd(&self) -> RawFd;
}

/// A trait to express the ability to construct an object from a raw file
/// descriptor.
#[stable(feature = "from_raw_os", since = "1.1.0")]
pub trait FromRawFd {
    /// Constructs a new instance of `Self` from the given raw file
    /// descriptor.
    ///
    /// This function **consumes ownership** of the specified file
    /// descriptor. The returned object will take responsibility for closing
    /// it when the object goes out of scope.
    ///
    /// This function is also unsafe as the primitives currently returned
    /// have the contract that they are the sole owner of the file
    /// descriptor they are wrapping. Usage of this function could
    /// accidentally allow violating this contract which can cause memory
    /// unsafety in code that relies on it being true.
    #[stable(feature = "from_raw_os", since = "1.1.0")]
    unsafe fn from_raw_fd(fd: RawFd) -> Self;
}

/// A trait to express the ability to consume an object and acquire ownership of
/// its raw file descriptor.
#[stable(feature = "into_raw_os", since = "1.4.0")]
pub trait IntoRawFd {
    /// Consumes this object, returning the raw underlying file descriptor.
    ///
    /// This function **transfers ownership** of the underlying file descriptor
    /// to the caller. Callers are then the unique owners of the file descriptor
    /// and must close the descriptor once it's no longer needed.
    #[stable(feature = "into_raw_os", since = "1.4.0")]
    fn into_raw_fd(self) -> RawFd;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for fs::File {
    fn as_raw_fd(&self) -> RawFd {
        self.as_inner().fd().raw()
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for fs::File {
    unsafe fn from_raw_fd(fd: RawFd) -> fs::File {
        fs::File::from_inner(sys::fs::File::from_inner(fd))
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for fs::File {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_fd().into_raw()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::TcpStream {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::TcpListener {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::UdpSocket {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}

#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::TcpStream {
    unsafe fn from_raw_fd(fd: RawFd) -> net::TcpStream {
        let socket = sys::net::Socket::from_inner(fd);
        net::TcpStream::from_inner(sys_common::net::TcpStream::from_inner(socket))
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::TcpListener {
    unsafe fn from_raw_fd(fd: RawFd) -> net::TcpListener {
        let socket = sys::net::Socket::from_inner(fd);
        net::TcpListener::from_inner(sys_common::net::TcpListener::from_inner(socket))
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::UdpSocket {
    unsafe fn from_raw_fd(fd: RawFd) -> net::UdpSocket {
        let socket = sys::net::Socket::from_inner(fd);
        net::UdpSocket::from_inner(sys_common::net::UdpSocket::from_inner(socket))
    }
}

#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::TcpStream {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::TcpListener {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::UdpSocket {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
<|endoftext|>


<commit_before>extern crate orbtk;

use orbtk::{Window, TextBox, Rect, Label, Event};
use orbtk::traits::{EventFilter, Place, Text};

fn main() {
    let mut window = Window::new(Rect::new(100, 100, 420, 420), "Filtered Textbox");

    let label = Label::new();
    label.text("Field below will ignore all 'e' chars.")
         .position(10, 10).size(400, 16);
    window.add(&label);

    let text_field = TextBox::new();
    text_field.position(10, 32).size(400, 28).event_filter(|_widget, event, _focused, _redraw| {
        match event {
            Event::KeyPressed(key_event) => {
                if let Some(character) = key_event.character {
                    if character == 'e' {
                        return None
                    }
                }
            }
            _ => {}
        }

        Some(event)
    });
    text_field.text_offset(6, 6);
    window.add(&text_field);

    let label = Label::new();
    label.text("Field below will only accept numbers \n(as defined by unicode)")
         .position(10, 32+28+6).size(400, 32);
    window.add(&label);

    let text_field = TextBox::new();
    text_field.position(10, 32+32+12+28).size(400, 28).event_filter(|_widget, event, _focused, _redraw| {
       match event {
            Event::KeyPressed (key_event) => {
                if let Some(character) = key_event.character {
                    if character.is_numeric() {
                        return Some(event)
                    }
                }
            },
            _ => {}
        }

        Some(event)
    });

    text_field.text_offset(6, 6);
    window.add(&text_field);

    window.exec();
}
<commit_msg>Modified examples/filtered.rs to fix the issue where the second textbox doesn't filter out letters.<commit_after>extern crate orbtk;

use orbtk::{Window, TextBox, Rect, Label, Event};
use orbtk::traits::{EventFilter, Place, Text};

fn main() {
    let mut window = Window::new(Rect::new(100, 100, 420, 420), "Filtered Textbox");

    let label = Label::new();
    label.text("Field below will ignore all 'e' chars.")
         .position(10, 10).size(400, 16);
    window.add(&label);

    let text_field = TextBox::new();
    text_field.position(10, 32).size(400, 28).event_filter(|_widget, event, _focused, _redraw| {
        match event {
            Event::KeyPressed(key_event) => {
                if let Some(character) = key_event.character {
                    if character == 'e' {
                        return None
                    }
                }
            }
            _ => {}
        }

        Some(event)
    });
    text_field.text_offset(6, 6);
    window.add(&text_field);

    let label = Label::new();
    label.text("Field below will only accept numbers \n(as defined by unicode)")
         .position(10, 32+28+6).size(400, 32);
    window.add(&label);

    let text_field = TextBox::new();
    text_field.position(10, 32+32+12+28).size(400, 28).event_filter(|_widget, event, _focused, _redraw| {
       match event {
            Event::KeyPressed (key_event) => {
                if let Some(character) = key_event.character {
                    if !character.is_numeric() {
                        return None
                    }
                }
            },
            _ => {}
        }

        Some(event)
    });

    text_field.text_offset(6, 6);
    window.add(&text_field);

    window.exec();
}
<|endoftext|>


<commit_before>use std::intrinsics::TypeId;
use std::cell::RefCell;
use std::rc::{Rc, Weak};
use std::fmt::{Formatter, Show, Result};
use std::collections::hashmap::HashMap;
use std::any::{Any, AnyRefExt, AnyMutRefExt};
use std::mem;
use uuid::Uuid;

/// Toplevel container of the entity component system.
pub struct World<T> {
    data: Rc<RefCell<WorldData<T>>>,
}

impl<T> Clone for World<T> {
    fn clone(&self) -> World<T> {
        World { data: self.data.clone() }
    }
}

impl<T: System> World<T> {
    /// Create a world coupled with an application specific system object.
    pub fn new(master_system: T) -> World<T> {
        let ret = World {
            data: Rc::new(RefCell::new(WorldData::new(master_system))),
        };
        ret.data.borrow_mut().master_system.register(&ret);
        ret
    }

    /// Wrap an EntityId struct into an entity handle that has a backreference
    /// to the world object.
    fn wrap(&self, id: EntityId) -> Entity<T> {
        Entity {
            world: self.data.downgrade(),
            id: id
        }
    }

    /// Create a new entity bound to this world.
    pub fn new_entity(&mut self) -> Entity<T> {
        let id = EntityId {
            idx: self.data.borrow_mut().get_idx(),
            uuid: Uuid::new_v4(),
        };
        self.data.borrow_mut().register_new_entity(id);
        let ret = self.wrap(id);
        self.data.borrow_mut().master_system.added(&ret);
        ret
    }

    pub fn system<'a>(&'a self) -> &'a T {
        unsafe { mem::transmute(&self.data.borrow().master_system) }
    }

    pub fn system_mut<'a>(&'a mut self) -> &'a mut T {
        unsafe { mem::transmute(&self.data.borrow_mut().master_system) }
    }

    pub fn find_entity(&self, uuid: &Uuid) -> Option<Entity<T>> {
        match self.data.borrow().uuids.find(uuid) {
            Some(idx) => Some(self.wrap(EntityId { uuid: *uuid, idx: *idx })),
            None => None
        }
    }

    pub fn entities(&self) -> Vec<Entity<T>> {
        // XXX: Inefficient
        self.data.borrow().uuids.iter()
            .map(|(&uuid, &idx)| self.wrap(EntityId { uuid: uuid, idx: idx }))
            .collect()
    }
}

/// Callback interface for application data connected to the component system
/// world.
pub trait System {
    /// Callback for initially attaching the system to a world.
    fn register(&mut self, world: &World<Self>);
    /// Callback for adding a new entity to world.
    fn added(&mut self, e: &Entity<Self>);
    /// Callback for a component being added or removed in an entity. Note that
    /// this is not called when the data of an existing component is written
    /// to, only if the component is replaced or removed.
    fn changed<C>(&mut self, e: &Entity<Self>, component: Option<&C>);
    /// Callback for an entity being deleted.
    fn deleted(&mut self, e: &Entity<Self>);
}

pub struct Entity<T> {
    world: Weak<RefCell<WorldData<T>>>,
    id: EntityId,
}

impl<T> Clone for Entity<T> {
    fn clone(&self) -> Entity<T> {
        Entity { world: self.world.clone(), id: self.id }
    }
}

impl<T> Show for Entity<T> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "{}", self.id)
    }
}

impl<T: System> Entity<T> {
    /// Add or reset a component in the entity. Causes a "changed" call to the
    /// world system.
    pub fn set_component<C: 'static+Clone>(&mut self, comp: C) {
        self.world.upgrade().unwrap().borrow_mut().deref_mut()
            .set_component(self, Some(comp));
    }

    /// Remove a component from the entity. Causes a "changed" call to the
    /// world system.
    pub fn remove_component<C: 'static+Clone>(&mut self) {
        let comp : Option<C> = None;
        self.world.upgrade().unwrap().borrow_mut().deref_mut()
            .set_component(self, comp);
    }

    /// Delete the entity from the world. Causes a "deleted" call to the world
    /// system.
    pub fn delete(&mut self) {
        self.world.upgrade().unwrap().borrow_mut().deref_mut()
            .delete_entity(self);
    }

    /// Query whether the entity has a type of component.
    pub fn has<'a, C: 'static>(&self) -> bool {
        self.world.upgrade().unwrap().borrow()
            .comp_ref::<'a, C>(self.id).is_some()
    }

    /// Get an access proxy to the entity's component if the entity has that
    /// component.
    pub fn into<C: 'static>(&self) -> Option<CompProxyMut<T, C>> {
        if self.has::<C>() {
            Some(CompProxyMut {
                world: self.world.clone(),
                id: self.id
            })
        } else {
            None
        }
    }

    /// Return unique identifier for this entity.
    pub fn uuid(&self) -> Uuid {
        self.id.uuid
    }

    /// Return a handle to the world.
    pub fn world(&self) -> World<T> {
        World { data: self.world.upgrade().unwrap() }
    }
}

/// Access proxy to entity components. The implementation RefCell (mutable)
/// borrow internally, so using this carelessly may lead to runtime borrow
/// errors. You should generally keep access to the concrete entity data short
/// in scope and low in the call stack to prevent unexpected borrow failures.
pub struct CompProxyMut<T, C> {
    world: Weak<RefCell<WorldData<T>>>,
    id: EntityId,
}

impl<T: System, C: 'static> Deref<C> for CompProxyMut<T, C> {
    fn deref<'a>(&'a self) -> &'a C {
        self.world.upgrade().unwrap().borrow()
            .comp_ref::<'a, C>(self.id).unwrap()
    }
}

/*
impl<T: System, C: 'static> DerefMut<C> for CompProxyMut<T, C> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut C {
        self.world.upgrade().unwrap().borrow_mut()
            .comp_ref_mut::<'a, C>(self.id).unwrap()
    }
}
*/

#[deriving(PartialEq, Clone, Show)]
struct EntityId {
    uuid: Uuid,
    idx: uint,
}

struct WorldData<T> {
    // XXX: This is much less efficient than it could be. A serious
    // implementation would use unboxed vecs for the components and would
    // provide lookup methods faster than a HashMap find to access the
    // components
    components: HashMap<TypeId, Vec<Option<Box<Any>>>>,

    next_idx: uint,
    reusable_idxs: Vec<uint>,
    uuids: HashMap<Uuid, uint>,

    master_system: T,
}

impl<T: System> WorldData<T> {
    fn new(master_system: T) -> WorldData<T> {
        WorldData {
            components: HashMap::new(),
            next_idx: 0,
            reusable_idxs: vec!(),
            uuids: HashMap::new(),
            master_system: master_system,
        }
    }

    fn register_new_entity(&mut self, id: EntityId) {
        assert!(!self.uuids.contains_key(&id.uuid),
            "New entity clobbering existing one");
        self.uuids.insert(id.uuid, id.idx);
    }

    fn delete_entity(&mut self, e: &Entity<T>) {
        self.check_entity(e.id);
        self.uuids.remove(&e.id.uuid);

        for (_, c) in self.components.mut_iter() {
            if c.len() > e.id.idx {
                c.as_mut_slice()[e.id.idx] = None;
            }
        }

        self.reusable_idxs.push(e.id.idx);

        self.master_system.deleted(e);
    }

    /// Return the next unused reusable entity id.
    fn get_idx(&mut self) -> uint {
        match self.reusable_idxs.pop() {
            None => {
                let ret = self.next_idx;
                self.next_idx += 1;
                ret
            }
            Some(idx) => idx
        }
    }

    fn check_entity(&self, id: EntityId) {
        assert!(self.uuids.contains_key(&id.uuid), "Unknown entity UUID");
        assert!(*self.uuids.find(&id.uuid).unwrap() == id.idx, "Entity UUID mismatch");
    }

    fn set_component<C: 'static+Clone>(&mut self, e: &Entity<T>, comp: Option<C>) {
        self.check_entity(e.id);
        let type_id = TypeId::of::<C>();
        // We haven't seen this kind of component yet.
        if !self.components.contains_key(&type_id) {
            self.components.insert(type_id, vec!());
        }

        let bin = self.components.find_mut(&type_id).unwrap();

        // XXX: grow_set didn't work.
        while bin.len() <= e.id.idx { bin.push(None); }
        bin.as_mut_slice()[e.id.idx] = match comp {
            None => None,
            Some(c) => Some(box c as Box<Any>),
        };

        match bin.as_mut_slice()[e.id.idx] {
            None => self.master_system.changed::<C>(e, None),
            Some(ref c) => self.master_system.changed(e, Some(&c)),
        };
    }

    fn comp_ref<'a, C: 'static>(
        &self, id: EntityId) -> Option<&'a C> {
        self.check_entity(id);
        let type_id = TypeId::of::<C>();
        match self.components.find(&type_id) {
            None => { None }
            Some(bin) => {
                if id.idx < bin.len() {
                    match bin.get(id.idx) {
                        &Some(ref c) => { unsafe { Some(mem::transmute(c.as_ref::<C>().unwrap())) } }
                        &None => None
                    }
                } else {
                    None
                }
            }
        }
    }

    /*
    fn comp_ref_mut<'a, C: 'static>(
        &mut self, id: EntityId) -> Option<&'a mut C> {
        self.check_entity(id);
        let type_id = TypeId::of::<C>();
        match self.components.find_mut(&type_id) {
            None => { None }
            Some(bin) => {
                if id.idx < bin.len() {
                    match bin.get_mut(id.idx) {
                        &Some(ref mut c) => {
                            unsafe { Some(mem::transmute(c.as_mut::<C>().unwrap())) }
                        }
                        &None => None
                    }
                } else {
                    None
                }
            }
        }
    }
    */
}

<commit_msg>Remove check_entity, was slowing things down a lot<commit_after>use std::intrinsics::TypeId;
use std::cell::RefCell;
use std::rc::{Rc, Weak};
use std::fmt::{Formatter, Show, Result};
use std::collections::hashmap::HashMap;
use std::any::{Any, AnyRefExt, AnyMutRefExt};
use std::mem;
use uuid::Uuid;

/// Toplevel container of the entity component system.
pub struct World<T> {
    data: Rc<RefCell<WorldData<T>>>,
}

impl<T> Clone for World<T> {
    fn clone(&self) -> World<T> {
        World { data: self.data.clone() }
    }
}

impl<T: System> World<T> {
    /// Create a world coupled with an application specific system object.
    pub fn new(master_system: T) -> World<T> {
        let ret = World {
            data: Rc::new(RefCell::new(WorldData::new(master_system))),
        };
        ret.data.borrow_mut().master_system.register(&ret);
        ret
    }

    /// Wrap an EntityId struct into an entity handle that has a backreference
    /// to the world object.
    fn wrap(&self, id: EntityId) -> Entity<T> {
        Entity {
            world: self.data.downgrade(),
            id: id
        }
    }

    /// Create a new entity bound to this world.
    pub fn new_entity(&mut self) -> Entity<T> {
        let id = EntityId {
            idx: self.data.borrow_mut().get_idx(),
            uuid: Uuid::new_v4(),
        };
        self.data.borrow_mut().register_new_entity(id);
        let ret = self.wrap(id);
        self.data.borrow_mut().master_system.added(&ret);
        ret
    }

    pub fn system<'a>(&'a self) -> &'a T {
        unsafe { mem::transmute(&self.data.borrow().master_system) }
    }

    pub fn system_mut<'a>(&'a mut self) -> &'a mut T {
        unsafe { mem::transmute(&self.data.borrow_mut().master_system) }
    }

    pub fn find_entity(&self, uuid: &Uuid) -> Option<Entity<T>> {
        match self.data.borrow().uuids.find(uuid) {
            Some(idx) => Some(self.wrap(EntityId { uuid: *uuid, idx: *idx })),
            None => None
        }
    }

    pub fn entities(&self) -> Vec<Entity<T>> {
        // XXX: Inefficient
        self.data.borrow().uuids.iter()
            .map(|(&uuid, &idx)| self.wrap(EntityId { uuid: uuid, idx: idx }))
            .collect()
    }
}

/// Callback interface for application data connected to the component system
/// world.
pub trait System {
    /// Callback for initially attaching the system to a world.
    fn register(&mut self, world: &World<Self>);
    /// Callback for adding a new entity to world.
    fn added(&mut self, e: &Entity<Self>);
    /// Callback for a component being added or removed in an entity. Note that
    /// this is not called when the data of an existing component is written
    /// to, only if the component is replaced or removed.
    fn changed<C>(&mut self, e: &Entity<Self>, component: Option<&C>);
    /// Callback for an entity being deleted.
    fn deleted(&mut self, e: &Entity<Self>);
}

pub struct Entity<T> {
    world: Weak<RefCell<WorldData<T>>>,
    id: EntityId,
}

impl<T> Clone for Entity<T> {
    fn clone(&self) -> Entity<T> {
        Entity { world: self.world.clone(), id: self.id }
    }
}

impl<T> Show for Entity<T> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "{}", self.id)
    }
}

impl<T: System> Entity<T> {
    /// Add or reset a component in the entity. Causes a "changed" call to the
    /// world system.
    pub fn set_component<C: 'static+Clone>(&mut self, comp: C) {
        self.world.upgrade().unwrap().borrow_mut().deref_mut()
            .set_component(self, Some(comp));
    }

    /// Remove a component from the entity. Causes a "changed" call to the
    /// world system.
    pub fn remove_component<C: 'static+Clone>(&mut self) {
        let comp : Option<C> = None;
        self.world.upgrade().unwrap().borrow_mut().deref_mut()
            .set_component(self, comp);
    }

    /// Delete the entity from the world. Causes a "deleted" call to the world
    /// system.
    pub fn delete(&mut self) {
        self.world.upgrade().unwrap().borrow_mut().deref_mut()
            .delete_entity(self);
    }

    /// Query whether the entity has a type of component.
    pub fn has<'a, C: 'static>(&self) -> bool {
        self.world.upgrade().unwrap().borrow()
            .comp_ref::<'a, C>(self.id).is_some()
    }

    /// Get an access proxy to the entity's component if the entity has that
    /// component.
    pub fn into<C: 'static>(&self) -> Option<CompProxyMut<T, C>> {
        if self.has::<C>() {
            Some(CompProxyMut {
                world: self.world.clone(),
                id: self.id
            })
        } else {
            None
        }
    }

    /// Return unique identifier for this entity.
    pub fn uuid(&self) -> Uuid {
        self.id.uuid
    }

    /// Return a handle to the world.
    pub fn world(&self) -> World<T> {
        World { data: self.world.upgrade().unwrap() }
    }
}

/// Access proxy to entity components. The implementation RefCell (mutable)
/// borrow internally, so using this carelessly may lead to runtime borrow
/// errors. You should generally keep access to the concrete entity data short
/// in scope and low in the call stack to prevent unexpected borrow failures.
pub struct CompProxyMut<T, C> {
    world: Weak<RefCell<WorldData<T>>>,
    id: EntityId,
}

impl<T: System, C: 'static> Deref<C> for CompProxyMut<T, C> {
    fn deref<'a>(&'a self) -> &'a C {
        self.world.upgrade().unwrap().borrow()
            .comp_ref::<'a, C>(self.id).unwrap()
    }
}

/*
impl<T: System, C: 'static> DerefMut<C> for CompProxyMut<T, C> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut C {
        self.world.upgrade().unwrap().borrow_mut()
            .comp_ref_mut::<'a, C>(self.id).unwrap()
    }
}
*/

#[deriving(PartialEq, Clone, Show)]
struct EntityId {
    uuid: Uuid,
    idx: uint,
}

struct WorldData<T> {
    // XXX: This is much less efficient than it could be. A serious
    // implementation would use unboxed vecs for the components and would
    // provide lookup methods faster than a HashMap find to access the
    // components
    components: HashMap<TypeId, Vec<Option<Box<Any>>>>,

    next_idx: uint,
    reusable_idxs: Vec<uint>,
    uuids: HashMap<Uuid, uint>,

    master_system: T,
}

impl<T: System> WorldData<T> {
    fn new(master_system: T) -> WorldData<T> {
        WorldData {
            components: HashMap::new(),
            next_idx: 0,
            reusable_idxs: vec!(),
            uuids: HashMap::new(),
            master_system: master_system,
        }
    }

    fn register_new_entity(&mut self, id: EntityId) {
        assert!(!self.uuids.contains_key(&id.uuid),
            "New entity clobbering existing one");
        self.uuids.insert(id.uuid, id.idx);
    }

    fn delete_entity(&mut self, e: &Entity<T>) {
        self.uuids.remove(&e.id.uuid);

        for (_, c) in self.components.mut_iter() {
            if c.len() > e.id.idx {
                c.as_mut_slice()[e.id.idx] = None;
            }
        }

        self.reusable_idxs.push(e.id.idx);

        self.master_system.deleted(e);
    }

    /// Return the next unused reusable entity id.
    fn get_idx(&mut self) -> uint {
        match self.reusable_idxs.pop() {
            None => {
                let ret = self.next_idx;
                self.next_idx += 1;
                ret
            }
            Some(idx) => idx
        }
    }

    fn set_component<C: 'static+Clone>(&mut self, e: &Entity<T>, comp: Option<C>) {
        let type_id = TypeId::of::<C>();
        // We haven't seen this kind of component yet.
        if !self.components.contains_key(&type_id) {
            self.components.insert(type_id, vec!());
        }

        let bin = self.components.find_mut(&type_id).unwrap();

        // XXX: grow_set didn't work.
        while bin.len() <= e.id.idx { bin.push(None); }
        bin.as_mut_slice()[e.id.idx] = match comp {
            None => None,
            Some(c) => Some(box c as Box<Any>),
        };

        match bin.as_mut_slice()[e.id.idx] {
            None => self.master_system.changed::<C>(e, None),
            Some(ref c) => self.master_system.changed(e, Some(&c)),
        };
    }

    fn comp_ref<'a, C: 'static>(
        &self, id: EntityId) -> Option<&'a C> {
        let type_id = TypeId::of::<C>();
        match self.components.find(&type_id) {
            None => { None }
            Some(bin) => {
                if id.idx < bin.len() {
                    match bin.get(id.idx) {
                        &Some(ref c) => { unsafe { Some(mem::transmute(c.as_ref::<C>().unwrap())) } }
                        &None => None
                    }
                } else {
                    None
                }
            }
        }
    }

    /*
    fn comp_ref_mut<'a, C: 'static>(
        &mut self, id: EntityId) -> Option<&'a mut C> {
        let type_id = TypeId::of::<C>();
        match self.components.find_mut(&type_id) {
            None => { None }
            Some(bin) => {
                if id.idx < bin.len() {
                    match bin.get_mut(id.idx) {
                        &Some(ref mut c) => {
                            unsafe { Some(mem::transmute(c.as_mut::<C>().unwrap())) }
                        }
                        &None => None
                    }
                } else {
                    None
                }
            }
        }
    }
    */
}

<|endoftext|>


<commit_before>//! Path summaries that are either child local, or leave the scope and re-enter from the parent.

use std::cmp::Ordering;
use std::default::Default;
use std::fmt::{Display, Formatter};
use std::fmt::Error;

use progress::{Timestamp, PathSummary};
use progress::nested::product::Product;
use progress::nested::summary::Summary::{Local, Outer};

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Summary<S, T> {
    Local(T),    // reachable within inner scope.
    Outer(S, T), // unreachable within scope, reachable through outer scope and then inner.
}

impl<S, T: Default> Default for Summary<S, T> {
    fn default() -> Summary<S, T> { Local(Default::default()) }
}

impl<S:PartialOrd+Copy, T:PartialOrd+Copy> PartialOrd for Summary<S, T> {
    #[inline]
    fn partial_cmp(&self, other: &Summary<S, T>) -> Option<Ordering> {
        // Two summaries are comparable if they are of the same type (Local, Outer).
        // Otherwise, as Local *updates* and Outer *sets* the inner coordinate, we
        // cannot be sure that either strictly improves on the other.
        match (*self, *other) {
            (Local(t1),    Local(t2))    => t1.partial_cmp(&t2),
            (Outer(s1,t1), Outer(s2,t2)) => (s1,t1).partial_cmp(&(s2,t2)),
            (Local(_),     Outer(_,_))   |
            (Outer(_,_),   Local(_))     => None,
        }
    }
}

impl<TOuter, SOuter, TInner, SInner> PathSummary<Product<TOuter, TInner>> for Summary<SOuter, SInner>
where TOuter: Timestamp,
      TInner: Timestamp,
      SOuter: PathSummary<TOuter>,
      SInner: PathSummary<TInner>,
{
    // this makes sense for a total order, but less clear for a partial order.
    #[inline]
    fn results_in(&self, product: &Product<TOuter, TInner>) -> Product<TOuter, TInner> {
        match *self {
            Local(ref iters)              => Product::new(product.outer, iters.results_in(&product.inner)),
            Outer(ref summary, ref iters) => Product::new(summary.results_in(&product.outer), iters.results_in(&Default::default())),
        }
    }
    #[inline]
    fn followed_by(&self, other: &Summary<SOuter, SInner>) -> Summary<SOuter, SInner> {
        match (*self, *other) {
            (Local(inner1), Local(inner2))             => Local(inner1.followed_by(&inner2)),
            (Local(_), Outer(_, _))                    => *other,
            (Outer(outer1, inner1), Local(inner2))     => Outer(outer1, inner1.followed_by(&inner2)),
            (Outer(outer1, _), Outer(outer2, inner2))  => Outer(outer1.followed_by(&outer2), inner2),
        }
    }
}

impl<SOuter: Display, SInner: Display> Display for Summary<SOuter, SInner> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match *self {
            Local(ref s) => f.write_str(&format!("Local({})", s)),
            Outer(ref s, ref t) => f.write_str(&format!("Outer({}, {})", s, t))
        }
    }
}
<commit_msg>shortened Display impl<commit_after>//! Path summaries that are either child local, or leave the scope and re-enter from the parent.

use std::cmp::Ordering;
use std::default::Default;
use std::fmt::{Display, Formatter};
use std::fmt::Error;

use progress::{Timestamp, PathSummary};
use progress::nested::product::Product;
use progress::nested::summary::Summary::{Local, Outer};

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Summary<S, T> {
    Local(T),    // reachable within inner scope.
    Outer(S, T), // unreachable within scope, reachable through outer scope and then inner.
}

impl<S, T: Default> Default for Summary<S, T> {
    fn default() -> Summary<S, T> { Local(Default::default()) }
}

impl<S:PartialOrd+Copy, T:PartialOrd+Copy> PartialOrd for Summary<S, T> {
    #[inline]
    fn partial_cmp(&self, other: &Summary<S, T>) -> Option<Ordering> {
        // Two summaries are comparable if they are of the same type (Local, Outer).
        // Otherwise, as Local *updates* and Outer *sets* the inner coordinate, we
        // cannot be sure that either strictly improves on the other.
        match (*self, *other) {
            (Local(t1),    Local(t2))    => t1.partial_cmp(&t2),
            (Outer(s1,t1), Outer(s2,t2)) => (s1,t1).partial_cmp(&(s2,t2)),
            (Local(_),     Outer(_,_))   |
            (Outer(_,_),   Local(_))     => None,
        }
    }
}

impl<TOuter, SOuter, TInner, SInner> PathSummary<Product<TOuter, TInner>> for Summary<SOuter, SInner>
where TOuter: Timestamp,
      TInner: Timestamp,
      SOuter: PathSummary<TOuter>,
      SInner: PathSummary<TInner>,
{
    // this makes sense for a total order, but less clear for a partial order.
    #[inline]
    fn results_in(&self, product: &Product<TOuter, TInner>) -> Product<TOuter, TInner> {
        match *self {
            Local(ref iters)              => Product::new(product.outer, iters.results_in(&product.inner)),
            Outer(ref summary, ref iters) => Product::new(summary.results_in(&product.outer), iters.results_in(&Default::default())),
        }
    }
    #[inline]
    fn followed_by(&self, other: &Summary<SOuter, SInner>) -> Summary<SOuter, SInner> {
        match (*self, *other) {
            (Local(inner1), Local(inner2))             => Local(inner1.followed_by(&inner2)),
            (Local(_), Outer(_, _))                    => *other,
            (Outer(outer1, inner1), Local(inner2))     => Outer(outer1, inner1.followed_by(&inner2)),
            (Outer(outer1, _), Outer(outer2, inner2))  => Outer(outer1.followed_by(&outer2), inner2),
        }
    }
}

impl<SOuter: Display, SInner: Display> Display for Summary<SOuter, SInner> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match *self {
            Local(ref s) => write!(f, "Local({})", s),
            Outer(ref s, ref t) => write!(f, "Outer({}, {})", s, t)
        }
    }
}
<|endoftext|>


<commit_before>use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::env;

use actix_web::http::StatusCode;
use actix_web::middleware::{Middleware, Response, Started};
use actix_web::{error, HttpRequest, HttpResponse, Result};

lazy_static! {
    static ref AUTH_TOKEN: String = env::var("AUTH_TOKEN").unwrap_or_else(|_| {
        let token = thread_rng().sample_iter(&Alphanumeric).take(32).collect();

        warn!("No AUTH_TOKEN was specified, using random token {}.", token);

        token
    });
}

pub struct AuthMiddleware;

pub fn init() {
    // Force avaluation of the AUTH_TOKEN, so it's printed on the console
    // if no value was specified.
    let _ = *AUTH_TOKEN;
}

#[cfg_attr(
    feature = "cargo-clippy",
    allow(clippy::needless_pass_by_value)
)]
/* Dummy route that will return OK, and unauthorized by below middleware. */
pub fn check_token<S>(_req: HttpRequest<S>) -> HttpResponse {
    HttpResponse::Ok().status(StatusCode::NO_CONTENT).finish()
}

fn extract_bearer_token<S>(req: &HttpRequest<S>) -> Option<String> {
    req.headers()
        .get("Authorization")
        .and_then(|header| header.to_str().ok())
        .and_then(|header_value| header_value.split(char::is_whitespace).last())
        .map(|string| string.to_owned())
}

impl<S> Middleware<S> for AuthMiddleware {
    fn start(&self, _req: &HttpRequest<S>) -> Result<Started> {
        Ok(Started::Done)
    }

    fn response(&self, req: &HttpRequest<S>, resp: HttpResponse) -> Result<Response> {
        match extract_bearer_token(req) {
            Some(ref token) if token == &*AUTH_TOKEN => Ok(Response::Done(resp)),

            _ => Err(error::ErrorUnauthorized("Unauthorized")),
        }
    }
}
<commit_msg>Remove . from generated token output to prevent confusion<commit_after>use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::env;

use actix_web::http::StatusCode;
use actix_web::middleware::{Middleware, Response, Started};
use actix_web::{error, HttpRequest, HttpResponse, Result};

lazy_static! {
    static ref AUTH_TOKEN: String = env::var("AUTH_TOKEN").unwrap_or_else(|_| {
        let token = thread_rng().sample_iter(&Alphanumeric).take(32).collect();

        warn!("No AUTH_TOKEN was specified, using random token {}", token);

        token
    });
}

pub struct AuthMiddleware;

pub fn init() {
    // Force avaluation of the AUTH_TOKEN, so it's printed on the console
    // if no value was specified.
    let _ = *AUTH_TOKEN;
}

#[cfg_attr(
    feature = "cargo-clippy",
    allow(clippy::needless_pass_by_value)
)]
/* Dummy route that will return OK, and unauthorized by below middleware. */
pub fn check_token<S>(_req: HttpRequest<S>) -> HttpResponse {
    HttpResponse::Ok().status(StatusCode::NO_CONTENT).finish()
}

fn extract_bearer_token<S>(req: &HttpRequest<S>) -> Option<String> {
    req.headers()
        .get("Authorization")
        .and_then(|header| header.to_str().ok())
        .and_then(|header_value| header_value.split(char::is_whitespace).last())
        .map(|string| string.to_owned())
}

impl<S> Middleware<S> for AuthMiddleware {
    fn start(&self, _req: &HttpRequest<S>) -> Result<Started> {
        Ok(Started::Done)
    }

    fn response(&self, req: &HttpRequest<S>, resp: HttpResponse) -> Result<Response> {
        match extract_bearer_token(req) {
            Some(ref token) if token == &*AUTH_TOKEN => Ok(Response::Done(resp)),

            _ => Err(error::ErrorUnauthorized("Unauthorized")),
        }
    }
}
<|endoftext|>


<commit_before>extern crate futures;
extern crate tokio_core;
extern crate tokio_proto;
extern crate tokio_service;

use std::io;
use std::str;
use tokio_core::io::{Codec, EasyBuf};

pub struct LineCodec;

impl Codec for LineCodec {
    type In = String;
    type Out = String;

    fn decode(&mut self, buf: &mut EasyBuf) -> io::Result<Option<Self::In>> {
        if let Some(i) = buf.as_slice().iter().position(|&b| b == b'\n') {
            // remove the serialized frame from the buffer.
            let line = buf.drain_to(i);

            // Also remove the '\n'
            buf.drain_to(1);

            // Turn this data into a UTF string and return it in a Frame.
            match str::from_utf8(line.as_slice()) {
                Ok(s) => Ok(Some(s.to_string())),
                Err(_) => Err(io::Error::new(io::ErrorKind::Other, "invalid UTF-8")),
            }
        } else {
            Ok(None)
        }
    }

    fn encode(&mut self, msg: String, buf: &mut Vec<u8>) -> io::Result<()> {
        buf.extend(msg.as_bytes());
        buf.push(b'\n');
        Ok(())
    }
}

use tokio_proto::pipeline::ServerProto;

pub struct LineProto;

use tokio_core::io::{Io, Framed};

impl<T: Io + 'static> ServerProto<T> for LineProto {
    /// For this protocol style, `Request` matches the codec `In` type
    type Request = String;

    /// For this protocol style, `Response` matches the coded `Out` type
    type Response = String;

    /// A bit of boilerplate to hook in the codec:
    type Transport = Framed<T, LineCodec>;
    type BindTransport = Result<Self::Transport, io::Error>;
    fn bind_transport(&self, io: T) -> Self::BindTransport {
        Ok(io.framed(LineCodec))
    }
}

use tokio_service::Service;
pub struct Echo;
use futures::{future, Future, BoxFuture};
impl Service for Echo {
    // These types must match the corresponding protocol types:
    type Request = String;
    type Response = String;

    // For non-streaming protocols, service errors are always io::Error
    type Error = io::Error;

    // The future for computing the response; box it for simplicity.
    type Future = BoxFuture<Self::Response, Self::Error>;

    // Produce a future for computing a response from a request.
    fn call(&self, req: Self::Request) -> Self::Future {
        // In this case, the response is immediate.
        future::ok(req).boxed()
    }
}
use tokio_proto::TcpServer;

fn main() {
    // Specify the localhost address
    let addr = "0.0.0.0:12345".parse().unwrap();

    // The builder requires a protocol and an address
    let server = TcpServer::new(LineProto, addr);

    // We provide a way to *instantiate* the service for each new
    // connection; here, we just immediately return a new instance.
    server.serve(|| Ok(Echo));
}
<commit_msg>change port to protocol port<commit_after>extern crate futures;
extern crate tokio_core;
extern crate tokio_proto;
extern crate tokio_service;

use std::io;
use std::str;
use tokio_core::io::{Codec, EasyBuf};

pub struct LineCodec;

impl Codec for LineCodec {
    type In = String;
    type Out = String;

    fn decode(&mut self, buf: &mut EasyBuf) -> io::Result<Option<Self::In>> {
        if let Some(i) = buf.as_slice().iter().position(|&b| b == b'\n') {
            // remove the serialized frame from the buffer.
            let line = buf.drain_to(i);

            // Also remove the '\n'
            buf.drain_to(1);

            // Turn this data into a UTF string and return it in a Frame.
            match str::from_utf8(line.as_slice()) {
                Ok(s) => Ok(Some(s.to_string())),
                Err(_) => Err(io::Error::new(io::ErrorKind::Other, "invalid UTF-8")),
            }
        } else {
            Ok(None)
        }
    }

    fn encode(&mut self, msg: String, buf: &mut Vec<u8>) -> io::Result<()> {
        buf.extend(msg.as_bytes());
        buf.push(b'\n');
        Ok(())
    }
}

use tokio_proto::pipeline::ServerProto;

pub struct LineProto;

use tokio_core::io::{Io, Framed};

impl<T: Io + 'static> ServerProto<T> for LineProto {
    /// For this protocol style, `Request` matches the codec `In` type
    type Request = String;

    /// For this protocol style, `Response` matches the coded `Out` type
    type Response = String;

    /// A bit of boilerplate to hook in the codec:
    type Transport = Framed<T, LineCodec>;
    type BindTransport = Result<Self::Transport, io::Error>;
    fn bind_transport(&self, io: T) -> Self::BindTransport {
        Ok(io.framed(LineCodec))
    }
}

use tokio_service::Service;
pub struct Echo;
use futures::{future, Future, BoxFuture};
impl Service for Echo {
    // These types must match the corresponding protocol types:
    type Request = String;
    type Response = String;

    // For non-streaming protocols, service errors are always io::Error
    type Error = io::Error;

    // The future for computing the response; box it for simplicity.
    type Future = BoxFuture<Self::Response, Self::Error>;

    // Produce a future for computing a response from a request.
    fn call(&self, req: Self::Request) -> Self::Future {
        // In this case, the response is immediate.
        future::ok(req).boxed()
    }
}
use tokio_proto::TcpServer;

fn main() {
    // Specify the localhost address
    let addr = "0.0.0.0:1337".parse().unwrap();

    // The builder requires a protocol and an address
    let server = TcpServer::new(LineProto, addr);

    // We provide a way to *instantiate* the service for each new
    // connection; here, we just immediately return a new instance.
    server.serve(|| Ok(Echo));
}
<|endoftext|>


<commit_before>extern crate rustc_serialize;
#[macro_use] extern crate nickel;
extern crate redis;
extern crate r2d2;
extern crate r2d2_redis;
extern crate plugin;
extern crate typemap;

extern crate core;

use std::env;
use r2d2::NopErrorHandler;
use nickel::{Nickel, HttpRouter, JsonBody};
use nickel::status::StatusCode;
use core::ops::Deref;
use redis::{Commands, RedisError};

use redis_middleware::{RedisMiddleware, RedisRequestExtensions};
mod redis_middleware;

#[derive(RustcDecodable, RustcEncodable)]
struct RatingSubmission {
	uuid: String,
	mod_str: String,
	rating: u8,
}

enum Rating {
	Poor = 0,
	BelowAverage,
	Average,
	AboveAverage,
	Excellent,
}

fn main() {
	let mut webserver = Nickel::new();

	let redis_url = env::var("DATABASE_URL").unwrap_or("redis://localhost/3".to_owned());
	let redispool = RedisMiddleware::new(&*redis_url,
										5,
										Box::new(NopErrorHandler)).unwrap();

	webserver.utilize(redispool);
	webserver.post("/submit", middleware! { |request|
		let _redis_conn = request.redis_conn();
		let redis_conn = _redis_conn.deref();
		let test = request.json_as::<RatingSubmission>().unwrap();
		println!("{}", test.uuid);
		let r: Result<u8, RedisError> = redis_conn.hset("mod", "uuid", Rating::Poor as u8);
		match r {
			Err(_) => (StatusCode::NotFound, "{\"not_found\": true}"),
			Ok(_) => (StatusCode::Ok, "ok"),
		}
	});
	webserver.get("/rating/:mod", middleware! { |request|
		let _redis_conn = request.redis_conn();
		let redis_conn = _redis_conn.deref();
		let r: Result<u8, RedisError> = redis_conn.incr("requests", 1);
		match request.param("mod") {
			Some("test") => (StatusCode::Ok, "ok"),
			_ => (StatusCode::NotFound, "{\"not_found\": true}"),
		}
	});
	webserver.get("/ratings", middleware! { |request, response|
		format!("{{\"mod\": {}}}", 3)
	});

	webserver.listen("127.0.0.1:8080")
}
<commit_msg>/submit path<commit_after>extern crate rustc_serialize;
#[macro_use] extern crate nickel;
extern crate redis;
extern crate r2d2;
extern crate r2d2_redis;
extern crate plugin;
extern crate typemap;

extern crate core;

use std::env;
use r2d2::NopErrorHandler;
use nickel::{Nickel, HttpRouter, JsonBody};
use nickel::status::StatusCode;
use core::ops::Deref;
use redis::{Commands, RedisError, Connection};
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};

use redis_middleware::{RedisMiddleware, RedisRequestExtensions};
mod redis_middleware;

#[derive(RustcDecodable, RustcEncodable)]
struct RatingSubmission {
	uuid: String,
	mod_str: String,
	rating: Rating,
}

#[derive(Clone, Copy, Debug)]
enum Rating {
	Poor = 0,
	BelowAverage,
	Average,
	AboveAverage,
	Excellent,
}

impl Decodable for Rating {
	fn decode<D: Decoder>(d: &mut D) -> Result<Rating, D::Error> {
		let r = try!(d.read_u8());
		Ok(match r {
			0 => Rating::Poor,
			1 => Rating::BelowAverage,
			2 => Rating::Average,
			3 => Rating::AboveAverage,
			_ => Rating::Excellent,
		})
	}
}

impl Encodable for Rating {
	fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
		let as_u8 = *self as u8;
		s.emit_u8(as_u8)
	}
}

fn incr_requests(conn: &Connection) {
	match conn.incr::<_, _, u64>("requests", 1) {
		Err(_) => println!("failed to incr requests."),
		Ok(a) => println!("request counter now at {}", a),
	}
}

const OK_RESP: (StatusCode, &'static str) = (StatusCode::Ok, "ok");

fn main() {
	let mut webserver = Nickel::new();

	let redis_url = env::var("DATABASE_URL").unwrap_or("redis://localhost/3".to_owned());
	let redispool = RedisMiddleware::new(&*redis_url,
										5,
										Box::new(NopErrorHandler)).unwrap();

	webserver.utilize(redispool);
	webserver.post("/submit", middleware! { |request|
		let _redis_conn = request.redis_conn();
		let redis_conn = _redis_conn.deref();
		incr_requests(&redis_conn);
		let test = request.json_as::<RatingSubmission>().unwrap();
		println!("{} rates {} as {:?}", test.uuid, test.mod_str, test.rating);
		let r: Result<u8, RedisError> = redis_conn.hset(test.mod_str, test.uuid, test.rating as u8);
		match r {
			Err(_) => (StatusCode::NotFound, "{\"not_found\": true}"),
			Ok(_) => OK_RESP,
		}
	});
	webserver.get("/rating/:mod", middleware! { |request|
		let _redis_conn = request.redis_conn();
		let redis_conn = _redis_conn.deref();
		incr_requests(&redis_conn);
		match request.param("mod") {
			Some("test") => OK_RESP,
			_ => (StatusCode::NotFound, "{\"not_found\": true}"),
		}
	});
	webserver.get("/ratings", middleware! { |request, response|
		format!("{{\"mod\": {}}}", 3)
	});

	webserver.listen("127.0.0.1:7998")
}
<|endoftext|>


<commit_before>//! Tests for setting custom rustdoc flags.

use cargo_test_support::project;

#[cargo_test]
fn parses_env() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("doc -v")
        .env("RUSTDOCFLAGS", "--cfg=foo")
        .with_stderr_contains("[RUNNING] `rustdoc [..] --cfg=foo[..]`")
        .run();
}

#[cargo_test]
fn parses_config() {
    let p = project()
        .file("src/lib.rs", "")
        .file(
            ".cargo/config",
            r#"
            [build]
            rustdocflags = ["--cfg", "foo"]
        "#,
        )
        .build();

    p.cargo("doc -v")
        .with_stderr_contains("[RUNNING] `rustdoc [..] --cfg foo[..]`")
        .run();
}

#[cargo_test]
fn bad_flags() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("doc")
        .env("RUSTDOCFLAGS", "--bogus")
        .with_status(101)
        .with_stderr_contains("[..]bogus[..]")
        .run();
}

#[cargo_test]
fn rerun() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("doc").env("RUSTDOCFLAGS", "--cfg=foo").run();
    p.cargo("doc")
        .env("RUSTDOCFLAGS", "--cfg=foo")
        .with_stderr("[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]")
        .run();
    p.cargo("doc")
        .env("RUSTDOCFLAGS", "--cfg=bar")
        .with_stderr(
            "\
[DOCUMENTING] foo v0.0.1 ([..])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn rustdocflags_passed_to_rustdoc_through_cargo_test() {
    let p = project()
        .file(
            "src/lib.rs",
            r#"
            //! ```
            //! assert!(cfg!(do_not_choke));
            //! ```
        "#,
        )
        .build();

    p.cargo("test --doc")
        .env("RUSTDOCFLAGS", "--cfg do_not_choke")
        .run();
}

#[cargo_test]
fn rustdocflags_passed_to_rustdoc_through_cargo_test_only_once() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("test --doc")
        .env("RUSTDOCFLAGS", "--markdown-no-toc")
        .run();
}

#[cargo_test]
fn rustdocflags_misspelled() {
    let p = project().file("src/main.rs", "fn main() { }").build();

    p.cargo("doc")
        .env("RUSTDOC_FLAGS", "foo")
        .with_stderr_contains("[WARNING] Cargo does not read `RUSTDOC_FLAGS` environment variable. Did you mean `RUSTDOCFLAGS`?")
        .run();
}
<commit_msg>Add test for whitespace behavior in env flags.<commit_after>//! Tests for setting custom rustdoc flags.

use cargo_test_support::project;

#[cargo_test]
fn parses_env() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("doc -v")
        .env("RUSTDOCFLAGS", "--cfg=foo")
        .with_stderr_contains("[RUNNING] `rustdoc [..] --cfg=foo[..]`")
        .run();
}

#[cargo_test]
fn parses_config() {
    let p = project()
        .file("src/lib.rs", "")
        .file(
            ".cargo/config",
            r#"
            [build]
            rustdocflags = ["--cfg", "foo"]
        "#,
        )
        .build();

    p.cargo("doc -v")
        .with_stderr_contains("[RUNNING] `rustdoc [..] --cfg foo[..]`")
        .run();
}

#[cargo_test]
fn bad_flags() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("doc")
        .env("RUSTDOCFLAGS", "--bogus")
        .with_status(101)
        .with_stderr_contains("[..]bogus[..]")
        .run();
}

#[cargo_test]
fn rerun() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("doc").env("RUSTDOCFLAGS", "--cfg=foo").run();
    p.cargo("doc")
        .env("RUSTDOCFLAGS", "--cfg=foo")
        .with_stderr("[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]")
        .run();
    p.cargo("doc")
        .env("RUSTDOCFLAGS", "--cfg=bar")
        .with_stderr(
            "\
[DOCUMENTING] foo v0.0.1 ([..])
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
        )
        .run();
}

#[cargo_test]
fn rustdocflags_passed_to_rustdoc_through_cargo_test() {
    let p = project()
        .file(
            "src/lib.rs",
            r#"
            //! ```
            //! assert!(cfg!(do_not_choke));
            //! ```
        "#,
        )
        .build();

    p.cargo("test --doc")
        .env("RUSTDOCFLAGS", "--cfg do_not_choke")
        .run();
}

#[cargo_test]
fn rustdocflags_passed_to_rustdoc_through_cargo_test_only_once() {
    let p = project().file("src/lib.rs", "").build();

    p.cargo("test --doc")
        .env("RUSTDOCFLAGS", "--markdown-no-toc")
        .run();
}

#[cargo_test]
fn rustdocflags_misspelled() {
    let p = project().file("src/main.rs", "fn main() { }").build();

    p.cargo("doc")
        .env("RUSTDOC_FLAGS", "foo")
        .with_stderr_contains("[WARNING] Cargo does not read `RUSTDOC_FLAGS` environment variable. Did you mean `RUSTDOCFLAGS`?")
        .run();
}

#[cargo_test]
fn whitespace() {
    // Checks behavior of different whitespace characters.
    let p = project().file("src/lib.rs", "").build();

    // "too many operands"
    p.cargo("doc")
        .env("RUSTDOCFLAGS", "--crate-version this has spaces")
        .with_stderr_contains("[ERROR] could not document `foo`")
        .with_status(101)
        .run();

    const SPACED_VERSION: &str = "a\nb\tc\u{00a0}d";
    p.cargo("doc")
        .env(
            "RUSTDOCFLAGS",
            format!("--crate-version {}", SPACED_VERSION),
        )
        .run();

    let contents = p.read_file("target/doc/foo/index.html");
    assert!(contents.contains(SPACED_VERSION));
}
<|endoftext|>