<commit_before>#[macro_use]
extern crate validator_derive;
extern crate validator;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate regex;
#[macro_use]
extern crate lazy_static;

use regex::Regex;
use validator::{Validate, ValidationError};

fn validate_unique_username(username: &str) -> Result<(), ValidationError> {
    if username == "xXxShad0wxXx" {
        return Err(ValidationError::new("terrible_username"));
    }

    Ok(())
}

fn validate_signup(data: &SignupData) -> Result<(), ValidationError> {
    if data.mail.ends_with("gmail.com") && data.age == 18 {
        return Err(ValidationError::new("stupid_rule"));
    }

    Ok(())
}

#[derive(Debug, Validate, Deserialize)]
#[validate(schema(function = "validate_signup", skip_on_field_errors = "false"))]
struct SignupData {
    #[validate(email)]
    mail: String,
    #[validate(url)]
    site: String,
    #[validate(length(min = "1"), custom = "validate_unique_username")]
    #[serde(rename = "firstName")]
    first_name: String,
    #[validate(range(min = "18", max = "20"))]
    age: u32,
}

#[test]
fn is_fine_with_many_valid_validations() {
    let signup = SignupData {
        mail: "bob@bob.com".to_string(),
        site: "http://hello.com".to_string(),
        first_name: "Bob".to_string(),
        age: 18,
    };

    assert!(signup.validate().is_ok());
}

#[test]
fn failed_validation_points_to_original_field_name() {
    let signup = SignupData {
        mail: "bob@bob.com".to_string(),
        site: "http://hello.com".to_string(),
        first_name: "".to_string(),
        age: 18,
    };
    let res = signup.validate();
    assert!(res.is_err());
    let errs = res.unwrap_err().inner();
    assert!(errs.contains_key("firstName"));
    assert_eq!(errs["firstName"].len(), 1);
    assert_eq!(errs["firstName"][0].code, "length");
}

#[test]
fn test_can_validate_option_fields_with_lifetime() {
    lazy_static! {
        static ref RE2: Regex = Regex::new(r"[a-z]{2}").unwrap();
    }

    #[derive(Debug, Validate)]
    struct PutStruct<'a> {
        #[validate(length(min = "1", max = "10"))]
        name: Option<&'a str>,
        #[validate(range(min = "1", max = "10"))]
        range: Option<usize>,
        #[validate(email)]
        email: Option<&'a str>,
        #[validate(url)]
        url: Option<&'a str>,
        #[validate(contains = "@")]
        text: Option<&'a str>,
        #[validate(regex = "RE2")]
        re: Option<&'a str>,
        #[validate(custom = "check_str")]
        custom: Option<&'a str>,
    }

    fn check_str(_: &str) -> Result<(), ValidationError> {
        Ok(())
    }

    let s = PutStruct {
        name: Some("al"),
        range: Some(2),
        email: Some("hi@gmail.com"),
        url: Some("http://google.com"),
        text: Some("@someone"),
        re: Some("hi"),
        custom: Some("hey"),
    };
    assert!(s.validate().is_ok());
}

#[test]
fn test_can_validate_option_fields_without_lifetime() {
    lazy_static! {
        static ref RE2: Regex = Regex::new(r"[a-z]{2}").unwrap();
    }

    #[derive(Debug, Validate)]
    struct PutStruct {
        #[validate(length(min = "1", max = "10"))]
        name: Option<String>,
        #[validate(length(min = "1", max = "10"))]
        ids: Option<Vec<usize>>,
        #[validate(range(min = "1", max = "10"))]
        range: Option<usize>,
        #[validate(email)]
        email: Option<String>,
        #[validate(url)]
        url: Option<String>,
        #[validate(contains = "@")]
        text: Option<String>,
        #[validate(regex = "RE2")]
        re: Option<String>,
        #[validate(custom = "check_str")]
        custom: Option<String>,
    }

    fn check_str(_: &str) -> Result<(), ValidationError> {
        Ok(())
    }

    let s = PutStruct {
        name: Some("al".to_string()),
        ids: Some(vec![1, 2, 3]),
        range: Some(2),
        email: Some("hi@gmail.com".to_string()),
        url: Some("http://google.com".to_string()),
        text: Some("@someone".to_string()),
        re: Some("hi".to_string()),
        custom: Some("hey".to_string()),
    };
    assert!(s.validate().is_ok());
}
<commit_msg>[#29] Add test for `?` operator<commit_after>#[macro_use]
extern crate validator_derive;
extern crate validator;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate regex;
#[macro_use]
extern crate lazy_static;

use regex::Regex;
use validator::{Validate, ValidationError, ValidationErrors};

fn validate_unique_username(username: &str) -> Result<(), ValidationError> {
    if username == "xXxShad0wxXx" {
        return Err(ValidationError::new("terrible_username"));
    }

    Ok(())
}

fn validate_signup(data: &SignupData) -> Result<(), ValidationError> {
    if data.mail.ends_with("gmail.com") && data.age == 18 {
        return Err(ValidationError::new("stupid_rule"));
    }

    Ok(())
}

#[derive(Debug, Validate, Deserialize)]
#[validate(schema(function = "validate_signup", skip_on_field_errors = "false"))]
struct SignupData {
    #[validate(email)]
    mail: String,
    #[validate(url)]
    site: String,
    #[validate(length(min = "1"), custom = "validate_unique_username")]
    #[serde(rename = "firstName")]
    first_name: String,
    #[validate(range(min = "18", max = "20"))]
    age: u32,
}

#[test]
fn is_fine_with_many_valid_validations() {
    let signup = SignupData {
        mail: "bob@bob.com".to_string(),
        site: "http://hello.com".to_string(),
        first_name: "Bob".to_string(),
        age: 18,
    };

    assert!(signup.validate().is_ok());
}

#[test]
fn failed_validation_points_to_original_field_name() {
    let signup = SignupData {
        mail: "bob@bob.com".to_string(),
        site: "http://hello.com".to_string(),
        first_name: "".to_string(),
        age: 18,
    };
    let res = signup.validate();
    assert!(res.is_err());
    let errs = res.unwrap_err().inner();
    assert!(errs.contains_key("firstName"));
    assert_eq!(errs["firstName"].len(), 1);
    assert_eq!(errs["firstName"][0].code, "length");
}

#[test]
fn test_can_validate_option_fields_with_lifetime() {
    lazy_static! {
        static ref RE2: Regex = Regex::new(r"[a-z]{2}").unwrap();
    }

    #[derive(Debug, Validate)]
    struct PutStruct<'a> {
        #[validate(length(min = "1", max = "10"))]
        name: Option<&'a str>,
        #[validate(range(min = "1", max = "10"))]
        range: Option<usize>,
        #[validate(email)]
        email: Option<&'a str>,
        #[validate(url)]
        url: Option<&'a str>,
        #[validate(contains = "@")]
        text: Option<&'a str>,
        #[validate(regex = "RE2")]
        re: Option<&'a str>,
        #[validate(custom = "check_str")]
        custom: Option<&'a str>,
    }

    fn check_str(_: &str) -> Result<(), ValidationError> {
        Ok(())
    }

    let s = PutStruct {
        name: Some("al"),
        range: Some(2),
        email: Some("hi@gmail.com"),
        url: Some("http://google.com"),
        text: Some("@someone"),
        re: Some("hi"),
        custom: Some("hey"),
    };
    assert!(s.validate().is_ok());
}

#[test]
fn test_can_validate_option_fields_without_lifetime() {
    lazy_static! {
        static ref RE2: Regex = Regex::new(r"[a-z]{2}").unwrap();
    }

    #[derive(Debug, Validate)]
    struct PutStruct {
        #[validate(length(min = "1", max = "10"))]
        name: Option<String>,
        #[validate(length(min = "1", max = "10"))]
        ids: Option<Vec<usize>>,
        #[validate(range(min = "1", max = "10"))]
        range: Option<usize>,
        #[validate(email)]
        email: Option<String>,
        #[validate(url)]
        url: Option<String>,
        #[validate(contains = "@")]
        text: Option<String>,
        #[validate(regex = "RE2")]
        re: Option<String>,
        #[validate(custom = "check_str")]
        custom: Option<String>,
    }

    fn check_str(_: &str) -> Result<(), ValidationError> {
        Ok(())
    }

    let s = PutStruct {
        name: Some("al".to_string()),
        ids: Some(vec![1, 2, 3]),
        range: Some(2),
        email: Some("hi@gmail.com".to_string()),
        url: Some("http://google.com".to_string()),
        text: Some("@someone".to_string()),
        re: Some("hi".to_string()),
        custom: Some("hey".to_string()),
    };
    assert!(s.validate().is_ok());
}

#[test]
fn test_works_with_question_mark_operator() {
    fn some_fn() -> Result<(), ValidationErrors> {
        let signup = SignupData {
            mail: "invalid_email".to_string(),
            site: "http://hello.com".to_string(),
            first_name: "Bob".to_string(),
            age: 18,
        };

        signup.validate()?;
        Ok(())
    }

    assert!(some_fn().is_err());
}
<|endoftext|>


<commit_before>#![allow(nonstandard_style)]

use libc::{c_int, c_void, uintptr_t};

#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum _Unwind_Reason_Code {
    _URC_NO_REASON = 0,
    _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
    _URC_FATAL_PHASE2_ERROR = 2,
    _URC_FATAL_PHASE1_ERROR = 3,
    _URC_NORMAL_STOP = 4,
    _URC_END_OF_STACK = 5,
    _URC_HANDLER_FOUND = 6,
    _URC_INSTALL_CONTEXT = 7,
    _URC_CONTINUE_UNWIND = 8,
    _URC_FAILURE = 9, // used only by ARM EHABI
}
pub use _Unwind_Reason_Code::*;

pub type _Unwind_Exception_Class = u64;
pub type _Unwind_Word = uintptr_t;
pub type _Unwind_Ptr = uintptr_t;
pub type _Unwind_Trace_Fn =
    extern "C" fn(ctx: *mut _Unwind_Context, arg: *mut c_void) -> _Unwind_Reason_Code;

#[cfg(target_arch = "x86")]
pub const unwinder_private_data_size: usize = 5;

#[cfg(target_arch = "x86_64")]
pub const unwinder_private_data_size: usize = 6;

#[cfg(all(target_arch = "arm", not(target_os = "ios")))]
pub const unwinder_private_data_size: usize = 20;

#[cfg(all(target_arch = "arm", target_os = "ios"))]
pub const unwinder_private_data_size: usize = 5;

#[cfg(target_arch = "aarch64")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "mips")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "mips64")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "s390x")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "sparc64")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "riscv64")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_os = "emscripten")]
pub const unwinder_private_data_size: usize = 20;

#[cfg(all(target_arch = "hexagon", target_os = "linux"))]
pub const unwinder_private_data_size: usize = 35;

#[repr(C)]
pub struct _Unwind_Exception {
    pub exception_class: _Unwind_Exception_Class,
    pub exception_cleanup: _Unwind_Exception_Cleanup_Fn,
    pub private: [_Unwind_Word; unwinder_private_data_size],
}

pub enum _Unwind_Context {}

pub type _Unwind_Exception_Cleanup_Fn =
    extern "C" fn(unwind_code: _Unwind_Reason_Code, exception: *mut _Unwind_Exception);
#[cfg_attr(
    all(feature = "llvm-libunwind", any(target_os = "fuchsia", target_os = "linux")),
    link(name = "unwind", kind = "static")
)]
extern "C" {
    #[unwind(allowed)]
    pub fn _Unwind_Resume(exception: *mut _Unwind_Exception) -> !;
    pub fn _Unwind_DeleteException(exception: *mut _Unwind_Exception);
    pub fn _Unwind_GetLanguageSpecificData(ctx: *mut _Unwind_Context) -> *mut c_void;
    pub fn _Unwind_GetRegionStart(ctx: *mut _Unwind_Context) -> _Unwind_Ptr;
    pub fn _Unwind_GetTextRelBase(ctx: *mut _Unwind_Context) -> _Unwind_Ptr;
    pub fn _Unwind_GetDataRelBase(ctx: *mut _Unwind_Context) -> _Unwind_Ptr;
}

cfg_if::cfg_if! {
if #[cfg(all(any(target_os = "ios", target_os = "netbsd", not(target_arch = "arm"))))] {
    // Not ARM EHABI
    #[repr(C)]
    #[derive(Copy, Clone, PartialEq)]
    pub enum _Unwind_Action {
        _UA_SEARCH_PHASE = 1,
        _UA_CLEANUP_PHASE = 2,
        _UA_HANDLER_FRAME = 4,
        _UA_FORCE_UNWIND = 8,
        _UA_END_OF_STACK = 16,
    }
    pub use _Unwind_Action::*;

    #[cfg_attr(all(feature = "llvm-libunwind",
                   any(target_os = "fuchsia", target_os = "linux")),
               link(name = "unwind", kind = "static"))]
    extern "C" {
        pub fn _Unwind_GetGR(ctx: *mut _Unwind_Context, reg_index: c_int) -> _Unwind_Word;
        pub fn _Unwind_SetGR(ctx: *mut _Unwind_Context, reg_index: c_int, value: _Unwind_Word);
        pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> _Unwind_Word;
        pub fn _Unwind_SetIP(ctx: *mut _Unwind_Context, value: _Unwind_Word);
        pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context, ip_before_insn: *mut c_int)
                                 -> _Unwind_Word;
        pub fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void;
    }

} else {
    // ARM EHABI
    #[repr(C)]
    #[derive(Copy, Clone, PartialEq)]
    pub enum _Unwind_State {
        _US_VIRTUAL_UNWIND_FRAME = 0,
        _US_UNWIND_FRAME_STARTING = 1,
        _US_UNWIND_FRAME_RESUME = 2,
        _US_ACTION_MASK = 3,
        _US_FORCE_UNWIND = 8,
        _US_END_OF_STACK = 16,
    }
    pub use _Unwind_State::*;

    #[repr(C)]
    enum _Unwind_VRS_Result {
        _UVRSR_OK = 0,
        _UVRSR_NOT_IMPLEMENTED = 1,
        _UVRSR_FAILED = 2,
    }
    #[repr(C)]
    enum _Unwind_VRS_RegClass {
        _UVRSC_CORE = 0,
        _UVRSC_VFP = 1,
        _UVRSC_FPA = 2,
        _UVRSC_WMMXD = 3,
        _UVRSC_WMMXC = 4,
    }
    use _Unwind_VRS_RegClass::*;
    #[repr(C)]
    enum _Unwind_VRS_DataRepresentation {
        _UVRSD_UINT32 = 0,
        _UVRSD_VFPX = 1,
        _UVRSD_FPAX = 2,
        _UVRSD_UINT64 = 3,
        _UVRSD_FLOAT = 4,
        _UVRSD_DOUBLE = 5,
    }
    use _Unwind_VRS_DataRepresentation::*;

    pub const UNWIND_POINTER_REG: c_int = 12;
    pub const UNWIND_SP_REG: c_int = 13;
    pub const UNWIND_IP_REG: c_int = 15;

    #[cfg_attr(all(feature = "llvm-libunwind",
                   any(target_os = "fuchsia", target_os = "linux")),
               link(name = "unwind", kind = "static"))]
    extern "C" {
        fn _Unwind_VRS_Get(ctx: *mut _Unwind_Context,
                           regclass: _Unwind_VRS_RegClass,
                           regno: _Unwind_Word,
                           repr: _Unwind_VRS_DataRepresentation,
                           data: *mut c_void)
                           -> _Unwind_VRS_Result;

        fn _Unwind_VRS_Set(ctx: *mut _Unwind_Context,
                           regclass: _Unwind_VRS_RegClass,
                           regno: _Unwind_Word,
                           repr: _Unwind_VRS_DataRepresentation,
                           data: *mut c_void)
                           -> _Unwind_VRS_Result;
    }

    // On Android or ARM/Linux, these are implemented as macros:

    pub unsafe fn _Unwind_GetGR(ctx: *mut _Unwind_Context, reg_index: c_int) -> _Unwind_Word {
        let mut val: _Unwind_Word = 0;
        _Unwind_VRS_Get(ctx, _UVRSC_CORE, reg_index as _Unwind_Word, _UVRSD_UINT32,
                        &mut val as *mut _ as *mut c_void);
        val
    }

    pub unsafe fn _Unwind_SetGR(ctx: *mut _Unwind_Context, reg_index: c_int, value: _Unwind_Word) {
        let mut value = value;
        _Unwind_VRS_Set(ctx, _UVRSC_CORE, reg_index as _Unwind_Word, _UVRSD_UINT32,
                        &mut value as *mut _ as *mut c_void);
    }

    pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context)
                                -> _Unwind_Word {
        let val = _Unwind_GetGR(ctx, UNWIND_IP_REG);
        (val & !1) as _Unwind_Word
    }

    pub unsafe fn _Unwind_SetIP(ctx: *mut _Unwind_Context,
                                value: _Unwind_Word) {
        // Propagate thumb bit to instruction pointer
        let thumb_state = _Unwind_GetGR(ctx, UNWIND_IP_REG) & 1;
        let value = value | thumb_state;
        _Unwind_SetGR(ctx, UNWIND_IP_REG, value);
    }

    pub unsafe fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context,
                                    ip_before_insn: *mut c_int)
                                    -> _Unwind_Word {
        *ip_before_insn = 0;
        _Unwind_GetIP(ctx)
    }

    // This function also doesn't exist on Android or ARM/Linux, so make it a no-op
    pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void {
        pc
    }
}
} // cfg_if!

cfg_if::cfg_if! {
if #[cfg(not(all(target_os = "ios", target_arch = "arm")))] {
    // Not 32-bit iOS
    #[cfg_attr(all(feature = "llvm-libunwind",
                   any(target_os = "fuchsia", target_os = "linux")),
               link(name = "unwind", kind = "static"))]
    extern "C" {
        #[unwind(allowed)]
        pub fn _Unwind_RaiseException(exception: *mut _Unwind_Exception) -> _Unwind_Reason_Code;
        pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
                                 trace_argument: *mut c_void)
                                 -> _Unwind_Reason_Code;
    }
} else {
    // 32-bit iOS uses SjLj and does not provide _Unwind_Backtrace()
    #[cfg_attr(all(feature = "llvm-libunwind",
                   any(target_os = "fuchsia", target_os = "linux")),
               link(name = "unwind", kind = "static"))]
    extern "C" {
        #[unwind(allowed)]
        pub fn _Unwind_SjLj_RaiseException(e: *mut _Unwind_Exception) -> _Unwind_Reason_Code;
    }

    #[inline]
    pub unsafe fn _Unwind_RaiseException(exc: *mut _Unwind_Exception) -> _Unwind_Reason_Code {
        _Unwind_SjLj_RaiseException(exc)
    }
}
} // cfg_if!

cfg_if::cfg_if! {
if #[cfg(all(windows, target_arch = "x86_64", target_env = "gnu"))] {
    // We declare these as opaque types. This is fine since you just need to
    // pass them to _GCC_specific_handler and forget about them.
    pub enum EXCEPTION_RECORD {}
    pub type LPVOID = *mut c_void;
    pub enum CONTEXT {}
    pub enum DISPATCHER_CONTEXT {}
    pub type EXCEPTION_DISPOSITION = c_int;
    type PersonalityFn = unsafe extern "C" fn(version: c_int,
                                              actions: _Unwind_Action,
                                              exception_class: _Unwind_Exception_Class,
                                              exception_object: *mut _Unwind_Exception,
                                              context: *mut _Unwind_Context)
                                              -> _Unwind_Reason_Code;

    extern "C" {
        pub fn _GCC_specific_handler(exceptionRecord: *mut EXCEPTION_RECORD,
                                establisherFrame: LPVOID,
                                contextRecord: *mut CONTEXT,
                                dispatcherContext: *mut DISPATCHER_CONTEXT,
                                personality: PersonalityFn)
                                -> EXCEPTION_DISPOSITION;
    }
}
} // cfg_if!
<commit_msg>library/unwind: Add support for RISC-V 32-bit<commit_after>#![allow(nonstandard_style)]

use libc::{c_int, c_void, uintptr_t};

#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum _Unwind_Reason_Code {
    _URC_NO_REASON = 0,
    _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
    _URC_FATAL_PHASE2_ERROR = 2,
    _URC_FATAL_PHASE1_ERROR = 3,
    _URC_NORMAL_STOP = 4,
    _URC_END_OF_STACK = 5,
    _URC_HANDLER_FOUND = 6,
    _URC_INSTALL_CONTEXT = 7,
    _URC_CONTINUE_UNWIND = 8,
    _URC_FAILURE = 9, // used only by ARM EHABI
}
pub use _Unwind_Reason_Code::*;

pub type _Unwind_Exception_Class = u64;
pub type _Unwind_Word = uintptr_t;
pub type _Unwind_Ptr = uintptr_t;
pub type _Unwind_Trace_Fn =
    extern "C" fn(ctx: *mut _Unwind_Context, arg: *mut c_void) -> _Unwind_Reason_Code;

#[cfg(target_arch = "x86")]
pub const unwinder_private_data_size: usize = 5;

#[cfg(target_arch = "x86_64")]
pub const unwinder_private_data_size: usize = 6;

#[cfg(all(target_arch = "arm", not(target_os = "ios")))]
pub const unwinder_private_data_size: usize = 20;

#[cfg(all(target_arch = "arm", target_os = "ios"))]
pub const unwinder_private_data_size: usize = 5;

#[cfg(target_arch = "aarch64")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "mips")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "mips64")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "s390x")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "sparc64")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "riscv64")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_arch = "riscv32")]
pub const unwinder_private_data_size: usize = 2;

#[cfg(target_os = "emscripten")]
pub const unwinder_private_data_size: usize = 20;

#[cfg(all(target_arch = "hexagon", target_os = "linux"))]
pub const unwinder_private_data_size: usize = 35;

#[repr(C)]
pub struct _Unwind_Exception {
    pub exception_class: _Unwind_Exception_Class,
    pub exception_cleanup: _Unwind_Exception_Cleanup_Fn,
    pub private: [_Unwind_Word; unwinder_private_data_size],
}

pub enum _Unwind_Context {}

pub type _Unwind_Exception_Cleanup_Fn =
    extern "C" fn(unwind_code: _Unwind_Reason_Code, exception: *mut _Unwind_Exception);
#[cfg_attr(
    all(feature = "llvm-libunwind", any(target_os = "fuchsia", target_os = "linux")),
    link(name = "unwind", kind = "static")
)]
extern "C" {
    #[unwind(allowed)]
    pub fn _Unwind_Resume(exception: *mut _Unwind_Exception) -> !;
    pub fn _Unwind_DeleteException(exception: *mut _Unwind_Exception);
    pub fn _Unwind_GetLanguageSpecificData(ctx: *mut _Unwind_Context) -> *mut c_void;
    pub fn _Unwind_GetRegionStart(ctx: *mut _Unwind_Context) -> _Unwind_Ptr;
    pub fn _Unwind_GetTextRelBase(ctx: *mut _Unwind_Context) -> _Unwind_Ptr;
    pub fn _Unwind_GetDataRelBase(ctx: *mut _Unwind_Context) -> _Unwind_Ptr;
}

cfg_if::cfg_if! {
if #[cfg(all(any(target_os = "ios", target_os = "netbsd", not(target_arch = "arm"))))] {
    // Not ARM EHABI
    #[repr(C)]
    #[derive(Copy, Clone, PartialEq)]
    pub enum _Unwind_Action {
        _UA_SEARCH_PHASE = 1,
        _UA_CLEANUP_PHASE = 2,
        _UA_HANDLER_FRAME = 4,
        _UA_FORCE_UNWIND = 8,
        _UA_END_OF_STACK = 16,
    }
    pub use _Unwind_Action::*;

    #[cfg_attr(all(feature = "llvm-libunwind",
                   any(target_os = "fuchsia", target_os = "linux")),
               link(name = "unwind", kind = "static"))]
    extern "C" {
        pub fn _Unwind_GetGR(ctx: *mut _Unwind_Context, reg_index: c_int) -> _Unwind_Word;
        pub fn _Unwind_SetGR(ctx: *mut _Unwind_Context, reg_index: c_int, value: _Unwind_Word);
        pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> _Unwind_Word;
        pub fn _Unwind_SetIP(ctx: *mut _Unwind_Context, value: _Unwind_Word);
        pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context, ip_before_insn: *mut c_int)
                                 -> _Unwind_Word;
        pub fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void;
    }

} else {
    // ARM EHABI
    #[repr(C)]
    #[derive(Copy, Clone, PartialEq)]
    pub enum _Unwind_State {
        _US_VIRTUAL_UNWIND_FRAME = 0,
        _US_UNWIND_FRAME_STARTING = 1,
        _US_UNWIND_FRAME_RESUME = 2,
        _US_ACTION_MASK = 3,
        _US_FORCE_UNWIND = 8,
        _US_END_OF_STACK = 16,
    }
    pub use _Unwind_State::*;

    #[repr(C)]
    enum _Unwind_VRS_Result {
        _UVRSR_OK = 0,
        _UVRSR_NOT_IMPLEMENTED = 1,
        _UVRSR_FAILED = 2,
    }
    #[repr(C)]
    enum _Unwind_VRS_RegClass {
        _UVRSC_CORE = 0,
        _UVRSC_VFP = 1,
        _UVRSC_FPA = 2,
        _UVRSC_WMMXD = 3,
        _UVRSC_WMMXC = 4,
    }
    use _Unwind_VRS_RegClass::*;
    #[repr(C)]
    enum _Unwind_VRS_DataRepresentation {
        _UVRSD_UINT32 = 0,
        _UVRSD_VFPX = 1,
        _UVRSD_FPAX = 2,
        _UVRSD_UINT64 = 3,
        _UVRSD_FLOAT = 4,
        _UVRSD_DOUBLE = 5,
    }
    use _Unwind_VRS_DataRepresentation::*;

    pub const UNWIND_POINTER_REG: c_int = 12;
    pub const UNWIND_SP_REG: c_int = 13;
    pub const UNWIND_IP_REG: c_int = 15;

    #[cfg_attr(all(feature = "llvm-libunwind",
                   any(target_os = "fuchsia", target_os = "linux")),
               link(name = "unwind", kind = "static"))]
    extern "C" {
        fn _Unwind_VRS_Get(ctx: *mut _Unwind_Context,
                           regclass: _Unwind_VRS_RegClass,
                           regno: _Unwind_Word,
                           repr: _Unwind_VRS_DataRepresentation,
                           data: *mut c_void)
                           -> _Unwind_VRS_Result;

        fn _Unwind_VRS_Set(ctx: *mut _Unwind_Context,
                           regclass: _Unwind_VRS_RegClass,
                           regno: _Unwind_Word,
                           repr: _Unwind_VRS_DataRepresentation,
                           data: *mut c_void)
                           -> _Unwind_VRS_Result;
    }

    // On Android or ARM/Linux, these are implemented as macros:

    pub unsafe fn _Unwind_GetGR(ctx: *mut _Unwind_Context, reg_index: c_int) -> _Unwind_Word {
        let mut val: _Unwind_Word = 0;
        _Unwind_VRS_Get(ctx, _UVRSC_CORE, reg_index as _Unwind_Word, _UVRSD_UINT32,
                        &mut val as *mut _ as *mut c_void);
        val
    }

    pub unsafe fn _Unwind_SetGR(ctx: *mut _Unwind_Context, reg_index: c_int, value: _Unwind_Word) {
        let mut value = value;
        _Unwind_VRS_Set(ctx, _UVRSC_CORE, reg_index as _Unwind_Word, _UVRSD_UINT32,
                        &mut value as *mut _ as *mut c_void);
    }

    pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context)
                                -> _Unwind_Word {
        let val = _Unwind_GetGR(ctx, UNWIND_IP_REG);
        (val & !1) as _Unwind_Word
    }

    pub unsafe fn _Unwind_SetIP(ctx: *mut _Unwind_Context,
                                value: _Unwind_Word) {
        // Propagate thumb bit to instruction pointer
        let thumb_state = _Unwind_GetGR(ctx, UNWIND_IP_REG) & 1;
        let value = value | thumb_state;
        _Unwind_SetGR(ctx, UNWIND_IP_REG, value);
    }

    pub unsafe fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context,
                                    ip_before_insn: *mut c_int)
                                    -> _Unwind_Word {
        *ip_before_insn = 0;
        _Unwind_GetIP(ctx)
    }

    // This function also doesn't exist on Android or ARM/Linux, so make it a no-op
    pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void {
        pc
    }
}
} // cfg_if!

cfg_if::cfg_if! {
if #[cfg(not(all(target_os = "ios", target_arch = "arm")))] {
    // Not 32-bit iOS
    #[cfg_attr(all(feature = "llvm-libunwind",
                   any(target_os = "fuchsia", target_os = "linux")),
               link(name = "unwind", kind = "static"))]
    extern "C" {
        #[unwind(allowed)]
        pub fn _Unwind_RaiseException(exception: *mut _Unwind_Exception) -> _Unwind_Reason_Code;
        pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
                                 trace_argument: *mut c_void)
                                 -> _Unwind_Reason_Code;
    }
} else {
    // 32-bit iOS uses SjLj and does not provide _Unwind_Backtrace()
    #[cfg_attr(all(feature = "llvm-libunwind",
                   any(target_os = "fuchsia", target_os = "linux")),
               link(name = "unwind", kind = "static"))]
    extern "C" {
        #[unwind(allowed)]
        pub fn _Unwind_SjLj_RaiseException(e: *mut _Unwind_Exception) -> _Unwind_Reason_Code;
    }

    #[inline]
    pub unsafe fn _Unwind_RaiseException(exc: *mut _Unwind_Exception) -> _Unwind_Reason_Code {
        _Unwind_SjLj_RaiseException(exc)
    }
}
} // cfg_if!

cfg_if::cfg_if! {
if #[cfg(all(windows, target_arch = "x86_64", target_env = "gnu"))] {
    // We declare these as opaque types. This is fine since you just need to
    // pass them to _GCC_specific_handler and forget about them.
    pub enum EXCEPTION_RECORD {}
    pub type LPVOID = *mut c_void;
    pub enum CONTEXT {}
    pub enum DISPATCHER_CONTEXT {}
    pub type EXCEPTION_DISPOSITION = c_int;
    type PersonalityFn = unsafe extern "C" fn(version: c_int,
                                              actions: _Unwind_Action,
                                              exception_class: _Unwind_Exception_Class,
                                              exception_object: *mut _Unwind_Exception,
                                              context: *mut _Unwind_Context)
                                              -> _Unwind_Reason_Code;

    extern "C" {
        pub fn _GCC_specific_handler(exceptionRecord: *mut EXCEPTION_RECORD,
                                establisherFrame: LPVOID,
                                contextRecord: *mut CONTEXT,
                                dispatcherContext: *mut DISPATCHER_CONTEXT,
                                personality: PersonalityFn)
                                -> EXCEPTION_DISPOSITION;
    }
}
} // cfg_if!
<|endoftext|>


<commit_before>use std::sync::atomic::Ordering::{Acquire, Release, Relaxed};
use std::ptr;

use epoch::{self, Atomic, Owned};

/// Treiber's lock-free stack.
///
/// Usable with any number of producers and consumers.
#[derive(Debug)]
pub struct TreiberStack<T> {
    head: Atomic<Node<T>>,
}

#[derive(Debug)]
struct Node<T> {
    data: T,
    next: Atomic<Node<T>>,
}

impl<T> TreiberStack<T> {
    /// Create a new, empty stack.
    pub fn new() -> TreiberStack<T> {
        TreiberStack { head: Atomic::null() }
    }

    /// Push `t` on top of the stack.
    pub fn push(&self, t: T) {
        let mut n = Owned::new(Node {
            data: t,
            next: Atomic::null(),
        });
        let guard = epoch::pin();
        loop {
            let head = self.head.load(Relaxed, &guard);
            n.next.store_shared(head, Relaxed);
            match self.head.cas_and_ref(head, n, Release, &guard) {
                Ok(_) => break,
                Err(owned) => n = owned,
            }
        }
    }

    /// Attempt to pop the top element of the stack.
    /// **Deprecated method**, use try_pop
    ///
    /// Returns `None` if the stack is observed to be empty.
    #[cfg_attr(any(feature="beta", feature="nightly"), deprecated(note="The pop method has been renamed to try_pop for consistency with other collections."))]
    pub fn pop(&self) -> Option<T> {
        self.try_pop()
    }

    /// Attempt to pop the top element of the stack.
    ///
    /// Returns `None` if the stack is observed to be empty.
    pub fn try_pop(&self) -> Option<T> {
        let guard = epoch::pin();
        loop {
            match self.head.load(Acquire, &guard) {
                Some(head) => {
                    let next = head.next.load(Relaxed, &guard);
                    if self.head.cas_shared(Some(head), next, Release) {
                        unsafe {
                            guard.unlinked(head);
                            return Some(ptr::read(&(*head).data));
                        }
                    }
                }
                None => return None,
            }
        }
    }

    /// Check if this queue is empty.
    pub fn is_empty(&self) -> bool {
        let guard = epoch::pin();
        self.head.load(Acquire, &guard).is_none()
    }
}

impl<T> Drop for TreiberStack<T> {
    fn drop(&mut self) {
        while self.try_pop().is_some() {}
    }
}

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

    #[test]
    fn is_empty() {
        let q: TreiberStack<i64> = TreiberStack::new();
        assert!(q.is_empty());
        q.push(20);
        q.push(20);
        assert!(!q.is_empty());
        assert!(!q.is_empty());
        assert!(q.try_pop().is_some());
        assert!(q.try_pop().is_some());
        assert!(q.is_empty());
        q.push(25);
        assert!(!q.is_empty());
    }
}
<commit_msg>Add Default implementation for TreiberStack<commit_after>use std::sync::atomic::Ordering::{Acquire, Release, Relaxed};
use std::ptr;

use epoch::{self, Atomic, Owned};

/// Treiber's lock-free stack.
///
/// Usable with any number of producers and consumers.
#[derive(Debug)]
pub struct TreiberStack<T> {
    head: Atomic<Node<T>>,
}

#[derive(Debug)]
struct Node<T> {
    data: T,
    next: Atomic<Node<T>>,
}

impl<T> TreiberStack<T> {
    /// Create a new, empty stack.
    pub fn new() -> TreiberStack<T> {
        TreiberStack { head: Atomic::null() }
    }

    /// Push `t` on top of the stack.
    pub fn push(&self, t: T) {
        let mut n = Owned::new(Node {
            data: t,
            next: Atomic::null(),
        });
        let guard = epoch::pin();
        loop {
            let head = self.head.load(Relaxed, &guard);
            n.next.store_shared(head, Relaxed);
            match self.head.cas_and_ref(head, n, Release, &guard) {
                Ok(_) => break,
                Err(owned) => n = owned,
            }
        }
    }

    /// Attempt to pop the top element of the stack.
    /// **Deprecated method**, use try_pop
    ///
    /// Returns `None` if the stack is observed to be empty.
    #[cfg_attr(any(feature="beta", feature="nightly"), deprecated(note="The pop method has been renamed to try_pop for consistency with other collections."))]
    pub fn pop(&self) -> Option<T> {
        self.try_pop()
    }

    /// Attempt to pop the top element of the stack.
    ///
    /// Returns `None` if the stack is observed to be empty.
    pub fn try_pop(&self) -> Option<T> {
        let guard = epoch::pin();
        loop {
            match self.head.load(Acquire, &guard) {
                Some(head) => {
                    let next = head.next.load(Relaxed, &guard);
                    if self.head.cas_shared(Some(head), next, Release) {
                        unsafe {
                            guard.unlinked(head);
                            return Some(ptr::read(&(*head).data));
                        }
                    }
                }
                None => return None,
            }
        }
    }

    /// Check if this queue is empty.
    pub fn is_empty(&self) -> bool {
        let guard = epoch::pin();
        self.head.load(Acquire, &guard).is_none()
    }
}

impl<T> Drop for TreiberStack<T> {
    fn drop(&mut self) {
        while self.try_pop().is_some() {}
    }
}

impl<T> Default for TreiberStack<T> {
    fn default() -> Self {
        TreiberStack::new()
    }
}

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

    #[test]
    fn is_empty() {
        let q: TreiberStack<i64> = TreiberStack::new();
        assert!(q.is_empty());
        q.push(20);
        q.push(20);
        assert!(!q.is_empty());
        assert!(!q.is_empty());
        assert!(q.try_pop().is_some());
        assert!(q.try_pop().is_some());
        assert!(q.is_empty());
        q.push(25);
        assert!(!q.is_empty());
    }
}
<|endoftext|>


<commit_before>//
// zhtta.rs
//
// Running on Rust 0.8
//
// Starting code for PS3
//
// Note: it would be very unwise to run this server on a machine that is
// on the Internet and contains any sensitive files!
//
// University of Virginia - cs4414 Fall 2013
// Weilin Xu and David Evans
// Version 0.3

extern mod extra;

use std::rt::io::*;
use std::rt::io::net::ip::SocketAddr;
use std::io::println;
use std::cell::Cell;
use std::{os, str, io};
use extra::arc;
use std::comm::*;
use extra::priority_queue::PriorityQueue;
use std::rt::io::net::ip::*;

static PORT:    int = 4414;
static IP: &'static str = "127.0.0.1";

struct sched_msg {
    stream: Option<std::rt::io::net::tcp::TcpStream>,
    filepath: ~std::path::PosixPath,
    ip: IpAddr,
}

fn main() {
    let mut req_vec : PriorityQueue<sched_msg> = PriorityQueue::new();
    let shared_req_vec = arc::RWArc::new(req_vec);
    let add_vec = shared_req_vec.clone();
    let take_vec = shared_req_vec.clone();

    let (port, chan) = stream();
    let chan = SharedChan::new(chan);

    // dequeue file requests, and send responses.
    // FIFO
    do spawn {
        let (sm_port, sm_chan) = stream();

        // a task for sending responses.
        do spawn {
            loop {
                let mut tf: sched_msg = sm_port.recv(); // wait for the dequeued request to handle
                match io::read_whole_file(tf.filepath) { // killed if file size is larger than memory size.
                    Ok(file_data) => {
                        println(fmt!("begin serving file [%?]", tf.filepath));
                        // A web server should always reply a HTTP header for any legal HTTP request.
                        tf.stream.write("HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream; charset=UTF-8\r\n\r\n".as_bytes());
                        tf.stream.write(file_data);
                        println(fmt!("finish file [%?]", tf.filepath));
                    }
                    Err(err) => {
                        println(err);
                    }
                }
            }
        }

        loop {
            port.recv(); // wait for arrving notification
            do take_vec.write |vec| {
                if ((*vec).len() > 0) {
                    // LIFO didn't make sense in service scheduling, so we modify it as FIFO by using shift_opt() rather than pop().
                    let tf : sched_msg = (*vec).pop();
                    println(fmt!("shift from queue, size: %ud", (*vec).len()));
                    sm_chan.send(tf); // send the request to send-response-task to serve.
                }
            }
        }
    }

    let ip = match FromStr::from_str(IP) { Some(ip) => ip,
                                           None => { println(fmt!("Error: Invalid IP address <%s>", IP));
                                                     return;},
                                         };

    let socket = net::tcp::TcpListener::bind(SocketAddr {ip: ip, port: PORT as u16});

    println(fmt!("Listening on %s:%d ...", ip.to_str(), PORT));
    let mut acceptor = socket.listen().unwrap();

    let mycount: uint = 0;
    let shared_mycount = arc::RWArc::new(mycount);

    for stream in acceptor.incoming() {
        let stream = Cell::new(stream);

        // Start a new task to handle the each connection
        let child_chan = chan.clone();
        let child_add_vec = add_vec.clone();
        let update_count = shared_mycount.clone();
        do spawn {
            let mut visitor_count = 0;
            do update_count.write |c| {
                *c += 1;
                visitor_count = *c;
             }

            let mut stream = stream.take();

            let mut visitor_ip: IpAddr = std::rt::io::net::ip::Ipv4Addr(-1, -1, -1, -1);

            stream.and_then_mut_ref(|x| {
                    match x.peer_name() {
                        Some(sock_addr) => {visitor_ip = sock_addr.ip;},
                        None => ()
                    }
                    Some(x)
                });

            println(fmt!("Visitor IP is %s", visitor_ip.to_str()));

            let mut buf = [0, ..500];
            stream.read(buf);
            let request_str = str::from_utf8(buf);

            let req_group : ~[&str]= request_str.splitn_iter(' ', 3).collect();
            if req_group.len() > 2 {
                let path = req_group[1];
                println(fmt!("Request for path: \n%?", path));

                let file_path = ~os::getcwd().push(path.replace("/../", ""));
                if !os::path_exists(file_path) || os::path_is_dir(file_path) {
                    println(fmt!("Request received:\n%s", request_str));
                    let response: ~str = fmt!(
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n
                         <doctype !html><title>Hello, Rust!</title>

Greetings, Krusty!

Visitor count: %u

                         \r\n", visitor_count);

                    stream.write(response.as_bytes());
                }
                else {
                    // Requests scheduling
                    let msg: sched_msg = sched_msg{stream: stream, filepath: file_path.clone(), ip: visitor_ip};
                    let (sm_port, sm_chan) = std::comm::stream();
                    sm_chan.send(msg);

                    do child_add_vec.write |vec| {
                        let msg = sm_port.recv();
                        (*vec).push(msg); // enqueue new request.
                        println("add to queue");
                    }
                    child_chan.send(""); //notify the new arriving request.
                    println(fmt!("get file request: %?", file_path));
                }
            }
            println!("connection terminates")
        }
    }
}

impl Ord for sched_msg {

	fn lt(&self, other: &sched_msg) -> bool {

		let selfIP: IpAddr = self.ip;
		let otherIP: IpAddr = other.ip;

		match selfIP {
			Ipv4Addr(a , b, c, d) => {
				if ((a == 128 && b == 143) || (a == 137 && b == 54)){
					return false;
				}else{
					return true;;
				}
			},
			Ipv6Addr(a, b, c, d, e, f, g, h) => {
				if ((a == 128 && b == 143) || (a == 137 && b == 54)){
					return false;
				}else{
					return true;
				}

			}
		}

	}

}
<commit_msg>Commit #5 Incomplete Problem 3, Look at Problem 3 comments to find where code needs editing<commit_after>//
// zhtta.rs
//
// Running on Rust 0.8
//
// Starting code for PS3
//
// Note: it would be very unwise to run this server on a machine that is
// on the Internet and contains any sensitive files!
//
// University of Virginia - cs4414 Fall 2013
// Weilin Xu and David Evans
// Version 0.3

extern mod extra;

use std::rt::io::*;
use std::rt::io::net::ip::SocketAddr;
use std::io::println;
use std::cell::Cell;
use std::{os, str, io, run, uint};
use extra::arc;
use std::comm::*;
use extra::priority_queue::PriorityQueue;
use std::rt::io::net::ip::*;

static PORT:    int = 4414;
static IP: &'static str = "127.0.0.1";

struct sched_msg {
    stream: Option<std::rt::io::net::tcp::TcpStream>,
    filepath: ~std::path::PosixPath,
    ip: IpAddr,
    filesize: Option<uint>, //filesize added to store file size
}

fn main() {
    let mut req_vec : PriorityQueue<sched_msg> = PriorityQueue::new();
    let shared_req_vec = arc::RWArc::new(req_vec);
    let add_vec = shared_req_vec.clone();
    let take_vec = shared_req_vec.clone();

    let (port, chan) = stream();
    let chan = SharedChan::new(chan);

    // dequeue file requests, and send responses.
    // FIFO
    do spawn {
        let (sm_port, sm_chan) = stream();

        // a task for sending responses.
        do spawn {
            loop {
                let mut tf: sched_msg = sm_port.recv(); // wait for the dequeued request to handle
                match io::read_whole_file(tf.filepath) { // killed if file size is larger than memory size.
                    Ok(file_data) => {
                        println(fmt!("begin serving file [%?]", tf.filepath));
                        // A web server should always reply a HTTP header for any legal HTTP request.
                        tf.stream.write("HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream; charset=UTF-8\r\n\r\n".as_bytes());
                        tf.stream.write(file_data);
                        println(fmt!("finish file [%?]", tf.filepath));
                    }
                    Err(err) => {
                        println(err);
                    }
                }
            }
        }

        loop {
            port.recv(); // wait for arrving notification
            do take_vec.write |vec| {
                if ((*vec).len() > 0) {
                    // LIFO didn't make sense in service scheduling, so we modify it as FIFO by using shift_opt() rather than pop().
                    let tf : sched_msg = (*vec).pop();
                    println(fmt!("shift from queue, size: %ud", (*vec).len()));
                    sm_chan.send(tf); // send the request to send-response-task to serve.
                }
            }
        }
    }

    let ip = match FromStr::from_str(IP) { Some(ip) => ip,
                                           None => { println(fmt!("Error: Invalid IP address <%s>", IP));
                                                     return;},
                                         };

    let socket = net::tcp::TcpListener::bind(SocketAddr {ip: ip, port: PORT as u16});

    println(fmt!("Listening on %s:%d ...", ip.to_str(), PORT));
    let mut acceptor = socket.listen().unwrap();

    let mycount: uint = 0;
    let shared_mycount = arc::RWArc::new(mycount);

    for stream in acceptor.incoming() {
        let stream = Cell::new(stream);

        // Start a new task to handle the each connection
        let child_chan = chan.clone();
        let child_add_vec = add_vec.clone();
        let update_count = shared_mycount.clone();
        do spawn {
            let mut visitor_count = 0;
            do update_count.write |c| {
                *c += 1;
                visitor_count = *c;
             }

            let mut stream = stream.take();

            let mut visitor_ip: IpAddr = std::rt::io::net::ip::Ipv4Addr(-1, -1, -1, -1);

            stream.and_then_mut_ref(|x| {
                    match x.peer_name() {
                        Some(sock_addr) => {visitor_ip = sock_addr.ip;},
                        None => ()
                    }
                    Some(x)
                });

            println(fmt!("Visitor IP is %s", visitor_ip.to_str()));

            let mut buf = [0, ..500];
            stream.read(buf);
            let request_str = str::from_utf8(buf);

            let req_group : ~[&str]= request_str.splitn_iter(' ', 3).collect();
            if req_group.len() > 2 {
                let path = req_group[1];
                println(fmt!("Request for path: \n%?", path));

                let file_path = ~os::getcwd().push(path.replace("/../", ""));
                if !os::path_exists(file_path) || os::path_is_dir(file_path) {
                    println(fmt!("Request received:\n%s", request_str));
                    let response: ~str = fmt!(
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n
                         <doctype !html><title>Hello, Rust!</title>

Greetings, Krusty!

Visitor count: %u

                         \r\n", visitor_count);

                    stream.write(response.as_bytes());
                }
                else {
                    // Requests scheduling

		    // Started Problem 3 code here
		    // Creates process that runs and parses file size command for problem 3
		    let mut args : ~[~str] = ~[~"-c", ~"<", file_path.to_str()];
		    let mut pr = run::Process::new("wc", args, run::ProcessOptions::new());
		    let poutput = pr.finish_with_output();
		    let mut poutputc = poutput.output;
		    let mut realstr = str::from_utf8(poutputc);
		    let mut formatfsize : Option<uint> = from_str(realstr);
                    let msg: sched_msg = sched_msg{stream: stream, filepath: file_path.clone(), ip: visitor_ip, filesize : formatfsize };
		    println(formatfsize.to_str());//print file size served
		    //Problem 3 Code finishes here

                    let (sm_port, sm_chan) = std::comm::stream();
                    sm_chan.send(msg);

                    do child_add_vec.write |vec| {
                        let msg = sm_port.recv();
                        (*vec).push(msg); // enqueue new request.
                        println("add to queue");
                    }
                    child_chan.send(""); //notify the new arriving request.
                    println(fmt!("get file request: %?", file_path));
                }
            }
            println!("connection terminates")
        }
    }
}

impl Ord for sched_msg {

	fn lt(&self, other: &sched_msg) -> bool {

		let selfIP: IpAddr = self.ip;
		let otherIP: IpAddr = other.ip;

		match selfIP {
			Ipv4Addr(a , b, c, d) => {
				if ((a == 128 && b == 143) || (a == 137 && b == 54)){
					return false;
				}else{
					return true;;
				}
			},
			Ipv6Addr(a, b, c, d, e, f, g, h) => {
				if ((a == 128 && b == 143) || (a == 137 && b == 54)){
					return false;
				}else{
					return true;
				}

			}
		}

	}

}
<|endoftext|>


<commit_before>// Copyright 2016 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Utilities to check the status of all the outputs we have stored in
//! the wallet storage and update them.

use std::collections::hash_map::Entry;
use std::collections::HashMap;

use api;
use types::*;
use keychain::{Identifier, Keychain};
use secp::pedersen;
use util;
use util::LOGGER;

// Transitions a local wallet output from Unconfirmed -> Unspent.
// Also updates the height and lock_height based on latest from the api.
fn refresh_output(out: &mut OutputData, api_out: &api::Output) {
	out.height = api_out.height;
	out.lock_height = api_out.lock_height;

	match out.status {
		OutputStatus::Unconfirmed => {
			out.status = OutputStatus::Unspent;
		},
		_ => (),
	}
}

// Transitions a local wallet output (based on it not being in the node utxo set) -
// Unspent -> Spent
// Locked -> Spent
fn mark_spent_output(out: &mut OutputData) {
	match out.status {
		OutputStatus::Unspent | OutputStatus::Locked => {
			out.status = OutputStatus::Spent
		},
		_ => (),
	}
}

/// Builds a single api query to retrieve the latest output data from the node.
/// So we can refresh the local wallet outputs.
pub fn refresh_outputs(
	config: &WalletConfig,
	keychain: &Keychain,
) -> Result<(), Error> {
	debug!(LOGGER, "Refreshing wallet outputs");
	let mut wallet_outputs: HashMap<pedersen::Commitment, Identifier> = HashMap::new();
	let mut commits: Vec<pedersen::Commitment> = vec![];

	// build a local map of wallet outputs by commits
	// and a list of outputs we wantot query the node for
	let _ = WalletData::read_wallet(&config.data_file_dir, |wallet_data| {
		for out in wallet_data.outputs
			.values()
			.filter(|out| out.root_key_id == keychain.root_key_id())
			.filter(|out| out.status != OutputStatus::Spent)
		{
			let key_id = keychain.derive_key_id(out.n_child).unwrap();
			let commit = keychain.commit(out.value, &key_id).unwrap();
			commits.push(commit);
			wallet_outputs.insert(commit, out.key_id.clone());
		}
	});

	// build the necessary query params -
	// ?id=xxx&id=yyy&id=zzz
	let query_params: Vec<String> = commits
		.iter()
		.map(|commit| {
			let id = util::to_hex(commit.as_ref().to_vec());
			format!("id={}", id)
		})
		.collect();
	let query_string = query_params.join("&");

	let url = format!(
		"{}/v2/chain/utxos?{}",
		config.check_node_api_http_addr,
		query_string,
	);

	// build a map of api outputs by commit so we can look them up efficiently
	let mut api_outputs: HashMap<pedersen::Commitment, api::Output> = HashMap::new();
	match api::client::get::<Vec<api::Output>>(url.as_str()) {
		Ok(outputs) => {
			for out in outputs {
				api_outputs.insert(out.commit, out);
			}
		},
		Err(_) => {},
	};

	// now for each commit, find the output in the wallet and
	// the corresponding api output (if it exists)
	// and refresh it in-place in the wallet.
	// Note: minimizing the time we spend holding the wallet lock.
	WalletData::with_wallet(&config.data_file_dir, |wallet_data| {
		for commit in commits {
			let id = wallet_outputs.get(&commit).unwrap();
			if let Entry::Occupied(mut output) = wallet_data.outputs.entry(id.to_hex()) {
				match api_outputs.get(&commit) {
					Some(api_output) => refresh_output(&mut output.get_mut(), api_output),
					None => mark_spent_output(&mut output.get_mut()),
				};
			}
		}
	})
}

pub fn get_tip_from_node(config: &WalletConfig) -> Result<api::Tip, Error> {
	let url = format!("{}/v1/chain/1", config.check_node_api_http_addr);
	api::client::get::<api::Tip>(url.as_str()).map_err(|e| Error::Node(e))
}
<commit_msg>Small fix to chain tip check for send<commit_after>// Copyright 2016 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Utilities to check the status of all the outputs we have stored in
//! the wallet storage and update them.

use std::collections::hash_map::Entry;
use std::collections::HashMap;

use api;
use types::*;
use keychain::{Identifier, Keychain};
use secp::pedersen;
use util;
use util::LOGGER;

// Transitions a local wallet output from Unconfirmed -> Unspent.
// Also updates the height and lock_height based on latest from the api.
fn refresh_output(out: &mut OutputData, api_out: &api::Output) {
	out.height = api_out.height;
	out.lock_height = api_out.lock_height;

	match out.status {
		OutputStatus::Unconfirmed => {
			out.status = OutputStatus::Unspent;
		},
		_ => (),
	}
}

// Transitions a local wallet output (based on it not being in the node utxo set) -
// Unspent -> Spent
// Locked -> Spent
fn mark_spent_output(out: &mut OutputData) {
	match out.status {
		OutputStatus::Unspent | OutputStatus::Locked => {
			out.status = OutputStatus::Spent
		},
		_ => (),
	}
}

/// Builds a single api query to retrieve the latest output data from the node.
/// So we can refresh the local wallet outputs.
pub fn refresh_outputs(
	config: &WalletConfig,
	keychain: &Keychain,
) -> Result<(), Error> {
	debug!(LOGGER, "Refreshing wallet outputs");
	let mut wallet_outputs: HashMap<pedersen::Commitment, Identifier> = HashMap::new();
	let mut commits: Vec<pedersen::Commitment> = vec![];

	// build a local map of wallet outputs by commits
	// and a list of outputs we wantot query the node for
	let _ = WalletData::read_wallet(&config.data_file_dir, |wallet_data| {
		for out in wallet_data.outputs
			.values()
			.filter(|out| out.root_key_id == keychain.root_key_id())
			.filter(|out| out.status != OutputStatus::Spent)
		{
			let key_id = keychain.derive_key_id(out.n_child).unwrap();
			let commit = keychain.commit(out.value, &key_id).unwrap();
			commits.push(commit);
			wallet_outputs.insert(commit, out.key_id.clone());
		}
	});

	// build the necessary query params -
	// ?id=xxx&id=yyy&id=zzz
	let query_params: Vec<String> = commits
		.iter()
		.map(|commit| {
			let id = util::to_hex(commit.as_ref().to_vec());
			format!("id={}", id)
		})
		.collect();
	let query_string = query_params.join("&");

	let url = format!(
		"{}/v2/chain/utxos?{}",
		config.check_node_api_http_addr,
		query_string,
	);

	// build a map of api outputs by commit so we can look them up efficiently
	let mut api_outputs: HashMap<pedersen::Commitment, api::Output> = HashMap::new();
	match api::client::get::<Vec<api::Output>>(url.as_str()) {
		Ok(outputs) => {
			for out in outputs {
				api_outputs.insert(out.commit, out);
			}
		},
		Err(_) => {},
	};

	// now for each commit, find the output in the wallet and
	// the corresponding api output (if it exists)
	// and refresh it in-place in the wallet.
	// Note: minimizing the time we spend holding the wallet lock.
	WalletData::with_wallet(&config.data_file_dir, |wallet_data| {
		for commit in commits {
			let id = wallet_outputs.get(&commit).unwrap();
			if let Entry::Occupied(mut output) = wallet_data.outputs.entry(id.to_hex()) {
				match api_outputs.get(&commit) {
					Some(api_output) => refresh_output(&mut output.get_mut(), api_output),
					None => mark_spent_output(&mut output.get_mut()),
				};
			}
		}
	})
}

pub fn get_tip_from_node(config: &WalletConfig) -> Result<api::Tip, Error> {
	let url = format!("{}/v2/chain", config.check_node_api_http_addr);
	api::client::get::<api::Tip>(url.as_str()).map_err(|e| Error::Node(e))
}
<|endoftext|>


<commit_before>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

#![deny(missing_docs)]
#![recursion_limit = "1024"]

//! Admission Control
//!
//! Admission Control (AC) is the public API end point taking public gRPC requests from clients.
//! AC serves two types of request from clients:
//! 1. SubmitTransaction, to submit transaction to associated validator.
//! 2. UpdateToLatestLedger, to query storage, e.g. account state, transaction log, and proofs.

#[cfg(feature = "fuzzing")]
/// Fuzzer for admission control
pub mod admission_control_fuzzing;
/// AC gRPC service.
pub mod admission_control_service;
#[cfg(feature = "fuzzing")]
/// Useful Mocks
pub mod mocks;
/// AC runtime to launch gRPC and network service
pub mod runtime;
/// Handler for sending transaction write requests upstream if needed
mod upstream_proxy;
use lazy_static::lazy_static;
use libra_metrics::OpMetrics;

use libra_types::account_address::AccountAddress;
type PeerId = AccountAddress;

lazy_static! {
    static ref OP_COUNTERS: OpMetrics = OpMetrics::new_and_registered("admission_control");
}
<commit_msg>[admission-control] Add service test into lib<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

#![deny(missing_docs)]
#![recursion_limit = "1024"]

//! Admission Control
//!
//! Admission Control (AC) is the public API end point taking public gRPC requests from clients.
//! AC serves two types of request from clients:
//! 1. SubmitTransaction, to submit transaction to associated validator.
//! 2. UpdateToLatestLedger, to query storage, e.g. account state, transaction log, and proofs.

#[cfg(test)]
#[path = "unit_tests/admission_control_service_test.rs"]
mod admission_control_service_test;

#[cfg(feature = "fuzzing")]
/// Fuzzer for admission control
pub mod admission_control_fuzzing;
/// AC gRPC service.
pub mod admission_control_service;
#[cfg(feature = "fuzzing")]
/// Useful Mocks
pub mod mocks;
/// AC runtime to launch gRPC and network service
pub mod runtime;
/// Handler for sending transaction write requests upstream if needed
mod upstream_proxy;
use lazy_static::lazy_static;
use libra_metrics::OpMetrics;

use libra_types::account_address::AccountAddress;
type PeerId = AccountAddress;

lazy_static! {
    static ref OP_COUNTERS: OpMetrics = OpMetrics::new_and_registered("admission_control");
}
<|endoftext|>


<commit_before>#![feature(plugin)]
#![feature(unboxed_closures)]
#![plugin(glium_macros)]

extern crate glutin;

#[macro_use]
extern crate glium;

use std::default::Default;
use glium::Surface;

mod support;

#[test]
fn texture_2d_draw() {
    let display = support::build_display();
    let (vb, ib) = support::build_rectangle_vb_ib(&display);

    let texture = glium::texture::Texture2d::new(&display, vec![
        vec![(255, 0, 0, 255), (255, 0, 0, 255)],
        vec![(255, 0, 0, 255), (255, 0, 0, 255u8)],
    ]);

    let program = glium::Program::from_source(&display,
        "
            #version 110

            attribute vec2 position;

            void main() {
                gl_Position = vec4(position, 0.0, 1.0);
            }
        ",
        "
            #version 110

            uniform sampler2D texture;

            void main() {
                gl_FragColor = texture2D(texture, vec2(0.5, 0.5));
            }
        ",
        None).unwrap();

    let output = support::build_renderable_texture(&display);
    output.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
    output.as_surface().draw(&vb, &ib, &program, &uniform!{ texture: &texture },
                             &Default::default()).unwrap();

    let data: Vec<Vec<(f32, f32, f32, f32)>> = output.read();
    for row in data.iter() {
        for pixel in row.iter() {
            assert_eq!(pixel, &(1.0, 0.0, 0.0, 1.0));
        }
    }

    display.assert_no_error();
}

#[test]
fn compressed_texture_2d_draw() {
    let display = support::build_display();
    let (vb, ib) = support::build_rectangle_vb_ib(&display);

    let texture = glium::texture::CompressedTexture2d::new(&display, vec![
        vec![(255, 0, 0, 255), (255, 0, 0, 255)],
        vec![(255, 0, 0, 255), (255, 0, 0, 255u8)],
    ]);

    let program = glium::Program::from_source(&display,
        "
            #version 110

            attribute vec2 position;

            void main() {
                gl_Position = vec4(position, 0.0, 1.0);
            }
        ",
        "
            #version 110

            uniform sampler2D texture;

            void main() {
                gl_FragColor = texture2D(texture, vec2(0.5, 0.5));
            }
        ",
        None).unwrap();

    let output = support::build_renderable_texture(&display);
    output.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
    output.as_surface().draw(&vb, &ib, &program, &uniform!{ texture: &texture },
                             &Default::default()).unwrap();

    let data: Vec<Vec<(f32, f32, f32, f32)>> = output.read();
    for row in data.iter() {
        for pixel in row.iter() {
            assert_eq!(pixel, &(1.0, 0.0, 0.0, 1.0));
        }
    }

    display.assert_no_error();
}
<commit_msg>Use macros in tests/texture_draw.rs<commit_after>#![feature(plugin)]
#![feature(unboxed_closures)]
#![plugin(glium_macros)]

extern crate glutin;

#[macro_use]
extern crate glium;

use std::default::Default;
use glium::Surface;

mod support;

macro_rules! texture_draw_test {
    ($test_name:ident, $tex_ty:ident, $sampler_ty:expr, $fun:expr, $coords:expr, $data:expr) => (
        #[test]
        fn $test_name() {
            let display = support::build_display();
            let (vb, ib) = support::build_rectangle_vb_ib(&display);

            let texture = glium::texture::$tex_ty::new(&display, vec![
                vec![(255, 0, 0, 255), (255, 0, 0, 255)],
                vec![(255, 0, 0, 255), (255, 0, 0, 255u8)],
            ]);

            let program = glium::Program::from_source(&display,
                "
                    #version 110

                    attribute vec2 position;

                    void main() {
                        gl_Position = vec4(position, 0.0, 1.0);
                    }
                ",
                format!("
                    #version 110

                    uniform {} texture;

                    void main() {{
                        gl_FragColor = {}(texture, {});
                    }}
                ", $sampler_ty, $fun, $coords).as_slice(),
                None).unwrap();

            let output = support::build_renderable_texture(&display);
            output.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
            output.as_surface().draw(&vb, &ib, &program, &uniform!{ texture: &texture },
                                     &Default::default()).unwrap();

            let data: Vec<Vec<(f32, f32, f32, f32)>> = output.read();
            for row in data.iter() {
                for pixel in row.iter() {
                    assert_eq!(pixel, &(1.0, 0.0, 0.0, 1.0));
                }
            }

            display.assert_no_error();
        }
    );
}

texture_draw_test!(texture_2d_draw, Texture2d, "sampler2D", "texture2D", "vec2(0.5, 0.5)",
    vec![
        vec![(255, 0, 0, 255), (255, 0, 0, 255)],
        vec![(255, 0, 0, 255), (255, 0, 0, 255u8)],
    ]);

texture_draw_test!(compressed_texture_2d_draw, CompressedTexture2d, "sampler2D", "texture2D",
    "vec2(0.5, 0.5)",
    vec![
        vec![(255, 0, 0, 255), (255, 0, 0, 255)],
        vec![(255, 0, 0, 255), (255, 0, 0, 255u8)],
    ]);
<|endoftext|>


<commit_before>use super::MessageAction;

use serde::de::{
    Deserialize,
    Deserializer,
    Error,
    MapVisitor,
    Visitor
};
use std::collections::BTreeMap;

impl Deserialize for MessageAction {
    fn deserialize<D>(deserializer: &mut D) -> Result<MessageAction, D::Error>
        where D: Deserializer
    {
        deserializer.visit_struct("MessageAction", &[], MessageActionVisitor)
    }
}

enum Field {
    Uuid,
    Name,
    Values,
}

impl Deserialize for Field {
    fn deserialize<D>(deserializer: &mut D) -> Result<Field, D::Error>
        where D: Deserializer
    {
        struct FieldVisitor;

        impl Visitor for FieldVisitor {
            type Value = Field;

            fn visit_str<E>(&mut self, value: &str) -> Result<Field, E>
                where E: Error
            {
                match value {
                    "name" => Ok(Field::Name),
                    "uuid" => Ok(Field::Uuid),
                    "values" => Ok(Field::Values),
                    _ => Err(Error::syntax(&format!("Unexpected field: {}", value))),
                }
            }
        }

        deserializer.visit(FieldVisitor)
    }
}

struct MessageActionVisitor;

impl Visitor for MessageActionVisitor {
    type Value = MessageAction;

    fn visit_map<V>(&mut self, mut visitor: V) -> Result<MessageAction, V::Error>
        where V: MapVisitor
    {
        let mut name = None;
        let mut uuid = None;
        let mut values = None;

        loop {
            match try!(visitor.visit_key()) {
                Some(Field::Name) => { name = Some(try!(visitor.visit_value())); }
                Some(Field::Uuid) => { uuid = Some(try!(visitor.visit_value())); }
                Some(Field::Values) => { values = Some(try!(visitor.visit_value())); }
                None => { break; }
            }
        }

        let uuid = match uuid {
            Some(uuid) => uuid,
            None => return visitor.missing_field("uuid"),
        };

        let values = match values {
            Some(values) => values,
            None => BTreeMap::new()
        };

        try!(visitor.end());

        Ok(
            MessageAction {
                name: name,
                uuid: uuid,
                values: values
            }
        )
    }
}

#[cfg(test)]
mod test {
    use config::action::message::{
        MessageActionBuilder, MessageAction
    };

    use serde_json::from_str;

    #[test]
    fn test_given_message_as_a_json_string_when_it_is_deserialized_then_we_get_the_expected_message() {
        let text = r#"
        {
          "uuid": "UUID",
          "name": "NAME",
          "values": {
            "key1": "value1",
            "key2": "value2"
          }
        }
        "#;

        let expected_message = MessageActionBuilder::new("UUID")
                                        .name("NAME")
                                        .pair("key1", "value1")
                                        .pair("key2", "value2")
                                        .build();
        let result = from_str::<MessageAction>(text);
        println!("{:?}", &result);
        let message = result.ok().expect("Failed to deserialize a valid MessageAction object");
        assert_eq!(expected_message, message);
    }

    #[test]
    fn test_given_message_as_a_json_string_when_only_the_required_fields_are_present_then_we_can_deserialize_the_message() {
        let text = r#"
        {
          "uuid": "UUID"
        }
        "#;

        let expected_message = MessageActionBuilder::new("UUID")
                                        .build();
        let result = from_str::<MessageAction>(text);
        println!("{:?}", &result);
        let message = result.ok().expect("Failed to deserialize a valid MessageAction object");
        assert_eq!(expected_message, message);
    }

    #[test]
    fn test_given_message_as_a_json_string_when_one_of_the_required_fields_are_not_present_then_we_get_error() {
        let text = r#"
        {
        }
        "#;

        let result = from_str::<MessageAction>(text);
        println!("{:?}", &result);
        let _ = result.err().expect("Successfully deserialized an invalid MessageAction object");
    }
}
<commit_msg>MessageAction::deser: use the message field during deserialization<commit_after>use super::MessageAction;

use serde::de::{
    Deserialize,
    Deserializer,
    Error,
    MapVisitor,
    Visitor
};
use std::collections::BTreeMap;

impl Deserialize for MessageAction {
    fn deserialize<D>(deserializer: &mut D) -> Result<MessageAction, D::Error>
        where D: Deserializer
    {
        deserializer.visit_struct("MessageAction", &[], MessageActionVisitor)
    }
}

enum Field {
    Uuid,
    Name,
    Message,
    Values,
}

impl Deserialize for Field {
    fn deserialize<D>(deserializer: &mut D) -> Result<Field, D::Error>
        where D: Deserializer
    {
        struct FieldVisitor;

        impl Visitor for FieldVisitor {
            type Value = Field;

            fn visit_str<E>(&mut self, value: &str) -> Result<Field, E>
                where E: Error
            {
                match value {
                    "name" => Ok(Field::Name),
                    "uuid" => Ok(Field::Uuid),
                    "values" => Ok(Field::Values),
                    "message" => Ok(Field::Message),
                    _ => Err(Error::syntax(&format!("Unexpected field: {}", value))),
                }
            }
        }

        deserializer.visit(FieldVisitor)
    }
}

struct MessageActionVisitor;

impl Visitor for MessageActionVisitor {
    type Value = MessageAction;

    fn visit_map<V>(&mut self, mut visitor: V) -> Result<MessageAction, V::Error>
        where V: MapVisitor
    {
        let mut name = None;
        let mut uuid = None;
        let mut message = None;
        let mut values = None;

        loop {
            match try!(visitor.visit_key()) {
                Some(Field::Name) => { name = Some(try!(visitor.visit_value())); }
                Some(Field::Uuid) => { uuid = Some(try!(visitor.visit_value())); }
                Some(Field::Message) => { message = Some(try!(visitor.visit_value())); }
                Some(Field::Values) => { values = Some(try!(visitor.visit_value())); }
                None => { break; }
            }
        }

        let uuid = match uuid {
            Some(uuid) => uuid,
            None => return visitor.missing_field("uuid"),
        };

        let message = match message {
            Some(message) => message,
            None => {
                error!("Missing 'message' field: uuid={}", &uuid);
                return visitor.missing_field("message");
            }
        };

        let values = match values {
            Some(values) => values,
            None => BTreeMap::new()
        };

        try!(visitor.end());

        Ok(
            MessageAction {
                name: name,
                uuid: uuid,
                message: message,
                values: values
            }
        )
    }
}

#[cfg(test)]
mod test {
    use config::action::message::{
        MessageActionBuilder, MessageAction
    };

    use serde_json::from_str;

    #[test]
    fn test_given_message_as_a_json_string_when_it_is_deserialized_then_we_get_the_expected_message() {
        let text = r#"
        {
          "uuid": "UUID",
          "name": "NAME",
          "message": "message",
          "values": {
            "key1": "value1",
            "key2": "value2"
          }
        }
        "#;

        let expected_message = MessageActionBuilder::new("UUID", "message")
                                        .name("NAME")
                                        .pair("key1", "value1")
                                        .pair("key2", "value2")
                                        .build();
        let result = from_str::<MessageAction>(text);
        println!("{:?}", &result);
        let message = result.ok().expect("Failed to deserialize a valid MessageAction object");
        assert_eq!(expected_message, message);
    }

    #[test]
    fn test_given_message_as_a_json_string_when_only_the_required_fields_are_present_then_we_can_deserialize_the_message() {
        let text = r#"
        {
          "uuid": "UUID",
          "message": "message"
        }
        "#;

        let expected_message = MessageActionBuilder::new("UUID", "message")
                                        .build();
        let result = from_str::<MessageAction>(text);
        println!("{:?}", &result);
        let message = result.ok().expect("Failed to deserialize a valid MessageAction object");
        assert_eq!(expected_message, message);
    }

    #[test]
    fn test_given_message_as_a_json_string_when_one_of_the_required_fields_are_not_present_then_we_get_error() {
        let text = r#"
        {
        }
        "#;

        let result = from_str::<MessageAction>(text);
        println!("{:?}", &result);
        let _ = result.err().expect("Successfully deserialized an invalid MessageAction object");
    }
}
<|endoftext|>


<commit_before>//! The simplest possible implementation of the TimeSteward API.
//!
//! This implementation is unusably slow on large simulations. Its main use is to cross-check with other TimeSteward implementations to make sure they are implementing the API correctly.
//!
//!

use super::{DeterministicRandomId, SiphashIdGenerator, RowId, FieldId, Column, ExtendedTime,
            EventRng, Basics, TimeSteward, FiatEventOperationResult, ValidSince,
            TimeStewardLifetimedMethods, TimeStewardStaticMethods};
use std::collections::{HashMap, BTreeMap};
use std::hash::Hash;
// use std::collections::Bound::{Included, Excluded, Unbounded};
use std::any::Any;
use std::borrow::Borrow;
use std::rc::Rc;
use std::marker::PhantomData;

#[derive (Clone)]
pub struct Steward<B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > (Steward0, Steward1, PhantomData <B::Constants>);
pub struct Snapshot<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > (
  <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Snapshot,
  <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Snapshot,
);
pub enum Mutator<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > where <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Mutator: 'a, <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Mutator: 'a {
  Form0 (& 'a mut <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Mutator),
  Form1 (& 'a mut <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Mutator),
}
pub enum PredictorAccessor<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > where <Steward0 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor: 'a, <Steward1 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor: 'a {
  Form0 (& 'a mut <Steward0 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor),
  Form1 (& 'a mut <Steward1 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor),
}
pub type Event<B, Steward0, Steward1> = Rc<for<'d, 'e> Fn(&'d mut Mutator<'e, B, Steward0, Steward1>)>;
pub type Predictor<B, Steward0, Steward1> = super::Predictor<PredictorFn<B, Steward0, Steward1>>;
pub type PredictorFn<B, Steward0, Steward1> = Rc<for<'b, 'c> Fn(&'b mut PredictorAccessor<'c, B, Steward0, Steward1>, RowId)>;

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for Snapshot<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match (self.0.get::<C> (id), self.1.get::<C> (id)) {
      (None, None) => None,
      //we cannot actually check whether the values are the same, so just use one of them
      (Some (value_0), Some (value_1)) => Some (value_0),
      //however, we CAN tell the difference between something and nothing
      _=> panic! ("One snapshot returned a value and the other didn't; this proves that one or both of the stewards is buggy")
    }
  }
  fn constants(&self) -> &B::Constants {
    //constants are usually implemented trivially; we don't bother checking them
    self.0.constants()
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for Mutator<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match self {
      &mut Mutator::Form0 (other) => other.get::<C> (id),
      &mut Mutator::Form1 (other) => other.get::<C> (id),
    }
  }
  fn constants(&self) -> &B::Constants {
    match self {
      & Mutator::Form0 (other) => other.constants (),
      & Mutator::Form1 (other) => other.constants (),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for PredictorAccessor<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match self {
      &mut PredictorAccessor::Form0 (other) => other.get::<C> (id),
      &mut PredictorAccessor::Form1 (other) => other.get::<C> (id),
    }
  }
  fn constants(&self) -> &B::Constants {
    match self {
      & PredictorAccessor::Form0 (other) => other.constants (),
      & PredictorAccessor::Form1 (other) => other.constants (),
    }
  }
}

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::MomentaryAccessor<B> for Snapshot<'a, B, Steward0, Steward1> {
  fn now(&self) -> &B::Time {
    let result = (self.0.now(), self.1.now());
    assert! (result.0 == result.1, "Snapshots returned different times; this is an egregious bug!");
    result.0
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::MomentaryAccessor<B> for Mutator<'a, B, Steward0, Steward1> {
  fn now(&self) -> &B::Time {
    match self {
      & Mutator::Form0 (other) => other.now(),
      & Mutator::Form1 (other) => other.now(),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::PredictorAccessor<B, Event <B, Steward0, Steward1>> for PredictorAccessor<'a, B, Steward0, Steward1> {
  fn predict_immediately(&mut self, event: Event<B, Steward0, Steward1>) {
    match self {
      &mut PredictorAccessor::Form0 (other) => other.predict_immediately(convert_event_0 (event)),
      &mut PredictorAccessor::Form1 (other) => other.predict_immediately(convert_event_1 (event)),
    }
  }
  fn predict_at_time(&mut self, time: &B::Time, event: Event<B, Steward0, Steward1>) {
    match self {
      &mut PredictorAccessor::Form0 (other) => other.predict_at_time(time, convert_event_0 (event)),
      &mut PredictorAccessor::Form1 (other) => other.predict_at_time(time, convert_event_1 (event)),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Snapshot<B> for Snapshot<'a, B, Steward0, Steward1> {}

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Mutator<B> for Mutator<'a, B, Steward0, Steward1> {
  fn set<C: Column>(&mut self, id: RowId, data: Option<C::FieldType>) {
    match self {
      &mut Mutator::Form0 (other) => other.set::<C>(id, data),
      &mut Mutator::Form1 (other) => other.set::<C>(id, data),
    }
  }
  fn rng(&mut self) -> &mut EventRng {
    match self {
      &mut Mutator::Form0 (other) => other.rng (),
      &mut Mutator::Form1 (other) => other.rng (),
    }
  }
  fn random_id(&mut self) -> RowId {
    match self {
      &mut Mutator::Form0 (other) => other.random_id(),
      &mut Mutator::Form1 (other) => other.random_id(),
    }
  }
}

fn convert_event_0 <B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B>> (event: Event <B, Steward0, Steward1>)-><Steward0 as TimeStewardStaticMethods <B>>::Event {
  Rc::new (| mutator | {event (&mut Mutator::Form0 (mutator))});
}
fn convert_event_1 <B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B>> (event: Event <B, Steward0, Steward1>)-><Steward1 as TimeStewardStaticMethods <B>>::Event {
  Rc::new (| mutator | {event (&mut Mutator::Form1 (mutator))});
}
fn convert_predictor_0 <B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B>> (event: Predictor <B, Steward0, Steward1>)-><Steward0 as TimeStewardStaticMethods <B>>::Predictor {
  <Steward0 as TimeStewardStaticMethods <B>>::Predictor {
    Rc::new (| mutator | {event (&mut Mutator::Form0 (mutator))}),
  }
}

impl<'a, B: Basics, Steward0: 'a + TimeSteward<B>, Steward1: 'a + TimeSteward<B> > TimeStewardLifetimedMethods<'a, B> for Steward<B, Steward0, Steward1> where B::Constants: Clone {
  type Snapshot = Snapshot<'a, B, Steward0, Steward1>;
  type Mutator = Mutator <'a, B, Steward0, Steward1>;
  type PredictorAccessor = PredictorAccessor <'a, B, Steward0, Steward1>;

  fn snapshot_before(&'a mut self, time: &B::Time) -> Option<Self::Snapshot> {
    match (
      self.0.snapshot_before (time),
      self.1.snapshot_before (time)
    ) {
      (None, None) => None,
      (Some (snapshot_0), Some (snapshot_1)) => Some (Snapshot (snapshot_0, snapshot_1)),
      _=> panic! ("One steward returned a snapshot and the other didn't; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)")
    }
  }
}
impl<B: Basics, Steward0: TimeSteward<B> , Steward1: TimeSteward<B> > TimeStewardStaticMethods <B> for Steward<B, Steward0, Steward1> where B::Constants: Clone {
  type Event = Event<B, Steward0, Steward1>;
  type Predictor = Predictor<B, Steward0, Steward1>;

  fn valid_since(&self) -> ValidSince<B::Time> {
    unimplemented!()
  }
  fn new_empty(constants: B::Constants, predictors: Vec<Self::Predictor>) -> Self {
    Steward (
      TimeStewardStaticMethods::new_empty (constants.clone(), predictors.iter().map(| predictor | Steward0::Predictor {predictor_id: predictor. predictor_id, column_id: predictor.column_id, function: Rc::new (| accessor, row | (predictor.function) (&mut PredictorAccessor::Form0 (accessor), row))}).collect()),
      TimeStewardStaticMethods::new_empty (constants, predictors.iter().map(| predictor | Steward1::Predictor {predictor_id: predictor. predictor_id, column_id: predictor.column_id, function: Rc::new (| accessor, row | (predictor.function) (&mut PredictorAccessor::Form1 (accessor), row))}).collect()),
      PhantomData,
    )
  }

  fn insert_fiat_event(&mut self,
                       time: B::Time,
                       id: DeterministicRandomId,
                       event: Self::Event)
                       -> FiatEventOperationResult {
    let result_0 = self.0.insert_fiat_event (time.clone(), id.clone(),convert_event_0 (event));
    let result_1 = self.1.insert_fiat_event (time, id, convert_event_1 (event));
    assert! (result_0 == result_1, "stewards returned different results for insert_fiat_event; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)");
    result_0
  }
  fn erase_fiat_event(&mut self,
                      time: &B::Time,
                      id: DeterministicRandomId)
                      -> FiatEventOperationResult {
    let result_0 = self.0.erase_fiat_event (time, id.clone());
    let result_1 = self.1.erase_fiat_event (time, id);
    assert! (result_0 == result_1, "stewards returned different results for erase_fiat_event; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)");
    result_0
  }
}
impl<B: Basics, Steward0: TimeSteward<B> , Steward1: TimeSteward<B> > TimeSteward<B> for Steward<B, Steward0, Steward1> where B::Constants: Clone {}
<commit_msg>More work trying to make the cross verified stuff work<commit_after>//! The simplest possible implementation of the TimeSteward API.
//!
//! This implementation is unusably slow on large simulations. Its main use is to cross-check with other TimeSteward implementations to make sure they are implementing the API correctly.
//!
//!

use super::{DeterministicRandomId, SiphashIdGenerator, RowId, FieldId, Column, ExtendedTime,
            EventRng, Basics, TimeSteward, FiatEventOperationResult, ValidSince,
            TimeStewardLifetimedMethods, TimeStewardStaticMethods};
use std::collections::{HashMap, BTreeMap};
use std::hash::Hash;
// use std::collections::Bound::{Included, Excluded, Unbounded};
use std::any::Any;
use std::borrow::Borrow;
use std::rc::Rc;
use std::marker::PhantomData;

#[derive (Clone)]
pub struct Steward<B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > (Steward0, Steward1, PhantomData <B::Constants>);
pub struct Snapshot<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > (
  <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Snapshot,
  <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Snapshot,
);
pub enum Mutator<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > where <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Mutator: 'a, <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Mutator: 'a {
  Form0 (& 'a mut <Steward0 as TimeStewardLifetimedMethods <'a, B>>::Mutator),
  Form1 (& 'a mut <Steward1 as TimeStewardLifetimedMethods <'a, B>>::Mutator),
}
pub enum PredictorAccessor<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > where <Steward0 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor: 'a, <Steward1 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor: 'a {
  Form0 (& 'a mut <Steward0 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor),
  Form1 (& 'a mut <Steward1 as TimeStewardLifetimedMethods <'a, B>>::PredictorAccessor),
}
pub type EventFn <B, Steward0, Steward1> = for<'d, 'e> Fn(&'d mut Mutator<'e, B, Steward0, Steward1>);
pub type Event<B, Steward0, Steward1> = Rc<EventFn <B, Steward0, Steward1>>;
pub type Predictor<B, Steward0, Steward1> = super::Predictor<PredictorFn<B, Steward0, Steward1>>;
pub type PredictorFn<B, Steward0, Steward1> = for<'b, 'c> Fn(&'b mut PredictorAccessor<'c, B, Steward0, Steward1>, RowId);

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for Snapshot<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match (self.0.get::<C> (id), self.1.get::<C> (id)) {
      (None, None) => None,
      //we cannot actually check whether the values are the same, so just use one of them
      (Some (value_0), Some (value_1)) => Some (value_0),
      //however, we CAN tell the difference between something and nothing
      _=> panic! ("One snapshot returned a value and the other didn't; this proves that one or both of the stewards is buggy")
    }
  }
  fn constants(&self) -> &B::Constants {
    //constants are usually implemented trivially; we don't bother checking them
    self.0.constants()
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for Mutator<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match self {
      &mut Mutator::Form0 (other) => other.get::<C> (id),
      &mut Mutator::Form1 (other) => other.get::<C> (id),
    }
  }
  fn constants(&self) -> &B::Constants {
    match self {
      & Mutator::Form0 (other) => other.constants (),
      & Mutator::Form1 (other) => other.constants (),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Accessor<B> for PredictorAccessor<'a, B, Steward0, Steward1> {
  fn get<C: Column>(&mut self, id: RowId) -> Option<&C::FieldType> {
    match self {
      &mut PredictorAccessor::Form0 (other) => other.get::<C> (id),
      &mut PredictorAccessor::Form1 (other) => other.get::<C> (id),
    }
  }
  fn constants(&self) -> &B::Constants {
    match self {
      & PredictorAccessor::Form0 (other) => other.constants (),
      & PredictorAccessor::Form1 (other) => other.constants (),
    }
  }
}

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::MomentaryAccessor<B> for Snapshot<'a, B, Steward0, Steward1> {
  fn now(&self) -> &B::Time {
    let result = (self.0.now(), self.1.now());
    assert! (result.0 == result.1, "Snapshots returned different times; this is an egregious bug!");
    result.0
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::MomentaryAccessor<B> for Mutator<'a, B, Steward0, Steward1> {
  fn now(&self) -> &B::Time {
    match self {
      & Mutator::Form0 (other) => other.now(),
      & Mutator::Form1 (other) => other.now(),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::PredictorAccessor<B, EventFn <B, Steward0, Steward1>> for PredictorAccessor<'a, B, Steward0, Steward1> {
  fn predict_immediately(&mut self, event: Event<B, Steward0, Steward1>) {
    match self {
      &mut PredictorAccessor::Form0 (other) => other.predict_immediately(convert_event_0 (event)),
      &mut PredictorAccessor::Form1 (other) => other.predict_immediately(convert_event_1 (event)),
    }
  }
  fn predict_at_time(&mut self, time: &B::Time, event: Event<B, Steward0, Steward1>) {
    match self {
      &mut PredictorAccessor::Form0 (other) => other.predict_at_time(time, convert_event_0 (event)),
      &mut PredictorAccessor::Form1 (other) => other.predict_at_time(time, convert_event_1 (event)),
    }
  }
}
impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Snapshot<B> for Snapshot<'a, B, Steward0, Steward1> {}

impl<'a, B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B> > super::Mutator<B> for Mutator<'a, B, Steward0, Steward1> {
  fn set<C: Column>(&mut self, id: RowId, data: Option<C::FieldType>) {
    match self {
      &mut Mutator::Form0 (other) => other.set::<C>(id, data),
      &mut Mutator::Form1 (other) => other.set::<C>(id, data),
    }
  }
  fn rng(&mut self) -> &mut EventRng {
    match self {
      &mut Mutator::Form0 (other) => other.rng (),
      &mut Mutator::Form1 (other) => other.rng (),
    }
  }
  fn random_id(&mut self) -> RowId {
    match self {
      &mut Mutator::Form0 (other) => other.random_id(),
      &mut Mutator::Form1 (other) => other.random_id(),
    }
  }
}

fn convert_event_0 <B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B>> (event: Event <B, Steward0, Steward1>)->Rc<<Steward0 as TimeStewardStaticMethods <B>>::EventFn> {
  Rc::new (| mutator | {event (&mut Mutator::Form0 (mutator))});
}
fn convert_event_1 <B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B>> (event: Event <B, Steward0, Steward1>)->Rc<<Steward1 as TimeStewardStaticMethods <B>>::EventFn> {
  Rc::new (| mutator | {event (&mut Mutator::Form1 (mutator))});
}
fn convert_predictor_0 <B: Basics, Steward0: TimeSteward<B>, Steward1: TimeSteward<B>> (predictor: Predictor <B, Steward0, Steward1>)
  ->super::Predictor <<Steward0 as TimeStewardStaticMethods <B>>::PredictorFn> {
  let inner_function =predictor.function .clone();
  let function: Rc<<Steward0 as TimeStewardStaticMethods <B>>::PredictorFn> =
    Rc::new (move | access, row | {
      inner_function (&mut PredictorAccessor::Form0 (access), row)
    });
}

impl<'a, B: Basics, Steward0: 'a + TimeSteward<B>, Steward1: 'a + TimeSteward<B> > TimeStewardLifetimedMethods<'a, B> for Steward<B, Steward0, Steward1> where B::Constants: Clone {
  type Snapshot = Snapshot<'a, B, Steward0, Steward1>;
  type Mutator = Mutator <'a, B, Steward0, Steward1>;
  type PredictorAccessor = PredictorAccessor <'a, B, Steward0, Steward1>;

  fn snapshot_before(&'a mut self, time: &B::Time) -> Option<Self::Snapshot> {
    match (
      self.0.snapshot_before (time),
      self.1.snapshot_before (time)
    ) {
      (None, None) => None,
      (Some (snapshot_0), Some (snapshot_1)) => Some (Snapshot (snapshot_0, snapshot_1)),
      _=> panic! ("One steward returned a snapshot and the other didn't; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)")
    }
  }
}
impl<B: Basics, Steward0: TimeSteward<B> , Steward1: TimeSteward<B> > TimeStewardStaticMethods <B> for Steward<B, Steward0, Steward1> where B::Constants: Clone {
  type EventFn = EventFn <B, Steward0, Steward1>;
  type PredictorFn = PredictorFn <B, Steward0, Steward1>;

  fn valid_since(&self) -> ValidSince<B::Time> {
    unimplemented!()
  }
  fn new_empty(constants: B::Constants, predictors: Vec<super::Predictor <Self::PredictorFn>>) -> Self {
    Steward (
      TimeStewardStaticMethods::new_empty (constants.clone(), predictors.iter().map(| predictor | super::Predictor {predictor_id: predictor. predictor_id, column_id: predictor.column_id, function: Rc::new (| accessor, row | (predictor.function) (&mut PredictorAccessor::Form0 (accessor), row))}).collect()),
      TimeStewardStaticMethods::new_empty (constants, predictors.iter().map(| predictor | super::Predictor {predictor_id: predictor. predictor_id, column_id: predictor.column_id, function: Rc::new (| accessor, row | (predictor.function) (&mut PredictorAccessor::Form1 (accessor), row))}).collect()),
      PhantomData,
    )
  }

  fn insert_fiat_event(&mut self,
                       time: B::Time,
                       id: DeterministicRandomId,
                       event: Event <B, Steward0, Steward1>)
                       -> FiatEventOperationResult {
    let result_0 = self.0.insert_fiat_event (time.clone(), id.clone(),convert_event_0 (event));
    let result_1 = self.1.insert_fiat_event (time, id, convert_event_1 (event));
    assert! (result_0 == result_1, "stewards returned different results for insert_fiat_event; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)");
    result_0
  }
  fn erase_fiat_event(&mut self,
                      time: &B::Time,
                      id: DeterministicRandomId)
                      -> FiatEventOperationResult {
    let result_0 = self.0.erase_fiat_event (time, id.clone());
    let result_1 = self.1.erase_fiat_event (time, id);
    assert! (result_0 == result_1, "stewards returned different results for erase_fiat_event; this could be an error in the stewards or a user error (calling at a time that is valid for one steward but not the other)");
    result_0
  }
}
impl<B: Basics, Steward0: TimeSteward<B> , Steward1: TimeSteward<B> > TimeSteward<B> for Steward<B, Steward0, Steward1> where B::Constants: Clone {}
<|endoftext|>