<commit_before>use backend::Backend;
use provider::error;
use provider::Provider;
use provider::Output;
use libc::{c_char, uint32_t};
use std::ffi::CString;
use std::ffi::CStr;

pub struct File<'a> {
    name: &'static str,
    backend: &'a Backend,
    provider: &'a Provider,
}

impl<'a> File<'a> {
    pub fn new(n: &'static str, b: &'a Backend, p: &'a Provider) -> File<'a> {
        File {
            name: n,
            backend: b,
            provider: p,
        }
    }

    pub fn mode(&self) -> Result<u32, error::Error> {
        self.backend
            .handle(self.provider.file.mode(self.name))
            .and_then(Output::to_u32)
    }

    pub fn size(&self) -> Result<i64, error::Error> {
        self.backend
            .handle(self.provider.file.size(self.name))
            .and_then(Output::to_i64)
    }

    pub fn is_file(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_file(self.name))
            .and_then(Output::to_bool)
    }

    pub fn exist(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.exist(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_directory(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_directory(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_block_device(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_block_device(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_character_device(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_character_device(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_pipe(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_pipe(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_socket(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_socket(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_symlink(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_symlink(self.name))
            .and_then(Output::to_bool)
    }

    pub fn contents(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.contents(self.name))
            .and_then(Output::to_string)
    }

    pub fn owner(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.owner(self.name))
            .and_then(Output::to_string)
    }

    pub fn group(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.group(self.name))
            .and_then(Output::to_string)
    }

    pub fn linked_to(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.linked_to(self.name))
            .and_then(Output::to_string)
    }

    pub fn is_readable(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_owner(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_owner(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_group(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_group(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_others(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_others(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_user(&self, user: &'static str) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_user(self.name, user))
            .and_then(Output::to_bool)
    }

    pub fn is_writable(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_owner(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_owner(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_group(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_group(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_others(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_others(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_user(&self, user: &'static str) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_user(self.name, user))
            .and_then(Output::to_bool)
    }

    pub fn md5sum(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.md5sum(self.name))
            .and_then(Output::to_string)
    }

    pub fn sha256sum(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.sha256sum(self.name))
            .and_then(Output::to_string)
    }
}

// Wrapper functions for FFI

#[no_mangle]
pub extern "C" fn resource_file_free(ptr: *mut File) {
    if ptr.is_null() {
        return;
    }
    unsafe {
        Box::from_raw(ptr);
    }
}

#[no_mangle]
pub extern "C" fn resource_file_mode(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    f.mode().unwrap()
}

#[no_mangle]
pub extern "C" fn resource_file_is_file(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_file().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_exist(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.exist().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_directory(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_directory().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_block_device(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_block_device().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_character_device(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_character_device().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_pipe(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_pipe().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_socket(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_socket().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_symlink(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_symlink().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_contents(ptr: *const File) -> *mut c_char {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };
    let c = f.contents().unwrap();
    CString::new(c).unwrap().into_raw()
}

#[no_mangle]
pub extern "C" fn resource_file_owner(ptr: *const File) -> *mut c_char {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };
    let c = f.owner().unwrap();
    CString::new(c).unwrap().into_raw()
}

#[no_mangle]
pub extern "C" fn resource_file_group(ptr: *const File) -> *mut c_char {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };
    let c = f.group().unwrap();
    CString::new(c).unwrap().into_raw()
}

#[no_mangle]
pub extern "C" fn resource_file_is_readable(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_readable().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_readable_by_owner(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_readable_by_owner().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_readable_by_group(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_readable_by_group().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_readable_by_others(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_readable_by_others().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_readable_by_user(ptr: *const File,
                                                    u: *const c_char)
                                                    -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    let c_str = unsafe {
        assert!(!u.is_null());
        CStr::from_ptr(u)
    };

    let user = c_str.to_str().unwrap();
    if f.is_readable_by_user(user).unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_writable(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_writable().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_writable_by_owner(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_writable_by_owner().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_writable_by_group(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_writable_by_group().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_writable_by_others(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_writable_by_others().unwrap() {
        1
    } else {
        0
    }
}
<commit_msg>Add wrapper function for file.is_writable_by_user()<commit_after>use backend::Backend;
use provider::error;
use provider::Provider;
use provider::Output;
use libc::{c_char, uint32_t};
use std::ffi::CString;
use std::ffi::CStr;

pub struct File<'a> {
    name: &'static str,
    backend: &'a Backend,
    provider: &'a Provider,
}

impl<'a> File<'a> {
    pub fn new(n: &'static str, b: &'a Backend, p: &'a Provider) -> File<'a> {
        File {
            name: n,
            backend: b,
            provider: p,
        }
    }

    pub fn mode(&self) -> Result<u32, error::Error> {
        self.backend
            .handle(self.provider.file.mode(self.name))
            .and_then(Output::to_u32)
    }

    pub fn size(&self) -> Result<i64, error::Error> {
        self.backend
            .handle(self.provider.file.size(self.name))
            .and_then(Output::to_i64)
    }

    pub fn is_file(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_file(self.name))
            .and_then(Output::to_bool)
    }

    pub fn exist(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.exist(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_directory(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_directory(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_block_device(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_block_device(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_character_device(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_character_device(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_pipe(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_pipe(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_socket(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_socket(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_symlink(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_symlink(self.name))
            .and_then(Output::to_bool)
    }

    pub fn contents(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.contents(self.name))
            .and_then(Output::to_string)
    }

    pub fn owner(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.owner(self.name))
            .and_then(Output::to_string)
    }

    pub fn group(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.group(self.name))
            .and_then(Output::to_string)
    }

    pub fn linked_to(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.linked_to(self.name))
            .and_then(Output::to_string)
    }

    pub fn is_readable(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_owner(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_owner(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_group(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_group(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_others(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_others(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_user(&self, user: &'static str) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_user(self.name, user))
            .and_then(Output::to_bool)
    }

    pub fn is_writable(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_owner(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_owner(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_group(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_group(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_others(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_others(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_user(&self, user: &'static str) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_user(self.name, user))
            .and_then(Output::to_bool)
    }

    pub fn md5sum(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.md5sum(self.name))
            .and_then(Output::to_string)
    }

    pub fn sha256sum(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.sha256sum(self.name))
            .and_then(Output::to_string)
    }
}

// Wrapper functions for FFI

#[no_mangle]
pub extern "C" fn resource_file_free(ptr: *mut File) {
    if ptr.is_null() {
        return;
    }
    unsafe {
        Box::from_raw(ptr);
    }
}

#[no_mangle]
pub extern "C" fn resource_file_mode(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    f.mode().unwrap()
}

#[no_mangle]
pub extern "C" fn resource_file_is_file(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_file().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_exist(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.exist().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_directory(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_directory().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_block_device(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_block_device().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_character_device(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_character_device().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_pipe(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_pipe().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_socket(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_socket().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_symlink(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_symlink().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_contents(ptr: *const File) -> *mut c_char {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };
    let c = f.contents().unwrap();
    CString::new(c).unwrap().into_raw()
}

#[no_mangle]
pub extern "C" fn resource_file_owner(ptr: *const File) -> *mut c_char {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };
    let c = f.owner().unwrap();
    CString::new(c).unwrap().into_raw()
}

#[no_mangle]
pub extern "C" fn resource_file_group(ptr: *const File) -> *mut c_char {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };
    let c = f.group().unwrap();
    CString::new(c).unwrap().into_raw()
}

#[no_mangle]
pub extern "C" fn resource_file_is_readable(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_readable().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_readable_by_owner(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_readable_by_owner().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_readable_by_group(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_readable_by_group().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_readable_by_others(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_readable_by_others().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_readable_by_user(ptr: *const File,
                                                    u: *const c_char)
                                                    -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    let c_str = unsafe {
        assert!(!u.is_null());
        CStr::from_ptr(u)
    };

    let user = c_str.to_str().unwrap();
    if f.is_readable_by_user(user).unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_writable(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_writable().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_writable_by_owner(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_writable_by_owner().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_writable_by_group(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_writable_by_group().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_writable_by_others(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_writable_by_others().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_writable_by_user(ptr: *const File,
                                                    u: *const c_char)
                                                    -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    let c_str = unsafe {
        assert!(!u.is_null());
        CStr::from_ptr(u)
    };

    let user = c_str.to_str().unwrap();
    if f.is_writable_by_user(user).unwrap() {
        1
    } else {
        0
    }
}
<|endoftext|>


<commit_before>#![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
//! (De)serialization helpers for other ruma crates.

#![warn(missing_docs)]

use serde_json::Value as JsonValue;

mod buf;
pub mod can_be_empty;
mod canonical_json;
mod cow;
pub mod duration;
mod empty;
pub mod json_string;
mod raw;
pub mod single_element_seq;
mod strings;
pub mod test;
pub mod urlencoded;

pub use buf::{json_to_buf, slice_to_buf};
pub use can_be_empty::{is_empty, CanBeEmpty};
pub use canonical_json::{
    to_canonical_value, try_from_json_map,
    value::{CanonicalJsonValue, Object as CanonicalJsonObject},
    Error as CanonicalJsonError,
};
pub use cow::deserialize_cow_str;
pub use empty::vec_as_map_of_empty;
pub use raw::Raw;
pub use strings::{
    btreemap_int_or_string_to_int_values, empty_string_as_none, int_or_string_to_int,
    none_as_empty_string,
};

/// The inner type of [`serde_json::Value:::Object`].
pub type JsonObject = serde_json::Map<String, JsonValue>;

/// Check whether a value is equal to its default value.
pub fn is_default<T: Default + PartialEq>(val: &T) -> bool {
    *val == T::default()
}

/// Simply returns `true`.
///
/// Useful for `#[serde(default = ...)]`.
pub fn default_true() -> bool {
    true
}

/// Simply dereferences the given bool.
///
/// Useful for `#[serde(skip_serializing_if = ...)]`
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn is_true(b: &bool) -> bool {
    *b
}

/// A type that can be sent to another party that understands the matrix protocol.
///
/// If any of the fields of `Self` don't implement serde's `Deserialize`, you can derive this trait
/// to generate a corresponding 'Incoming' type that supports deserialization. This is useful for
/// things like ruma_events' `EventResult` type. For more details, see the
/// [derive macro's documentation][doc].
///
/// [doc]: derive.Outgoing.html
// TODO: Better explain how this trait relates to serde's traits
pub trait Outgoing {
    /// The 'Incoming' variant of `Self`.
    type Incoming;
}

// -- Everything below is macro-related --

pub use ruma_serde_macros::*;

/// This module is used to support the generated code from ruma-serde-macros.
/// It is not considered part of ruma-serde's public API.
#[doc(hidden)]
pub mod exports {
    pub use serde;
}
<commit_msg>serde: Fix docs for JsonObject<commit_after>#![doc(html_favicon_url = "https://www.ruma.io/favicon.ico")]
#![doc(html_logo_url = "https://www.ruma.io/images/logo.png")]
//! (De)serialization helpers for other ruma crates.

#![warn(missing_docs)]

use serde_json::Value as JsonValue;

mod buf;
pub mod can_be_empty;
mod canonical_json;
mod cow;
pub mod duration;
mod empty;
pub mod json_string;
mod raw;
pub mod single_element_seq;
mod strings;
pub mod test;
pub mod urlencoded;

pub use buf::{json_to_buf, slice_to_buf};
pub use can_be_empty::{is_empty, CanBeEmpty};
pub use canonical_json::{
    to_canonical_value, try_from_json_map,
    value::{CanonicalJsonValue, Object as CanonicalJsonObject},
    Error as CanonicalJsonError,
};
pub use cow::deserialize_cow_str;
pub use empty::vec_as_map_of_empty;
pub use raw::Raw;
pub use strings::{
    btreemap_int_or_string_to_int_values, empty_string_as_none, int_or_string_to_int,
    none_as_empty_string,
};

/// The inner type of [`JsonValue::Object`].
pub type JsonObject = serde_json::Map<String, JsonValue>;

/// Check whether a value is equal to its default value.
pub fn is_default<T: Default + PartialEq>(val: &T) -> bool {
    *val == T::default()
}

/// Simply returns `true`.
///
/// Useful for `#[serde(default = ...)]`.
pub fn default_true() -> bool {
    true
}

/// Simply dereferences the given bool.
///
/// Useful for `#[serde(skip_serializing_if = ...)]`
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn is_true(b: &bool) -> bool {
    *b
}

/// A type that can be sent to another party that understands the matrix protocol.
///
/// If any of the fields of `Self` don't implement serde's `Deserialize`, you can derive this trait
/// to generate a corresponding 'Incoming' type that supports deserialization. This is useful for
/// things like ruma_events' `EventResult` type. For more details, see the
/// [derive macro's documentation][doc].
///
/// [doc]: derive.Outgoing.html
// TODO: Better explain how this trait relates to serde's traits
pub trait Outgoing {
    /// The 'Incoming' variant of `Self`.
    type Incoming;
}

// -- Everything below is macro-related --

pub use ruma_serde_macros::*;

/// This module is used to support the generated code from ruma-serde-macros.
/// It is not considered part of ruma-serde's public API.
#[doc(hidden)]
pub mod exports {
    pub use serde;
}
<|endoftext|>


<commit_before>// xfail-pretty
// xfail-win32

use std;
import std::timer::sleep;
import std::uv;

import pipes::{recv, select};

proto! oneshot {
    waiting:send {
        signal -> signaled
    }

    signaled:send { }
}

proto! stream {
    stream:send<T:send> {
        send(T) -> stream<T>
    }
}

fn main() {
    import oneshot::client::*;
    import stream::client::*;

    let iotask = uv::global_loop::get();

    let c = pipes::spawn_service(stream::init, |p| {
        #error("waiting for pipes");
        let stream::send(x, p) = recv(p);
        #error("got pipes");
        let (left, right) : (oneshot::server::waiting,
                             oneshot::server::waiting)
            = x;
        #error("selecting");
        let (i, _, _) = select(~[left, right]);
        #error("selected");
        assert i == 0;

        #error("waiting for pipes");
        let stream::send(x, _) = recv(p);
        #error("got pipes");
        let (left, right) : (oneshot::server::waiting,
                             oneshot::server::waiting)
            = x;
        #error("selecting");
        let (i, _, _) = select(~[left, right]);
        #error("selected");
        assert i == 1;
    });

    let (c1, p1) = oneshot::init();
    let (_c2, p2) = oneshot::init();

    let c = send(c, (p1, p2));

    sleep(iotask, 1000);

    signal(c1);

    let (_c1, p1) = oneshot::init();
    let (c2, p2) = oneshot::init();

    send(c, (p1, p2));

    sleep(iotask, 1000);

    signal(c2);

    test_select2();
}

fn test_select2() {
    let (ac, ap) = stream::init();
    let (bc, bp) = stream::init();

    stream::client::send(ac, 42);

    alt pipes::select2(ap, bp) {
      either::left(*) { }
      either::right(*) { fail }
    }

    stream::client::send(bc, "abc");

    #error("done with first select2");

    let (ac, ap) = stream::init();
    let (bc, bp) = stream::init();

    stream::client::send(bc, "abc");

    alt pipes::select2(ap, bp) {
      either::left(*) { fail }
      either::right(*) { }
    }

    stream::client::send(ac, 42);
}
<commit_msg>xfail a broken seeming test.<commit_after>// xfail
// xfail-pretty
// xfail-win32

use std;
import std::timer::sleep;
import std::uv;

import pipes::{recv, select};

proto! oneshot {
    waiting:send {
        signal -> signaled
    }

    signaled:send { }
}

proto! stream {
    stream:send<T:send> {
        send(T) -> stream<T>
    }
}

fn main() {
    import oneshot::client::*;
    import stream::client::*;

    let iotask = uv::global_loop::get();

    let c = pipes::spawn_service(stream::init, |p| {
        #error("waiting for pipes");
        let stream::send(x, p) = recv(p);
        #error("got pipes");
        let (left, right) : (oneshot::server::waiting,
                             oneshot::server::waiting)
            = x;
        #error("selecting");
        let (i, _, _) = select(~[left, right]);
        #error("selected");
        assert i == 0;

        #error("waiting for pipes");
        let stream::send(x, _) = recv(p);
        #error("got pipes");
        let (left, right) : (oneshot::server::waiting,
                             oneshot::server::waiting)
            = x;
        #error("selecting");
        let (i, _, _) = select(~[left, right]);
        #error("selected");
        assert i == 1;
    });

    let (c1, p1) = oneshot::init();
    let (_c2, p2) = oneshot::init();

    let c = send(c, (p1, p2));

    sleep(iotask, 1000);

    signal(c1);

    let (_c1, p1) = oneshot::init();
    let (c2, p2) = oneshot::init();

    send(c, (p1, p2));

    sleep(iotask, 1000);

    signal(c2);

    test_select2();
}

fn test_select2() {
    let (ac, ap) = stream::init();
    let (bc, bp) = stream::init();

    stream::client::send(ac, 42);

    alt pipes::select2(ap, bp) {
      either::left(*) { }
      either::right(*) { fail }
    }

    stream::client::send(bc, "abc");

    #error("done with first select2");

    let (ac, ap) = stream::init();
    let (bc, bp) = stream::init();

    stream::client::send(bc, "abc");

    alt pipes::select2(ap, bp) {
      either::left(*) { fail }
      either::right(*) { }
    }

    stream::client::send(ac, 42);
}
<|endoftext|>


<commit_before>//! Eigendecomposition for Hermitian matrices.
//!
//! For a Hermitian matrix `A`, this solves the eigenvalue problem `A V = V D`
//! for `D` and `V`, where `D` is the diagonal matrix of eigenvalues in
//! ascending order and `V` is the orthonormal matrix of corresponding
//! eigenvectors.
//!
//! For a pair of Hermitian matrices `A` and `B` where `B` is also positive
//! definite, this solves the generalized eigenvalue problem `A V = B V D`,
//! where `D` is the diagonal matrix of generalized eigenvalues in ascending
//! order and `V` is the matrix of corresponding generalized eigenvectors. The
//! matrix `V` is normalized such that `V^H B V = I`.

use ndarray::*;

use crate::diagonal::*;
use crate::error::*;
use crate::layout::*;
use crate::operator::LinearOperator;
use crate::types::*;
use crate::UPLO;

/// Eigenvalue decomposition of Hermite matrix reference
pub trait Eigh {
    type EigVal;
    type EigVec;
    fn eigh(&self, uplo: UPLO) -> Result<(Self::EigVal, Self::EigVec)>;
}

/// Eigenvalue decomposition of mutable reference of Hermite matrix
pub trait EighInplace {
    type EigVal;
    fn eigh_inplace(&mut self, uplo: UPLO) -> Result<(Self::EigVal, &mut Self)>;
}

/// Eigenvalue decomposition of Hermite matrix
pub trait EighInto: Sized {
    type EigVal;
    fn eigh_into(self, uplo: UPLO) -> Result<(Self::EigVal, Self)>;
}

impl<A, S> EighInto for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigh_into(mut self, uplo: UPLO) -> Result<(Self::EigVal, Self)> {
        let (val, _) = self.eigh_inplace(uplo)?;
        Ok((val, self))
    }
}

impl<A, S, S2> EighInto for (ArrayBase<S, Ix2>, ArrayBase<S2, Ix2>)
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
    S2: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigh_into(mut self, uplo: UPLO) -> Result<(Self::EigVal, Self)> {
        let (val, _) = self.eigh_inplace(uplo)?;
        Ok((val, self))
    }
}

impl<A, S> Eigh for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: Data<Elem = A>,
{
    type EigVal = Array1<A::Real>;
    type EigVec = Array2<A>;

    fn eigh(&self, uplo: UPLO) -> Result<(Self::EigVal, Self::EigVec)> {
        let a = self.to_owned();
        a.eigh_into(uplo)
    }
}

impl<A, S, S2> Eigh for (ArrayBase<S, Ix2>, ArrayBase<S2, Ix2>)
where
    A: Scalar + Lapack,
    S: Data<Elem = A>,
    S2: Data<Elem = A>,
{
    type EigVal = Array1<A::Real>;
    type EigVec = (Array2<A>, Array2<A>);

    fn eigh(&self, uplo: UPLO) -> Result<(Self::EigVal, Self::EigVec)> {
        let (a, b) = (self.0.to_owned(), self.1.to_owned());
        (a, b).eigh_into(uplo)
    }
}

impl<A, S> EighInplace for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigh_inplace(&mut self, uplo: UPLO) -> Result<(Self::EigVal, &mut Self)> {
        let layout = self.square_layout()?;
        // XXX Force layout to be Fortran (see #146)
        match layout {
            MatrixLayout::C { .. } => self.swap_axes(0, 1),
            MatrixLayout::F { .. } => {}
        }
        let s = A::eigh(true, self.square_layout()?, uplo, self.as_allocated_mut()?)?;
        Ok((ArrayBase::from(s), self))
    }
}

impl<A, S, S2> EighInplace for (ArrayBase<S, Ix2>, ArrayBase<S2, Ix2>)
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
    S2: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigh_inplace(&mut self, uplo: UPLO) -> Result<(Self::EigVal, &mut Self)> {
        let layout = self.0.square_layout()?;
        // XXX Force layout to be Fortran (see #146)
        match layout {
            MatrixLayout::C { .. } => self.0.swap_axes(0, 1),
            MatrixLayout::F { .. } => {}
        }

        let layout = self.1.square_layout()?;
        match layout {
            MatrixLayout::C { .. } => self.1.swap_axes(0, 1),
            MatrixLayout::F { .. } => {}
        }

        let s = A::eigh_generalized(
            true,
            self.0.square_layout()?,
            uplo,
            self.0.as_allocated_mut()?,
            self.1.as_allocated_mut()?,
        )?;

        Ok((ArrayBase::from(s), self))
    }
}

/// Calculate eigenvalues without eigenvectors
pub trait EigValsh {
    type EigVal;
    fn eigvalsh(&self, uplo: UPLO) -> Result<Self::EigVal>;
}

/// Calculate eigenvalues without eigenvectors
pub trait EigValshInto {
    type EigVal;
    fn eigvalsh_into(self, uplo: UPLO) -> Result<Self::EigVal>;
}

/// Calculate eigenvalues without eigenvectors
pub trait EigValshInplace {
    type EigVal;
    fn eigvalsh_inplace(&mut self, uplo: UPLO) -> Result<Self::EigVal>;
}

impl<A, S> EigValshInto for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigvalsh_into(mut self, uplo: UPLO) -> Result<Self::EigVal> {
        self.eigvalsh_inplace(uplo)
    }
}

impl<A, S> EigValsh for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: Data<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigvalsh(&self, uplo: UPLO) -> Result<Self::EigVal> {
        let a = self.to_owned();
        a.eigvalsh_into(uplo)
    }
}

impl<A, S> EigValshInplace for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigvalsh_inplace(&mut self, uplo: UPLO) -> Result<Self::EigVal> {
        let s = A::eigh(true, self.square_layout()?, uplo, self.as_allocated_mut()?)?;
        Ok(ArrayBase::from(s))
    }
}

/// Calculate symmetric square-root matrix using `eigh`
pub trait SymmetricSqrt {
    type Output;
    fn ssqrt(&self, uplo: UPLO) -> Result<Self::Output>;
}

impl<A, S> SymmetricSqrt for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: Data<Elem = A>,
{
    type Output = Array2<A>;

    fn ssqrt(&self, uplo: UPLO) -> Result<Self::Output> {
        let a = self.to_owned();
        a.ssqrt_into(uplo)
    }
}

/// Calculate symmetric square-root matrix using `eigh`
pub trait SymmetricSqrtInto {
    type Output;
    fn ssqrt_into(self, uplo: UPLO) -> Result<Self::Output>;
}

impl<A, S> SymmetricSqrtInto for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A> + DataOwned,
{
    type Output = Array2<A>;

    fn ssqrt_into(self, uplo: UPLO) -> Result<Self::Output> {
        let (e, v) = self.eigh_into(uplo)?;
        let e_sqrt = Array::from_iter(e.iter().map(|r| Scalar::from_real(r.sqrt())));
        let ev = e_sqrt.into_diagonal().apply2(&v.t());
        Ok(v.apply2(&ev))
    }
}
<commit_msg>Add example to eigh module<commit_after>//! Eigendecomposition for Hermitian matrices.
//!
//! For a Hermitian matrix `A`, this solves the eigenvalue problem `A V = V D`
//! for `D` and `V`, where `D` is the diagonal matrix of eigenvalues in
//! ascending order and `V` is the orthonormal matrix of corresponding
//! eigenvectors.
//!
//! For a pair of Hermitian matrices `A` and `B` where `B` is also positive
//! definite, this solves the generalized eigenvalue problem `A V = B V D`,
//! where `D` is the diagonal matrix of generalized eigenvalues in ascending
//! order and `V` is the matrix of corresponding generalized eigenvectors. The
//! matrix `V` is normalized such that `V^H B V = I`.
//!
//! # Example
//!
//! Find the eigendecomposition of a Hermitian (or real symmetric) matrix.
//!
//! ```
//! use approx::assert_abs_diff_eq;
//! use ndarray::{array, Array2};
//! use ndarray_linalg::{Eigh, UPLO};
//!
//! let a: Array2<f64> = array![
//!     [2., 1.],
//!     [1., 2.],
//! ];
//! let (eigvals, eigvecs) = a.eigh(UPLO::Lower)?;
//! assert_abs_diff_eq!(eigvals, array![1., 3.]);
//! assert_abs_diff_eq!(
//!     a.dot(&eigvecs),
//!     eigvecs.dot(&Array2::from_diag(&eigvals)),
//! );
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use ndarray::*;

use crate::diagonal::*;
use crate::error::*;
use crate::layout::*;
use crate::operator::LinearOperator;
use crate::types::*;
use crate::UPLO;

/// Eigenvalue decomposition of Hermite matrix reference
pub trait Eigh {
    type EigVal;
    type EigVec;
    fn eigh(&self, uplo: UPLO) -> Result<(Self::EigVal, Self::EigVec)>;
}

/// Eigenvalue decomposition of mutable reference of Hermite matrix
pub trait EighInplace {
    type EigVal;
    fn eigh_inplace(&mut self, uplo: UPLO) -> Result<(Self::EigVal, &mut Self)>;
}

/// Eigenvalue decomposition of Hermite matrix
pub trait EighInto: Sized {
    type EigVal;
    fn eigh_into(self, uplo: UPLO) -> Result<(Self::EigVal, Self)>;
}

impl<A, S> EighInto for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigh_into(mut self, uplo: UPLO) -> Result<(Self::EigVal, Self)> {
        let (val, _) = self.eigh_inplace(uplo)?;
        Ok((val, self))
    }
}

impl<A, S, S2> EighInto for (ArrayBase<S, Ix2>, ArrayBase<S2, Ix2>)
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
    S2: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigh_into(mut self, uplo: UPLO) -> Result<(Self::EigVal, Self)> {
        let (val, _) = self.eigh_inplace(uplo)?;
        Ok((val, self))
    }
}

impl<A, S> Eigh for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: Data<Elem = A>,
{
    type EigVal = Array1<A::Real>;
    type EigVec = Array2<A>;

    fn eigh(&self, uplo: UPLO) -> Result<(Self::EigVal, Self::EigVec)> {
        let a = self.to_owned();
        a.eigh_into(uplo)
    }
}

impl<A, S, S2> Eigh for (ArrayBase<S, Ix2>, ArrayBase<S2, Ix2>)
where
    A: Scalar + Lapack,
    S: Data<Elem = A>,
    S2: Data<Elem = A>,
{
    type EigVal = Array1<A::Real>;
    type EigVec = (Array2<A>, Array2<A>);

    fn eigh(&self, uplo: UPLO) -> Result<(Self::EigVal, Self::EigVec)> {
        let (a, b) = (self.0.to_owned(), self.1.to_owned());
        (a, b).eigh_into(uplo)
    }
}

impl<A, S> EighInplace for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigh_inplace(&mut self, uplo: UPLO) -> Result<(Self::EigVal, &mut Self)> {
        let layout = self.square_layout()?;
        // XXX Force layout to be Fortran (see #146)
        match layout {
            MatrixLayout::C { .. } => self.swap_axes(0, 1),
            MatrixLayout::F { .. } => {}
        }
        let s = A::eigh(true, self.square_layout()?, uplo, self.as_allocated_mut()?)?;
        Ok((ArrayBase::from(s), self))
    }
}

impl<A, S, S2> EighInplace for (ArrayBase<S, Ix2>, ArrayBase<S2, Ix2>)
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
    S2: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigh_inplace(&mut self, uplo: UPLO) -> Result<(Self::EigVal, &mut Self)> {
        let layout = self.0.square_layout()?;
        // XXX Force layout to be Fortran (see #146)
        match layout {
            MatrixLayout::C { .. } => self.0.swap_axes(0, 1),
            MatrixLayout::F { .. } => {}
        }

        let layout = self.1.square_layout()?;
        match layout {
            MatrixLayout::C { .. } => self.1.swap_axes(0, 1),
            MatrixLayout::F { .. } => {}
        }

        let s = A::eigh_generalized(
            true,
            self.0.square_layout()?,
            uplo,
            self.0.as_allocated_mut()?,
            self.1.as_allocated_mut()?,
        )?;

        Ok((ArrayBase::from(s), self))
    }
}

/// Calculate eigenvalues without eigenvectors
pub trait EigValsh {
    type EigVal;
    fn eigvalsh(&self, uplo: UPLO) -> Result<Self::EigVal>;
}

/// Calculate eigenvalues without eigenvectors
pub trait EigValshInto {
    type EigVal;
    fn eigvalsh_into(self, uplo: UPLO) -> Result<Self::EigVal>;
}

/// Calculate eigenvalues without eigenvectors
pub trait EigValshInplace {
    type EigVal;
    fn eigvalsh_inplace(&mut self, uplo: UPLO) -> Result<Self::EigVal>;
}

impl<A, S> EigValshInto for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigvalsh_into(mut self, uplo: UPLO) -> Result<Self::EigVal> {
        self.eigvalsh_inplace(uplo)
    }
}

impl<A, S> EigValsh for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: Data<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigvalsh(&self, uplo: UPLO) -> Result<Self::EigVal> {
        let a = self.to_owned();
        a.eigvalsh_into(uplo)
    }
}

impl<A, S> EigValshInplace for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A>,
{
    type EigVal = Array1<A::Real>;

    fn eigvalsh_inplace(&mut self, uplo: UPLO) -> Result<Self::EigVal> {
        let s = A::eigh(true, self.square_layout()?, uplo, self.as_allocated_mut()?)?;
        Ok(ArrayBase::from(s))
    }
}

/// Calculate symmetric square-root matrix using `eigh`
pub trait SymmetricSqrt {
    type Output;
    fn ssqrt(&self, uplo: UPLO) -> Result<Self::Output>;
}

impl<A, S> SymmetricSqrt for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: Data<Elem = A>,
{
    type Output = Array2<A>;

    fn ssqrt(&self, uplo: UPLO) -> Result<Self::Output> {
        let a = self.to_owned();
        a.ssqrt_into(uplo)
    }
}

/// Calculate symmetric square-root matrix using `eigh`
pub trait SymmetricSqrtInto {
    type Output;
    fn ssqrt_into(self, uplo: UPLO) -> Result<Self::Output>;
}

impl<A, S> SymmetricSqrtInto for ArrayBase<S, Ix2>
where
    A: Scalar + Lapack,
    S: DataMut<Elem = A> + DataOwned,
{
    type Output = Array2<A>;

    fn ssqrt_into(self, uplo: UPLO) -> Result<Self::Output> {
        let (e, v) = self.eigh_into(uplo)?;
        let e_sqrt = Array::from_iter(e.iter().map(|r| Scalar::from_real(r.sqrt())));
        let ev = e_sqrt.into_diagonal().apply2(&v.t());
        Ok(v.apply2(&ev))
    }
}
<|endoftext|>


<commit_before>#![cfg(not(feature = "unstable-pre-spec"))]

use std::{
    collections::BTreeMap,
    time::{Duration, SystemTime},
};

use ruma_events::{
    pdu::{EventHash, Pdu, RoomV1Pdu, RoomV3Pdu},
    EventType,
};
use ruma_identifiers::{event_id, room_id, server_name, server_signing_key_id, user_id};
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};

#[test]
fn serialize_pdu_as_v1() {
    let mut signatures = BTreeMap::new();
    let mut inner_signature = BTreeMap::new();
    inner_signature.insert(
        server_signing_key_id!("ed25519:key_version"),
        "86BytesOfSignatureOfTheRedactedEvent".into(),
    );
    signatures.insert(server_name!("example.com"), inner_signature);

    let mut unsigned = BTreeMap::new();
    unsigned.insert("somekey".into(), json!({"a": 456}));

    let v1_pdu = RoomV1Pdu {
        room_id: room_id!("!n8f893n9:example.com"),
        event_id: event_id!("$somejoinevent:matrix.org"),
        sender: user_id!("@sender:example.com"),
        origin: "matrix.org".into(),
        origin_server_ts: SystemTime::UNIX_EPOCH + Duration::from_millis(1_592_050_773_658),
        kind: EventType::RoomPowerLevels,
        content: json!({"testing": 123}),
        state_key: Some("state".into()),
        prev_events: vec![(
            event_id!("$previousevent:matrix.org"),
            EventHash { sha256: "123567".into() },
        )],
        depth: 2_u32.into(),
        auth_events: vec![(
            event_id!("$someauthevent:matrix.org"),
            EventHash { sha256: "21389CFEDABC".into() },
        )],
        redacts: Some(event_id!("$9654:matrix.org")),
        unsigned,
        hashes: EventHash { sha256: "1233543bABACDEF".into() },
        signatures,
    };
    let pdu = Pdu::RoomV1Pdu(v1_pdu);
    let json = json!({
        "room_id": "!n8f893n9:example.com",
        "event_id": "$somejoinevent:matrix.org",
        "sender": "@sender:example.com",
        "origin": "matrix.org",
        "origin_server_ts": 1_592_050_773_658usize,
        "type": "m.room.power_levels",
        "content": {
            "testing": 123
        },
        "state_key": "state",
        "prev_events": [
            [ "$previousevent:matrix.org", {"sha256": "123567"} ]
        ],
        "depth": 2,
        "auth_events": [
            ["$someauthevent:matrix.org", {"sha256": "21389CFEDABC"}]
        ],
        "redacts": "$9654:matrix.org",
        "unsigned": {
            "somekey": { "a": 456 } },
        "hashes": { "sha256": "1233543bABACDEF" },
        "signatures": {
            "example.com": { "ed25519:key_version":"86BytesOfSignatureOfTheRedactedEvent" }
        }
    });

    assert_eq!(to_json_value(&pdu).unwrap(), json);
}

#[test]
fn serialize_pdu_as_v3() {
    let mut signatures = BTreeMap::new();
    let mut inner_signature = BTreeMap::new();
    inner_signature.insert(
        server_signing_key_id!("ed25519:key_version"),
        "86BytesOfSignatureOfTheRedactedEvent".into(),
    );
    signatures.insert(server_name!("example.com"), inner_signature);

    let mut unsigned = BTreeMap::new();
    unsigned.insert("somekey".into(), json!({"a": 456}));

    let v3_pdu = RoomV3Pdu {
        room_id: room_id!("!n8f893n9:example.com"),
        sender: user_id!("@sender:example.com"),
        origin: "matrix.org".into(),
        origin_server_ts: SystemTime::UNIX_EPOCH + Duration::from_millis(1_592_050_773_658),
        kind: EventType::RoomPowerLevels,
        content: json!({"testing": 123}),
        state_key: Some("state".into()),
        prev_events: vec![event_id!("$previousevent:matrix.org")],
        depth: 2_u32.into(),
        auth_events: vec![event_id!("$someauthevent:matrix.org")],
        redacts: Some(event_id!("$9654:matrix.org")),
        unsigned,
        hashes: EventHash { sha256: "1233543bABACDEF".into() },
        signatures,
    };
    let pdu_stub = Pdu::RoomV3Pdu(v3_pdu);
    let json = json!({
        "room_id": "!n8f893n9:example.com",
        "sender": "@sender:example.com",
        "origin": "matrix.org",
        "origin_server_ts": 1_592_050_773_658usize,
        "type": "m.room.power_levels",
        "content": {
            "testing": 123
        },
        "state_key": "state",
        "prev_events": [ "$previousevent:matrix.org" ],
        "depth": 2,
        "auth_events": ["$someauthevent:matrix.org" ],
        "redacts": "$9654:matrix.org",
        "unsigned": {
            "somekey": { "a": 456 } },
        "hashes": { "sha256": "1233543bABACDEF" },
        "signatures": {
            "example.com": { "ed25519:key_version":"86BytesOfSignatureOfTheRedactedEvent" }
        }
    });

    assert_eq!(to_json_value(&pdu_stub).unwrap(), json);
}

#[test]
fn deserialize_pdu_as_v1() {
    let json = json!({
        "room_id": "!n8f893n9:example.com",
        "event_id": "$somejoinevent:matrix.org",
        "auth_events": [
            [
                "$abc123:matrix.org",
                {
                    "sha256": "Base64EncodedSha256HashesShouldBe43BytesLong"
                }
            ]
        ],
        "content": {
            "key": "value"
        },
        "depth": 12,
        "event_id": "$a4ecee13e2accdadf56c1025:example.com",
        "hashes": {
            "sha256": "ThisHashCoversAllFieldsInCaseThisIsRedacted"
        },
        "origin": "matrix.org",
        "origin_server_ts": 1_234_567_890,
        "prev_events": [
            [
                "$abc123:matrix.org",
                {
                    "sha256": "Base64EncodedSha256HashesShouldBe43BytesLong"
                }
            ]
        ],
        "redacts": "$def456:matrix.org",
        "room_id": "!abc123:matrix.org",
        "sender": "@someone:matrix.org",
        "signatures": {
            "example.com": {
                "ed25519:key_version": "86BytesOfSignatureOfTheRedactedEvent"
            }
        },
        "state_key": "my_key",
        "type": "m.room.message",
        "unsigned": {
            "key": "value"
        }
    });
    let parsed = from_json_value::<Pdu>(json).unwrap();

    match parsed {
        Pdu::RoomV1Pdu(v1_pdu) => {
            assert_eq!(v1_pdu.auth_events.first().unwrap().0, event_id!("$abc123:matrix.org"));
            assert_eq!(
                v1_pdu.auth_events.first().unwrap().1.sha256,
                "Base64EncodedSha256HashesShouldBe43BytesLong"
            );
        }
        Pdu::RoomV3Pdu(_) => panic!("Matched V3 PDU"),
    }
}

#[cfg(not(feature = "unstable-pre-spec"))]
#[test]
fn deserialize_pdu_as_v3() {
    let json = json!({
        "room_id": "!n8f893n9:example.com",
        "auth_events": [
            "$abc123:matrix.org"
        ],
        "content": {
            "key": "value"
        },
        "depth": 12,
        "event_id": "$a4ecee13e2accdadf56c1025:example.com",
        "hashes": {
            "sha256": "ThisHashCoversAllFieldsInCaseThisIsRedacted"
        },
        "origin": "matrix.org",
        "origin_server_ts": 1_234_567_890,
        "prev_events": [
                "$abc123:matrix.org"
        ],
        "redacts": "$def456:matrix.org",
        "room_id": "!abc123:matrix.org",
        "sender": "@someone:matrix.org",
        "signatures": {
            "example.com": {
                "ed25519:key_version": "86BytesOfSignatureOfTheRedactedEvent"
            }
        },
        "state_key": "my_key",
        "type": "m.room.message",
        "unsigned": {
            "key": "value"
        }
    });
    let parsed = from_json_value::<Pdu>(json).unwrap();

    match parsed {
        Pdu::RoomV1Pdu(_) => panic!("Matched V1 PDU"),
        Pdu::RoomV3Pdu(v3_pdu) => {
            assert_eq!(v3_pdu.auth_events.first().unwrap(), &event_id!("$abc123:matrix.org"));
        }
    }
}
<commit_msg>Fix integer literals in PDU tests<commit_after>#![cfg(not(feature = "unstable-pre-spec"))]

use std::{
    collections::BTreeMap,
    time::{Duration, SystemTime},
};

use ruma_events::{
    pdu::{EventHash, Pdu, RoomV1Pdu, RoomV3Pdu},
    EventType,
};
use ruma_identifiers::{event_id, room_id, server_name, server_signing_key_id, user_id};
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};

#[test]
fn serialize_pdu_as_v1() {
    let mut signatures = BTreeMap::new();
    let mut inner_signature = BTreeMap::new();
    inner_signature.insert(
        server_signing_key_id!("ed25519:key_version"),
        "86BytesOfSignatureOfTheRedactedEvent".into(),
    );
    signatures.insert(server_name!("example.com"), inner_signature);

    let mut unsigned = BTreeMap::new();
    unsigned.insert("somekey".into(), json!({"a": 456}));

    let v1_pdu = RoomV1Pdu {
        room_id: room_id!("!n8f893n9:example.com"),
        event_id: event_id!("$somejoinevent:matrix.org"),
        sender: user_id!("@sender:example.com"),
        origin: "matrix.org".into(),
        origin_server_ts: SystemTime::UNIX_EPOCH + Duration::from_millis(1_592_050_773_658),
        kind: EventType::RoomPowerLevels,
        content: json!({"testing": 123}),
        state_key: Some("state".into()),
        prev_events: vec![(
            event_id!("$previousevent:matrix.org"),
            EventHash { sha256: "123567".into() },
        )],
        depth: 2_u32.into(),
        auth_events: vec![(
            event_id!("$someauthevent:matrix.org"),
            EventHash { sha256: "21389CFEDABC".into() },
        )],
        redacts: Some(event_id!("$9654:matrix.org")),
        unsigned,
        hashes: EventHash { sha256: "1233543bABACDEF".into() },
        signatures,
    };
    let pdu = Pdu::RoomV1Pdu(v1_pdu);
    let json = json!({
        "room_id": "!n8f893n9:example.com",
        "event_id": "$somejoinevent:matrix.org",
        "sender": "@sender:example.com",
        "origin": "matrix.org",
        "origin_server_ts": 1_592_050_773_658u64,
        "type": "m.room.power_levels",
        "content": {
            "testing": 123
        },
        "state_key": "state",
        "prev_events": [
            [ "$previousevent:matrix.org", {"sha256": "123567"} ]
        ],
        "depth": 2,
        "auth_events": [
            ["$someauthevent:matrix.org", {"sha256": "21389CFEDABC"}]
        ],
        "redacts": "$9654:matrix.org",
        "unsigned": {
            "somekey": { "a": 456 } },
        "hashes": { "sha256": "1233543bABACDEF" },
        "signatures": {
            "example.com": { "ed25519:key_version":"86BytesOfSignatureOfTheRedactedEvent" }
        }
    });

    assert_eq!(to_json_value(&pdu).unwrap(), json);
}

#[test]
fn serialize_pdu_as_v3() {
    let mut signatures = BTreeMap::new();
    let mut inner_signature = BTreeMap::new();
    inner_signature.insert(
        server_signing_key_id!("ed25519:key_version"),
        "86BytesOfSignatureOfTheRedactedEvent".into(),
    );
    signatures.insert(server_name!("example.com"), inner_signature);

    let mut unsigned = BTreeMap::new();
    unsigned.insert("somekey".into(), json!({"a": 456}));

    let v3_pdu = RoomV3Pdu {
        room_id: room_id!("!n8f893n9:example.com"),
        sender: user_id!("@sender:example.com"),
        origin: "matrix.org".into(),
        origin_server_ts: SystemTime::UNIX_EPOCH + Duration::from_millis(1_592_050_773_658),
        kind: EventType::RoomPowerLevels,
        content: json!({"testing": 123}),
        state_key: Some("state".into()),
        prev_events: vec![event_id!("$previousevent:matrix.org")],
        depth: 2_u32.into(),
        auth_events: vec![event_id!("$someauthevent:matrix.org")],
        redacts: Some(event_id!("$9654:matrix.org")),
        unsigned,
        hashes: EventHash { sha256: "1233543bABACDEF".into() },
        signatures,
    };
    let pdu_stub = Pdu::RoomV3Pdu(v3_pdu);
    let json = json!({
        "room_id": "!n8f893n9:example.com",
        "sender": "@sender:example.com",
        "origin": "matrix.org",
        "origin_server_ts": 1_592_050_773_658u64,
        "type": "m.room.power_levels",
        "content": {
            "testing": 123
        },
        "state_key": "state",
        "prev_events": [ "$previousevent:matrix.org" ],
        "depth": 2,
        "auth_events": ["$someauthevent:matrix.org" ],
        "redacts": "$9654:matrix.org",
        "unsigned": {
            "somekey": { "a": 456 } },
        "hashes": { "sha256": "1233543bABACDEF" },
        "signatures": {
            "example.com": { "ed25519:key_version":"86BytesOfSignatureOfTheRedactedEvent" }
        }
    });

    assert_eq!(to_json_value(&pdu_stub).unwrap(), json);
}

#[test]
fn deserialize_pdu_as_v1() {
    let json = json!({
        "room_id": "!n8f893n9:example.com",
        "event_id": "$somejoinevent:matrix.org",
        "auth_events": [
            [
                "$abc123:matrix.org",
                {
                    "sha256": "Base64EncodedSha256HashesShouldBe43BytesLong"
                }
            ]
        ],
        "content": {
            "key": "value"
        },
        "depth": 12,
        "event_id": "$a4ecee13e2accdadf56c1025:example.com",
        "hashes": {
            "sha256": "ThisHashCoversAllFieldsInCaseThisIsRedacted"
        },
        "origin": "matrix.org",
        "origin_server_ts": 1_234_567_890,
        "prev_events": [
            [
                "$abc123:matrix.org",
                {
                    "sha256": "Base64EncodedSha256HashesShouldBe43BytesLong"
                }
            ]
        ],
        "redacts": "$def456:matrix.org",
        "room_id": "!abc123:matrix.org",
        "sender": "@someone:matrix.org",
        "signatures": {
            "example.com": {
                "ed25519:key_version": "86BytesOfSignatureOfTheRedactedEvent"
            }
        },
        "state_key": "my_key",
        "type": "m.room.message",
        "unsigned": {
            "key": "value"
        }
    });
    let parsed = from_json_value::<Pdu>(json).unwrap();

    match parsed {
        Pdu::RoomV1Pdu(v1_pdu) => {
            assert_eq!(v1_pdu.auth_events.first().unwrap().0, event_id!("$abc123:matrix.org"));
            assert_eq!(
                v1_pdu.auth_events.first().unwrap().1.sha256,
                "Base64EncodedSha256HashesShouldBe43BytesLong"
            );
        }
        Pdu::RoomV3Pdu(_) => panic!("Matched V3 PDU"),
    }
}

#[cfg(not(feature = "unstable-pre-spec"))]
#[test]
fn deserialize_pdu_as_v3() {
    let json = json!({
        "room_id": "!n8f893n9:example.com",
        "auth_events": [
            "$abc123:matrix.org"
        ],
        "content": {
            "key": "value"
        },
        "depth": 12,
        "event_id": "$a4ecee13e2accdadf56c1025:example.com",
        "hashes": {
            "sha256": "ThisHashCoversAllFieldsInCaseThisIsRedacted"
        },
        "origin": "matrix.org",
        "origin_server_ts": 1_234_567_890,
        "prev_events": [
                "$abc123:matrix.org"
        ],
        "redacts": "$def456:matrix.org",
        "room_id": "!abc123:matrix.org",
        "sender": "@someone:matrix.org",
        "signatures": {
            "example.com": {
                "ed25519:key_version": "86BytesOfSignatureOfTheRedactedEvent"
            }
        },
        "state_key": "my_key",
        "type": "m.room.message",
        "unsigned": {
            "key": "value"
        }
    });
    let parsed = from_json_value::<Pdu>(json).unwrap();

    match parsed {
        Pdu::RoomV1Pdu(_) => panic!("Matched V1 PDU"),
        Pdu::RoomV3Pdu(v3_pdu) => {
            assert_eq!(v3_pdu.auth_events.first().unwrap(), &event_id!("$abc123:matrix.org"));
        }
    }
}
<|endoftext|>


<commit_before>use crate::mir::mono::Linkage;
use rustc_attr::{InlineAttr, OptimizeAttr};
use rustc_span::symbol::Symbol;

#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
pub struct CodegenFnAttrs {
    pub flags: CodegenFnAttrFlags,
    /// Parsed representation of the `#[inline]` attribute
    pub inline: InlineAttr,
    /// Parsed representation of the `#[optimize]` attribute
    pub optimize: OptimizeAttr,
    /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
    /// function should be exported under
    pub export_name: Option<Symbol>,
    /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
    /// imported function should be imported as. Note that `export_name`
    /// probably isn't set when this is set, this is for foreign items while
    /// `#[export_name]` is for Rust-defined functions.
    pub link_name: Option<Symbol>,
    /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
    /// imported function has in the dynamic library. Note that this must not
    /// be set when `link_name` is set. This is for foreign items with the
    /// "raw-dylib" kind.
    pub link_ordinal: Option<usize>,
    /// The `#[target_feature(enable = "...")]` attribute and the enabled
    /// features (only enabled features are supported right now).
    pub target_features: Vec<Symbol>,
    /// The `#[linkage = "..."]` attribute and the value we found.
    pub linkage: Option<Linkage>,
    /// The `#[link_section = "..."]` attribute, or what executable section this
    /// should be placed in.
    pub link_section: Option<Symbol>,
}

bitflags! {
    #[derive(RustcEncodable, RustcDecodable, HashStable)]
    pub struct CodegenFnAttrFlags: u32 {
        /// `#[cold]`: a hint to LLVM that this function, when called, is never on
        /// the hot path.
        const COLD                      = 1 << 0;
        /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
        /// function is never null.
        const ALLOCATOR                 = 1 << 1;
        /// `#[unwind]`: an indicator that this function may unwind despite what
        /// its ABI signature may otherwise imply.
        const UNWIND                    = 1 << 2;
        /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
        /// function will never unwind. Probably obsolete by recent changes with
        /// #[unwind], but hasn't been removed/migrated yet
        const RUSTC_ALLOCATOR_NOUNWIND  = 1 << 3;
        /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
        /// should be generated.
        const NAKED                     = 1 << 4;
        /// `#[no_mangle]`: an indicator that the function's name should be the same
        /// as its symbol.
        const NO_MANGLE                 = 1 << 5;
        /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
        /// "weird symbol" for the standard library in that it has slightly
        /// different linkage, visibility, and reachability rules.
        const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
        /// `#[no_debug]`: an indicator that no debugging information should be
        /// generated for this function by LLVM.
        const NO_DEBUG                  = 1 << 7;
        /// `#[thread_local]`: indicates a static is actually a thread local
        /// piece of memory
        const THREAD_LOCAL              = 1 << 8;
        /// `#[used]`: indicates that LLVM can't eliminate this function (but the
        /// linker can!).
        const USED                      = 1 << 9;
        /// `#[ffi_returns_twice]`, indicates that an extern function can return
        /// multiple times
        const FFI_RETURNS_TWICE         = 1 << 10;
        /// `#[track_caller]`: allow access to the caller location
        const TRACK_CALLER              = 1 << 11;
        /// `#[no_sanitize(address)]`: disables address sanitizer instrumentation
        const NO_SANITIZE_ADDRESS = 1 << 12;
        /// `#[no_sanitize(memory)]`: disables memory sanitizer instrumentation
        const NO_SANITIZE_MEMORY  = 1 << 13;
        /// `#[no_sanitize(thread)]`: disables thread sanitizer instrumentation
        const NO_SANITIZE_THREAD  = 1 << 14;
        /// All `#[no_sanitize(...)]` attributes.
        const NO_SANITIZE_ANY = Self::NO_SANITIZE_ADDRESS.bits | Self::NO_SANITIZE_MEMORY.bits | Self::NO_SANITIZE_THREAD.bits;
    }
}

impl CodegenFnAttrs {
    pub fn new() -> CodegenFnAttrs {
        CodegenFnAttrs {
            flags: CodegenFnAttrFlags::empty(),
            inline: InlineAttr::None,
            optimize: OptimizeAttr::None,
            export_name: None,
            link_name: None,
            link_ordinal: None,
            target_features: vec![],
            linkage: None,
            link_section: None,
        }
    }

    /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
    pub fn requests_inline(&self) -> bool {
        match self.inline {
            InlineAttr::Hint | InlineAttr::Always => true,
            InlineAttr::None | InlineAttr::Never => false,
        }
    }

    /// Returns `true` if it looks like this symbol needs to be exported, for example:
    ///
    /// * `#[no_mangle]` is present
    /// * `#[export_name(...)]` is present
    /// * `#[linkage]` is present
    pub fn contains_extern_indicator(&self) -> bool {
        self.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
            || self.export_name.is_some()
            || match self.linkage {
                // These are private, so make sure we don't try to consider
                // them external.
                None | Some(Linkage::Internal) | Some(Linkage::Private) => false,
                Some(_) => true,
            }
    }
}
<commit_msg>Remove `NO_DEBUG` const<commit_after>use crate::mir::mono::Linkage;
use rustc_attr::{InlineAttr, OptimizeAttr};
use rustc_span::symbol::Symbol;

#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
pub struct CodegenFnAttrs {
    pub flags: CodegenFnAttrFlags,
    /// Parsed representation of the `#[inline]` attribute
    pub inline: InlineAttr,
    /// Parsed representation of the `#[optimize]` attribute
    pub optimize: OptimizeAttr,
    /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
    /// function should be exported under
    pub export_name: Option<Symbol>,
    /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
    /// imported function should be imported as. Note that `export_name`
    /// probably isn't set when this is set, this is for foreign items while
    /// `#[export_name]` is for Rust-defined functions.
    pub link_name: Option<Symbol>,
    /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
    /// imported function has in the dynamic library. Note that this must not
    /// be set when `link_name` is set. This is for foreign items with the
    /// "raw-dylib" kind.
    pub link_ordinal: Option<usize>,
    /// The `#[target_feature(enable = "...")]` attribute and the enabled
    /// features (only enabled features are supported right now).
    pub target_features: Vec<Symbol>,
    /// The `#[linkage = "..."]` attribute and the value we found.
    pub linkage: Option<Linkage>,
    /// The `#[link_section = "..."]` attribute, or what executable section this
    /// should be placed in.
    pub link_section: Option<Symbol>,
}

bitflags! {
    #[derive(RustcEncodable, RustcDecodable, HashStable)]
    pub struct CodegenFnAttrFlags: u32 {
        /// `#[cold]`: a hint to LLVM that this function, when called, is never on
        /// the hot path.
        const COLD                      = 1 << 0;
        /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
        /// function is never null.
        const ALLOCATOR                 = 1 << 1;
        /// `#[unwind]`: an indicator that this function may unwind despite what
        /// its ABI signature may otherwise imply.
        const UNWIND                    = 1 << 2;
        /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
        /// function will never unwind. Probably obsolete by recent changes with
        /// #[unwind], but hasn't been removed/migrated yet
        const RUSTC_ALLOCATOR_NOUNWIND  = 1 << 3;
        /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
        /// should be generated.
        const NAKED                     = 1 << 4;
        /// `#[no_mangle]`: an indicator that the function's name should be the same
        /// as its symbol.
        const NO_MANGLE                 = 1 << 5;
        /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
        /// "weird symbol" for the standard library in that it has slightly
        /// different linkage, visibility, and reachability rules.
        const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
        /// `#[thread_local]`: indicates a static is actually a thread local
        /// piece of memory
        const THREAD_LOCAL              = 1 << 8;
        /// `#[used]`: indicates that LLVM can't eliminate this function (but the
        /// linker can!).
        const USED                      = 1 << 9;
        /// `#[ffi_returns_twice]`, indicates that an extern function can return
        /// multiple times
        const FFI_RETURNS_TWICE         = 1 << 10;
        /// `#[track_caller]`: allow access to the caller location
        const TRACK_CALLER              = 1 << 11;
        /// `#[no_sanitize(address)]`: disables address sanitizer instrumentation
        const NO_SANITIZE_ADDRESS = 1 << 12;
        /// `#[no_sanitize(memory)]`: disables memory sanitizer instrumentation
        const NO_SANITIZE_MEMORY  = 1 << 13;
        /// `#[no_sanitize(thread)]`: disables thread sanitizer instrumentation
        const NO_SANITIZE_THREAD  = 1 << 14;
        /// All `#[no_sanitize(...)]` attributes.
        const NO_SANITIZE_ANY = Self::NO_SANITIZE_ADDRESS.bits | Self::NO_SANITIZE_MEMORY.bits | Self::NO_SANITIZE_THREAD.bits;
    }
}

impl CodegenFnAttrs {
    pub fn new() -> CodegenFnAttrs {
        CodegenFnAttrs {
            flags: CodegenFnAttrFlags::empty(),
            inline: InlineAttr::None,
            optimize: OptimizeAttr::None,
            export_name: None,
            link_name: None,
            link_ordinal: None,
            target_features: vec![],
            linkage: None,
            link_section: None,
        }
    }

    /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
    pub fn requests_inline(&self) -> bool {
        match self.inline {
            InlineAttr::Hint | InlineAttr::Always => true,
            InlineAttr::None | InlineAttr::Never => false,
        }
    }

    /// Returns `true` if it looks like this symbol needs to be exported, for example:
    ///
    /// * `#[no_mangle]` is present
    /// * `#[export_name(...)]` is present
    /// * `#[linkage]` is present
    pub fn contains_extern_indicator(&self) -> bool {
        self.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
            || self.export_name.is_some()
            || match self.linkage {
                // These are private, so make sure we don't try to consider
                // them external.
                None | Some(Linkage::Internal) | Some(Linkage::Private) => false,
                Some(_) => true,
            }
    }
}
<|endoftext|>


<commit_before>#![allow(dead_code, unused_imports)]
extern crate iron;
extern crate handlebars_iron as hbs;
extern crate rustc_serialize;
extern crate env_logger;

use iron::prelude::*;
use iron::{status};
use hbs::{Template, HandlebarsEngine, DirectorySource};
#[cfg(feature = "watch")]
use hbs::Watchable;
use rustc_serialize::json::{ToJson, Json};

use std::collections::BTreeMap;
use std::sync::Arc;
use std::error::Error;

struct Team {
    name: String,
    pts: u16
}

impl ToJson for Team {
    fn to_json(&self) -> Json {
        let mut m: BTreeMap<String, Json> = BTreeMap::new();
        m.insert("name".to_string(), self.name.to_json());
        m.insert("pts".to_string(), self.pts.to_json());
        m.to_json()
    }
}

fn make_data () -> BTreeMap<String, Json> {
    let mut data = BTreeMap::new();

    data.insert("year".to_string(), "2015".to_json());

    let teams = vec![ Team { name: "Jiangsu Sainty".to_string(),
                             pts: 43u16 },
                      Team { name: "Beijing Guoan".to_string(),
                             pts: 27u16 },
                      Team { name: "Guangzhou Evergrand".to_string(),
                             pts: 22u16 },
                      Team { name: "Shandong Luneng".to_string(),
                             pts: 12u16 } ];

    data.insert("teams".to_string(), teams.to_json());
    data
}

/// the handler
fn hello_world(_: &mut Request) -> IronResult<Response> {
    let mut resp = Response::new();

    let data = make_data();
    resp.set_mut(Template::new("index", data)).set_mut(status::Ok);
    Ok(resp)
}

#[cfg(feature = "watch")]
fn main() {
    env_logger::init().unwrap();

    let mut chain = Chain::new(hello_world);

    let mut hbse = HandlebarsEngine::new2();
    let source = Box::new(DirectorySource::new("./examples/templates/", ".hbs"));
    hbse.add(source);
    if let Err(r) = hbse.reload() {
        panic!("{}", r.description());
    }

    let hbse_ref = Arc::new(hbse);
    hbse_ref.watch("./examples/templates/");

    chain.link_after(hbse_ref);

    println!("Server running at http://localhost:3000/");
    Iron::new(chain).http("localhost:3000").unwrap();
}

#[cfg(not(feature = "watch"))]
fn main() {
    println!("Watch only enabled via --features watch option");
}
<commit_msg>(fix) disable watch_server for serde_type<commit_after>#![allow(dead_code, unused_imports)]
extern crate iron;
extern crate handlebars_iron as hbs;
#[cfg(not(feature = "serde_type"))]
extern crate rustc_serialize;
extern crate env_logger;

use iron::prelude::*;
use hbs::{HandlebarsEngine, DirectorySource};
#[cfg(feature = "watch")]
use hbs::Watchable;

use std::sync::Arc;
use std::error::Error;

#[cfg(not(feature = "serde_type"))]
mod data {
    use std::collections::BTreeMap;
    use rustc_serialize::json::{ToJson, Json};
    use iron::prelude::*;
    use iron::status;
    use hbs::Template;

    struct Team {
        name: String,
        pts: u16
    }

    impl ToJson for Team {
        fn to_json(&self) -> Json {
            let mut m: BTreeMap<String, Json> = BTreeMap::new();
            m.insert("name".to_string(), self.name.to_json());
            m.insert("pts".to_string(), self.pts.to_json());
            m.to_json()
        }
    }

    fn make_data () -> BTreeMap<String, Json> {
        let mut data = BTreeMap::new();

        data.insert("year".to_string(), "2015".to_json());

        let teams = vec![ Team { name: "Jiangsu Sainty".to_string(),
                                 pts: 43u16 },
                          Team { name: "Beijing Guoan".to_string(),
                                 pts: 27u16 },
                          Team { name: "Guangzhou Evergrand".to_string(),
                                 pts: 22u16 },
                          Team { name: "Shandong Luneng".to_string(),
                                 pts: 12u16 } ];

        data.insert("teams".to_string(), teams.to_json());
        data.insert("engine".to_string(), "rustc_serialize".to_json());
        data
    }

    /// the handler
    pub fn hello_world(_: &mut Request) -> IronResult<Response> {
        let mut resp = Response::new();

        let data = make_data();
        resp.set_mut(Template::new("index", data)).set_mut(status::Ok);
        Ok(resp)
    }
}

#[cfg(feature = "watch")]
fn main() {
    use data::*;
    env_logger::init().unwrap();

    let mut chain = Chain::new(hello_world);

    let mut hbse = HandlebarsEngine::new2();
    let source = Box::new(DirectorySource::new("./examples/templates/", ".hbs"));
    hbse.add(source);
    if let Err(r) = hbse.reload() {
        panic!("{}", r.description());
    }

    let hbse_ref = Arc::new(hbse);
    hbse_ref.watch("./examples/templates/");

    chain.link_after(hbse_ref);

    println!("Server running at http://localhost:3000/");
    Iron::new(chain).http("localhost:3000").unwrap();
}

#[cfg(not(feature = "watch"))]
fn main() {
    println!("Watch only enabled via --features watch option");
}
<|endoftext|>


<commit_before>extern crate clap;

use std::io::prelude::*;
use std::fs::File;
use std::str::from_utf8;
use std::ascii::AsciiExt;

#[derive(Debug)]
struct Abbas<'a> {
    inner: &'a [u8],
    idx: usize, // idx must never be left in a [] block
}

fn is_abba(candidate: &[u8]) -> bool {
    candidate.len() == 4
        && candidate[0] == candidate[3]
        && candidate[1] == candidate[2]
        && candidate[0] != candidate[1]
}

impl<'a> Iterator for Abbas<'a> {
    type Item = &'a str;
    fn next(&mut self) -> Option<Self::Item> {
        let inner_end = self.inner.len();
        while self.idx < inner_end {
            // stop = next '[' or end of string
            let stop = self.inner[self.idx..]
                .iter()
                .position(|ch| *ch == '[' as u8) // position relative to idx
                .map(|pos| pos + self.idx) // position relative to start
                .unwrap_or(inner_end);
            // continue until would run into stop
            while self.idx <= stop - 4 {
                let window = &self.inner[self.idx .. self.idx + 4];
                if is_abba(window) {
                    self.idx += 1;
                    return Some(from_utf8(window).unwrap());
                }
                self.idx += 1;
            }
            // skip to stop
            self.idx = stop;
            // skip to next ']'
            while self.idx < inner_end && self.inner[self.idx] != ']' as u8 {
                self.idx += 1;
            }
            // go past ']'
            if self.idx < inner_end {
                self.idx += 1;
            }
        }
        return None;
    }
}

#[derive(Debug)]
struct AntiAbbas<'a> {
    inner: &'a [u8],
    idx: usize, // idx must always be left in a [] block, or at end
}

impl<'a> Iterator for AntiAbbas<'a> {
    type Item = &'a str;
    fn next(&mut self) -> Option<Self::Item> {
        let inner_end = self.inner.len();
        while self.idx < inner_end {
            // stop = next ']' or end of string
            let stop = self.inner[self.idx..]
                .iter()
                .position(|ch| *ch == ']' as u8) // position relative to idx
                .map(|pos| pos + self.idx) // position relative to start
                .unwrap_or(inner_end);
            // continue until would run into stop
            while self.idx <= stop - 4 {
                let window = &self.inner[self.idx .. self.idx + 4];
                if is_abba(window) {
                    self.idx += 1;
                    return Some(from_utf8(window).unwrap());
                }
                self.idx += 1;
            }
            // skip to stop
            self.idx = stop;
            // skip to next '['
            while self.idx < inner_end && self.inner[self.idx] != '[' as u8 {
                self.idx += 1;
            }
            // go into [] block
            if self.idx < inner_end {
                self.idx += 1;
            }
        }
        return None;
    }
}

fn abbas(s: &str) -> Abbas {
    if !s.is_ascii() {
        panic!("Only ascii strings are supported");
    }
    Abbas { inner: s.as_bytes(), idx: 0 }
}

fn anti_abbas(s: &str) -> AntiAbbas {
    if !s.is_ascii() {
        panic!("Only ascii strings are supported");
    }
    AntiAbbas {
        inner: s.as_bytes(),
        idx: s.find('[').map(|pos| pos + 1).unwrap_or(s.len())
    }
}

fn is_valid_ip(candidate: &str) -> bool {
    anti_abbas(candidate).next().is_none()
        && abbas(candidate).next().is_some()
}

fn parse_args() -> std::io::Result<Box<Read>> {
    let source = clap::App::new("Day 07")
        .author("Devon Hollowood")
        .arg(clap::Arg::with_name("ips")
             .index(1)
             .short("f")
             .long("ips")
             .help("file to read IPs from. Reads from stdin otherwise")
             .takes_value(true)
        )
        .get_matches()
        .value_of_os("ips")
        .map(|str| str.to_owned());
    match source {
        Some(filename) => Ok(Box::new(File::open(filename)?)),
        None => Ok(Box::new(std::io::stdin())),
    }
}

fn read_ips<R: Read>(source: &mut R) -> std::io::Result<Vec<String>> {
    let mut contents = String::new();
    source.read_to_string(&mut contents)?;
    Ok(contents.lines().map(|line| line.trim().to_owned()).collect())
}

fn main() {
    let mut source = parse_args()
        .unwrap_or_else(|err| panic!("Error reading file: {}", err));
    let ips = read_ips(&mut source)
        .unwrap_or_else(|err| panic!("Error reading ips: {}", err));
    let n_valid_ips = ips.iter().filter(|ip| is_valid_ip(&ip)).count();
    println!("# of valid IPs: {}", n_valid_ips);
}
<commit_msg>Day 7 refactor<commit_after>extern crate clap;

use std::io::prelude::*;
use std::fs::File;

#[derive(Debug)]
/// Iterator over parts of str in delimiters
struct Delimited<'a> {
    inner: &'a str,
    start_char: char,
    end_char: char,
}

impl<'a> Iterator for Delimited<'a> {
    type Item = &'a str;
    fn next(&mut self) -> Option<Self::Item> {
        if self.inner.is_empty() {
            return None;
        }
        let end = self.inner.len();
        let next_end = self.inner
            .find(self.end_char)
            .unwrap_or(end);
        let (delimited, rest) = self.inner.split_at(next_end);
        let next_start = rest
            .find(self.start_char)
            .map(|p| p + 1)
            .unwrap_or(end-delimited.len());
        self.inner = &rest[next_start .. ];
        Some(delimited)
    }
}

fn exteriors(s: &str) -> Delimited {
    Delimited { inner: &s, start_char: ']', end_char: '[' }
}

fn interiors(s: &str) -> Delimited {
    let start = s.find('[').map(|p| p + 1).unwrap_or(s.len());
    Delimited { inner: &s[start..], start_char: '[', end_char: ']' }
}

#[derive(Debug)]
struct Abbas<'a> {
    current: Option<&'a str>,
    inner: Delimited<'a>,
}

impl<'a> Iterator for Abbas<'a> {
    type Item = &'a str;
    fn next(&mut self) -> Option<Self::Item> {
        while self.current.is_some() {
            while let Some(win) = window(self.current.unwrap(), 4) {
                self.current = Some(advance(self.current.unwrap()));
                if is_abba(win) {
                    return Some(win);
                }
            }
            self.current = self.inner.next();
        }
        None
    }
}

fn abbas(s: &str) -> Abbas {
    let mut delimiters = exteriors(s);
    Abbas { current: delimiters.next(), inner: delimiters }
}

fn anti_abbas(s: &str) -> Abbas {
    let mut delimiters = interiors(s);
    Abbas { current: delimiters.next(), inner: delimiters }
}

fn advance(s: &str) -> &str {
    let mut iter = s.chars();
    iter.next();
    iter.as_str()
}

fn window(s: &str, len: usize) -> Option<&str> {
    if len == 0 {
        return None;
    }
    s.char_indices().nth(len-1).map(|(idx, ch)| &s[.. idx + ch.len_utf8()])
}

fn is_abba(candidate: &str) -> bool {
    if candidate.len() != 4 {
        return false;
    }
    let mut iter = candidate.chars();
    let a = iter.next().unwrap();
    let b = iter.next().unwrap();
    let c = iter.next().unwrap();
    let d = iter.next().unwrap();
    a == d && b == c && a != b
}

fn supports_tls(candidate: &str) -> bool {
    //anti_abbas(candidate).next().is_none()
    //    && abbas(candidate).next().is_some()
    let fst = abbas(candidate).count();
    let snd = anti_abbas(candidate).count();
    fst >= 1 && snd == 0
}

fn parse_args() -> std::io::Result<Box<Read>> {
    let source = clap::App::new("Day 07")
        .author("Devon Hollowood")
        .arg(clap::Arg::with_name("ips")
             .index(1)
             .short("f")
             .long("ips")
             .help("file to read IPs from. Reads from stdin otherwise")
             .takes_value(true)
        )
        .get_matches()
        .value_of_os("ips")
        .map(|str| str.to_owned());
    match source {
        Some(filename) => Ok(Box::new(File::open(filename)?)),
        None => Ok(Box::new(std::io::stdin())),
    }
}

fn read_ips<R: Read>(source: &mut R) -> std::io::Result<Vec<String>> {
    let mut contents = String::new();
    source.read_to_string(&mut contents)?;
    Ok(contents.lines().map(|line| line.trim().to_owned()).collect())
}

fn main() {
    let mut source = parse_args()
        .unwrap_or_else(|err| panic!("Error reading file: {}", err));
    let ips = read_ips(&mut source)
        .unwrap_or_else(|err| panic!("Error reading ips: {}", err));
    let n_valid_ips = ips.iter().filter(|ip| supports_tls(&ip)).count();
    println!("# of valid IPs: {}", n_valid_ips);
}
<|endoftext|>


<commit_before>use super::nodrop::NoDrop;
use array::Array;
use std::mem;
use std::ops::{Deref, DerefMut};

/// A combination of NoDrop and “maybe uninitialized”;
/// this wraps a value that can be wholly or partially uninitialized.
///
/// NOTE: This is known to not be a good solution, but it's the one we have kept
/// working on stable Rust. Stable improvements are encouraged, in any form,
/// but of course we are waiting for a real, stable, MaybeUninit.
#[repr(C)] // for cast from self ptr to value
pub struct MaybeUninit<T>(NoDrop<T>);
// why don't we use ManuallyDrop here: It doesn't inhibit
// enum layout optimizations that depend on T, and we support older Rust.

impl<T> MaybeUninit<T> {
    /// Create a new MaybeUninit with uninitialized interior
    pub unsafe fn uninitialized() -> Self {
        Self(NoDrop::new(mem::uninitialized()))
    }
}

impl<A: Array> Deref for MaybeUninit<A> {
    type Target = A;

    #[inline(always)]
    fn deref(&self) -> &A {
        &self.0
    }
}

impl<A: Array> DerefMut for MaybeUninit<A> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut A {
        &mut self.0
    }
}
<commit_msg>fix failure on rust 1.20<commit_after>use super::nodrop::NoDrop;
use array::Array;
use std::mem;
use std::ops::{Deref, DerefMut};

/// A combination of NoDrop and “maybe uninitialized”;
/// this wraps a value that can be wholly or partially uninitialized.
///
/// NOTE: This is known to not be a good solution, but it's the one we have kept
/// working on stable Rust. Stable improvements are encouraged, in any form,
/// but of course we are waiting for a real, stable, MaybeUninit.
#[repr(C)] // for cast from self ptr to value
pub struct MaybeUninit<T>(NoDrop<T>);
// why don't we use ManuallyDrop here: It doesn't inhibit
// enum layout optimizations that depend on T, and we support older Rust.

impl<T> MaybeUninit<T> {
    /// Create a new MaybeUninit with uninitialized interior
    pub unsafe fn uninitialized() -> Self {
        MaybeUninit(NoDrop::new(mem::uninitialized()))
    }
}

impl<A: Array> Deref for MaybeUninit<A> {
    type Target = A;

    #[inline(always)]
    fn deref(&self) -> &A {
        &self.0
    }
}

impl<A: Array> DerefMut for MaybeUninit<A> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut A {
        &mut self.0
    }
}
<|endoftext|>


<commit_before>extern crate basiccms;

#[cfg(test)]
mod tests {

    use basiccms::*;

    #[test]
    #[should_panic]
    fn you_cannot_add_two_sketches_together_if_they_have_different_hashers () {
        let mut left  = Sketch::new(0.0001, 0.99);
        let mut right =  Sketch::new(0.0001, 0.99);

        let third = &left + &right;
    }

    #[test]
    fn but_you_can_add_together_two_sketches_from_a_common_base () {
        let mut left  = Sketch::new(0.0001, 0.99);
        let mut right = left.clone();

        left.add(1);
        right.add(1);

        let mut third = &left + &right;

        assert_eq!(1, left.point(1));
        assert_eq!(1, right.point(1));
        assert_eq!(2, third.point(1));
    }
}
<commit_msg>Remove warnings from test project<commit_after>extern crate basiccms;

#[cfg(test)]
mod tests {

    use basiccms::*;

    #[test]
    #[should_panic]
    fn you_cannot_add_two_sketches_together_if_they_have_different_hashers () {
        let mut left  = Sketch::new(0.0001, 0.99);
        let mut right =  Sketch::new(0.0001, 0.99);

        left.add(1); right.add(1);

        let mut third = &left + &right;

        third.point(1);
    }

    #[test]
    fn but_you_can_add_together_two_sketches_from_a_common_base () {
        let mut left  = Sketch::new(0.0001, 0.99);
        let mut right = left.clone();

        left.add(1);
        right.add(1);

        let mut third = &left + &right;

        assert_eq!(1, left.point(1));
        assert_eq!(1, right.point(1));
        assert_eq!(2, third.point(1));
    }
}
<|endoftext|>


<commit_before>use super::utils::parse_string;
use ast::rules;

#[test]
fn test_table_fields() {
    assert_eq!(
        parse_string(r#"["Key"] = true"#, rules::field), r#"[Single(TableField { key: Some(String("Key")), value: Boolean(true) })]"#
    );
    assert_eq!(
        parse_string("Key = false", rules::field), r#"[Single(TableField { key: Some(Id("Key")), value: Boolean(false) })]"#
    );
    assert_eq!(
        parse_string("7", rules::field), "[Single(TableField { key: None, value: Number(7.0) })]"
    );
}

#[test]
fn test_table() {
    assert_eq!(parse_string(r#"{["Key"] = true, Key = false, 7}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(Id("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
    assert_eq!(parse_string(r#"{["Key"] = true, Key = false, 7,}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(Id("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
    assert_eq!(parse_string(r#"{["Key"] = true; Key = false; 7}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(Id("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
    assert_eq!(parse_string(r#"{["Key"] = true; Key = false; 7;}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(Id("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
    assert_eq!(parse_string(r#"{["Key"] = true; Key = false, 7}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(Id("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
    assert_eq!(parse_string(r#"{["Key"] = true, Key = false; 7}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(Id("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
}

#[test]
#[should_panic]
fn test_invalid0() {
    parse_string(r#"{["Key"] = true, Key = }"#, rules::tableconstructor);
}

#[test]
#[should_panic]
fn test_invalid1() {
    parse_string(r#"{["Key"] = true, , 7}"#, rules::tableconstructor);
}

#[test]
#[should_panic]
fn test_invalid2() {
    parse_string(r#"{["Key"] = true Key = false, 7}"#, rules::tableconstructor);
}

#[test]
#[should_panic]
fn test_invalid3() {
    parse_string(r#"{["Key"] = true Key = false, 7"#, rules::tableconstructor);
}
<commit_msg>Fixed tests<commit_after>use super::utils::parse_string;
use ast::rules;

#[test]
fn test_table_fields() {
    assert_eq!(
        parse_string(r#"["Key"] = true"#, rules::field), r#"[Single(TableField { key: Some(String("Key")), value: Boolean(true) })]"#
    );
    assert_eq!(
        parse_string("Key = false", rules::field), r#"[Single(TableField { key: Some(String("Key")), value: Boolean(false) })]"#
    );
    assert_eq!(
        parse_string("7", rules::field), "[Single(TableField { key: None, value: Number(7.0) })]"
    );
}

#[test]
fn test_table() {
    assert_eq!(parse_string(r#"{["Key"] = true, Key = false, 7}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(String("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
    assert_eq!(parse_string(r#"{["Key"] = true, Key = false, 7,}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(String("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
    assert_eq!(parse_string(r#"{["Key"] = true; Key = false; 7}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(String("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
    assert_eq!(parse_string(r#"{["Key"] = true; Key = false; 7;}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(String("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
    assert_eq!(parse_string(r#"{["Key"] = true; Key = false, 7}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(String("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
    assert_eq!(parse_string(r#"{["Key"] = true, Key = false; 7}"#, rules::tableconstructor),
        r#"[Single(Table([TableField { key: Some(String("Key")), value: Boolean(true) }, TableField { key: Some(String("Key")), value: Boolean(false) }, TableField { key: None, value: Number(7.0) }]))]"#);
}

#[test]
#[should_panic]
fn test_invalid0() {
    parse_string(r#"{["Key"] = true, Key = }"#, rules::tableconstructor);
}

#[test]
#[should_panic]
fn test_invalid1() {
    parse_string(r#"{["Key"] = true, , 7}"#, rules::tableconstructor);
}

#[test]
#[should_panic]
fn test_invalid2() {
    parse_string(r#"{["Key"] = true Key = false, 7}"#, rules::tableconstructor);
}

#[test]
#[should_panic]
fn test_invalid3() {
    parse_string(r#"{["Key"] = true Key = false, 7"#, rules::tableconstructor);
}
<|endoftext|>


<commit_before>#![feature(const_let)]

fn main() {
    let x: &'static u32 = {
        let y = 42;
        &y //~ ERROR does not live long enough
    };
}<commit_msg>Trailing newline<commit_after>#![feature(const_let)]

fn main() {
    let x: &'static u32 = {
        let y = 42;
        &y //~ ERROR does not live long enough
    };
}
<|endoftext|>