text
stringlengths
8
4.13M
use super::{Block, BlockId, Field}; use crate::{random_id::U128Id, resource::ResourceId, JsObject, Promise}; use std::collections::HashSet; use wasm_bindgen::{prelude::*, JsCast}; #[derive(Clone)] pub enum Icon { None, Resource(ResourceId), DefaultUser, } #[derive(Clone)] pub enum Sender { System, User, Character(BlockId), } #[derive(Clone)] pub struct Item { peer_id: String, display_name: String, icon: Icon, sender: Sender, text: String, reply: Option<String>, } impl Sender { pub fn as_character(&self) -> Option<&BlockId> { match self { Self::Character(block_id) => Some(block_id), _ => None, } } } impl Icon { pub fn to_jsobject(&self) -> JsObject { match self { Self::None => object! { type: "None" }, Self::DefaultUser => object! { type: "DefaultUser" }, Self::Resource(r_id) => object! { type: "Resource", payload: r_id.to_jsvalue() }, } } pub fn from_jsobject(val: JsObject) -> Option<Self> { val.get("type") .and_then(|t| t.as_string()) .and_then(|t| match t.as_str() { "None" => Some(Self::None), "DefaultUser" => Some(Self::DefaultUser), "Resource" => val .get("payload") .and_then(|p| U128Id::from_jsvalue(&p)) .map(|p| Self::Resource(p)), _ => None, }) } } impl Sender { pub fn to_jsobject(&self) -> JsObject { match self { Self::System => object! { type: "System" }, Self::User => object! { type: "User" }, Self::Character(c_id) => object! { type: "Character", payload: c_id.to_jsvalue() }, } } pub fn from_jsobject(field: &mut Field, val: JsObject) -> Option<Self> { val.get("type") .and_then(|t| t.as_string()) .and_then(|t| match t.as_str() { "System" => Some(Self::System), "User" => Some(Self::User), "Character" => val .get("payload") .and_then(|p| U128Id::from_jsvalue(&p)) .map(|p| Self::Character(field.block_id(p))), _ => None, }) } } impl Item { pub fn new( peer_id: String, display_name: String, icon: Icon, sender: Sender, text: String, reply: Option<String>, ) -> Self { Self { peer_id, display_name, icon, sender, text, reply, } } pub fn display_name(&self) -> &String { &self.display_name } pub fn peer_id(&self) -> &String { &self.peer_id } pub fn icon(&self) -> &Icon { &self.icon } pub fn sender(&self) -> &Sender { &self.sender } pub fn text(&self) -> &String { &self.text } pub fn reply(&self) -> Option<&String> { self.reply.as_ref() } } impl Block for Item { fn pack(&self) -> Promise<JsValue> { let icon: js_sys::Object = self.icon.to_jsobject().into(); let sender: js_sys::Object = self.sender.to_jsobject().into(); let data = object! { peer_id: &self.peer_id, display_name: &self.display_name, icon: icon, sender: sender, text: &self.text, reply: self.reply.as_ref() }; let data: js_sys::Object = data.into(); let data: JsValue = data.into(); Promise::new(move |resolve| resolve(Some(data))) } fn unpack(field: &mut Field, val: JsValue) -> Promise<Box<Self>> { let self_ = if let Ok(val) = val.dyn_into::<JsObject>() { let peer_id = val.get("peer_id").and_then(|x| x.as_string()); let display_name = val.get("display_name").and_then(|x| x.as_string()); let icon = val.get("icon").and_then(|x| Icon::from_jsobject(x)); let sender = val .get("sender") .and_then(|x| Sender::from_jsobject(field, x)); let text = val.get("text").and_then(|x| x.as_string()); let reply = Some(val.get("reply").and_then(|x| x.as_string())); if let ( Some(peer_id), Some(display_name), Some(icon), Some(sender), Some(text), Some(reply), ) = (peer_id, display_name, icon, sender, text, reply) { Some(Box::new(Self { peer_id, display_name, icon, sender, text, reply, })) } else { None } } else { None }; Promise::new(move |resolve| resolve(self_)) } fn dependents(&self, field: &Field) -> HashSet<BlockId> { let mut deps = set! {}; if let Sender::Character(block_id) = &self.sender { if let Some(block) = field.get::<super::super::Character>(block_id) { let block_deps = block.dependents(field); for block_dep in block_deps { deps.insert(block_dep); } deps.insert(block_id.clone()); } } deps } fn resources(&self, field: &Field) -> HashSet<ResourceId> { let mut reses = set! {}; if let Icon::Resource(r_id) = &self.icon { reses.insert(r_id.clone()); } if let Sender::Character(block_id) = &self.sender { if let Some(block) = field.get::<super::super::Character>(block_id) { let block_reses = block.resources(field); for block_res in block_reses { reses.insert(block_res); } } } reses } }
//! GUI bottom footer use std::sync::{Arc, Mutex}; use iced::alignment::{Horizontal, Vertical}; use iced::widget::horizontal_space; use iced::widget::tooltip::Position; use iced::widget::{button, Container, Row, Text, Tooltip}; use iced::{Alignment, Font, Length, Renderer}; use crate::gui::styles::button::ButtonType; use crate::gui::styles::container::ContainerType; use crate::gui::styles::style_constants::{FONT_SIZE_FOOTER, FONT_SIZE_SUBTITLE}; use crate::gui::styles::text::TextType; use crate::gui::styles::types::gradient_type::GradientType; use crate::gui::styles::types::style_type::StyleType; use crate::gui::types::message::Message; use crate::translations::translations_2::new_version_available_translation; use crate::utils::formatted_strings::APP_VERSION; use crate::utils::types::icon::Icon; use crate::utils::types::web_page::WebPage; use crate::Language; pub fn footer( language: Language, color_gradient: GradientType, font: Font, font_footer: Font, newer_release_available: &Arc<Mutex<Result<bool, String>>>, ) -> Container<'static, Message, Renderer<StyleType>> { let release_details_row = get_release_details(language, font, font_footer, newer_release_available); let footer_row = Row::new() .spacing(10) .width(Length::Fill) .padding([0, 20]) .align_items(Alignment::Center) .push(release_details_row) .push(get_button_website(font)) .push(get_button_github(font)) .push(get_button_sponsor(font)) .push( Text::new("Made with ❤ by Giuliano Bellini") .width(Length::FillPortion(1)) .horizontal_alignment(Horizontal::Right) .size(FONT_SIZE_FOOTER) .font(font_footer), ); Container::new(footer_row) .height(Length::Fixed(45.0)) .width(Length::Fill) .align_y(Vertical::Center) .align_x(Horizontal::Center) .style(ContainerType::Gradient(color_gradient)) } fn get_button_website(font: Font) -> Tooltip<'static, Message, Renderer<StyleType>> { let content = button( Icon::Globe .to_text() .size(17) .horizontal_alignment(Horizontal::Center) .vertical_alignment(Vertical::Center), ) .height(Length::Fixed(30.0)) .width(Length::Fixed(30.0)) .on_press(Message::OpenWebPage(WebPage::Website)); Tooltip::new(content, "Website", Position::Top) .font(font) .style(ContainerType::Tooltip) } fn get_button_github(font: Font) -> Tooltip<'static, Message, Renderer<StyleType>> { let content = button( Icon::GitHub .to_text() .size(26) .horizontal_alignment(Horizontal::Center) .vertical_alignment(Vertical::Center), ) .height(Length::Fixed(40.0)) .width(Length::Fixed(40.0)) .on_press(Message::OpenWebPage(WebPage::Repo)); Tooltip::new(content, "GitHub", Position::Top) .font(font) .style(ContainerType::Tooltip) } fn get_button_sponsor(font: Font) -> Tooltip<'static, Message, Renderer<StyleType>> { let content = button( Text::new('❤'.to_string()) .size(23) .style(TextType::Sponsor) .horizontal_alignment(Horizontal::Center) .vertical_alignment(Vertical::Center), ) .padding([2, 0, 0, 0]) .height(Length::Fixed(30.0)) .width(Length::Fixed(30.0)) .on_press(Message::OpenWebPage(WebPage::Sponsor)); Tooltip::new(content, "Sponsor", Position::Top) .font(font) .style(ContainerType::Tooltip) } fn get_release_details( language: Language, font: Font, font_footer: Font, newer_release_available: &Arc<Mutex<Result<bool, String>>>, ) -> Row<'static, Message, Renderer<StyleType>> { let mut ret_val = Row::new() .align_items(Alignment::Center) .height(Length::Fill) .width(Length::FillPortion(1)) .push( Text::new(format!("Version {APP_VERSION}")) .size(FONT_SIZE_FOOTER) .font(font_footer), ); if let Ok(boolean_response) = *newer_release_available.lock().unwrap() { if boolean_response { // a newer release is available on GitHub let button = button( Text::new('!'.to_string()) .style(TextType::Danger) .size(28) .horizontal_alignment(Horizontal::Center) .vertical_alignment(Vertical::Center), ) .padding(0) .height(Length::Fixed(35.0)) .width(Length::Fixed(35.0)) .style(ButtonType::Alert) .on_press(Message::OpenWebPage(WebPage::WebsiteDownload)); let tooltip = Tooltip::new( button, new_version_available_translation(language), Position::Top, ) .font(font) .style(ContainerType::Tooltip); ret_val = ret_val .push(horizontal_space(Length::Fixed(10.0))) .push(tooltip); } else { // this is the latest release ret_val = ret_val.push(Text::new(" ✔").size(FONT_SIZE_SUBTITLE).font(font_footer)); } } ret_val }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ //! Everything related to ioctl arguments. use serde::Deserialize; use serde::Serialize; use crate::Addr; use crate::AddrMut; use crate::Errno; use crate::FromToRaw; use crate::MemoryAccess; /// The type of ioctl from the perspective of userspace. That is, whether /// userspace is reading, writing, or doing nothing. #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum Direction { /// Userspace is reading. Read, /// Userspace is writing. Write, /// There is neither reading nor writing. This is the case for ioctls that /// have value parameters instead of pointer parameters. None, } command_enum! { /// An `ioctl` request. /// /// The `ioctl` syscall is a dumping ground for sending a request to a file /// descriptor. This is not a complete list of all the possible requests, but /// we try to have the most-commonly used requests listed. /// /// See [`ioctl_list(2)`][ioctl_list] for a more complete list. /// /// [ioctl_list]: http://man7.org/linux/man-pages/man2/ioctl_list.2.html pub enum Request<'a>: usize { // <include/asm-i386/socket.h> FIOSETOWN(Option<Addr<'a, libc::c_int>>) = 0x00008901, SIOCSPGRP(Option<Addr<'a, libc::c_int>>) = 0x00008902, FIOGETOWN(Option<AddrMut<'a, libc::c_int>>) = 0x00008903, SIOCGPGRP(Option<AddrMut<'a, libc::c_int>>) = 0x00008904, SIOCATMAR(Option<AddrMut<'a, libc::c_int>>) = 0x00008905, SIOCGSTAMP(Option<AddrMut<'a, libc::timeval>>) = 0x00008906, // <include/asm-i386/termios.h> TCGETS(Option<AddrMut<'a, Termios>>) = 0x00005401, TCSETS(Option<Addr<'a, Termios>>) = 0x00005402, TCSETSW(Option<Addr<'a, Termios>>) = 0x00005403, TCSETSF(Option<Addr<'a, Termios>>) = 0x00005404, TCGETA(Option<AddrMut<'a, Termios>>) = 0x00005405, TCSETA(Option<Addr<'a, Termios>>) = 0x00005406, TCSETAW(Option<Addr<'a, Termios>>) = 0x00005407, TCSETAF(Option<Addr<'a, Termios>>) = 0x00005408, TCSBRK(libc::c_int) = 0x00005409, TCXONC(libc::c_int) = 0x0000540A, TCFLSH(libc::c_int) = 0x0000540B, TIOCEXCL = 0x0000540C, TIOCNXCL = 0x0000540D, TIOCSCTTY(libc::c_int) = 0x0000540E, TIOCGPGRP(Option<AddrMut<'a, libc::pid_t>>) = 0x0000540F, TIOCSPGRP(Option<Addr<'a, libc::pid_t>>) = 0x00005410, TIOCOUTQ(Option<AddrMut<'a, libc::c_int>>) = 0x00005411, TIOCSTI(Option<Addr<'a, libc::c_char>>) = 0x00005412, TIOCGWINSZ(Option<AddrMut<'a, Winsize>>) = 0x00005413, TIOCSWINSZ(Option<Addr<'a, Winsize>>) = 0x00005414, TIOCMGET(Option<AddrMut<'a, libc::c_int>>) = 0x00005415, TIOCMBIS(Option<Addr<'a, libc::c_int>>) = 0x00005416, TIOCMBIC(Option<Addr<'a, libc::c_int>>) = 0x00005417, TIOCMSET(Option<Addr<'a, libc::c_int>>) = 0x00005418, TIOCGSOFTCAR(Option<AddrMut<'a, libc::c_int>>) = 0x00005419, TIOCSSOFTCAR(Option<Addr<'a, libc::c_int>>) = 0x0000541A, FIONREAD(Option<AddrMut<'a, libc::c_int>>) = 0x0000541B, // Duplicate of FIONREAD; can't properly match the ID. #[cfg(none)] TIOCINQ(Option<AddrMut<'a, libc::c_int>>) = 0x0000541B, TIOCLINUX(Option<Addr<'a, libc::c_char>>) = 0x0000541C, TIOCCONS = 0x0000541D, // Disabled because `libc::serial_struct` isn't defined. #[cfg(none)] TIOCGSERIAL(Option<AddrMut<'a, libc::serial_struct>>) = 0x0000541E, // Disabled because `libc::serial_struct` isn't defined. #[cfg(none)] TIOCSSERIAL(Option<Addr<'a, libc::serial_struct>>) = 0x0000541F, TIOCPKT(Option<Addr<'a, libc::c_int>>) = 0x00005420, FIONBIO(Option<Addr<'a, libc::c_int>>) = 0x00005421, TIOCNOTTY = 0x00005422, TIOCSETD(Option<Addr<'a, libc::c_int>>) = 0x00005423, TIOCGETD(Option<AddrMut<'a, libc::c_int>>) = 0x00005424, TCSBRKP(libc::c_int) = 0x00005425, // Disabled because `libc::tty_struct` isn't defined. #[cfg(none)] TIOCTTYGSTRUCT(Option<AddrMut<'a, libc::tty_struct>>) = 0x00005426, TIOCGPTPEER(libc::c_int) = 0x00005441, FIONCLEX = 0x00005450, FIOCLEX = 0x00005451, FIOASYNC(Option<Addr<'a, libc::c_int>>) = 0x00005452, TIOCSERCONFIG = 0x00005453, TIOCSERGWILD(Option<AddrMut<'a, libc::c_int>>) = 0x00005454, TIOCSERSWILD(Option<Addr<'a, libc::c_int>>) = 0x00005455, TIOCGLCKTRMIOS(Option<AddrMut<'a, Termios>>) = 0x00005456, TIOCSLCKTRMIOS(Option<Addr<'a, Termios>>) = 0x00005457, // Disabled because `libc::async_struct` isn't defined. #[cfg(none)] TIOCSERGSTRUCT(Option<AddrMut<'a, libc::async_struct>>) = 0x00005458, TIOCSERGETLSR(Option<AddrMut<'a, libc::c_int>>) = 0x00005459, FICLONE(libc::c_int) = 0x40049409, FICLONERANGE(Option<Addr<'a, libc::file_clone_range>>) = 0x4020940D, } } impl<'a> Request<'a> { /// Returns the direction of the request. That is, whether it is a read or /// write request. pub fn direction(&self) -> Direction { // TODO: Generate this with a macro. match self { Self::TCGETS(_) => Direction::Read, Self::TCSETS(_) => Direction::Write, Self::TIOCGWINSZ(_) => Direction::Read, Self::TIOCSWINSZ(_) => Direction::Write, Self::TIOCSPGRP(_) => Direction::Write, Self::TIOCGPGRP(_) => Direction::Read, Self::FIONREAD(_) => Direction::Read, other => { panic!("ioctl: unsupported request: {:?}", other) } } } /// Reads the output associated with this request. If the request has no /// outputs, returns `Ok(None)`. /// /// Panics if this request is unsupported. pub fn read_output<M: MemoryAccess>(&self, m: &M) -> Result<Option<Output>, Errno> { // TODO: Generate this with a macro. Ok(Some(match self { Self::TCGETS(p) => Output::TCGETS(m.read_value(p.ok_or(Errno::EFAULT)?)?), Self::TCSETS(_) => return Ok(None), Self::TIOCGWINSZ(p) => Output::TIOCGWINSZ(m.read_value(p.ok_or(Errno::EFAULT)?)?), Self::TIOCSWINSZ(_) => return Ok(None), Self::TIOCGPGRP(p) => Output::TIOCGPGRP(m.read_value(p.ok_or(Errno::EFAULT)?)?), Self::TIOCSPGRP(_) => return Ok(None), Self::FIONREAD(p) => Output::FIONREAD(m.read_value(p.ok_or(Errno::EFAULT)?)?), other => { panic!("ioctl: unsupported request: {:?}", other); } })) } /// Writes the output associated with this request to the provided address /// (if any). If the request has no outputs, returns `Ok(())`. pub fn write_output<M: MemoryAccess>(&self, m: &mut M, output: &Output) -> Result<(), Errno> { match (self, output) { (Self::TCGETS(p), Output::TCGETS(output)) => { m.write_value(p.ok_or(Errno::EFAULT)?, output) } (Self::TCSETS(_), _) => Ok(()), (Self::TIOCGWINSZ(p), Output::TIOCGWINSZ(output)) => { m.write_value(p.ok_or(Errno::EFAULT)?, output) } (Self::TIOCSWINSZ(_), _) => Ok(()), (Self::TIOCGPGRP(p), Output::TIOCGPGRP(output)) => { m.write_value(p.ok_or(Errno::EFAULT)?, output) } (Self::TIOCSPGRP(_), _) => Ok(()), (Self::FIONREAD(p), Output::FIONREAD(output)) => { m.write_value(p.ok_or(Errno::EFAULT)?, output) } (other, output) => { panic!( "ioctl: unsupported request/output pair: {:?}, {:?}", other, output ); } } } } /// The output after a successful call to `ioctl`. This is only relavent for /// requests with outputs. /// /// Note that this is a `union`. The descriminator is the [`Request`] type. #[allow(missing_docs, non_camel_case_types, clippy::upper_case_acronyms)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum Output { TCGETS(Termios), TIOCGWINSZ(Winsize), TIOCGPGRP(libc::pid_t), FIONREAD(libc::c_int), } /// Terminal I/O. This is the same as `termios` as defined in /// `include/uapi/asm-generic/termbits.h`. Note that this is *different* from the /// struct exposed by libc (which maps the smaller kernel-defined struct onto a /// larger libc-defined struct). #[repr(C)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct Termios { /// input mode flags pub c_iflag: libc::tcflag_t, /// output mode flags pub c_oflag: libc::tcflag_t, /// control mode flags pub c_cflag: libc::tcflag_t, /// local mode flags pub c_lflag: libc::tcflag_t, /// line discipline pub c_line: libc::cc_t, /// control characters pub c_cc: [libc::cc_t; 19], } #[allow(missing_docs)] #[repr(C)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct Winsize { pub ws_row: libc::c_ushort, pub ws_col: libc::c_ushort, pub ws_xpixel: libc::c_ushort, pub ws_ypixel: libc::c_ushort, }
/// Main architecture-independent kernel functionality /// /// Called from `arch::kstart()` pub fn kmain() { println!("kmain()"); loop {} }
pub mod home_page; pub mod poll_results_page; pub mod poll_voting_page; pub mod profile_page; pub use self::home_page::HomePage; pub use self::poll_results_page::PollResultsPage; pub use self::poll_voting_page::PollVotingPage; pub use self::profile_page::ProfilePage;
use crypto::scrypt::{scrypt, ScryptParams}; use rust_sodium::crypto::secretbox::xsalsa20poly1305; use crate::util::bytes_to_hex; lazy_static! { static ref SCRYPT_PARAMS: ScryptParams = ScryptParams::new(4, 8, 1); } pub fn generate_key(data: &str, salt_vec: &Vec<u8>) -> String { let data_vec: Vec<u8> = data.bytes().collect(); let mut output_vec: Vec<u8> = vec![0; 32]; scrypt( &data_vec, &salt_vec, &SCRYPT_PARAMS, output_vec.as_mut_slice(), ); bytes_to_hex(&output_vec) } pub fn encrypt_secret( data: &str, key_vec: &Vec<u8>, nonce_vec: &Vec<u8>, ) -> Result<String, String> { let key = match xsalsa20poly1305::Key::from_slice(&key_vec) { Some(val) => val, None => return Err("invalid key".to_string()), }; let nonce = match xsalsa20poly1305::Nonce::from_slice(&nonce_vec) { Some(val) => val, None => return Err("invalid nonce".to_string()), }; let data_vec: Vec<u8> = data.bytes().collect(); let output_vec = xsalsa20poly1305::seal(&data_vec, &nonce, &key); Ok(bytes_to_hex(&output_vec)) }
extern crate iron; extern crate iron_cms; use iron::{Iron, Chain}; fn main() { // Add routers let mut chain = Chain::new(iron_cms::routes()); // Add db middleware chain.link_before(iron_cms::middleware::db("postgres://postgres:qwe123qwe123@172.18.0.2:5432/test_db")); // Add Template renderer and views path chain.link_after(iron_cms::middleware::template_render(vec!["/home/evgeny/rs/iron-cms/views/"])); // Add error-404 handler chain.link_after(iron_cms::middleware::Error404); // Start application Iron::new(chain).http("localhost:3000").unwrap(); }
union IntOrFloat { i: i32, f: f32 } fn main() { let mut iof = IntOrFloat{ i: 123 }; unsafe { println!("unsafe union access {} ", iof.i); } unsafe { match iof { IntOrFloat { i } => println!("int {}", i), IntOrFloat { f } => println!("float {}", f), } } }
//! A module that implements the Adobe RGB color space. The Adobe RGB space differs greatly from //! sRGB: its components are floating points that range between 0 and 1, and it has a set of //! primaries designed to give it a wider coverage (over half of CIE 1931). use coord::Coord; use color::{Color, XYZColor}; use consts::ADOBE_RGB_TRANSFORM_MAT as ADOBE_RGB; use consts; use na::Vector3; use illuminants::Illuminant; #[derive(Debug, Copy, Clone)] pub struct AdobeRGBColor { /// The red primary component. This is a float that should range between 0 and 1. pub r: f64, /// The green primary component. This is a float that should range between 0 and 1. pub g: f64, /// The blue primary component. This is a float that should range between 0 and 1. pub b: f64, } impl Color for AdobeRGBColor { /// Converts a given XYZ color to Adobe RGB. Adobe RGB is implicitly D65, so any color will be /// converted to D65 before conversion. Values outside of the Adobe RGB gamut will be clipped. fn from_xyz(xyz: XYZColor) -> AdobeRGBColor { // convert to D65 let xyz_c = xyz.color_adapt(Illuminant::D65); // matrix multiplication // https://en.wikipedia.org/wiki/Adobe_RGB_color_space let rgb = ADOBE_RGB() * Vector3::new(xyz_c.x, xyz_c.y, xyz_c.z); // clamp let clamp = |x: f64| { if x > 1.0 { 1.0 } else if x < 0.0 { 0.0 } else { x } }; // now we apply gamma transformation let gamma = |x: f64| x.powf(256.0 / 563.0); AdobeRGBColor { r: gamma(clamp(rgb[0])), g: gamma(clamp(rgb[1])), b: gamma(clamp(rgb[2])), } } /// Converts from Adobe RGB to an XYZ color in a given illuminant (via chromatic adaptation). fn to_xyz(&self, illuminant: Illuminant) -> XYZColor { // undo gamma transformation let ungamma = |x: f64| x.powf(563.0 / 256.0); // inverse matrix to the one in from_xyz let xyz_vec = consts::inv(ADOBE_RGB()) * Vector3::new(ungamma(self.r), ungamma(self.g), ungamma(self.b)); XYZColor { x: xyz_vec[0], y: xyz_vec[1], z: xyz_vec[2], illuminant: Illuminant::D65, }.color_adapt(illuminant) } } impl From<Coord> for AdobeRGBColor { /// Converts from a Coordinate (R, G, B) to a color. Clamps values outside of the range [0, 1]. fn from(c: Coord) -> AdobeRGBColor { // clamp values let clamp = |x: f64| { if x <= 0.0 { 0.0 } else if x >= 1.0 { 1.0 } else { x } }; AdobeRGBColor { r: clamp(c.x), g: clamp(c.y), b: clamp(c.z), } } } impl Into<Coord> for AdobeRGBColor { fn into(self) -> Coord { Coord { x: self.r, y: self.g, z: self.b, } } } #[cfg(test)] mod tests { #[allow(unused_imports)] use super::*; use color::Mix; #[test] fn test_adobe_rgb_xyz_conversion() { let xyz1 = XYZColor { x: 0.4, y: 0.2, z: 0.5, illuminant: Illuminant::D75, }; let xyz2 = AdobeRGBColor::from_xyz(xyz1).to_xyz(Illuminant::D75); assert!(xyz1.approx_equal(&xyz2)); } #[test] fn test_adobe_rgb_clamping() { let argb = AdobeRGBColor { r: 1.1, g: 0.6, b: 0.8, }; let argb2 = AdobeRGBColor { r: 1.0, g: 0.6, b: 0.8, }; let argbprime = argb.convert::<XYZColor>().convert::<AdobeRGBColor>(); let argb2prime = argb2.convert::<XYZColor>().convert::<AdobeRGBColor>(); let xyz1 = argbprime.to_xyz(Illuminant::D50); let xyz2 = argb2prime.to_xyz(Illuminant::D50); println!( "{} {} {} {} {} {}", xyz1.x, xyz2.x, xyz1.y, xyz2.y, xyz1.z, xyz2.z ); assert!(xyz1.approx_equal(&xyz2)); } #[test] fn test_adobe_rgb_mixing() { let argb = AdobeRGBColor { r: 0.4, g: 0.2, b: 0.5, }; let argb2 = AdobeRGBColor { r: 0.6, g: 0.6, b: 0.8, }; let argb_mixed = argb.mix(argb2); assert!((argb_mixed.r - 0.5).abs() <= 1e-7); assert!((argb_mixed.g - 0.4).abs() <= 1e-7); assert!((argb_mixed.b - 0.65).abs() <= 1e-7); } }
extern crate pest; #[macro_use] extern crate pest_derive; use pest::Parser; use pest::prec_climber; #[cfg(debug_assertions)] const _GRAMMAR: &'static str = include_str!("ident.pest"); #[derive(Parser)] #[grammar = "ident.pest"] struct IdentParser; fn main() { }
#![feature(plugin_registrar)] #![feature(box_syntax, rustc_private)] extern crate syntax; extern crate syntax_pos; // Load rustc as a plugin to get macros #[macro_use] extern crate rustc; extern crate rustc_plugin; extern crate docstrings; extern crate ispell; extern crate markdown; mod helpers; mod doc_params_mismatch; mod spelling_error; use doc_params_mismatch::DocParamsMismatch; use spelling_error::SpellingError; use rustc::lint::LateLintPassObject; use rustc_plugin::Registry; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_late_lint_pass(box DocParamsMismatch as LateLintPassObject); reg.register_late_lint_pass(box SpellingError::new() as LateLintPassObject); }
use std::io; use std::convert::TryFrom; use bytes::{BufMut, BytesMut}; use tokio_io::codec::{ Decoder, Encoder }; use varmint::{self, ReadVarInt, WriteVarInt}; use message::{Flag, Message}; #[derive(Debug, Clone, Copy)] enum State { /// We have not read any part of the message, waiting on the header value. Ready, /// We have read the header value, waiting on the length value. Header { stream_id: u64, flag: Flag, }, /// We have read the header and length values, waiting on the data to be /// fully available. // TODO: Could we just start streaming out data chunks as they appear and // decrementing `length` instead of waiting for it to be fully available? Length { stream_id: u64, flag: Flag, length: usize, }, } #[derive(Debug)] pub(crate) struct Codec { state: Result<State, String> } impl Codec { pub(crate) fn new() -> Codec { Codec { state: Ok(State::Ready) } } } impl State { fn step(self, src: &mut BytesMut) -> Result<Option<(State, Option<Message>)>, String> { Ok(match self { State::Ready => { // TODO: Specified to be base128, but a 61 bit stream id space // should be enough for anyone, right? match src.as_ref().try_read_u64_varint().map_err(|e| e.to_string())? { Some(header) => { let header_len = varmint::len_u64_varint(header); let _discarded = src.split_to(header_len); let stream_id = header >> 3; let flag = Flag::try_from(header & 0b00000111)?; Some((State::Header { stream_id, flag }, None)) } None => None, } } State::Header { stream_id, flag } => { // TODO: Specified to be base128, but since the max message size is // limited to much less than that reading a 64 bit/32 bit length should // be fine, right? src.as_ref() .try_read_usize_varint() .map_err(|e| e.to_string())? .map(|length| { let length_len = varmint::len_usize_varint(length); let _discarded = src.split_to(length_len); (State::Length { stream_id, flag, length }, None) }) } State::Length { stream_id, flag, length } => { if src.len() < length { None } else { let data = src.split_to(length).freeze(); Some((State::Ready, Some(Message { stream_id, data, flag }))) } } }) } } impl Decoder for Codec { type Item = Message; type Error = io::Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { loop { let state = self.state.clone().map_err(|s| io::Error::new(io::ErrorKind::Other, s))?; match state.step(src) { Ok(None) => { // There was not enough data available to transition to the // next state, return and wait till we are next invoked. return Ok(None); } Ok(Some((state, msg))) => { // We transitioned to the next state, and may have finished // parsing a message, if so return it, otherwise loop back // and see if the next state can also transition onwards. self.state = Ok(state); if let Some(msg) = msg { return Ok(Some(msg)); } } Err(error) => { // We encountered an error while parsing a message, there // is no form of re-synchronization in the protocol so we // cannot recover from this. self.state = Err(error); } } } } } impl Encoder for Codec { type Item = Message; type Error = io::Error; fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> { let header = item.header(); let len = item.data.len(); let prefix_len = varmint::len_u64_varint(header) + varmint::len_usize_varint(len); dst.reserve(prefix_len + len); dst.writer().write_u64_varint(header).unwrap(); dst.writer().write_usize_varint(len).unwrap(); dst.put(item.data); Ok(()) } }
fn main(){ println!(" Hello Rust"); }
use anyhow::Result; use assembly_maps::lvl::reader::LevelReader; use std::{fs::File, io::BufReader, path::PathBuf}; use structopt::StructOpt; #[derive(StructOpt)] struct Opt { /// The lvl file to analyze file: PathBuf, } fn main() -> Result<()> { let opt = Opt::from_args(); let file = File::open(&opt.file)?; let br = BufReader::new(file); let mut lvl = LevelReader::new(br); let level = lvl.read_level_file()?; println!("{:#?}", level); Ok(()) }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// SyntheticsPrivateLocationSecretsAuthentication : Authentication part of the secrets. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyntheticsPrivateLocationSecretsAuthentication { /// Access key for the private location. #[serde(rename = "id", skip_serializing_if = "Option::is_none")] pub id: Option<String>, /// Secret access key for the private location. #[serde(rename = "key", skip_serializing_if = "Option::is_none")] pub key: Option<String>, } impl SyntheticsPrivateLocationSecretsAuthentication { /// Authentication part of the secrets. pub fn new() -> SyntheticsPrivateLocationSecretsAuthentication { SyntheticsPrivateLocationSecretsAuthentication { id: None, key: None, } } }
fn main() { let main_text = [ "A partridge in a pear tree", "Two turtle doves, and", "Three french hens", "Four colly birds", "Five gold rings", ]; let words = ["first", "second", "third", "fourth", "fifth"]; for (i, word) in words.iter().enumerate() { println!("On the {} day of christmas my true love sent me", word); let end = i + 1; for number in (0..end).rev() { println!("{}", main_text[number]); } println!(""); } }
use std::io; use std::sync::Arc; use failure::Fallible; pub use rpdf_graphics::font::{Font, FontMap}; pub use rpdf_graphics::text::{TextFragment, TextObject}; use rpdf_graphics::*; use rpdf_lopdf_extra::*; pub struct Document { inner: Arc<lopdf::Document>, pages: Vec<Page>, } impl Document { pub fn parse<R>(reader: R) -> Fallible<Self> where R: io::Read, { let document = Arc::new(lopdf::Document::load_from(reader)?); let pages = document .get_pages() .values() .map(|object_id| { let page_dict = document .get_dictionary(*object_id) .ok_or_else(|| failure::format_err!("page is missing dictionary"))?; let media_box = document.deserialize_object(page_dict.try_get(b"MediaBox")?)?; let content = document.get_page_content(*object_id)?; let font_map = FontMap::try_from_page_fonts(&document, document.get_page_fonts(*object_id))?; let graphics_objects = GraphicsObjectDecoder::decode(document.clone(), &font_map, &content)? .collect::<Fallible<_>>()?; Ok(Page { document: document.clone(), object_id: *object_id, media_box, graphics_objects, font_map, }) }) .collect::<Fallible<Vec<Page>>>()?; Ok(Self { inner: document, pages, }) } pub fn pages(&self) -> &[Page] { &self.pages } } pub struct Page { document: Arc<lopdf::Document>, object_id: lopdf::ObjectId, media_box: data::Rectangle, graphics_objects: Vec<GraphicsObject>, font_map: FontMap, } impl Page { pub fn width(&self) -> f64 { self.media_box.width() } pub fn height(&self) -> f64 { self.media_box.height() } pub fn graphics_objects(&self) -> &[GraphicsObject] { &self.graphics_objects } pub fn font(&self, name: &[u8]) -> Option<&Font> { self.font_map.get(name) } }
//! Encoding of a binary [`SpawnAccount`]. //! //! ```text //! //! +-----------+-------------+----------------+ //! | | | | //! | Version | Template | Name | //! | (u16) | (Address) | (String) | //! | | | | //! +-----------+-------------+----------------+ //! | | | //! | Ctor | CallData | //! | (String) | (Blob) | //! | | | //! +-----------+------------------------------+ //! //! ``` use std::io::Cursor; use svm_types::{Account, SpawnAccount, TemplateAddr}; use crate::{inputdata, version}; use crate::{Field, ParseError, ReadExt, WriteExt}; /// Encodes a binary [`SpawnAccount`] transaction. pub fn encode(spawn: &SpawnAccount, w: &mut Vec<u8>) { encode_version(spawn, w); encode_template(spawn, w); encode_name(spawn, w); encode_ctor(spawn, w); encode_ctor_calldata(spawn, w); } /// Parsing a binary [`SpawnAccount`] transaction. /// /// Returns the parsed [`SpawnAccount`], /// On failure, returns [`ParseError`]. pub fn decode(cursor: &mut Cursor<&[u8]>) -> Result<SpawnAccount, ParseError> { let version = decode_version(cursor)?; let template_addr = decode_template(cursor)?; let name = decode_name(cursor)?; let ctor_name = decode_ctor(cursor)?; let calldata = decode_ctor_calldata(cursor)?; let account = Account { name, template_addr, }; let spawn = SpawnAccount { version, account, ctor_name, calldata, }; Ok(spawn) } /// Encoders fn encode_version(spawn: &SpawnAccount, w: &mut Vec<u8>) { let v = &spawn.version; version::encode_version(*v, w); } fn encode_name(spawn: &SpawnAccount, w: &mut Vec<u8>) { let name = spawn.account_name(); w.write_string(name); } fn encode_template(spawn: &SpawnAccount, w: &mut Vec<u8>) { let template = spawn.template_addr(); w.write_template_addr(template); } fn encode_ctor(spawn: &SpawnAccount, w: &mut Vec<u8>) { let ctor = spawn.ctor_name(); w.write_string(ctor); } fn encode_ctor_calldata(spawn: &SpawnAccount, w: &mut Vec<u8>) { let calldata = &*spawn.calldata; inputdata::encode_inputdata(calldata, w); } /// Decoders #[inline] fn decode_version(cursor: &mut Cursor<&[u8]>) -> Result<u16, ParseError> { version::decode_version(cursor) } fn decode_template(cursor: &mut Cursor<&[u8]>) -> Result<TemplateAddr, ParseError> { cursor .read_template_addr() .map_err(|_| ParseError::NotEnoughBytes(Field::Address)) } fn decode_name(cursor: &mut Cursor<&[u8]>) -> Result<String, ParseError> { match cursor.read_string() { Ok(Ok(name)) => Ok(name), Ok(Err(..)) => Err(ParseError::InvalidUTF8String(Field::Name)), Err(..) => Err(ParseError::NotEnoughBytes(Field::Name)), } } fn decode_ctor(cursor: &mut Cursor<&[u8]>) -> Result<String, ParseError> { match cursor.read_string() { Ok(Ok(ctor)) => Ok(ctor), Ok(Err(..)) => Err(ParseError::InvalidUTF8String(Field::Ctor)), Err(..) => Err(ParseError::NotEnoughBytes(Field::Ctor)), } } fn decode_ctor_calldata(cursor: &mut Cursor<&[u8]>) -> Result<Vec<u8>, ParseError> { inputdata::decode_inputdata(cursor) } #[cfg(test)] mod tests { use super::*; use svm_types::TemplateAddr; #[test] fn encode_decode_spawn() { let spawn = SpawnAccount { version: 0, account: Account { name: "@account".to_string(), template_addr: TemplateAddr::of("@template"), }, ctor_name: "initialize".to_string(), calldata: vec![0x10, 0x20, 0x30], }; let mut bytes = Vec::new(); encode(&spawn, &mut bytes); let mut cursor = Cursor::new(&bytes[..]); let decoded = decode(&mut cursor).unwrap(); assert_eq!(spawn, decoded); } }
#![no_main] #![no_std] // PWM Example // PWM Output on Pin A6 (D12 on the Nucleo Board) // nmt @ nt-com 2021 /// IMPORTS use stm32f4::stm32f401; use cortex_m_rt::entry; #[allow(unused_extern_crates)] extern crate panic_halt; // panic handler /// FUNCTIONS fn delay() { for _i in 0..1000 { // do nothing } } /// MAIN #[entry] fn main() -> ! { // get peripherals of the STM32F401 let peripherals = stm32f401::Peripherals::take().unwrap(); // extract peripherals let rcc = &peripherals.RCC; let gpioa = &peripherals.GPIOA; let tim = &peripherals.TIM3; let mut duty_cycle : u32 = 0; // clock gate rcc.ahb1enr.write(|w| w.gpioaen().set_bit()); rcc.apb1enr.write(|w| w.tim3en().set_bit()); // no pull gpioa.pupdr.modify(|_, w| w.pupdr6().floating()); // push pull output type gpioa.otyper.modify(|_, w| w.ot6().push_pull()); // alternate function mode gpioa.moder.modify(|_, w| w.moder6().alternate()); // set concrete alternate function // af02 is timer3 channel 1 gpioa.afrl.modify(|_, w| w.afrl6().af2()); // set timer frequency and initial duty cycle unsafe { tim.arr.write(|w| w.bits(0x8000)); // frequency tim.ccr1.write(|w| w.bits(0x0)); // duty cycle } // clear enable to zero just to be sure. tim.ccmr1_output().write(|w| w.oc1ce().clear_bit()); // enable preload tim.ccmr1_output().write(|w| w.oc1pe().enabled()); // set pwm mode tim.ccmr1_output().write(|w| w.oc1m().pwm_mode1()); // enable output tim.ccer.write(|w| w.cc1e().set_bit()); // enable auto-reload tim.cr1.write(|w| w.arpe().set_bit()); // enable update generation - needed at first start tim.egr.write(|w| w.ug().set_bit()); // start pwm tim.cr1.write(|w| w.cen().set_bit()); loop { unsafe { // increase DC by 256, then start again at zero. tim.ccr1.write(|w| w.bits(duty_cycle)); // duty cycle } duty_cycle = (duty_cycle + 256) % 0x8000; delay(); } // main loop }
use std::env; use failure::Error; use std::io::{self, Read}; use atty::Stream; use std::io::{stdout, Write, BufWriter}; // エイリアス pub type Result<T> = std::result::Result<T, Error>; fn is_pipe() -> bool { // Terminalでなければ標準入力から読み込む ! atty::is(Stream::Stdin) } fn read_from_stdin() -> Result<String> { // パイプで渡されていなければヘルプ表示 if ! is_pipe() { // 引数がなければヘルプ表示 panic!("required stdin from pipeline."); } let mut buf = String::new(); let stdin = io::stdin(); let mut handle = stdin.lock(); handle.read_to_string(&mut buf)?; Ok(buf) } fn separate_options(args: Vec<String>) -> Result<Vec<Vec<String>>> { let mut is_v:bool = false; let mut is_force_v:bool = false; let mut excludes = Vec::<String>::new(); let mut includes = Vec::<String>::new(); for arg in args { let arg_str: &str = arg.as_str(); match arg_str { "-v" => is_v = true, "-V" => is_force_v = true, "-G" => is_force_v = false, _ => { if is_v || is_force_v { excludes.push(arg_str.to_string()); } else { includes.push(arg_str.to_string()); } is_v = false; } } } Ok(vec![includes, excludes]) } fn is_included(input: std::string::String, targets: Vec<String>) -> Result<bool> { for target in targets { if !input.contains(&target) { return Ok(false) } } Ok(true) } fn is_excluded(input: std::string::String, targets: Vec<String>) -> Result<bool> { for target in targets { if input.contains(&target) { return Ok(false) } } Ok(true) } fn extract(input: std::string::String, includes: Vec<String>, excludes: Vec<String>) -> Result<Vec<String>> { let mut remained_lines = Vec::<String>::new(); for line in input.lines() { if is_included(line.to_string(), includes.clone())? && is_excluded(line.to_string(), excludes.clone())?{ remained_lines.push(line.to_string()); } } Ok(remained_lines) } fn output(lines: Vec<String>) -> Result<()> { let out = stdout(); let mut out = BufWriter::new(out.lock()); for line in lines { writeln!(out, "{}", line).unwrap(); } Ok(()) } fn main() -> Result<()>{ let targets: String = read_from_stdin()?; let mut args: Vec<String> = env::args().collect(); //コマンド名部分は不要なので削除 args.remove(0); let separated_options = separate_options(args)?; let includes = &separated_options[0]; let excludes = &separated_options[1]; let extracted_lines: Vec<String> = extract(targets, includes.to_vec(), excludes.to_vec())?; output(extracted_lines)?; Ok(()) }
use std::collections::HashSet; use apllodb_shared_components::SchemaIndex; use serde::{Deserialize, Serialize}; /// Projection query for single table columns. #[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum RowProjectionQuery { /// All columns in a table. /// Note that this variant cannot hold field/correlation alias. All, /// Some columns in a table. ColumnIndexes(HashSet<SchemaIndex>), }
use crate::entity::user::{User, UserID}; use super::gateway::repository::user_repository::UserRepository; pub struct UserOperation<U: UserRepository> { pub ur: U } impl<U: UserRepository> UserOperation<U> { pub fn create(&self) -> Option<User> { self.ur.create() } pub fn find(&self, id: UserID) -> Option<User> { self.ur.find(id) } }
use super::{ dockarea::DockArea, rect::Rect, screen::Screen, windowwrapper::WindowWrapper, workspace::Workspace, Direction, HandleState, }; use crate::{ layout::LayoutTag, xlibwrapper::{ util::{Position, Size}, xlibmodels::{MonitorId, Window}, }, }; use std::cell::RefCell; use std::collections::HashMap; #[derive(Debug)] pub struct Monitor { pub id: MonitorId, pub screen: Screen, pub workspaces: HashMap<u32, Workspace>, pub dock_area: DockArea, pub current_ws: u32, pub mouse_follow: RefCell<bool>, pub handle_state: RefCell<HandleState>, } impl Monitor { pub fn new(id: u32, screen: Screen, ws: Workspace) -> Self { let (current_ws, workspaces) = { let current_ws = ws.tag; let mut workspaces = HashMap::default(); workspaces.insert(current_ws, ws); (current_ws, workspaces) }; Self { id, screen, workspaces, dock_area: Default::default(), current_ws, mouse_follow: RefCell::new(false), handle_state: RefCell::new(HandleState::Handled), } } pub fn set_dock_area(&mut self, dock_area: DockArea) { self.dock_area = dock_area; } pub fn add_window(&mut self, w: Window, ww: WindowWrapper) { match self.workspaces.get_mut(&self.current_ws) { Some(ws) => ws.add_window(w, ww), None => warn!("Monitor: {}, current_ws: {}", self.id, self.current_ws), //TODO: fekking fix } } pub fn add_window_non_current(&mut self, w: Window, ww: WindowWrapper, ws: u32) { match self.workspaces.get_mut(&ws) { Some(ws) => ws.add_window(w, ww), None => warn!("Monitor: {}, current_ws: {}", self.id, self.current_ws), //TODO: fekking fix } } pub fn remove_window(&mut self, w: Window) -> Option<WindowWrapper> { let ret = self .workspaces .get_mut(&self.current_ws)? .remove_window(w)?; Some(ret) } pub fn remove_window_non_current(&mut self, w: Window, ws: u32) -> Option<WindowWrapper> { let ret = self.workspaces.get_mut(&ws)?.remove_window(w)?; Some(ret) } pub fn get_ws_by_window(&self, w: Window) -> Option<u32> { let mut tag_vec = self .workspaces .values() .filter(|ws| ws.contains_window(w)) .map(|ws| ws.tag) .collect::<Vec<u32>>(); if !tag_vec.is_empty() { Some(tag_vec.remove(0)) } else { None } } pub fn get_newest(&self) -> Option<(&Window, &WindowWrapper)> { self.workspaces.get(&self.current_ws)?.get_newest() } pub fn get_previous(&self, win: Window) -> Option<&WindowWrapper> { let ws = self.workspaces.get(&self.current_ws)?; match ws.clients.get(&win) { Some(ww) => ws.get_previous(ww), _ => None, } } pub fn get_next(&self, win: Window) -> Option<&WindowWrapper> { let ws = self.workspaces.get(&self.current_ws)?; match ws.clients.get(&win) { Some(ww) => ws.get_next(ww), _ => None, } } /* In current workspace */ pub fn swap_window<F>(&mut self, win: Window, mut f: F) -> Option<()> where F: FnMut(&Monitor, WindowWrapper) -> WindowWrapper + Sized, { let old_ww = self .workspaces .get_mut(&self.current_ws)? .remove_window(win)?; let new_ww = f(&self, old_ww); self.add_window(win, new_ww); Some(()) } pub fn contains_window(&self, w: Window) -> bool { self.get_client_keys().contains(&&w) } pub fn contains_ws(&self, ws: u32) -> bool { debug!("in contains_ws"); debug!( "{}, monitors ws' :{:?}", ws, self.workspaces.keys().collect::<Vec<&u32>>() ); self.workspaces.contains_key(&ws) } pub fn get_current_ws_mut(&mut self) -> Option<&mut Workspace> { self.workspaces.get_mut(&self.current_ws) } pub fn get_current_ws(&self) -> Option<&Workspace> { self.workspaces.get(&self.current_ws) } pub fn get_current_layout(&self) -> Option<LayoutTag> { let ret = self.get_current_ws()?.get_current_layout(); Some(ret) } pub fn remove_ws(&mut self, ws: u32) -> Option<Workspace> { self.workspaces.remove(&ws) } pub fn add_ws(&mut self, ws: Workspace) { self.workspaces.insert(ws.tag, ws); } pub fn swap_ws<F>(&mut self, ws: u32, mut f: F) -> Option<()> where F: FnMut(&Monitor, Workspace) -> Workspace + Sized, { let old_ws = self.remove_ws(ws)?; let new_ws = f(&self, old_ws); self.add_ws(new_ws); Some(()) } pub fn get_current_windows(&self) -> Vec<Window> { match self.get_current_ws() { Some(ws) => ws.clients.keys().copied().collect::<Vec<Window>>(), None => vec![], } } pub fn get_client_keys(&self) -> Vec<Window> { self.workspaces .values() .map(|x| x.clients.keys().collect::<Vec<&Window>>()) .flatten() .copied() .collect::<Vec<Window>>() } pub fn get_client_mut(&mut self, w: Window) -> Option<&mut WindowWrapper> { self.workspaces .get_mut(&self.current_ws)? .clients .get_mut(&w) } pub fn get_client(&self, w: Window) -> Option<&WindowWrapper> { self.workspaces.get(&self.current_ws)?.clients.get(&w) } // Layout functions pub fn place_window(&mut self, w: Window) -> Vec<(Window, Rect)> { let screen = self.screen.clone(); let dock_area = self.dock_area.clone(); let ws = self.get_current_ws_mut().expect("monitor: place_window 2"); let windows = ws.clients.values().collect::<Vec<&WindowWrapper>>(); ws.layout.place_window(&dock_area, &screen, w, windows) } pub fn move_window(&mut self, w: Window, x: i32, y: i32) -> (Position, Position) { let screen = self.screen.clone(); let dock_area = self.dock_area.clone(); self.get_current_ws_mut() .expect("monitor: move_window") .layout .move_window(&screen, &dock_area, w, true, x, y) } pub fn reorder(&mut self, focus: Window, windows: &[WindowWrapper]) -> Vec<(Window, Rect)> { let screen = self.screen.clone(); let dock_area = self.dock_area.clone(); self.get_current_ws_mut() .expect("Monitor: reorder") .layout .reorder(focus, &screen, &dock_area, windows.to_vec()) } pub fn resize_window(&mut self, w: Window, width: i32, height: i32) -> (Size, Size) { let ww = self .get_client(w) .expect("monitor: resize_window 1") .clone(); self.get_current_ws_mut() .expect("monitor: resize_window 2") .layout .resize_window(&ww, w, width, height) } pub fn maximize(&self, w: Window, ww: &WindowWrapper) -> (Position, Size) { let screen = self.screen.clone(); let dock_area = self.dock_area.clone(); self.get_current_ws() .expect("monitor: maximize 2") .layout .maximize(&screen, &dock_area, &ww, w) } pub fn monocle(&self, w: Window, ww: &WindowWrapper) -> (Position, Size) { let screen = self.screen.clone(); let dock_area = self.dock_area.clone(); self.get_current_ws() .expect("monitor: maximize 2") .layout .monocle(&screen, &dock_area, &ww, w) } pub fn shift_window(&mut self, w: Window, direction: Direction) -> Vec<WindowWrapper> { let ww = self.get_client(w).expect("monitor: shift_window 1").clone(); let screen = self.screen.clone(); let dock_area = self.dock_area.clone(); self.get_current_ws_mut() .expect("monitor: shift_window 2") .layout .shift_window(&screen, &ww, &dock_area, w, direction) } } impl std::fmt::Display for Monitor { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.current_ws) } } #[cfg(test)] mod test { use crate::models::{ monitor::Monitor, rect::*, screen::Screen, windowwrapper::*, workspace::Workspace, HandleState, WindowState, }; use crate::xlibwrapper::util::*; use std::time::Instant; const ROOT: u64 = 111; fn setup_mon(amount_ws: u32) -> Monitor { let screen = Screen::new(ROOT, 1920, 1080, 0, 0); let mut mon = Monitor::new(0, screen, Workspace::new(0)); for i in 0..(amount_ws - 1) { mon.add_ws(Workspace::new(i + 1)) } mon } #[test] fn add_window() { let mut mon = setup_mon(1); let base_ww = WindowWrapper::new( 1, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); mon.add_window(base_ww.window(), base_ww.clone()); assert_eq!(Some(&base_ww), mon.get_client(base_ww.window())) } #[test] fn remove_window_pass() { let mut mon = setup_mon(1); let base_ww = WindowWrapper::new( 1, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); mon.add_window(base_ww.window(), base_ww.clone()); assert_eq!(Some(base_ww.clone()), mon.remove_window(base_ww.window())) } #[test] fn remove_window_fail() { let mut mon = setup_mon(1); let base_ww = WindowWrapper::new( 1, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); mon.add_window(base_ww.window(), base_ww.clone()); let tested = WindowWrapper { window: 12, ..base_ww }; assert_eq!(None, mon.remove_window(tested.window())) } #[test] fn get_newest_pass() { let mut mon = setup_mon(1); let base_ww = WindowWrapper::new( 1, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); mon.add_window(base_ww.window(), base_ww.clone()); let tested_win = 12; let tested = WindowWrapper { window: tested_win, toc: Instant::now(), ..base_ww }; mon.add_window(tested.window(), tested.clone()); assert_eq!(Some((&tested_win, &tested)), mon.get_newest()) } #[test] fn get_newest_fail() { let mon = setup_mon(1); assert_eq!(None, mon.get_newest()) } #[test] fn get_previous_pass() { let mut mon = setup_mon(1); let base_ww = WindowWrapper::new( 1, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); let tested = base_ww.clone(); mon.add_window(base_ww.window(), base_ww.clone()); let second_win = 12; let second = WindowWrapper { window: second_win, toc: Instant::now(), ..base_ww }; mon.add_window(second.window(), second); assert_eq!(Some(&tested), mon.get_previous(second_win)) } #[test] fn get_previous_fail() { let mut mon = setup_mon(1); let base_ww = WindowWrapper::new( 1, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); let tested = base_ww.clone(); mon.add_window(base_ww.window(), base_ww.clone()); assert_eq!(None, mon.get_previous(tested.window())) } #[test] fn get_next_pass() { let mut mon = setup_mon(1); let base_ww = WindowWrapper::new( 1, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); let first = base_ww.clone(); mon.add_window(base_ww.window(), base_ww.clone()); let next_win = 12; let next = WindowWrapper { window: next_win, toc: Instant::now(), ..base_ww }; mon.add_window(next_win, next.clone()); let tested_win = next_win + 1; let tested = WindowWrapper::new( tested_win, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); mon.add_window(tested_win + 1, tested); assert_eq!(Some(&next), mon.get_next(first.window())) } #[test] fn get_next_fail() { let mut mon = setup_mon(1); let base_ww = WindowWrapper::new( 1, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); let tested = base_ww.clone(); mon.add_window(base_ww.window(), base_ww.clone()); assert_eq!(None, mon.get_next(tested.window())) } #[test] fn swap_window_pass() { let mut mon = setup_mon(1); let base_ww = WindowWrapper::new( 1, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); mon.add_window(base_ww.window(), base_ww.clone()); let tested = WindowWrapper { current_state: WindowState::Maximized, handle_state: HandleState::Move.into(), ..base_ww }; mon.swap_window(1, |_mon, ww| WindowWrapper { current_state: WindowState::Maximized, handle_state: HandleState::Move.into(), ..ww }); assert_eq!(Some(&tested), mon.get_client(tested.window())) } #[test] fn swap_window_fail() { let mut mon = setup_mon(1); let base_ww = WindowWrapper::new( 1, Rect::new( Position { x: 0, y: 0 }, Size { width: 200, height: 200, }, ), false, ); mon.add_window(base_ww.window(), base_ww.clone()); let tested = WindowWrapper { window: 10, current_state: WindowState::Maximized, handle_state: HandleState::Move.into(), ..base_ww }; mon.swap_window(10, |_mon, ww| WindowWrapper { current_state: WindowState::Maximized, handle_state: HandleState::Move.into(), ..ww }); assert_eq!(None, mon.get_client(tested.window())) } }
use crate::{ grid::config::ColoredConfig, grid::config::Entity, grid::dimension::CompleteDimensionVecRecords, grid::records::{ExactRecords, PeekableRecords, Records, RecordsMut}, grid::util::string::count_lines, settings::{measurement::Measurement, peaker::Peaker, CellOption, Height, TableOption}, }; use super::TableHeightIncrease; /// A modification for cell/table to increase its height. /// /// If used for a [`Table`] [`PriorityNone`] is used. /// /// [`PriorityNone`]: crate::settings::peaker::PriorityNone /// [`Table`]: crate::Table #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct CellHeightIncrease<W = usize> { height: W, } impl<W> CellHeightIncrease<W> { /// Creates a new object of the structure. pub fn new(height: W) -> Self where W: Measurement<Height>, { Self { height } } /// The priority makes scence only for table, so the function /// converts it to [`TableHeightIncrease`] with a given priority. pub fn priority<P>(self) -> TableHeightIncrease<W, P> where P: Peaker, W: Measurement<Height>, { TableHeightIncrease::new(self.height).priority::<P>() } } impl<W, R> CellOption<R, ColoredConfig> for CellHeightIncrease<W> where W: Measurement<Height>, R: Records + ExactRecords + PeekableRecords + RecordsMut<String>, for<'a> &'a R: Records, { fn change(self, records: &mut R, cfg: &mut ColoredConfig, entity: Entity) { let height = self.height.measure(&*records, cfg); let count_rows = records.count_rows(); let count_columns = records.count_columns(); for pos in entity.iter(count_rows, count_columns) { let is_valid_pos = pos.0 < count_rows && pos.1 < count_columns; if !is_valid_pos { continue; } let text = records.get_text(pos); let cell_height = count_lines(text); if cell_height >= height { continue; } let content = add_lines(text, height - cell_height); records.set(pos, content); } } } impl<R, W> TableOption<R, CompleteDimensionVecRecords<'_>, ColoredConfig> for CellHeightIncrease<W> where W: Measurement<Height>, R: Records + ExactRecords + PeekableRecords, for<'a> &'a R: Records, { fn change( self, records: &mut R, cfg: &mut ColoredConfig, dims: &mut CompleteDimensionVecRecords<'_>, ) { let height = self.height.measure(&*records, cfg); TableHeightIncrease::new(height).change(records, cfg, dims) } fn hint_change(&self) -> Option<Entity> { Some(Entity::Row(0)) } } fn add_lines(s: &str, n: usize) -> String { let mut text = String::with_capacity(s.len() + n); text.push_str(s); text.extend(std::iter::repeat('\n').take(n)); text }
use super::drawable::Drawable; use super::color::Color; use super::canvas::*; use wasm_bindgen::JsValue; /// A drawable rectangle pub struct Rectangle { /// the [style](../canvas/struct.LineStyle.html) of the border pub line_style: LineStyle, /// point y and point y (in pixels) pub top_left: (f64, f64), /// width and height (in pixels) pub dimensions: (f64, f64), /// if some, the square will be filled by this color pub fill_color: Option<Color> } impl Rectangle { /// Create a rectangle from the top left and the bottom right point pub fn new_with_two_points(point_a: (f64, f64), point_b: (f64, f64)) -> Rectangle { Rectangle { line_style: LineStyle::default(), top_left: point_a, dimensions: (point_b.0 - point_a.0, point_b.1 - point_a.1), fill_color: None } } /// Create a rectangle from the top left point and a dimension pub fn new_with_dimension(point: (f64, f64), dimensions: (f64, f64)) -> Rectangle { Rectangle { line_style: LineStyle::default(), top_left: point, dimensions, fill_color: None } } } impl Drawable for Rectangle { fn draw_on_canvas(&self, mut canvas: &mut Canvas) { canvas.context.begin_path(); canvas.context.rect(self.top_left.0, self.top_left.1, self.dimensions.0, self.dimensions.1); if let Some(color) = &self.fill_color { canvas.context.set_fill_style(&JsValue::from_str(&color.to_string())); canvas.context.fill(); } self.line_style.apply_on_canvas(&mut canvas); canvas.context.stroke(); } } /// A simple drawable line pub struct Line { /// the [style](../canvas/struct.LineStyle.html) of the line pub line_style: LineStyle, #[allow(missing_docs)] pub point_a: (f64, f64), #[allow(missing_docs)] pub point_b: (f64, f64) } impl Line { /// Create a line with a [default style](../canvas/struct.LineStyle.html#method.default) pub fn new(point_a: (f64, f64), point_b: (f64, f64)) -> Line { Line { line_style: LineStyle::default(), point_a, point_b } } } impl Drawable for Line { fn draw_on_canvas(&self, mut canvas: &mut Canvas) { canvas.context.begin_path(); canvas.context.move_to(self.point_a.0, self.point_a.1); canvas.context.line_to(self.point_b.0, self.point_b.1); self.line_style.apply_on_canvas(&mut canvas); canvas.context.stroke(); } }
#[macro_export] macro_rules! fmt(($token:expr) => (format!("{:?}", $token))); #[macro_export] macro_rules! say_hello { () => { println!("Hello"); }; }
use anyhow::Result; use std::fs; #[derive(Eq, PartialEq, Hash, Clone, Copy, Debug, Default)] struct Point { x: isize, y: isize, } #[derive(Debug)] struct Ship { position: Point, waypoint: Point, } #[derive(Debug)] enum Operation { North(usize), South(usize), East(usize), West(usize), Left(usize), Right(usize), Forward(usize), } fn parse_operations(input: &str) -> Vec<Operation> { input .lines() .map(|op| { let (op, arg) = op.split_at(1); let num: usize = arg.parse().unwrap(); match op { "N" => Operation::North(num), "S" => Operation::South(num), "E" => Operation::East(num), "W" => Operation::West(num), "L" => Operation::Left(num), "R" => Operation::Right(num), "F" => Operation::Forward(num), _ => panic!("Unknown operation"), } }) .collect() } fn do_the_thing(input: &str) -> Result<usize> { let ops = parse_operations(input); let mut ship = Ship { position: Point { x: 0, y: 0 }, waypoint: Point { x: 10, y: 1 }, }; for op in ops { match op { Operation::North(distance) => ship.waypoint.y += distance as isize, Operation::South(distance) => ship.waypoint.y -= distance as isize, Operation::East(distance) => ship.waypoint.x += distance as isize, Operation::West(distance) => ship.waypoint.x -= distance as isize, Operation::Left(180) | Operation::Right(180) => { ship.waypoint.x = -ship.waypoint.x; ship.waypoint.y = -ship.waypoint.y; } Operation::Left(90) | Operation::Right(270) => { ship.waypoint = Point { x: -ship.waypoint.y, y: ship.waypoint.x, }; } Operation::Right(90) | Operation::Left(270) => { ship.waypoint = Point { x: ship.waypoint.y, y: -ship.waypoint.x, }; } Operation::Forward(times) => { ship.position.x += ship.waypoint.x * times as isize; ship.position.y += ship.waypoint.y * times as isize; } _ => panic!("Illegal turn? {:?}", op), } } Ok((ship.position.x.abs() + ship.position.y.abs()) as usize) } fn main() -> Result<()> { let input = fs::read_to_string("input.txt")?; println!("{:?}", do_the_thing(&input)); Ok(()) } #[cfg(test)] mod tests { use super::*; use test_case::test_case; #[test_case("F10 N3 F7 R90 F11" => 286)] fn first(input: &str) -> usize { do_the_thing(&input).unwrap() } }
use crate::types::{draft_version::DraftVersion, schema::Schema}; use std::{collections::HashMap, sync::Arc}; use url::Url; pub(in crate) struct Scope { pub(in crate) draft_version: DraftVersion, // TODO: Verify if we need a thread-safe cache or this is good enough pub(in crate) schema_cache: HashMap<Url, Arc<Schema>>, }
use std::path::{Path, PathBuf}; use clap::Parser as ClapParser; use crate::error::{self, VestiCommandUtilErrKind}; #[derive(ClapParser)] #[command(author, version, about)] pub enum VestiOpt { /// Initialize the vesti project Init { #[clap(name = "PROJECT_NAME")] project_name: Option<String>, }, /// Compile vesti into Latex file Run { /// Compile vesti continuously. #[clap(short, long)] continuous: bool, /// If this flag is on, then vesti compiles all vesti files in that directory. #[clap(long)] all: bool, /// Input file names or directory name. /// Directory name must type once. #[clap(value_name = "FILE")] file_name: Vec<PathBuf>, }, } impl VestiOpt { pub fn take_filename(&self) -> error::Result<Vec<PathBuf>> { let mut output: Vec<PathBuf> = Vec::new(); if let Self::Run { continuous: _, all, file_name, } = self { if !all { return Ok(file_name.clone()); } assert_eq!(file_name.len(), 1); let file_dir = file_name[0].ancestors().nth(1); let current_dir = if file_dir == Some(Path::new("")) { Path::new(".").to_path_buf() } else if let Some(path) = file_dir { path.to_path_buf() } else { return Err(error::VestiErr::UtilErr { err_kind: VestiCommandUtilErrKind::NoFilenameInputErr, }); }; for path in walkdir::WalkDir::new(current_dir) { match path { Ok(dir) => { if let Some(ext) = dir.path().extension() { if ext == "ves" { output.push(dir.into_path()) } } } Err(_) => { return Err(error::VestiErr::UtilErr { err_kind: VestiCommandUtilErrKind::TakeFilesErr, }) } } } output.sort(); } Ok(output) } }
use std::sync::mpsc::Receiver; use std::sync::mpsc::sync_channel; use rocket::http::ContentType; use rocket::http::Status; use rocket::local::{Client, LocalResponse}; use crate::comms; use crate::mechatronics::commands::RobotCommand; use super::*; struct TestEnvironment { receiver: Receiver<Box<RobotCommand>>, client: Client, status: Arc<GlobalRobotState>, } impl TestEnvironment { pub fn send_drive(&self, left: f32, right: f32) -> LocalResponse { self.client.put("/robot/drive") .header(ContentType::JSON) .body(format!("{{ 'drive' : {{ 'left': {}, 'right': {} }} }}", left, right)) .dispatch() } } fn setup() -> TestEnvironment { let (controller_sender, controller_receiver) = sync_channel(20); // Create Robot status let robot_status = Arc::new(GlobalRobotState::new()); // Create RobotView let robot_view = RobotMessenger::new(controller_sender); // Create server let grasshopper = comms::stage(robot_view, robot_status.clone(), RobotCommandFactory::new()); let client = Client::new(grasshopper).unwrap(); TestEnvironment { receiver: controller_receiver, client, status: robot_status, } } #[test] fn test_bad_switch() { let env = setup(); let response = env.client .put("/robot") .header(ContentType::JSON) .body(r#"{ "mode" : "invalid" }"#) .dispatch(); assert_eq!(Status::UnprocessableEntity, response.status()); } #[test] fn test_bad_drive() { let env = setup(); let response = env.send_drive(2.0, 1.0); assert_eq!(Status::BadRequest, response.status()); let response = env.send_drive(1.0, 2.0); assert_eq!(Status::BadRequest, response.status()); let response = env.send_drive(2.0, 2.0); assert_eq!(Status::BadRequest, response.status()); let env = setup(); let response = env.send_drive(-2.0, 1.0); assert_eq!(Status::BadRequest, response.status()); let response = env.send_drive(1.0, -2.0); assert_eq!(Status::BadRequest, response.status()); let response = env.send_drive(-2.0, -2.0); assert_eq!(Status::BadRequest, response.status()); } #[test] fn test_state() { let env = setup(); let mut response = env.client.get("/robot").dispatch(); assert_eq!(Status::Ok, response.status()); assert!(response.body().is_some()); } #[test] fn test_index() { let env = setup(); let mut response = env.client.get("/").dispatch(); assert_eq!(Status::Ok, response.status()); assert!(response.body().is_some()); } #[test] fn favicon() { let env = setup(); let mut response = env.client.get("/favicon.ico").dispatch(); assert_eq!(Status::Ok, response.status()); assert!(response.body().is_some()); } #[test] fn test_file() { let env = setup(); let mut response = env.client.get("/static/main.css").dispatch(); assert_eq!(Status::Ok, response.status()); assert!(response.body().is_some()); }
use crate::gc::*; use cons::*; use self::{closure::Closure, macro_::Macro, package::Package, symbol::Symbol, vector::Vector}; pub type TagKind = u32; pub const CMP_FALSE: i32 = 0; pub const CMP_TRUE: i32 = 1; pub const CMP_UNDEF: i32 = -1; pub const FIRST_TAG: TagKind = 0xfff9; pub const LAST_TAG: TagKind = 0xffff; pub const EMPTY_INVALID_TAG: u32 = FIRST_TAG; pub const UNDEFINED_NULL_TAG: u32 = FIRST_TAG + 1; pub const BOOL_TAG: u32 = FIRST_TAG + 2; pub const INT32_TAG: u32 = FIRST_TAG + 3; pub const NATIVE_VALUE_TAG: u32 = FIRST_TAG + 4; pub const STR_TAG: u32 = FIRST_TAG + 5; pub const OBJECT_TAG: u32 = FIRST_TAG + 6; pub const FIRST_PTR_TAG: u32 = STR_TAG; #[repr(u32)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum ExtendedTag { Empty = EMPTY_INVALID_TAG * 2 + 1, Undefined = UNDEFINED_NULL_TAG * 2, Null = UNDEFINED_NULL_TAG * 2 + 1, Bool = BOOL_TAG * 2, Int32 = INT32_TAG * 2, Native1 = NATIVE_VALUE_TAG * 2, Native2 = NATIVE_VALUE_TAG * 2 + 1, Str1 = STR_TAG * 2, Str2 = STR_TAG * 2 + 1, Object1 = OBJECT_TAG * 2, Object2 = OBJECT_TAG * 2 + 1, } /// A NaN-boxed encoded value. #[derive(Clone, Copy, PartialEq, Eq)] #[repr(transparent)] pub struct Value(u64); impl Value { pub const NUM_TAG_EXP_BITS: u32 = 16; pub const NUM_DATA_BITS: u32 = (64 - Self::NUM_TAG_EXP_BITS); pub const TAG_WIDTH: u32 = 4; pub const TAG_MASK: u32 = (1 << Self::TAG_WIDTH) - 1; pub const DATA_MASK: u64 = (1 << Self::NUM_DATA_BITS as u64) - 1; pub const ETAG_WIDTH: u32 = 5; pub const ETAG_MASK: u32 = (1 << Self::ETAG_WIDTH) - 1; #[inline] pub const fn from_raw(x: u64) -> Self { Self(x) } #[inline] pub const fn get_tag(&self) -> TagKind { (self.0 >> Self::NUM_DATA_BITS as u64) as u32 } #[inline] pub fn get_etag(&self) -> ExtendedTag { unsafe { std::mem::transmute((self.0 >> (Self::NUM_DATA_BITS as u64 - 1)) as u32) } } #[inline] pub const fn combine_tags(a: TagKind, b: TagKind) -> u32 { ((a & Self::TAG_MASK) << Self::TAG_WIDTH) | (b & Self::TAG_MASK) } #[inline] const fn internal_new(val: u64, tag: TagKind) -> Self { Self(val | ((tag as u64) << Self::NUM_DATA_BITS)) } #[inline] const fn new_extended(val: u64, tag: ExtendedTag) -> Self { Self(val | ((tag as u64) << (Self::NUM_DATA_BITS - 1))) } #[inline] pub const fn encode_null_ptr_object_value() -> Self { Self::internal_new(0, OBJECT_TAG) } #[inline] pub fn encode_object_value<T: GcCell + ?Sized>(val: GcPointer<T>) -> Self { Self::internal_new( unsafe { std::mem::transmute::<_, usize>(val) } as _, OBJECT_TAG, ) } #[inline] pub const fn encode_native_u32(val: u32) -> Self { Self::internal_new(val as _, NATIVE_VALUE_TAG) } #[inline] pub fn encode_native_pointer(p: *const ()) -> Self { Self::internal_new(p as _, NATIVE_VALUE_TAG) } #[inline] pub const fn encode_bool_value(val: bool) -> Self { Self::internal_new(val as _, BOOL_TAG) } #[inline] pub const fn encode_null_value() -> Self { Self::new_extended(0, ExtendedTag::Null) } #[inline] pub fn encode_int32(x: i32) -> Self { Self::internal_new(x as u32 as u64, INT32_TAG) } #[inline] pub const fn encode_undefined_value() -> Self { Self::new_extended(0, ExtendedTag::Undefined) } #[inline] pub const fn encode_empty_value() -> Self { Self::new_extended(0, ExtendedTag::Empty) } #[inline] pub fn encode_f64_value(x: f64) -> Self { Self::from_raw(x.to_bits()) } #[inline] pub const fn encode_nan_value() -> Self { Self::from_raw(0x7ff8000000000000) } #[inline] pub fn encode_untrusted_f64_value(val: f64) -> Self { if val.is_nan() { return Self::encode_nan_value(); } Self::encode_f64_value(val) } #[inline] pub fn update_pointer(&self, val: *const ()) -> Self { Self::internal_new(val as _, self.get_tag()) } #[inline] pub unsafe fn unsafe_update_pointer(&mut self, val: *const ()) { self.0 = val as u64 | (self.get_tag() as u64) << Self::NUM_DATA_BITS as u64 } #[inline] pub fn is_null(&self) -> bool { self.get_etag() == ExtendedTag::Null } #[inline] pub fn is_undefined(&self) -> bool { self.get_etag() == ExtendedTag::Undefined } #[inline] pub fn is_empty(&self) -> bool { self.get_etag() == ExtendedTag::Empty } #[inline] pub fn is_native_value(&self) -> bool { self.get_tag() == NATIVE_VALUE_TAG } #[inline] pub fn is_int32(&self) -> bool { self.get_tag() == INT32_TAG } #[inline] pub fn is_bool(&self) -> bool { self.get_tag() == BOOL_TAG } #[inline] pub fn is_object(&self) -> bool { self.get_tag() == OBJECT_TAG } #[inline] pub fn is_string(&self) -> bool { self.get_tag() == STR_TAG } #[inline] pub fn is_double(&self) -> bool { self.0 < ((FIRST_TAG as u64) << Self::NUM_DATA_BITS as u64) } #[inline] pub fn is_pointer(&self) -> bool { self.0 >= ((FIRST_PTR_TAG as u64) << Self::NUM_DATA_BITS as u64) } #[inline] pub fn get_raw(&self) -> u64 { self.0 } #[inline] pub fn get_pointer(&self) -> *mut () { assert!(self.is_pointer()); unsafe { std::mem::transmute(self.0 & Self::DATA_MASK) } } #[inline] pub fn get_int32(&self) -> i32 { assert!(self.is_int32()); self.0 as u32 as i32 } #[inline] pub fn get_double(&self) -> f64 { f64::from_bits(self.0) } #[inline] pub fn get_native_value(&self) -> i64 { assert!(self.is_native_value()); (((self.0 & Self::DATA_MASK as u64) as i64) << (64 - Self::NUM_DATA_BITS as i64)) >> (64 - Self::NUM_DATA_BITS as i64) } #[inline] pub fn get_native_u32(&self) -> u32 { assert!(self.is_native_value()); self.0 as u32 } #[inline] pub fn get_native_ptr(&self) -> *mut () { assert!(self.is_native_value()); (self.0 & Self::DATA_MASK) as *mut () } #[inline] pub fn get_bool(&self) -> bool { assert!(self.is_bool()); (self.0 & 0x1) != 0 } #[inline] pub fn get_object(&self) -> GcPointer<dyn GcCell> { assert!(self.is_object()); unsafe { std::mem::transmute::<_, GcPointer<dyn GcCell>>(self.0 & Self::DATA_MASK) }.clone() } /// Get number value from value. If value is int32 value then it is casted to f64. #[inline] pub fn get_number(&self) -> f64 { if self.is_int32() { return self.get_int32() as f64; } self.get_double() } pub unsafe fn set_no_barrier(&mut self, val: Self) { self.0 = val.0; } pub fn is_number(&self) -> bool { self.is_double() || self.is_int32() } pub fn as_cons_or_null(self) -> Option<GcPointer<Cons>> { if self.is_object() { self.get_object().downcast() } else { None } } /// Returns true if the value is a cons cell pub fn is_cons(&self) -> bool { self.is_object() && self.get_object().is::<Cons>() } /// Returns true if the value is an atom, ie. not a cons cell pub fn is_atom(&self) -> bool { !self.is_cons() } /// Returns true if the value is a properly null-terminated cons list pub fn is_list(&self) -> bool { if self.is_null() { return true; } let mut cons = self.as_cons_or_null(); while let Some(c) = cons { if c.rest.is_null() { return true; } cons = c.rest.as_cons_or_null(); } false } /// Returns the number of cons cells in the list, starting at value. O(n) operation. /// /// ## TODO /// We might need to also check if value is a vector and return vector length. pub fn length(&self) -> Option<usize> { self.as_cons_or_null().map(|x| x.length()) } pub fn as_symbol(self) -> Result<GcPointer<Symbol>, SchemeError> { if self.is_object() && self.get_object().is::<Symbol>() { Ok(unsafe { self.get_object().downcast_unchecked() }) } else { Err(SchemeError::new( "Value type was expected to be a symbol".to_owned(), )) } } pub fn as_vector_or_null(self) -> Option<GcPointer<Vector>> { if self.is_object() && self.get_object().is::<Vector>() { Some(unsafe { self.get_object().downcast_unchecked() }) } else { None } } pub fn as_symbol_or_null(self) -> Option<GcPointer<Symbol>> { if self.is_object() && self.get_object().is::<Symbol>() { Some(unsafe { self.get_object().downcast_unchecked() }) } else { None } } pub fn as_closure_or_null(self) -> Option<GcPointer<Closure>> { if self.is_object() && self.get_object().is::<Closure>() { Some(unsafe { self.get_object().downcast_unchecked() }) } else { None } } pub fn as_macro_or_null(self) -> Option<GcPointer<Macro>> { if self.is_object() && self.get_object().is::<Macro>() { Some(unsafe { self.get_object().downcast_unchecked() }) } else { None } } pub fn as_package_or_null(self) -> Option<GcPointer<Package>> { if self.is_object() && self.get_object().is::<Package>() { Some(unsafe { self.get_object().downcast_unchecked() }) } else { None } } } unsafe impl Trace for Value { fn trace(&self, visitor: &mut Tracer) { if self.is_pointer() && !self.is_empty() { self.get_object().trace(visitor); } } } pub mod closure; pub mod cons; pub mod environment; pub mod instruction; pub mod macro_; pub mod package; pub mod symbol; pub mod vector; pub struct SchemeError { pub msg: String, } impl SchemeError { pub fn new(msg: String) -> Self { Self { msg } } }
use std::collections::HashMap; use pyo3::prelude::*; use crate::{CreateTableStatement, PropertyPair, RowFormat, StoredAs, TableColumn}; // add bindings to the generated Python module // N.B: "rust2py" must be the name of the `.so` or `.pyd` file. /// This module is implemented in Rust. #[pymodule] fn hive_ddl_parser(_py: Python, _module: &PyModule) -> PyResult<()> { // PyO3 aware function. All of our Python interfaces could be declared in a separate module. // Note that the `#[pyfn()]` annotation automatically converts the arguments from // Python objects to Rust values, and the Rust return value back into a Python object. // The `_py` argument represents that we're holding the GIL. #[pyfn(_module, "parse_ddl")] fn sum_as_string_py<'a>(_py: Python<'a>, ddl: &'a str) -> PyResult<CreateTableStatement<'a>> { let result = crate::parse_hive_create_table(ddl) .map_err(|_| pyo3::exceptions::PyValueError::new_err("Failed to parse ddl!"))?; Ok(result) } Ok(()) } impl ToPyObject for TableColumn<'_> { fn to_object(&self, py: Python) -> PyObject { (self.name(), self.data_type()).to_object(py) } } impl ToPyObject for PropertyPair<'_> { fn to_object(&self, py: Python) -> PyObject { (self.key(), self.value()).to_object(py) } } impl ToPyObject for StoredAs<'_> { fn to_object(&self, py: Python) -> PyObject { let mut map = HashMap::new(); match self { Self::InputOutputFormat { input_type, output_type, } => { map.insert("input_type", input_type.to_object(py)); map.insert("output_type", output_type.to_object(py)); } } map.to_object(py) } } impl ToPyObject for RowFormat<'_> { fn to_object(&self, py: Python) -> PyObject { let mut map = HashMap::new(); match self { Self::Serde { type_name, properties, } => { map.insert("type_name", type_name.to_object(py)); map.insert("properties", properties.to_object(py)); } } map.to_object(py) } } impl ToPyObject for CreateTableStatement<'_> { fn to_object(&self, py: Python) -> PyObject { let mut map = HashMap::new(); map.insert("database_name", self.database_name().to_object(py)); map.insert("table_name", self.table_name().to_object(py)); map.insert("columns", self.columns().to_object(py)); map.insert("partitioned_by", self.partition_keys().to_object(py)); map.insert("location", self.location().to_object(py)); map.insert("table_properties", self.table_properties().to_object(py)); map.insert("row_format", self.row_format().to_object(py)); map.insert("stored_as", self.stored_as().to_object(py)); map.to_object(py) } } impl IntoPy<PyObject> for CreateTableStatement<'_> { fn into_py(self, py: Python) -> PyObject { self.to_object(py) } }
pub mod arbiter { use core::cell::RefCell; pub struct MicLease; pub struct TimerLease; pub static mut MIC: RefCell<MicLease> = RefCell::new(MicLease); pub static mut TIMER0: RefCell<TimerLease> = RefCell::new(TimerLease); pub static mut TIMER1: RefCell<TimerLease> = RefCell::new(TimerLease); pub static mut TIMER2: RefCell<TimerLease> = RefCell::new(TimerLease); pub static mut TIMER3: RefCell<TimerLease> = RefCell::new(TimerLease); } macro_rules! lease { ($which:ident) => (unsafe { $crate::io::arbiter::$which.borrow_mut() }) } macro_rules! lease_ty { ($lifetime:tt, $which:ident) => (::core::cell::RefMut<$lifetime, $crate::io::arbiter::$which>); } pub trait RegEnum { fn addr_of(&self) -> u32; fn ptr<T: Copy>(&self) -> *mut T { assert!((self.addr_of() as usize) & (::core::mem::align_of::<T>() - 1) == 0); self.addr_of() as *mut T } fn read8(&self) -> u8 { unsafe { self.ptr::<u8>().read_volatile() } } fn read16(&self) -> u16 { unsafe { self.ptr::<u16>().read_volatile() } } fn read32(&self) -> u32 { unsafe { self.ptr::<u32>().read_volatile() } } fn write8(&self, val: u8) { unsafe { self.ptr::<u8>().write_volatile(val) }; } fn write16(&self, val: u16) { unsafe { self.ptr::<u16>().write_volatile(val) }; } fn write32(&self, val: u32) { unsafe { self.ptr::<u32>().write_volatile(val) }; } } pub mod aes; pub mod hid; pub mod i2c; pub mod irq; pub mod mic; pub mod ndma; pub mod rsa; pub mod sdmmc; pub mod sha; pub mod timer; pub mod xdma;
enum CPUOp { Add { src1: usize, src2: usize, dst: usize, }, Mul { src1: usize, src2: usize, dst: usize, }, Halt, Undefined(u32), } impl CPUOp { fn next_pc_offset(&self) -> usize { match *self { CPUOp::Add { .. } | CPUOp::Mul { .. } => 4, CPUOp::Halt | CPUOp::Undefined { .. } => 0, } } } #[derive(Copy, Clone, Debug)] pub enum CPUState { Running, Halted, } #[derive(Copy, Clone, Debug)] pub enum CPUExceptionKind { InvalidOpcode, OutOfBounds, } #[derive(Clone, Debug)] pub struct CPUException { kind: CPUExceptionKind, message: String, } impl CPUException { pub fn new(kind: CPUExceptionKind, message: String) -> Self { CPUException { kind, message } } pub fn out_of_bounds(ident: &str, pos: usize) -> Self { CPUException { kind: CPUExceptionKind::OutOfBounds, message: format!("{}: pos {} is outside program bounds", ident, pos), } } pub fn invalid_opcode(opcode: u32) -> Self { CPUException { kind: CPUExceptionKind::InvalidOpcode, message: format!("Invalid opcode {}", opcode), } } } pub type CPUResult<T> = Result<T, CPUException>; pub struct IntcodeCPU { program: Vec<u32>, state: CPUState, pc: usize, } impl IntcodeCPU { pub fn new(program: Vec<u32>) -> Self { IntcodeCPU { program, state: CPUState::Running, pc: 0, } } fn execute_op(&mut self, op: CPUOp) -> CPUResult<()> { use CPUExceptionKind::*; match op { CPUOp::Add { src1, src2, dst } => { let src1_val = *self .program .get(src1) .ok_or_else(|| CPUException::out_of_bounds("EXEC!ADD.src1", src1))?; let src2_val = *self .program .get(src2) .ok_or_else(|| CPUException::out_of_bounds("EXEC!ADD.src2", src2))?; let dst_cell = self .program .get_mut(dst) .ok_or_else(|| CPUException::out_of_bounds("EXEC!ADD.dst", dst))?; *dst_cell = src1_val + src2_val; } CPUOp::Mul { src1, src2, dst } => { let src1_val = *self .program .get(src1) .ok_or_else(|| CPUException::out_of_bounds("EXEC!MUL.src1", src1))?; let src2_val = *self .program .get(src2) .ok_or_else(|| CPUException::out_of_bounds("EXEC!MUL.src2", src2))?; let dst_cell = self .program .get_mut(dst) .ok_or_else(|| CPUException::out_of_bounds("EXEC!MUL.dst", dst))?; *dst_cell = src1_val * src2_val; } CPUOp::Halt => self.state = CPUState::Halted, CPUOp::Undefined(opcode) => return Err(CPUException::invalid_opcode(opcode)), } self.pc += op.next_pc_offset(); Ok(()) } fn fetch_op(&mut self) -> CPUResult<CPUOp> { use CPUExceptionKind::*; let opcode = self .program .get(self.pc) .ok_or_else(|| CPUException::out_of_bounds("FETCH!OP", self.pc))?; match opcode { 1 => { let src1 = *self .program .get(self.pc + 1) .ok_or_else(|| CPUException::out_of_bounds("FETCH!ADD.src1", self.pc + 1))? as usize; let src2 = *self .program .get(self.pc + 2) .ok_or_else(|| CPUException::out_of_bounds("FETCH!ADD.src2", self.pc + 2))? as usize; let dst = *self .program .get(self.pc + 3) .ok_or_else(|| CPUException::out_of_bounds("FETCH!ADD.dst", self.pc + 3))? as usize; Ok(CPUOp::Add { src1, src2, dst }) } 2 => { let src1 = *self .program .get(self.pc + 1) .ok_or_else(|| CPUException::out_of_bounds("FETCH!MUL.src1", self.pc + 1))? as usize; let src2 = *self .program .get(self.pc + 2) .ok_or_else(|| CPUException::out_of_bounds("FETCH!MUL.src2", self.pc + 2))? as usize; let dst = *self .program .get(self.pc + 3) .ok_or_else(|| CPUException::out_of_bounds("FETCH!MUL.dst", self.pc + 3))? as usize; Ok(CPUOp::Mul { src1, src2, dst }) } 99 => Ok(CPUOp::Halt), undef_op => Ok(CPUOp::Undefined(*undef_op)), } } pub fn step(&mut self) -> CPUResult<CPUState> { let op = self.fetch_op()?; self.execute_op(op)?; Ok(self.state) } pub fn run(&mut self) -> CPUResult<()> { loop { if let CPUState::Halted = self.step()? { return Ok(()); } } } pub fn get_position(&self, pos: usize) -> Option<u32> { self.program.get(pos).cloned() } pub fn pc(&self) -> u32 { self.pc as u32 } pub fn output(&self) -> u32 { *self .program .get(0) .expect("Output (pos 0) not found in program") } /// noun = input 1 in challenge parlance pub fn noun(&self) -> u32 { *self .program .get(1) .expect("Noun (pos 1) not found in program") } /// verb = input 2 in challenge parlance pub fn verb(&self) -> u32 { *self .program .get(2) .expect("Verb (pos 2) not found in program") } pub fn inspect_state(&self) -> &[u32] { &*self.program } }
use handlebars::*; use itertools::join; use std::collections::BTreeMap; use serde_json::value::Value as Json; use serde_json; use url::Url; // Change an array of items into a comma seperated list with formatting // Usage: {{#comma-list array}}{{elementAttribute}}:{{attribute2}}{{/comma-list}} pub(crate) fn comma_delimited_list_helper( h: &Helper, r: &Handlebars, rc: &mut RenderContext, ) -> HelperResult { let value = h.param(0) .ok_or_else(|| RenderError::new("Param not found for helper \"comma-list\""))?; match h.template() { Some(template) => match *value.value() { Json::Array(ref list) => { let len = list.len(); let mut render_list = Vec::new(); for i in 0..len { let mut local_rc = rc.derive(); if let Some(inner_path) = value.path() { let new_path = format!("{}/{}/[{}]", local_rc.get_path(), inner_path, i); local_rc.set_path(new_path.clone()); } if let Some(block_param) = h.block_param() { let mut map = BTreeMap::new(); map.insert(block_param.to_string(), to_json(&list[i])); local_rc.push_block_context(&map)?; } render_list.push(template.renders(r, &mut local_rc)?); } rc.writer.write_all(&join(&render_list, ",").into_bytes())?; Ok(()) } Json::Null => Ok(()), _ => Err(RenderError::new(format!( "Param type is not array for helper \"comma-list\": {:?}", value ))), }, None => Ok(()), } } pub(crate) fn equal_helper(h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> HelperResult { let lvalue = h.param(0) .ok_or_else(|| RenderError::new("Left param not found for helper \"equal\""))? .value(); let rvalue = h.param(1) .ok_or_else(|| RenderError::new("Right param not found for helper \"equal\""))? .value(); let comparison = lvalue == rvalue; if h.is_block() { let template = if comparison { h.template() } else { h.inverse() }; match template { Some(ref t) => t.render(r, rc), None => Ok(()), } } else { if comparison { rc.writer.write(comparison.to_string().as_bytes())?; } Ok(()) } } pub(crate) fn or_helper(h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> HelperResult { let lvalue = h.param(0) .ok_or_else(|| RenderError::new("Left param not found for helper \"or\""))? .value(); let rvalue = h.param(1) .ok_or_else(|| RenderError::new("Right param not found for helper \"or\""))? .value(); let comparison = lvalue.as_str().map_or(false, |v| v.len() > 0) || rvalue.as_str().map_or(false, |v| v.len() > 0); if h.is_block() { let template = if comparison { h.template() } else { h.inverse() }; match template { Some(ref t) => t.render(r, rc), None => Ok(()), } } else { if comparison { rc.writer.write(comparison.to_string().as_bytes())?; } Ok(()) } } // Escapes strings to that they can be safely used inside yaml (And JSON for that matter). pub(crate) fn yaml_string_helper( h: &Helper, _: &Handlebars, rc: &mut RenderContext, ) -> HelperResult { let value = h.param(0) .ok_or_else(|| RenderError::new("Param not found for helper \"yaml-string\""))?; match *value.value() { ref s @ Json::String(_) => { let mut stringified = serde_json::to_string(&s).unwrap(); if stringified.starts_with('"') { stringified.remove(0); } if stringified.ends_with('"') { stringified.pop(); } rc.writer.write(stringified.as_bytes())?; Ok(()) } Json::Null => Ok(()), _ => Err(RenderError::new(format!( "Param type is not string for helper \"yaml-string\": {:?}", value, ))), } } // Removes the trailing slash on an endpoint pub(crate) fn url_rm_slash_helper( h: &Helper, _: &Handlebars, rc: &mut RenderContext, ) -> HelperResult { let value = h.param(0) .ok_or_else(|| RenderError::new("Param not found for helper \"url-rm-slash\""))?; match *value.value() { Json::String(ref s) => { if s.ends_with("/") { rc.writer.write(s[..s.len() - 1].as_bytes())?; } else { rc.writer.write(s.as_bytes())?; } Ok(()) } Json::Null => Ok(()), _ => Err(RenderError::new(format!( "Param type is not string for helper \"url-rm-slash\": {:?}", value, ))), } } // Adds the trailing slashes on an endpoint pub(crate) fn url_add_slash_helper( h: &Helper, _: &Handlebars, rc: &mut RenderContext, ) -> HelperResult { let value = h.param(0) .ok_or_else(|| RenderError::new("Param not found for helper \"url-add-slash\""))?; match *value.value() { Json::String(ref s) => { let output = if Url::parse(s).is_ok() && !s.ends_with("/") { format!("{}/", s) } else { s.clone() }; rc.writer.write(output.as_bytes())?; Ok(()) } Json::Null => Ok(()), _ => Err(RenderError::new(format!( "Param type is not string for helper \"url-add-slash\": {:?}", value, ))), } } // Removes the last slash plus content to the end of the string pub(crate) fn url_rm_path(h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> HelperResult { let value = h.param(0) .ok_or_else(|| RenderError::new("Param not found for helper \"url-rm-path\""))?; match *value.value() { Json::String(ref s) => { let url = if s.ends_with("/") { &s[..s.len() - 1] } else { &s }; match Url::parse(url) { Ok(ref mut url) => { if let Ok(ref mut paths) = url.path_segments_mut() { paths.pop(); } let mut url_str = url.as_str(); if url_str.ends_with("/") { url_str = &url_str[..url_str.len() - 1]; } rc.writer.write(url_str.as_bytes())?; Ok(()) } _ => { rc.writer.write(s.as_bytes())?; Ok(()) } } } Json::Null => Ok(()), _ => Err(RenderError::new(format!( "Param type is not string for helper \"url-rm-path\": {:?}", value ))), } } pub(crate) fn lowercase_string_helper( h: &Helper, _: &Handlebars, rc: &mut RenderContext, ) -> HelperResult { let value = h.param(0) .ok_or_else(|| RenderError::new("Param not found for helper \"lowercase\""))?; match *value.value() { Json::String(ref s) => { rc.writer.write(s.to_lowercase().as_bytes())?; Ok(()) } Json::Null => Ok(()), _ => Err(RenderError::new(format!( "Param type is not string for helper \"lowercase\": {:?}", value ))), } } #[cfg(test)] mod test { use super::*; use serde_json::{self, Value}; fn config_fixture() -> Value { let mut config: Value = serde_json::from_str(&include_str!( "../../tests/fixtures/configs/config.TEST.json" )).unwrap(); config["ConfigData"].take() } fn test_against_configs(handlebars: &Handlebars, template: &str, expected: &str) { let config_rendered = handlebars.render_template(template, &config_fixture()); assert!(config_rendered.is_ok()); assert_eq!(&config_rendered.unwrap(), expected); let null_rendered = handlebars.render_template(template, &Json::Null); assert!(null_rendered.is_ok()); assert_eq!(&null_rendered.unwrap(), ""); } #[test] fn test_comma_list() { let mut handlebars = Handlebars::new(); handlebars.register_helper("comma-list", Box::new(comma_delimited_list_helper)); test_against_configs( &handlebars, "{{#comma-list Memcache.Servers}}{{Endpoint}}:{{Port}}{{/comma-list}}", "192.168.1.100:1122,192.168.1.101:1122,192.168.1.102:1122", ); } #[test] fn test_equal() { let mut handlebars = Handlebars::new(); handlebars.register_helper("equal", Box::new(equal_helper)); handlebars.register_helper("eq", Box::new(equal_helper)); let templates = vec![ (r#"{{#equal Region.Key "TEST"}}Foo{{/equal}}"#, "Foo"), (r#"{{#equal Region.Key null}}{{else}}Bar{{/equal}}"#, "Bar"), (r#"{{#eq Region.Key "TEST"}}Foo{{/eq}}"#, "Foo"), (r#"{{#eq Region.Key null}}{{else}}Bar{{/eq}}"#, "Bar"), (r#"{{#if (equal Region.Key "TEST")}}Foo{{/if}}"#, "Foo"), ( r#"{{#if (equal Region.Key null)}}{{else}}Bar{{/if}}"#, "Bar", ), (r#"{{#if (eq Region.Key "TEST")}}Foo{{/if}}"#, "Foo"), (r#"{{#if (eq Region.Key null)}}{{else}}Bar{{/if}}"#, "Bar"), ]; for (template, expected) in templates { test_against_configs(&handlebars, template, expected) } } #[test] fn test_or() { let mut handlebars = Handlebars::new(); handlebars.register_helper("eq", Box::new(equal_helper)); handlebars.register_helper("or", Box::new(or_helper)); let templates = vec![ ( r#"{{#or (eq Region.Key "TEST") (eq Region.Key "TEST2")}}Foo{{/or}}"#, "Foo", ), ( r#"{{#or (eq Region.Key null) (eq Region.Key "NO")}}{{else}}Bar{{/or}}"#, "Bar", ), ( r#"{{#if (or (eq Region.Key "TEST") (eq Region.Key "TEST2"))}}Foo{{/if}}"#, "Foo", ), ( r#"{{#if (or (eq Region.Key null) (eq Region.Key "NO"))}}{{else}}Bar{{/if}}"#, "Bar", ), ]; for (template, expected) in templates { test_against_configs(&handlebars, template, expected) } } #[test] fn test_yaml_string() { let mut handlebars = Handlebars::new(); handlebars.register_helper("yaml-string", Box::new(yaml_string_helper)); test_against_configs( &handlebars, "{{yaml-string DB.Endpoint}}", r#"host-name\\TEST\""#, ); } #[test] fn test_url_rm_slash() { let mut handlebars = Handlebars::new(); handlebars.register_helper("url-rm-slash", Box::new(url_rm_slash_helper)); test_against_configs( &handlebars, "{{url-rm-slash SlashService.endpoint}}", "https://slash.com", ); } #[test] fn test_url_add_slash() { let mut handlebars = Handlebars::new(); handlebars.register_helper("url-add-slash", Box::new(url_add_slash_helper)); let templates = vec![ ( "{{url-add-slash NonSlashService.endpoint}}", "https://nonslash.com/", ), ( "{{url-add-slash NonSlashService.notAnEndpoint}}", "no-protocol.no-slash.com", ), ]; for (template, expected) in templates { test_against_configs(&handlebars, template, expected) } } #[test] fn test_url_rm_path() { let mut handlebars = Handlebars::new(); handlebars.register_helper("url-rm-path", Box::new(url_rm_path)); let templates = vec![ ( "{{url-rm-path PathService.endpoint}}", "https://path.com/path", ), ( "{{url-rm-path PathService.trailingSlash}}", "https://trailing-path.com/path", ), ]; for (template, expected) in templates { test_against_configs(&handlebars, template, expected) } } #[test] fn test_double_url_rm_path() { let mut handlebars = Handlebars::new(); handlebars.register_helper("url-rm-path", Box::new(url_rm_path)); test_against_configs( &handlebars, "{{url-rm-path (url-rm-path PathService.trailingSlash)}}", "https://trailing-path.com", ); } #[test] fn test_lowercase() { let mut handlebars = Handlebars::new(); handlebars.register_helper("lowercase", Box::new(lowercase_string_helper)); test_against_configs(&handlebars, "{{lowercase UpperCaseString}}", "uppercase"); } }
//! Styx symbols are global identifiers for `Member`s, such as types or functions. //! //! This module provides the `Symbol` trait, useful for symbol lookup, //! the `Sym` struct, its main implementation, and the `SymbolTree`, used to //! efficiently lookup symbols based on their name. use std::fmt::{self, Display, Formatter}; use std::hash::{Hash, Hasher}; use std::mem; // //==========================================================================// // // SYMBOL // // //==========================================================================// /// Defines an entity which has a name that can be decomposed in multiple /// parts, all of which corresponding to the hash of the symbol. pub trait Symbol { /// Returns the hashes that make up this symbol. fn parts(&self) -> &[u64]; /// Returns the full name of this symbol. fn full_name(&self) -> &str; /// Returns a `bool` that represents whether the given symbol matches /// the end of the current symbol. /// /// # Example /// ``` /// use styx::symbols::{Sym, Symbol}; /// /// let a = Sym::from("Hello"); /// let b = Sym::from("System"); /// let c = Sym::from("Hello.World"); /// let d = Sym::from("Hell"); /// /// assert!(c.matches(&a)); /// ``` fn matches(&self, other: &Symbol) -> bool { let a = self.parts(); let b = other.parts(); if a.len() < b.len() { return false } for i in (0..b.len()).rev() { if a[i] != b[i] { return false } } true } } impl PartialEq for Symbol { fn eq(&self, other: &Symbol) -> bool { self.parts() == other.parts() } } impl Eq for Symbol {} impl Display for Symbol { fn fmt(&self, f: &mut Formatter) -> fmt::Result { self.full_name().fmt(f) } } impl Hash for Symbol { default fn hash<H: Hasher>(&self, state: &mut H) { self.parts().hash(state); } } /// Implements a basic `Symbol`. #[derive(Clone, Debug)] pub struct Sym { parts: Vec<u64>, full_name: String } impl Symbol for Sym { #[inline] fn parts(&self) -> &[u64] { &self.parts } #[inline] fn full_name(&self) -> &str { self.full_name.as_str() } } impl Hash for Sym { fn hash<H: Hasher>(&self, state: &mut H) { self.parts().hash(state); } } impl Default for Sym { fn default() -> Sym { Sym { parts: Vec::new(), full_name: String::new() } } } impl AsRef<str> for Sym { fn as_ref(&self) -> &str { self.full_name.as_str() } } impl Display for Sym { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.write_str(self.full_name.as_str()) } } impl From<String> for Sym { fn from(sym: String) -> Sym { let parts = Self::parts(sym.as_str()); Sym { parts, full_name: sym } } } impl<'a> From<&'a str> for Sym { fn from(sym: &'a str) -> Sym { let sym = sym.to_string(); let parts = Self::parts(sym.as_str()); Sym { parts, full_name: sym } } } impl Sym { /// Creates and returns the `parts` part of a `Symbol`, given a string. /// /// # Example /// ``` /// use styx::symbols::Sym; /// /// assert_eq!(Sym::parts("System.+").len(), 2); /// ``` pub fn parts<S: AsRef<str>>(sym: S) -> Vec<u64> { use fnv::FnvHasher; let mut parts = Vec::new(); for part in sym.as_ref().split('.') { let mut hasher = FnvHasher::default(); part.hash(&mut hasher); parts.push(hasher.finish()); } parts } /// Creates and returns a new symbol whose full name is the current symbol's name, /// plus the specified string. /// /// # Example /// ``` /// use styx::symbols::Sym; /// /// assert_eq!(Sym::from("Hello").child("World"), Sym::from("Hello.World")); /// assert_ne!(Sym::from("Foo").child("Bar.Baz"), Sym::from("Foo.Bar.Baz")); /// ``` pub fn child<S: Display + Hash>(&self, sym: S) -> Sym { use fnv::FnvHasher; let mut hasher = FnvHasher::default(); sym.to_string().hash(&mut hasher); let parts = self.parts.iter().chain(&[hasher.finish()]).cloned().collect(); Sym { parts, full_name: format!("{}.{}", self.full_name, sym) } } /// Creates and returns a new symbol whose full name is the current symbol's name, /// plus the specified string. /// /// Additionally, the child might have multiple parts itself. /// /// # Example /// ``` /// use styx::symbols::Sym; /// /// assert_eq!(Sym::from("Foo").nested_child("Bar.Baz"), Sym::from("Foo.Bar.Baz")); /// ``` #[allow(needless_pass_by_value)] pub fn nested_child<S: ToString>(&self, sym: S) -> Sym { let sym = sym.to_string(); let parts = self.parts.iter().cloned().chain(Self::parts(sym.as_str())).collect(); Sym { parts, full_name: format!("{}.{}", self.full_name, sym) } } } impl PartialEq for Sym { fn eq(&self, other: &Sym) -> bool { self.parts == other.parts } } impl Eq for Sym {} /// Implements a simple `Symbol` with no name, only used during lookups. pub struct LookupSym { parts: Vec<u64> } impl Symbol for LookupSym { #[inline] fn parts(&self) -> &[u64] { &self.parts } #[inline] fn full_name(&self) -> &str { panic!("Unable to get full name of lookup symbol.") } } impl<'s> From<&'s str> for LookupSym { #[inline] fn from(symbol: &'s str) -> LookupSym { LookupSym { parts: Sym::parts(symbol) } } } impl From<Vec<u64>> for LookupSym { #[inline] fn from(parts: Vec<u64>) -> LookupSym { LookupSym { parts } } } impl<'a> From<&'a Symbol> for LookupSym { #[inline] fn from(symbol: &'a Symbol) -> LookupSym { LookupSym { parts: Vec::from(symbol.parts()) } } } // //==========================================================================// // // TREE // // //==========================================================================// /// An `Iterator` over siblings of a `SymbolTree`. pub struct SiblingsIterator<'a, T: 'a> { node: Option<&'a SymbolTree<T>> } impl<'a, T: 'a> Iterator for SiblingsIterator<'a, T> { type Item = &'a SymbolTree<T>; fn next(&mut self) -> Option<&'a SymbolTree<T>> { match self.node { None => None, Some(node) => { let node = node.sibling(); mem::replace(&mut self.node, node.map(|s| s as &_)) } } } } /// An `Iterator` over every node of a `SymbolTree`. pub enum TreeIterator<'a, T: 'a> { /// Iterating over a single child. Child(&'a SymbolTree<T>), /// Iterating over children of a node. Children(&'a SymbolTree<T>, Box<TreeIterator<'a, T>>), /// Iterating over a single sibling. Sibling(&'a SymbolTree<T>), /// Iterating over siblings of a node. Siblings(&'a SymbolTree<T>, Box<TreeIterator<'a, T>>), /// Done iterating. Done } impl<'a, T: 'a> Iterator for TreeIterator<'a, T> { type Item = &'a SymbolTree<T>; fn next(&mut self) -> Option<&'a SymbolTree<T>> { use self::TreeIterator::*; loop { let mut to_return = None; *self = match self { &mut Done => return None, &mut Child(tree) => { to_return = Some(tree as *const _); Children(tree, box tree.iter()) }, &mut Sibling(tree) => { to_return = Some(tree as *const _); Siblings(tree, box tree.iter()) }, &mut Siblings(_, ref mut iter) => match iter.as_mut().next() { Some(value) => return Some(value), None => Done }, &mut Children(ref mut tree, ref mut iter) => match iter.as_mut().next() { Some(value) => return Some(value), None => match tree.sibling() { Some(sibling) => Siblings(tree, box sibling.iter()), None => Done } } }; if let Some(ret) = to_return { return Some(unsafe { ret.as_ref().unwrap() }) } } } } /// A binary tree that holds items of type `T`. /// /// Items are looked up using each part of a `Symbol`, making the lookup very fast. /// References are held as raw memory addresses; that way, the whole tree gets destroyed /// at once when it is dropped, instead of counting references between each node. pub struct SymbolTree<T> { hash: u64, value: Option<T>, sibling_ptr: usize, child_ptr: usize } impl<T: ::std::fmt::Debug> ::std::fmt::Debug for SymbolTree<T> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let mut debg = f.debug_struct("Tree"); if let &Some(c) = &self.child() { debg.field("child", c); } if let &Some(s) = &self.sibling() { debg.field("sibling", s); } if let &Some(ref v) = &self.value { debg.field("value", v); } debg.finish() } } impl<T> Drop for SymbolTree<T> { fn drop(&mut self) { match self.sibling_ptr { 0 => (), n => unsafe { Box::from_raw(n as *mut T); } } match self.child_ptr { 0 => (), n => unsafe { Box::from_raw(n as *mut T); } } } } impl<T> SymbolTree<T> { /// Returns a new `SymbolTree`, given its hash and value. #[inline] pub fn new(hash: u64, value: Option<T>) -> Self { SymbolTree { hash, value, sibling_ptr: 0, child_ptr: 0 } } /// Gets the value contained in the node. #[inline] pub fn value(&self) -> Option<&T> { self.value.as_ref() } /// Gets the hash of the symbol part represented by this node. #[inline] pub fn hash(&self) -> u64 { self.hash } /// Gets the next sibling of the node. #[inline] pub fn sibling(&self) -> Option<&SymbolTree<T>> { match self.sibling_ptr { 0 => None, n => Some(unsafe { &mut *(n as *mut _) }) } } /// Gets the first child of the node. #[inline] pub fn child(&self) -> Option<&SymbolTree<T>> { match self.child_ptr { 0 => None, n => Some(unsafe { &mut *(n as *mut _) }) } } /// Gets an iterator that returns all next siblings of this node. #[inline] pub fn siblings(&self) -> SiblingsIterator<T> { SiblingsIterator { node: Some(self) } } /// Gets an iterator that returns all siblings and children of this node. #[inline] pub fn iter(&self) -> TreeIterator<T> { use self::TreeIterator::*; match self.child() { Some(child) => Child(child), None => match self.sibling() { Some(sibling) => Sibling(sibling), None => Done } } } /// Gets the value associated with the given symbol. #[inline] pub fn get<'a>(&'a self, symbol: &'a Symbol) -> Option<&'a T> { self.lookup(symbol).and_then(Self::value) } /// Looks up the node associated with the given symbol. #[inline] pub fn lookup<'a, 'b>(&'a self, symbol: &'b Symbol) -> Option<&'a SymbolTree<T>> { if symbol.parts().is_empty() { None } else { self.recursive_lookup(symbol.parts()) } } fn recursive_lookup<'a, 'b>(&'a self, parts: &'b [u64]) -> Option<&'a SymbolTree<T>> { if parts[0] == self.hash { if parts.len() == 1 { Some(self) } else if let Some(child) = self.child() { child.recursive_lookup(&parts[1..]) } else { None } } else if let Some(sibling) = self.sibling() { sibling.recursive_lookup(parts) } else { None } } /// Inserts the given value, given its symbol. #[inline] pub fn insert<'a>(&'a mut self, symbol: &'a [u64], value: T, force: bool) -> Result<&'a SymbolTree<T>, T> { if symbol.is_empty() { Err(value) } else { self.recursive_insert(symbol, 0, value, force) } } fn recursive_insert<'a>(&'a mut self, sym: &'a [u64], part: usize, value: T, force: bool) -> Result<&'a SymbolTree<T>, T> { if part == sym.len() - 1 { // Reached the end of the symbol name, insert value as sibling self.insert_sibling(sym[part], value, force) } else if sym[part] == self.hash { // Matching hash, keep going let child = unsafe { &mut *match self.child_ptr { 0 => { let ptr = Box::into_raw(box Self::new(sym[part], None)); self.child_ptr = ptr as usize; ptr }, n => n as *mut _ }}; child.recursive_insert(sym, part + 1, value, force) } else { // None matching hash, insert sibling let sibling = unsafe { &mut *match self.sibling_ptr { 0 => { let ptr = Box::into_raw(box Self::new(sym[part], None)); self.sibling_ptr = ptr as usize; ptr }, n => n as *mut _ }}; sibling.recursive_insert(sym, part, value, force) } } fn insert_sibling(&mut self, hash: u64, value: T, force: bool) -> Result<&SymbolTree<T>, T> { if !force && self.hash == hash { // Return error if inserting an exact match Err(value) } else { match self.sibling_ptr { 0 => { let sibling = Box::into_raw(box Self::new(hash, Some(value))); self.sibling_ptr = sibling as usize; Ok(unsafe { &*sibling }) }, n => unsafe { &mut *(n as *mut Self) }.insert_sibling(hash, value, force) } } } } impl<T> Default for SymbolTree<T> { fn default() -> Self { SymbolTree { hash: 0, value: None, child_ptr: 0, sibling_ptr: 0 } } }
//! Get info on members of your Slack team. use crate::http::{Cursor, Paging}; use crate::id::*; use crate::Timestamp; /// Lists all users in a Slack team. /// /// Wraps https://api.slack.com/methods/users.list /// At this time, providing no limit value will result in Slack /// attempting to deliver you the entire result set. /// If the collection is too large you may experience HTTP 500 errors. /// Resolve this scenario by using pagination. /// /// One day pagination will become required to use this method. #[derive(Serialize, new)] pub struct ListRequest { /// Whether to include presence data in the output #[new(default)] pub presence: Option<bool>, #[new(default)] pub cursor: Option<Cursor>, #[new(default)] pub limit: Option<usize>, #[new(default)] pub include_locale: Option<bool>, } #[derive(Deserialize)] pub struct ListResponse { pub ok: bool, pub members: Vec<User>, pub cache_ts: Option<Timestamp>, pub response_metadata: Option<Paging>, pub is_limited: Option<bool>, } #[derive(Deserialize)] pub struct User { pub id: UserId, pub name: String, pub real_name: Option<String>, }
#[derive(Debug, PartialEq)] pub struct Clock { minute_of_day: u16 } impl Clock { const MINUTES_IN_DAY: isize = 24 * 60; pub fn new(hours: isize, minutes: isize) -> Self { let total_minutes = (hours % 24) * 60 + minutes; if total_minutes < 0 { Self { minute_of_day: (Self::MINUTES_IN_DAY + total_minutes % Self::MINUTES_IN_DAY) as u16 } } else { Self { minute_of_day: (total_minutes % Self::MINUTES_IN_DAY) as u16 } } } pub fn add_minutes(&self, minutes: isize) -> Self { Self::new(0, self.minute_of_day as isize + minutes) } } impl std::fmt::Display for Clock { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let hours = self.minute_of_day / 60; let minutes = self.minute_of_day - hours * 60; write!(formatter, "{:02}:{:02}", hours, minutes) } }
#[cfg(feature = "in-use-encryption-unstable")] mod csfle; #[cfg(feature = "in-use-encryption-unstable")] use self::csfle::*; use std::{ collections::HashMap, convert::TryInto, fmt::Debug, ops::Deref, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, time::Duration, }; use futures::{ future::BoxFuture, io::AsyncReadExt, stream::{StreamExt, TryStreamExt}, FutureExt, }; use serde::{ de::{DeserializeOwned, Deserializer}, Deserialize, }; use time::OffsetDateTime; use tokio::sync::Mutex; use super::{ results_match, Entity, EntityMap, ExpectError, ExpectedEvent, TestCursor, TestFileEntity, TestRunner, }; use crate::{ bson::{doc, to_bson, Bson, Document}, change_stream::options::ChangeStreamOptions, client::session::TransactionState, coll::options::Hint, collation::Collation, db::options::RunCursorCommandOptions, error::{ErrorKind, Result}, gridfs::options::{GridFsDownloadByNameOptions, GridFsUploadOptions}, options::{ AggregateOptions, CountOptions, CreateCollectionOptions, DeleteOptions, DistinctOptions, DropCollectionOptions, EstimatedDocumentCountOptions, FindOneAndDeleteOptions, FindOneAndReplaceOptions, FindOneAndUpdateOptions, FindOneOptions, FindOptions, IndexOptions, InsertManyOptions, InsertOneOptions, ListCollectionsOptions, ListDatabasesOptions, ListIndexesOptions, ReadConcern, ReplaceOptions, SelectionCriteria, UpdateModifications, UpdateOptions, }, runtime, selection_criteria::ReadPreference, serde_util, test::FailPoint, Collection, Database, IndexModel, ServerType, TopologyType, }; pub(crate) trait TestOperation: Debug + Send + Sync { fn execute_test_runner_operation<'a>( &'a self, _test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { panic!( "execute_test_runner_operation called on unsupported operation {:?}", self ) } fn execute_entity_operation<'a>( &'a self, _id: &'a str, _test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { Err(ErrorKind::InvalidArgument { message: format!( "execute_entity_operation called on unsupported operation {:?}", self ), } .into()) } .boxed() } /// Whether or not this operation returns an array of root documents. This information is /// necessary to determine how the return value of an operation should be compared to the /// expected value. fn returns_root_documents(&self) -> bool { false } /// If this operation specifies entities to create, returns those entities. Otherwise, /// returns None. fn test_file_entities(&self) -> Option<&Vec<TestFileEntity>> { None } } /// To facilitate working with sessions through the lock, this macro pops it out of the entity map, /// "passes" it to the provided block, and then returns it to the entity map. It does it this way /// so that we can continue to borrow the entity map in other ways even when we're using a session, /// which we'd have to borrow mutably from the map. macro_rules! with_mut_session { ($test_runner:ident, $id:expr, |$session:ident| $body:expr) => { async { let id = $id; let mut session_owned = match $test_runner.entities.write().await.remove(id).unwrap() { Entity::Session(session_owned) => session_owned, o => panic!( "expected {} to be a session entity, instead was {:?}", $id, o ), }; let $session = &mut session_owned; let out = $body.await; $test_runner .entities .write() .await .insert(id.to_string(), Entity::Session(session_owned)); out } }; } #[derive(Debug)] pub(crate) struct Operation { operation: Box<dyn TestOperation>, pub(crate) name: String, pub(crate) object: OperationObject, pub(crate) expectation: Expectation, } impl Operation { pub(crate) async fn execute<'a>(&self, test_runner: &TestRunner, description: &str) { match self.object { OperationObject::TestRunner => { self.execute_test_runner_operation(test_runner).await; } OperationObject::Entity(ref id) => { let result = self.execute_entity_operation(id, test_runner).await; match &self.expectation { Expectation::Result { expected_value, save_as_entity, } => { let opt_entity = result.unwrap_or_else(|e| { panic!( "[{}] {} should succeed, but failed with the following error: {}", description, self.name, e ) }); if expected_value.is_some() || save_as_entity.is_some() { let entity = opt_entity.unwrap_or_else(|| { panic!("[{}] {} did not return an entity", description, self.name) }); if let Some(expected_bson) = expected_value { let actual = match &entity { Entity::Bson(bs) => Some(bs), Entity::None => None, _ => panic!( "[{}] Incorrect entity type returned from {}, expected \ BSON", description, self.name ), }; if let Err(e) = results_match( actual, expected_bson, self.returns_root_documents(), Some(&*test_runner.entities.read().await), ) { panic!( "[{}] result mismatch, expected = {:#?} actual = \ {:#?}\nmismatch detail: {}", description, expected_bson, actual, e ); } } if let Some(id) = save_as_entity { test_runner.insert_entity(id, entity).await; } } } Expectation::Error(expect_error) => { let error = result.expect_err(&format!( "{}: {} should return an error", description, self.name )); expect_error.verify_result(&error, description).unwrap(); } Expectation::Ignore => (), } } } } } #[derive(Debug)] pub(crate) enum OperationObject { TestRunner, Entity(String), } impl<'de> Deserialize<'de> for OperationObject { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> { let object = String::deserialize(deserializer)?; if object.as_str() == "testRunner" { Ok(OperationObject::TestRunner) } else { Ok(OperationObject::Entity(object)) } } } #[derive(Debug)] pub(crate) enum Expectation { Result { expected_value: Option<Bson>, save_as_entity: Option<String>, }, Error(ExpectError), Ignore, } fn deserialize_op<'de, 'a, T: 'a + DeserializeOwned + TestOperation>( value: Document, ) -> std::result::Result<Box<dyn TestOperation + 'a>, bson::de::Error> { bson::from_document::<T>(value).map(|op| Box::new(op) as Box<dyn TestOperation>) } impl<'de> Deserialize<'de> for Operation { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct OperationDefinition { pub(crate) name: String, pub(crate) object: OperationObject, #[serde(default = "default_arguments")] pub(crate) arguments: Document, pub(crate) expect_error: Option<ExpectError>, pub(crate) expect_result: Option<Bson>, pub(crate) save_result_as_entity: Option<String>, pub(crate) ignore_result_and_error: Option<bool>, } fn default_arguments() -> Document { doc! {} } let definition = OperationDefinition::deserialize(deserializer)?; let boxed_op = match definition.name.as_str() { "insertOne" => deserialize_op::<InsertOne>(definition.arguments), "insertMany" => deserialize_op::<InsertMany>(definition.arguments), "updateOne" => deserialize_op::<UpdateOne>(definition.arguments), "updateMany" => deserialize_op::<UpdateMany>(definition.arguments), "deleteMany" => deserialize_op::<DeleteMany>(definition.arguments), "deleteOne" => deserialize_op::<DeleteOne>(definition.arguments), "find" => deserialize_op::<Find>(definition.arguments), "createFindCursor" => deserialize_op::<CreateFindCursor>(definition.arguments), "createCommandCursor" => deserialize_op::<CreateCommandCursor>(definition.arguments), "aggregate" => deserialize_op::<Aggregate>(definition.arguments), "distinct" => deserialize_op::<Distinct>(definition.arguments), "countDocuments" => deserialize_op::<CountDocuments>(definition.arguments), "estimatedDocumentCount" => { deserialize_op::<EstimatedDocumentCount>(definition.arguments) } "findOne" => deserialize_op::<FindOne>(definition.arguments), "listDatabases" => deserialize_op::<ListDatabases>(definition.arguments), "listDatabaseNames" => deserialize_op::<ListDatabaseNames>(definition.arguments), "listCollections" => deserialize_op::<ListCollections>(definition.arguments), "listCollectionNames" => deserialize_op::<ListCollectionNames>(definition.arguments), "replaceOne" => deserialize_op::<ReplaceOne>(definition.arguments), "findOneAndUpdate" => deserialize_op::<FindOneAndUpdate>(definition.arguments), "findOneAndReplace" => deserialize_op::<FindOneAndReplace>(definition.arguments), "findOneAndDelete" => deserialize_op::<FindOneAndDelete>(definition.arguments), "failPoint" => deserialize_op::<FailPointCommand>(definition.arguments), "targetedFailPoint" => deserialize_op::<TargetedFailPoint>(definition.arguments), "assertCollectionExists" => { deserialize_op::<AssertCollectionExists>(definition.arguments) } "assertCollectionNotExists" => { deserialize_op::<AssertCollectionNotExists>(definition.arguments) } "createCollection" => deserialize_op::<CreateCollection>(definition.arguments), "dropCollection" => deserialize_op::<DropCollection>(definition.arguments), "runCommand" => deserialize_op::<RunCommand>(definition.arguments), "runCursorCommand" => deserialize_op::<RunCursorCommand>(definition.arguments), "endSession" => deserialize_op::<EndSession>(definition.arguments), "assertSessionTransactionState" => { deserialize_op::<AssertSessionTransactionState>(definition.arguments) } "assertSessionPinned" => deserialize_op::<AssertSessionPinned>(definition.arguments), "assertSessionUnpinned" => { deserialize_op::<AssertSessionUnpinned>(definition.arguments) } "assertDifferentLsidOnLastTwoCommands" => { deserialize_op::<AssertDifferentLsidOnLastTwoCommands>(definition.arguments) } "assertSameLsidOnLastTwoCommands" => { deserialize_op::<AssertSameLsidOnLastTwoCommands>(definition.arguments) } "assertSessionDirty" => deserialize_op::<AssertSessionDirty>(definition.arguments), "assertSessionNotDirty" => { deserialize_op::<AssertSessionNotDirty>(definition.arguments) } "startTransaction" => deserialize_op::<StartTransaction>(definition.arguments), "commitTransaction" => deserialize_op::<CommitTransaction>(definition.arguments), "abortTransaction" => deserialize_op::<AbortTransaction>(definition.arguments), "createIndex" => deserialize_op::<CreateIndex>(definition.arguments), "listIndexes" => deserialize_op::<ListIndexes>(definition.arguments), "listIndexNames" => deserialize_op::<ListIndexNames>(definition.arguments), "assertIndexExists" => deserialize_op::<AssertIndexExists>(definition.arguments), "assertIndexNotExists" => deserialize_op::<AssertIndexNotExists>(definition.arguments), "iterateUntilDocumentOrError" => { deserialize_op::<IterateUntilDocumentOrError>(definition.arguments) } "assertNumberConnectionsCheckedOut" => { deserialize_op::<AssertNumberConnectionsCheckedOut>(definition.arguments) } "close" => deserialize_op::<Close>(definition.arguments), "createChangeStream" => deserialize_op::<CreateChangeStream>(definition.arguments), "rename" => deserialize_op::<RenameCollection>(definition.arguments), "loop" => deserialize_op::<Loop>(definition.arguments), "waitForEvent" => deserialize_op::<WaitForEvent>(definition.arguments), "assertEventCount" => deserialize_op::<AssertEventCount>(definition.arguments), "runOnThread" => deserialize_op::<RunOnThread>(definition.arguments), "waitForThread" => deserialize_op::<WaitForThread>(definition.arguments), "recordTopologyDescription" => { deserialize_op::<RecordTopologyDescription>(definition.arguments) } "assertTopologyType" => deserialize_op::<AssertTopologyType>(definition.arguments), "waitForPrimaryChange" => deserialize_op::<WaitForPrimaryChange>(definition.arguments), "wait" => deserialize_op::<Wait>(definition.arguments), "createEntities" => deserialize_op::<CreateEntities>(definition.arguments), "download" => deserialize_op::<Download>(definition.arguments), "downloadByName" => deserialize_op::<DownloadByName>(definition.arguments), "delete" => deserialize_op::<Delete>(definition.arguments), "upload" => deserialize_op::<Upload>(definition.arguments), #[cfg(feature = "in-use-encryption-unstable")] "getKeyByAltName" => deserialize_op::<GetKeyByAltName>(definition.arguments), #[cfg(feature = "in-use-encryption-unstable")] "deleteKey" => deserialize_op::<DeleteKey>(definition.arguments), #[cfg(feature = "in-use-encryption-unstable")] "getKey" => deserialize_op::<GetKey>(definition.arguments), #[cfg(feature = "in-use-encryption-unstable")] "addKeyAltName" => deserialize_op::<AddKeyAltName>(definition.arguments), #[cfg(feature = "in-use-encryption-unstable")] "createDataKey" => deserialize_op::<CreateDataKey>(definition.arguments), #[cfg(feature = "in-use-encryption-unstable")] "getKeys" => deserialize_op::<GetKeys>(definition.arguments), #[cfg(feature = "in-use-encryption-unstable")] "removeKeyAltName" => deserialize_op::<RemoveKeyAltName>(definition.arguments), "iterateOnce" => deserialize_op::<IterateOnce>(definition.arguments), s => Ok(Box::new(UnimplementedOperation { _name: s.to_string(), }) as Box<dyn TestOperation>), } .map_err(|e| serde::de::Error::custom(format!("{}", e)))?; let expectation = if let Some(true) = definition.ignore_result_and_error { if definition.expect_result.is_some() || definition.expect_error.is_some() || definition.save_result_as_entity.is_some() { return Err(serde::de::Error::custom( "ignoreResultAndError is mutually exclusive with expectResult, expectError, \ and saveResultAsEntity", )); } Expectation::Ignore } else if let Some(err) = definition.expect_error { if definition.expect_result.is_some() || definition.save_result_as_entity.is_some() { return Err(serde::de::Error::custom( "expectError is mutually exclusive with expectResult and saveResultAsEntity", )); } Expectation::Error(err) } else { Expectation::Result { expected_value: definition.expect_result, save_as_entity: definition.save_result_as_entity, } }; Ok(Operation { operation: boxed_op, name: definition.name, object: definition.object, expectation, }) } } impl Deref for Operation { type Target = Box<dyn TestOperation>; fn deref(&self) -> &Box<dyn TestOperation> { &self.operation } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct DeleteMany { filter: Document, #[serde(flatten)] options: DeleteOptions, } impl TestOperation for DeleteMany { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = collection .delete_many(self.filter.clone(), self.options.clone()) .await?; let result = to_bson(&result)?; Ok(Some(result.into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct DeleteOne { filter: Document, session: Option<String>, #[serde(flatten)] options: DeleteOptions, } impl TestOperation for DeleteOne { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| async { collection .delete_one_with_session( self.filter.clone(), self.options.clone(), session, ) .await }) .await? } None => { collection .delete_one(self.filter.clone(), self.options.clone()) .await? } }; let result = to_bson(&result)?; Ok(Some(result.into())) } .boxed() } } #[derive(Debug, Default, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct Find { filter: Document, session: Option<String>, // `FindOptions` cannot be embedded directly because serde doesn't support combining `flatten` // and `deny_unknown_fields`, so its fields are replicated here. allow_disk_use: Option<bool>, allow_partial_results: Option<bool>, batch_size: Option<u32>, comment: Option<Bson>, hint: Option<Hint>, limit: Option<i64>, max: Option<Document>, max_scan: Option<u64>, #[serde( default, rename = "maxTimeMS", deserialize_with = "serde_util::deserialize_duration_option_from_u64_millis" )] max_time: Option<Duration>, min: Option<Document>, no_cursor_timeout: Option<bool>, projection: Option<Document>, read_concern: Option<ReadConcern>, return_key: Option<bool>, show_record_id: Option<bool>, skip: Option<u64>, sort: Option<Document>, collation: Option<Collation>, #[serde(rename = "let")] let_vars: Option<Document>, } impl Find { async fn get_cursor<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> Result<TestCursor> { let collection = test_runner.get_collection(id).await; let (comment, comment_bson) = match &self.comment { Some(Bson::String(string)) => (Some(string.clone()), None), Some(bson) => (None, Some(bson.clone())), None => (None, None), }; // `FindOptions` is constructed without the use of `..Default::default()` to enforce at // compile-time that any new fields added there need to be considered here. let options = FindOptions { allow_disk_use: self.allow_disk_use, allow_partial_results: self.allow_partial_results, batch_size: self.batch_size, comment, comment_bson, hint: self.hint.clone(), limit: self.limit, max: self.max.clone(), max_scan: self.max_scan, max_time: self.max_time, min: self.min.clone(), no_cursor_timeout: self.no_cursor_timeout, projection: self.projection.clone(), read_concern: self.read_concern.clone(), return_key: self.return_key, show_record_id: self.show_record_id, skip: self.skip, sort: self.sort.clone(), collation: self.collation.clone(), cursor_type: None, max_await_time: None, selection_criteria: None, let_vars: self.let_vars.clone(), }; match &self.session { Some(session_id) => { let cursor = with_mut_session!(test_runner, session_id, |session| async { collection .find_with_session(self.filter.clone(), options, session) .await }) .await?; Ok(TestCursor::Session { cursor, session_id: session_id.clone(), }) } None => { let cursor = collection.find(self.filter.clone(), options).await?; Ok(TestCursor::Normal(Mutex::new(cursor))) } } } } impl TestOperation for Find { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let result = match self.get_cursor(id, test_runner).await? { TestCursor::Session { mut cursor, session_id, } => { with_mut_session!(test_runner, session_id.as_str(), |s| async { cursor.stream(s).try_collect::<Vec<Document>>().await }) .await? } TestCursor::Normal(cursor) => { let cursor = cursor.into_inner(); cursor.try_collect::<Vec<Document>>().await? } TestCursor::ChangeStream(_) => panic!("get_cursor returned a change stream"), TestCursor::Closed => panic!("get_cursor returned a closed cursor"), }; Ok(Some(Bson::from(result).into())) } .boxed() } fn returns_root_documents(&self) -> bool { true } } #[derive(Debug, Default, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct CreateFindCursor { // `Find` cannot be embedded directly because serde doesn't support combining `flatten` // and `deny_unknown_fields`, so its fields are replicated here. filter: Document, session: Option<String>, allow_disk_use: Option<bool>, allow_partial_results: Option<bool>, batch_size: Option<u32>, comment: Option<Bson>, hint: Option<Hint>, limit: Option<i64>, max: Option<Document>, max_scan: Option<u64>, #[serde(rename = "maxTimeMS")] max_time: Option<Duration>, min: Option<Document>, no_cursor_timeout: Option<bool>, projection: Option<Document>, read_concern: Option<ReadConcern>, return_key: Option<bool>, show_record_id: Option<bool>, skip: Option<u64>, sort: Option<Document>, collation: Option<Collation>, #[serde(rename = "let")] let_vars: Option<Document>, } impl TestOperation for CreateFindCursor { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let find = Find { filter: self.filter.clone(), session: self.session.clone(), allow_disk_use: self.allow_disk_use, allow_partial_results: self.allow_partial_results, batch_size: self.batch_size, comment: self.comment.clone(), hint: self.hint.clone(), limit: self.limit, max: self.max.clone(), max_scan: self.max_scan, max_time: self.max_time, min: self.min.clone(), no_cursor_timeout: self.no_cursor_timeout, projection: self.projection.clone(), read_concern: self.read_concern.clone(), return_key: self.return_key, show_record_id: self.show_record_id, skip: self.skip, sort: self.sort.clone(), collation: self.collation.clone(), let_vars: self.let_vars.clone(), }; let cursor = find.get_cursor(id, test_runner).await?; Ok(Some(Entity::Cursor(cursor))) } .boxed() } fn returns_root_documents(&self) -> bool { false } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct InsertMany { documents: Vec<Document>, session: Option<String>, #[serde(flatten)] options: InsertManyOptions, } impl TestOperation for InsertMany { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| { async move { collection .insert_many_with_session( self.documents.clone(), self.options.clone(), session, ) .await } .boxed() }) .await? } None => { collection .insert_many(self.documents.clone(), self.options.clone()) .await? } }; let ids: HashMap<String, Bson> = result .inserted_ids .into_iter() .map(|(k, v)| (k.to_string(), v)) .collect(); let ids = to_bson(&ids)?; Ok(Some(Bson::from(doc! { "insertedIds": ids }).into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct InsertOne { document: Document, session: Option<String>, #[serde(flatten)] options: InsertOneOptions, } impl TestOperation for InsertOne { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| async { collection .insert_one_with_session( self.document.clone(), self.options.clone(), session, ) .await }) .await? } None => { collection .insert_one(self.document.clone(), self.options.clone()) .await? } }; let result = to_bson(&result)?; Ok(Some(result.into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct UpdateMany { filter: Document, update: UpdateModifications, #[serde(flatten)] options: UpdateOptions, } impl TestOperation for UpdateMany { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = collection .update_many( self.filter.clone(), self.update.clone(), self.options.clone(), ) .await?; let result = to_bson(&result)?; Ok(Some(result.into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct UpdateOne { filter: Document, update: UpdateModifications, #[serde(flatten)] options: UpdateOptions, session: Option<String>, } impl TestOperation for UpdateOne { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| async { collection .update_one_with_session( self.filter.clone(), self.update.clone(), self.options.clone(), session, ) .await }) .await? } None => { collection .update_one( self.filter.clone(), self.update.clone(), self.options.clone(), ) .await? } }; let result = to_bson(&result)?; Ok(Some(result.into())) } .boxed() } } #[derive(Debug)] pub(super) struct Aggregate { pipeline: Vec<Document>, session: Option<String>, options: AggregateOptions, } // TODO RUST-1364: remove this impl and derive Deserialize instead impl<'de> Deserialize<'de> for Aggregate { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> { #[derive(Deserialize)] struct Helper { pipeline: Vec<Document>, session: Option<String>, comment: Option<Bson>, #[serde(flatten)] options: AggregateOptions, } let mut helper = Helper::deserialize(deserializer)?; match helper.comment { Some(Bson::String(string)) => { helper.options.comment = Some(string); } Some(bson) => { helper.options.comment_bson = Some(bson); } _ => {} } Ok(Self { pipeline: helper.pipeline, session: helper.session, options: helper.options, }) } } impl TestOperation for Aggregate { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let result = match &self.session { Some(session_id) => { enum AggregateEntity { Collection(Collection<Document>), Database(Database), Other(String), } let entity = match test_runner.entities.read().await.get(id).unwrap() { Entity::Collection(c) => AggregateEntity::Collection(c.clone()), Entity::Database(d) => AggregateEntity::Database(d.clone()), other => AggregateEntity::Other(format!("{:?}", other)), }; with_mut_session!(test_runner, session_id, |session| async { let mut cursor = match entity { AggregateEntity::Collection(collection) => { collection .aggregate_with_session( self.pipeline.clone(), self.options.clone(), session, ) .await? } AggregateEntity::Database(db) => { db.aggregate_with_session( self.pipeline.clone(), self.options.clone(), session, ) .await? } AggregateEntity::Other(debug) => { panic!("Cannot execute aggregate on {}", &debug) } }; cursor.stream(session).try_collect::<Vec<Document>>().await }) .await? } None => { let entities = test_runner.entities.read().await; let cursor = match entities.get(id).unwrap() { Entity::Collection(collection) => { collection .aggregate(self.pipeline.clone(), self.options.clone()) .await? } Entity::Database(db) => { db.aggregate(self.pipeline.clone(), self.options.clone()) .await? } other => panic!("Cannot execute aggregate on {:?}", &other), }; cursor.try_collect::<Vec<Document>>().await? } }; Ok(Some(Bson::from(result).into())) } .boxed() } fn returns_root_documents(&self) -> bool { true } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct Distinct { field_name: String, filter: Option<Document>, session: Option<String>, #[serde(flatten)] options: DistinctOptions, } impl TestOperation for Distinct { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| async { collection .distinct_with_session( &self.field_name, self.filter.clone(), self.options.clone(), session, ) .await }) .await? } None => { collection .distinct(&self.field_name, self.filter.clone(), self.options.clone()) .await? } }; Ok(Some(Bson::Array(result).into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct CountDocuments { filter: Document, session: Option<String>, #[serde(flatten)] options: CountOptions, } impl TestOperation for CountDocuments { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| async { collection .count_documents_with_session( self.filter.clone(), self.options.clone(), session, ) .await }) .await? } None => { collection .count_documents(self.filter.clone(), self.options.clone()) .await? } }; Ok(Some(Bson::Int64(result.try_into().unwrap()).into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct EstimatedDocumentCount { #[serde(flatten)] options: EstimatedDocumentCountOptions, } impl TestOperation for EstimatedDocumentCount { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = collection .estimated_document_count(self.options.clone()) .await?; Ok(Some(Bson::Int64(result.try_into().unwrap()).into())) } .boxed() } } #[derive(Debug, Default)] pub(super) struct FindOne { filter: Option<Document>, options: FindOneOptions, } // TODO RUST-1364: remove this impl and derive Deserialize instead impl<'de> Deserialize<'de> for FindOne { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> { #[derive(Deserialize)] struct Helper { filter: Option<Document>, comment: Option<Bson>, #[serde(flatten)] options: FindOneOptions, } let mut helper = Helper::deserialize(deserializer)?; match helper.comment { Some(Bson::String(string)) => { helper.options.comment = Some(string); } Some(bson) => { helper.options.comment_bson = Some(bson); } _ => {} } Ok(Self { filter: helper.filter, options: helper.options, }) } } impl TestOperation for FindOne { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = collection .find_one(self.filter.clone(), self.options.clone()) .await?; match result { Some(result) => Ok(Some(Bson::from(result).into())), None => Ok(Some(Entity::None)), } } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct ListDatabases { filter: Option<Document>, session: Option<String>, #[serde(flatten)] options: ListDatabasesOptions, } impl TestOperation for ListDatabases { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let client = test_runner.get_client(id).await; let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| async { client .list_databases_with_session( self.filter.clone(), self.options.clone(), session, ) .await }) .await? } None => { client .list_databases(self.filter.clone(), self.options.clone()) .await? } }; Ok(Some(bson::to_bson(&result)?.into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct ListDatabaseNames { filter: Option<Document>, #[serde(flatten)] options: ListDatabasesOptions, } impl TestOperation for ListDatabaseNames { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let client = test_runner.get_client(id).await; let result = client .list_database_names(self.filter.clone(), self.options.clone()) .await?; let result: Vec<Bson> = result.iter().map(|s| Bson::String(s.to_string())).collect(); Ok(Some(Bson::Array(result).into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct ListCollections { filter: Option<Document>, session: Option<String>, #[serde(flatten)] options: ListCollectionsOptions, } impl TestOperation for ListCollections { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let db = test_runner.get_database(id).await; let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| async { let mut cursor = db .list_collections_with_session( self.filter.clone(), self.options.clone(), session, ) .await?; cursor.stream(session).try_collect::<Vec<_>>().await }) .await? } None => { let cursor = db .list_collections(self.filter.clone(), self.options.clone()) .await?; cursor.try_collect::<Vec<_>>().await? } }; Ok(Some(bson::to_bson(&result)?.into())) } .boxed() } fn returns_root_documents(&self) -> bool { true } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct ListCollectionNames { filter: Option<Document>, } impl TestOperation for ListCollectionNames { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let db = test_runner.get_database(id).await; let result = db.list_collection_names(self.filter.clone()).await?; let result: Vec<Bson> = result.iter().map(|s| Bson::String(s.to_string())).collect(); Ok(Some(Bson::from(result).into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct ReplaceOne { filter: Document, replacement: Document, #[serde(flatten)] options: ReplaceOptions, } impl TestOperation for ReplaceOne { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = collection .replace_one( self.filter.clone(), self.replacement.clone(), self.options.clone(), ) .await?; let result = to_bson(&result)?; Ok(Some(result.into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct FindOneAndUpdate { filter: Document, update: UpdateModifications, session: Option<String>, #[serde(flatten)] options: FindOneAndUpdateOptions, } impl TestOperation for FindOneAndUpdate { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| async { collection .find_one_and_update_with_session( self.filter.clone(), self.update.clone(), self.options.clone(), session, ) .await }) .await? } None => { collection .find_one_and_update( self.filter.clone(), self.update.clone(), self.options.clone(), ) .await? } }; let result = to_bson(&result)?; Ok(Some(result.into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct FindOneAndReplace { filter: Document, replacement: Document, #[serde(flatten)] options: FindOneAndReplaceOptions, } impl TestOperation for FindOneAndReplace { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = collection .find_one_and_replace( self.filter.clone(), self.replacement.clone(), self.options.clone(), ) .await?; let result = to_bson(&result)?; Ok(Some(result.into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct FindOneAndDelete { filter: Document, #[serde(flatten)] options: FindOneAndDeleteOptions, } impl TestOperation for FindOneAndDelete { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let result = collection .find_one_and_delete(self.filter.clone(), self.options.clone()) .await?; let result = to_bson(&result)?; Ok(Some(result.into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct FailPointCommand { fail_point: FailPoint, client: String, } impl TestOperation for FailPointCommand { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let client = test_runner.get_client(&self.client).await; let guard = self .fail_point .enable(&client, Some(ReadPreference::Primary.into())) .await .unwrap(); test_runner.fail_point_guards.write().await.push(guard); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct TargetedFailPoint { fail_point: FailPoint, session: String, } impl TestOperation for TargetedFailPoint { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let selection_criteria = with_mut_session!(test_runner, self.session.as_str(), |session| async { session .transaction .pinned_mongos() .cloned() .unwrap_or_else(|| panic!("ClientSession not pinned")) }) .await; let fail_point_guard = test_runner .internal_client .enable_failpoint(self.fail_point.clone(), Some(selection_criteria)) .await .unwrap(); test_runner .fail_point_guards .write() .await .push(fail_point_guard); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertCollectionExists { collection_name: String, database_name: String, } impl TestOperation for AssertCollectionExists { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let db = test_runner.internal_client.database(&self.database_name); let names = db.list_collection_names(None).await.unwrap(); assert!(names.contains(&self.collection_name)); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertCollectionNotExists { collection_name: String, database_name: String, } impl TestOperation for AssertCollectionNotExists { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let db = test_runner.internal_client.database(&self.database_name); let names = db.list_collection_names(None).await.unwrap(); assert!(!names.contains(&self.collection_name)); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct CreateCollection { collection: String, #[serde(flatten)] options: CreateCollectionOptions, session: Option<String>, } impl TestOperation for CreateCollection { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let database = test_runner.get_database(id).await; if let Some(session_id) = &self.session { with_mut_session!(test_runner, session_id, |session| async { database .create_collection_with_session( &self.collection, self.options.clone(), session, ) .await }) .await?; } else { database .create_collection(&self.collection, self.options.clone()) .await?; } Ok(Some(Entity::Collection( database.collection(&self.collection), ))) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct DropCollection { collection: String, #[serde(flatten)] options: DropCollectionOptions, session: Option<String>, } impl TestOperation for DropCollection { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let database = test_runner.get_database(id).await; let collection = database.collection::<Document>(&self.collection).clone(); if let Some(session_id) = &self.session { with_mut_session!(test_runner, session_id, |session| async { collection .drop_with_session(self.options.clone(), session) .await }) .await?; } else { collection.drop(self.options.clone()).await?; } Ok(None) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct RunCommand { command: Document, // We don't need to use this field, but it needs to be included during deserialization so that // we can use the deny_unknown_fields tag. #[serde(rename = "commandName")] _command_name: String, read_preference: Option<SelectionCriteria>, session: Option<String>, } impl TestOperation for RunCommand { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let command = self.command.clone(); let db = test_runner.get_database(id).await; let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| async { db.run_command_with_session(command, self.read_preference.clone(), session) .await }) .await? } None => { db.run_command(command, self.read_preference.clone()) .await? } }; let result = to_bson(&result)?; Ok(Some(result.into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct RunCursorCommand { command: Document, // We don't need to use this field, but it needs to be included during deserialization so that // we can use the deny_unknown_fields tag. #[serde(rename = "commandName")] _command_name: String, #[serde(flatten)] options: RunCursorCommandOptions, session: Option<String>, } impl TestOperation for RunCursorCommand { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let command = self.command.clone(); let db = test_runner.get_database(id).await; let options = self.options.clone(); let result = match &self.session { Some(session_id) => { with_mut_session!(test_runner, session_id, |session| async { let mut cursor = db .run_cursor_command_with_session(command, options, session) .await?; cursor.stream(session).try_collect::<Vec<_>>().await }) .await? } None => { let cursor = db.run_cursor_command(command, options).await?; cursor.try_collect::<Vec<_>>().await? } }; Ok(Some(bson::to_bson(&result)?.into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CreateCommandCursor { command: Document, // We don't need to use this field, but it needs to be included during deserialization so that // we can use the deny_unknown_fields tag. #[serde(rename = "commandName")] _command_name: String, #[serde(flatten)] options: RunCursorCommandOptions, session: Option<String>, } impl TestOperation for CreateCommandCursor { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let command = self.command.clone(); let db = test_runner.get_database(id).await; let options = self.options.clone(); match &self.session { Some(session_id) => { let mut ses_cursor = None; with_mut_session!(test_runner, session_id, |session| async { ses_cursor = Some( db.run_cursor_command_with_session(command, options, session) .await, ); }) .await; let test_cursor = TestCursor::Session { cursor: ses_cursor.unwrap().unwrap(), session_id: session_id.clone(), }; Ok(Some(Entity::Cursor(test_cursor))) } None => { let doc_cursor = db.run_cursor_command(command, options).await?; let test_cursor = TestCursor::Normal(Mutex::new(doc_cursor)); Ok(Some(Entity::Cursor(test_cursor))) } } } .boxed() } fn returns_root_documents(&self) -> bool { false } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct EndSession {} impl TestOperation for EndSession { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { with_mut_session!(test_runner, id, |session| async { session.client_session.take(); }) .await; runtime::delay_for(Duration::from_secs(1)).await; Ok(None) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertSessionTransactionState { session: String, state: String, } impl TestOperation for AssertSessionTransactionState { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let session_state = with_mut_session!(test_runner, self.session.as_str(), |session| async { match &session.transaction.state { TransactionState::None => "none", TransactionState::Starting => "starting", TransactionState::InProgress => "inprogress", TransactionState::Committed { data_committed: _ } => "committed", TransactionState::Aborted => "aborted", } }) .await; assert_eq!(session_state, self.state); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertSessionPinned { session: String, } impl TestOperation for AssertSessionPinned { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let is_pinned = with_mut_session!(test_runner, self.session.as_str(), |session| async { session.transaction.pinned_mongos().is_some() }) .await; assert!(is_pinned); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertSessionUnpinned { session: String, } impl TestOperation for AssertSessionUnpinned { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let is_pinned = with_mut_session!(test_runner, self.session.as_str(), |session| { async move { session.transaction.pinned_mongos().is_some() } }) .await; assert!(!is_pinned); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertDifferentLsidOnLastTwoCommands { client: String, } impl TestOperation for AssertDifferentLsidOnLastTwoCommands { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let entities = test_runner.entities.read().await; let client = entities.get(&self.client).unwrap().as_client(); let events = client.get_all_command_started_events(); let lsid1 = events[events.len() - 1].command.get("lsid").unwrap(); let lsid2 = events[events.len() - 2].command.get("lsid").unwrap(); assert_ne!(lsid1, lsid2); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertSameLsidOnLastTwoCommands { client: String, } impl TestOperation for AssertSameLsidOnLastTwoCommands { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let entities = test_runner.entities.read().await; let client = entities.get(&self.client).unwrap().as_client(); client.sync_workers().await; let events = client.get_all_command_started_events(); let lsid1 = events[events.len() - 1].command.get("lsid").unwrap(); let lsid2 = events[events.len() - 2].command.get("lsid").unwrap(); assert_eq!(lsid1, lsid2); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertSessionDirty { session: String, } impl TestOperation for AssertSessionDirty { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let dirty = with_mut_session!(test_runner, self.session.as_str(), |session| { async move { session.is_dirty() }.boxed() }) .await; assert!(dirty); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertSessionNotDirty { session: String, } impl TestOperation for AssertSessionNotDirty { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let dirty = with_mut_session!(test_runner, self.session.as_str(), |session| { async move { session.is_dirty() } }) .await; assert!(!dirty); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct StartTransaction {} impl TestOperation for StartTransaction { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { with_mut_session!(test_runner, id, |session| { async move { session.start_transaction(None).await } }) .await?; Ok(None) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct CommitTransaction {} impl TestOperation for CommitTransaction { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { with_mut_session!(test_runner, id, |session| { async move { session.commit_transaction().await } }) .await?; Ok(None) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AbortTransaction {} impl TestOperation for AbortTransaction { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { with_mut_session!(test_runner, id, |session| { async move { session.abort_transaction().await } }) .await?; Ok(None) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub(super) struct CreateIndex { session: Option<String>, keys: Document, name: Option<String>, } impl TestOperation for CreateIndex { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let options = IndexOptions::builder().name(self.name.clone()).build(); let index = IndexModel::builder() .keys(self.keys.clone()) .options(options) .build(); let collection = test_runner.get_collection(id).await; let name = match self.session { Some(ref session_id) => { with_mut_session!(test_runner, session_id, |session| { async move { collection .create_index_with_session(index, None, session) .await .map(|model| model.index_name) } }) .await? } None => collection.create_index(index, None).await?.index_name, }; Ok(Some(Bson::String(name).into())) } .boxed() } } #[derive(Debug, Deserialize)] pub(super) struct ListIndexes { session: Option<String>, #[serde(flatten)] options: ListIndexesOptions, } impl TestOperation for ListIndexes { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let indexes: Vec<IndexModel> = match self.session { Some(ref session) => { with_mut_session!(test_runner, session, |session| { async { collection .list_indexes_with_session(self.options.clone(), session) .await? .stream(session) .try_collect() .await } }) .await? } None => { collection .list_indexes(self.options.clone()) .await? .try_collect() .await? } }; let indexes: Vec<Document> = indexes .iter() .map(|index| bson::to_document(index).unwrap()) .collect(); Ok(Some(Bson::from(indexes).into())) } .boxed() } } #[derive(Debug, Deserialize)] pub(super) struct ListIndexNames { session: Option<String>, } impl TestOperation for ListIndexNames { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let collection = test_runner.get_collection(id).await; let names = match self.session { Some(ref session) => { with_mut_session!(test_runner, session.as_str(), |s| { async move { collection.list_index_names_with_session(s).await } }) .await? } None => collection.list_index_names().await?, }; Ok(Some(Bson::from(names).into())) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertIndexExists { collection_name: String, database_name: String, index_name: String, } impl TestOperation for AssertIndexExists { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let coll = test_runner .internal_client .database(&self.database_name) .collection::<Document>(&self.collection_name); let names = coll.list_index_names().await.unwrap(); assert!(names.contains(&self.index_name)); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertIndexNotExists { collection_name: String, database_name: String, index_name: String, } impl TestOperation for AssertIndexNotExists { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let coll = test_runner .internal_client .database(&self.database_name) .collection::<Document>(&self.collection_name); match coll.list_index_names().await { Ok(indexes) => assert!(!indexes.contains(&self.index_name)), // a namespace not found error indicates that the index does not exist Err(err) => assert_eq!(err.sdam_code(), Some(26)), } } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct IterateUntilDocumentOrError {} impl TestOperation for IterateUntilDocumentOrError { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { // A `SessionCursor` also requires a `&mut Session`, which would cause conflicting // borrows, so take the cursor from the map and return it after execution instead. let mut cursor = test_runner.take_cursor(id).await; let next = match &mut cursor { TestCursor::Normal(cursor) => { let mut cursor = cursor.lock().await; cursor.next().await } TestCursor::Session { cursor, session_id } => { cursor .next( test_runner .entities .write() .await .get_mut(session_id) .unwrap() .as_mut_session_entity(), ) .await } TestCursor::ChangeStream(stream) => { let mut stream = stream.lock().await; stream.next().await.map(|res| { res.map(|ev| match bson::to_bson(&ev) { Ok(Bson::Document(doc)) => doc, _ => panic!("invalid serialization result"), }) }) } TestCursor::Closed => None, }; test_runner.return_cursor(id, cursor).await; next.transpose() .map(|opt| opt.map(|doc| Entity::Bson(Bson::Document(doc)))) } .boxed() } fn returns_root_documents(&self) -> bool { true } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct Close {} impl TestOperation for Close { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let mut entities = test_runner.entities.write().await; let target_entity = entities.get(id).unwrap(); match target_entity { Entity::Client(_) => { let client = entities.get_mut(id).unwrap().as_mut_client(); let closed_client_topology_id = client.topology_id; client.client = None; let mut entities_to_remove = vec![]; for (key, value) in entities.iter() { match value { // skip clients so that we don't remove the client entity itself from // the map: we want to preserve it so we can // access the other data stored on the entity. Entity::Client(_) => {} _ => { if value.client_topology_id().await == Some(closed_client_topology_id) { entities_to_remove.push(key.clone()); } } } } for entity_id in entities_to_remove { entities.remove(&entity_id); } Ok(None) } Entity::Cursor(_) => { let cursor = entities.get_mut(id).unwrap().as_mut_cursor(); let rx = cursor.make_kill_watcher().await; *cursor = TestCursor::Closed; drop(entities); let _ = rx.await; Ok(None) } _ => panic!( "Unsupported entity {:?} for close operation; expected Client or Cursor", target_entity ), } } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertNumberConnectionsCheckedOut { client: String, connections: u32, } impl TestOperation for AssertNumberConnectionsCheckedOut { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let client = test_runner.get_client(&self.client).await; client.sync_workers().await; assert_eq!(client.connections_checked_out(), self.connections); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct CreateChangeStream { pipeline: Vec<Document>, #[serde(flatten)] options: Option<ChangeStreamOptions>, } impl TestOperation for CreateChangeStream { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let entities = test_runner.entities.read().await; let target = entities.get(id).unwrap(); let stream = match target { Entity::Client(ce) => { ce.watch(self.pipeline.clone(), self.options.clone()) .await? } Entity::Database(db) => { db.watch(self.pipeline.clone(), self.options.clone()) .await? } Entity::Collection(coll) => { coll.watch(self.pipeline.clone(), self.options.clone()) .await? } _ => panic!("Invalid entity for createChangeStream"), }; Ok(Some(Entity::Cursor(TestCursor::ChangeStream(Mutex::new( stream.with_type::<Document>(), ))))) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct RenameCollection { to: String, } impl TestOperation for RenameCollection { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let target = test_runner.get_collection(id).await; let ns = target.namespace(); let mut to_ns = ns.clone(); to_ns.coll = self.to.clone(); let cmd = doc! { "renameCollection": crate::bson::to_bson(&ns)?, "to": crate::bson::to_bson(&to_ns)?, }; let admin = test_runner.internal_client.database("admin"); admin.run_command(cmd, None).await?; Ok(None) } .boxed() } } macro_rules! report_error { ($loop:expr, $error:expr, $entities:expr) => {{ let error = format!("{:?}", $error); report_error_or_failure!( $loop.store_errors_as_entity, $loop.store_failures_as_entity, error, $entities ); }}; } macro_rules! report_failure { ($loop:expr, $name:expr, $actual:expr, $expected:expr, $entities:expr) => {{ let error = format!( "{} error: got {:?}, expected {:?}", $name, $actual, $expected ); report_error_or_failure!( $loop.store_failures_as_entity, $loop.store_errors_as_entity, error, $entities ); }}; } macro_rules! report_error_or_failure { ($first_option:expr, $second_option:expr, $error:expr, $entities:expr) => {{ let id = if let Some(ref id) = $first_option { id } else if let Some(ref id) = $second_option { id } else { panic!( "At least one of storeErrorsAsEntity and storeFailuresAsEntity must be specified \ for a loop operation" ); }; match $entities.get_mut(id) { Some(Entity::Bson(Bson::Array(array))) => { let doc = doc! { "error": $error, "time": OffsetDateTime::now_utc().unix_timestamp(), }; array.push(doc.into()); } _ => panic!("Test runner should contain a Bson::Array entity for {}", id), }; // The current iteration should end if an error or failure is encountered. break; }}; } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct Loop { operations: Vec<Operation>, store_errors_as_entity: Option<String>, store_failures_as_entity: Option<String>, store_successes_as_entity: Option<String>, store_iterations_as_entity: Option<String>, } impl TestOperation for Loop { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { if let Some(id) = &self.store_errors_as_entity { let errors = Bson::Array(vec![]); test_runner.insert_entity(id, errors).await; } if let Some(id) = &self.store_failures_as_entity { let failures = Bson::Array(vec![]); test_runner.insert_entity(id, failures).await; } if let Some(id) = &self.store_successes_as_entity { let successes = Bson::Int64(0); test_runner.insert_entity(id, successes).await; } if let Some(id) = &self.store_iterations_as_entity { let iterations = Bson::Int64(0); test_runner.insert_entity(id, iterations).await; } let continue_looping = Arc::new(AtomicBool::new(true)); let continue_looping_handle = continue_looping.clone(); ctrlc::set_handler(move || { continue_looping_handle.store(false, Ordering::SeqCst); }) .expect("Failed to set ctrl-c handler"); while continue_looping.load(Ordering::SeqCst) { for operation in &self.operations { let result = match operation.object { OperationObject::TestRunner => { panic!("Operations within a loop must be entity operations") } OperationObject::Entity(ref id) => { operation.execute_entity_operation(id, test_runner).await } }; let mut entities = test_runner.entities.write().await; match (result, &operation.expectation) { ( Ok(entity), Expectation::Result { expected_value, save_as_entity, }, ) => { if let Some(expected_value) = expected_value { let actual_value = match entity { Some(Entity::Bson(ref actual_value)) => Some(actual_value), None => None, _ => { report_failure!( self, &operation.name, entity, expected_value, &mut entities ); } }; if results_match( actual_value, expected_value, operation.returns_root_documents(), Some(&entities), ) .is_ok() { self.report_success(&mut entities); } else { report_failure!( self, &operation.name, actual_value, expected_value, &mut entities ); } } else { self.report_success(&mut entities); } if let (Some(entity), Some(id)) = (entity, save_as_entity) { entities.insert(id.to_string(), entity); } } (Ok(result), Expectation::Error(ref expected_error)) => { report_failure!( self, &operation.name, result, expected_error, &mut entities ); } (Ok(_), Expectation::Ignore) => { self.report_success(&mut entities); } (Err(error), Expectation::Error(ref expected_error)) => { match expected_error.verify_result(&error, operation.name.as_str()) { Ok(_) => self.report_success(&mut entities), Err(e) => report_error_or_failure!( self.store_failures_as_entity, self.store_errors_as_entity, e, &mut entities ), } } (Err(error), Expectation::Result { .. } | Expectation::Ignore) => { report_error!(self, error, &mut entities); } } } let mut entities = test_runner.entities.write().await; self.report_iteration(&mut entities); } } .boxed() } } impl Loop { fn report_iteration(&self, entities: &mut EntityMap) { Self::increment_count(self.store_iterations_as_entity.as_ref(), entities) } fn report_success(&self, test_runner: &mut EntityMap) { Self::increment_count(self.store_successes_as_entity.as_ref(), test_runner) } fn increment_count(id: Option<&String>, entities: &mut EntityMap) { if let Some(id) = id { match entities.get_mut(id) { Some(Entity::Bson(Bson::Int64(count))) => *count += 1, _ => panic!("Test runner should contain a Bson::Int64 entity for {}", id), } } } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct RunOnThread { thread: String, operation: Arc<Operation>, } impl TestOperation for RunOnThread { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async { let thread = test_runner.get_thread(self.thread.as_str()).await; thread.run_operation(self.operation.clone()); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct WaitForThread { thread: String, } impl TestOperation for WaitForThread { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async { let thread = test_runner.get_thread(self.thread.as_str()).await; thread.wait().await.unwrap_or_else(|e| { panic!("thread {:?} did not exit successfully: {}", self.thread, e) }); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertEventCount { client: String, event: ExpectedEvent, count: usize, } impl TestOperation for AssertEventCount { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async { let client = test_runner.get_client(self.client.as_str()).await; let entities = test_runner.entities.clone(); let actual_events = client .observer .lock() .await .matching_events(&self.event, entities) .await; assert_eq!( actual_events.len(), self.count, "expected to see {} events matching: {:#?}, instead saw: {:#?}", self.count, self.event, actual_events ); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct WaitForEvent { client: String, event: ExpectedEvent, count: usize, } impl TestOperation for WaitForEvent { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async { let client = test_runner.get_client(self.client.as_str()).await; let entities = test_runner.entities.clone(); client .observer .lock() .await .wait_for_matching_events(&self.event, self.count, entities) .await .unwrap(); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct RecordTopologyDescription { id: String, client: String, } impl TestOperation for RecordTopologyDescription { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async { let client = test_runner.get_client(&self.client).await; let description = client.topology_description(); test_runner.insert_entity(&self.id, description).await; } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct AssertTopologyType { topology_description: String, topology_type: TopologyType, } impl TestOperation for AssertTopologyType { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async { let td = test_runner .get_topology_description(&self.topology_description) .await; assert_eq!(td.topology_type, self.topology_type); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct WaitForPrimaryChange { client: String, prior_topology_description: String, #[serde(rename = "timeoutMS")] timeout_ms: Option<u64>, } impl TestOperation for WaitForPrimaryChange { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { async move { let client = test_runner.get_client(&self.client).await; let td = test_runner .get_topology_description(&self.prior_topology_description) .await; let old_primary = td.servers_with_type(&[ServerType::RsPrimary]).next(); let timeout = Duration::from_millis(self.timeout_ms.unwrap_or(10_000)); runtime::timeout(timeout, async { let mut watcher = client.topology().watch(); loop { let latest = watcher.observe_latest(); if let Some(primary) = latest.description.primary() { if Some(primary) != old_primary { return; } } watcher.wait_for_update(None).await; } }) .await .unwrap(); } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct Wait { ms: u64, } impl TestOperation for Wait { fn execute_test_runner_operation<'a>( &'a self, _test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { runtime::delay_for(Duration::from_millis(self.ms)).boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct CreateEntities { entities: Vec<TestFileEntity>, } impl TestOperation for CreateEntities { fn execute_test_runner_operation<'a>( &'a self, test_runner: &'a TestRunner, ) -> BoxFuture<'a, ()> { test_runner .populate_entity_map(&self.entities[..], "createEntities operation") .boxed() } fn test_file_entities(&self) -> Option<&Vec<TestFileEntity>> { Some(&self.entities) } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct Download { id: Bson, } impl TestOperation for Download { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let bucket = test_runner.get_bucket(id).await; // First, read via the download_to_writer API. let mut buf: Vec<u8> = vec![]; bucket .download_to_futures_0_3_writer(self.id.clone(), &mut buf) .await?; let writer_data = hex::encode(buf); // Next, read via the open_download_stream API. let mut buf: Vec<u8> = vec![]; let mut stream = bucket.open_download_stream(self.id.clone()).await?; stream.read_to_end(&mut buf).await?; let stream_data = hex::encode(buf); // Assert that both APIs returned the same data. assert_eq!(writer_data, stream_data); Ok(Some(Entity::Bson(writer_data.into()))) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct DownloadByName { filename: String, #[serde(flatten)] options: GridFsDownloadByNameOptions, } impl TestOperation for DownloadByName { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let bucket = test_runner.get_bucket(id).await; // First, read via the download_to_writer API. let mut buf: Vec<u8> = vec![]; bucket .download_to_futures_0_3_writer_by_name( self.filename.clone(), &mut buf, self.options.clone(), ) .await?; let writer_data = hex::encode(buf); // Next, read via the open_download_stream API. let mut buf: Vec<u8> = vec![]; let mut stream = bucket .open_download_stream_by_name(self.filename.clone(), self.options.clone()) .await?; stream.read_to_end(&mut buf).await?; let stream_data = hex::encode(buf); // Assert that both APIs returned the same data. assert_eq!(writer_data, stream_data); Ok(Some(Entity::Bson(writer_data.into()))) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct Delete { id: Bson, } impl TestOperation for Delete { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let bucket = test_runner.get_bucket(id).await; bucket.delete(self.id.clone()).await?; Ok(None) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct Upload { source: Document, filename: String, // content_type and disableMD5 are deprecated and no longer supported. // Options included for deserialization. #[serde(rename = "contentType")] _content_type: Option<String>, #[serde(rename = "disableMD5")] _disable_md5: Option<bool>, #[serde(flatten)] options: GridFsUploadOptions, } impl TestOperation for Upload { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let bucket = test_runner.get_bucket(id).await; let hex_string = self.source.get("$$hexBytes").unwrap().as_str().unwrap(); let bytes = hex::decode(hex_string).unwrap(); let id = bucket .upload_from_futures_0_3_reader( self.filename.clone(), &bytes[..], self.options.clone(), ) .await?; Ok(Some(Entity::Bson(id.into()))) } .boxed() } } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(super) struct IterateOnce {} impl TestOperation for IterateOnce { fn execute_entity_operation<'a>( &'a self, id: &'a str, test_runner: &'a TestRunner, ) -> BoxFuture<'a, Result<Option<Entity>>> { async move { let mut cursor = test_runner.take_cursor(id).await; match &mut cursor { TestCursor::Normal(cursor) => { let mut cursor = cursor.lock().await; cursor.try_advance().await?; } TestCursor::Session { cursor, session_id } => { cursor .try_advance( test_runner .entities .write() .await .get_mut(session_id) .unwrap() .as_mut_session_entity(), ) .await?; } TestCursor::ChangeStream(change_stream) => { let mut change_stream = change_stream.lock().await; change_stream.next_if_any().await?; } TestCursor::Closed => panic!("Attempted to call IterateOnce on a closed cursor"), } test_runner.return_cursor(id, cursor).await; Ok(None) } .boxed() } } #[derive(Debug, Deserialize)] pub(super) struct UnimplementedOperation { _name: String, } impl TestOperation for UnimplementedOperation {}
use ::image; pub use graphics::*; use image::RgbaImage; use opengl_graphics::{GlGraphics, Texture, TextureSettings}; use piston::input::RenderArgs; use crate::caengine::SandBox; pub struct CaRender { width: u32, height: u32, } impl CaRender { pub fn render_sandbox(&mut self, sandbox: &SandBox, gl: &mut GlGraphics, args: &RenderArgs) { //Turn the buffer into a texture let cell_tex = { let img: image::RgbaImage = image::ImageBuffer::from_fn( self.width as u32, self.height as u32, |x, y| sandbox.to_rgba(x as i32, y as i32)); Texture::from_image( &img, &TextureSettings::new(), ) }; gl.draw(args.viewport(), |c, g| { // Clear the screen graphics::clear(graphics::color::TRANSPARENT, g); //Draw image Image::new().draw(&cell_tex, &c.draw_state, c.transform, g); }); } pub fn new(width: u32, height: u32) -> CaRender { CaRender { width, height, } } }
use super::bit_search::{find_last_one}; pub struct ForwardOnesIterator <'a> { pub words : &'a[u64], pub current_word : u64, pub word_pos : usize, pub word_limit : usize, pub end_mask : u64, } impl <'a> Iterator for ForwardOnesIterator<'a> { type Item = usize; fn next(&mut self) -> Option<usize> { if self.current_word == 0 { if self.word_pos >= self.word_limit { return None; } self.word_pos += 1; self.current_word = self.words[self.word_pos]; while self.word_pos < self.word_limit { self.current_word = self.words[self.word_pos]; if self.current_word != 0 { break; } self.word_pos += 1; } if self.word_pos == self.word_limit { self.current_word &= self.end_mask; } if self.current_word == 0 { return None; } } let b = self.current_word.trailing_zeros() as usize; self.current_word ^= 1u64 << b; return Some((self.word_pos << 6) + b); } } #[doc=" Returns an Iterator of `usize` that enumerates all the bit positions greater than or equal to `offset` and less than `limit`, in ascending order, which contain 1. "] pub fn iter_ones<'a>(words : &'a[u64], offset : usize, limit : usize) -> ForwardOnesIterator<'a> { let word_start = offset >> 6; let bit_start = offset & 0x3f; let bit_limit = (limit - 1) & 0x3f; let word_limit = (limit - 1) >> 6; let start_mask = !((1u64 << bit_start) - 1); let end_mask = if bit_limit == 63 { !0u64 } else {(1u64 << (1 + bit_limit)) - 1}; ForwardOnesIterator { words: words, current_word: words[word_start] & start_mask & (if word_start == word_limit { end_mask } else { !0u64 }), word_pos: word_start, word_limit: word_limit, end_mask: end_mask } } #[test] pub fn test_iter_ones_1() { let bitarray = [0x0004000002000001u64, 0x2000001000000800u64,0x0000800000400000u64,0x0000000000000300u64 ]; let onesarray = [ 0usize, 25, 50, 75, 100, 125, 150, 175, 200, 201 ]; let mut k = 0; let mut vec = Vec::new(); for i in iter_ones(&bitarray, 80, 200) { k += 1; assert!(k < 100); println!("Found a one: {}", i); vec.push(i); } assert_eq!(vec![100usize, 125, 150, 175], vec); vec.clear(); for i in iter_ones(&bitarray, 80, 201) { k += 1; assert!(k < 100); println!("Found a one: {}", i); vec.push(i); } assert_eq!(vec![100usize, 125, 150, 175, 200], vec); vec.clear(); for i in iter_ones(&bitarray, 0, 51) { k += 1; assert!(k < 100); println!("Found a one: {}", i); vec.push(i); } assert_eq!(vec![0usize, 25, 50], vec); vec.clear(); for i in iter_ones(&bitarray, 74, 76) { k += 1; assert!(k < 100); println!("Found a one: {}", i); vec.push(i); } assert_eq!(vec![75usize], vec); vec.clear(); for i in iter_ones(&bitarray, 128, 256) { k += 1; assert!(k < 100); println!("Found a one: {}", i); vec.push(i); } assert_eq!(vec![150usize, 175, 200, 201], vec); } pub struct BackwardOnesIterator <'a> { pub words : &'a[u64], pub offset : usize, pub limit : usize, } impl <'a> Iterator for BackwardOnesIterator<'a> { type Item = usize; fn next(&mut self) -> Option<usize> { match find_last_one(&self.words, self.offset, self.limit) { None => None, Some(next_limit) => { self.limit = next_limit; Some(next_limit) } } } } #[doc=" Returns an Iterator of `usize` that enumerates all the bit positions greater than or equal to `offset` and less than `limit`, in descending order, which contain 1. "] pub fn backward_iter_ones<'a>(words : &'a[u64], offset : usize, limit : usize) -> BackwardOnesIterator<'a> { BackwardOnesIterator { words: words, offset: offset, limit: limit } } #[test] pub fn test_backward_iter_ones_1() { let bitarray = [0x0004000002000001u64, 0x2000001000000800u64,0x0000800000400000u64,0x0000000000000300u64 ]; let onesarray = [ 0usize, 25, 50, 75, 100, 125, 150, 175, 200, 201 ]; let mut vec = Vec::new(); for i in backward_iter_ones(&bitarray, 80, 200) { println!("Found a one: {}", i); vec.push(i); } assert_eq!(vec![175usize, 150, 125, 100], vec); vec.clear(); for i in backward_iter_ones(&bitarray, 0, 51) { println!("Found a one: {}", i); vec.push(i); } assert_eq!(vec![50usize, 25, 0], vec); vec.clear(); for i in backward_iter_ones(&bitarray, 74, 76) { println!("Found a one: {}", i); vec.push(i); } assert_eq!(vec![75usize], vec); vec.clear(); for i in backward_iter_ones(&bitarray, 128, 256) { println!("Found a one: {}", i); vec.push(i); } assert_eq!(vec![201usize, 200, 175, 150], vec); }
fn main() { let string_entries: Vec<&str> = DAYS_INPUT.split(',').collect(); println!("string entries: {:?}", string_entries); let mut int_entries: Vec<i32> = string_entries .iter() .map(|x| x.parse::<i32>().unwrap()) .collect(); // instructions say: // replace position 1 with the value 12 and replace position 2 with the value 2 int_entries[1] = 12; int_entries[2] = 2; all_operations(&mut int_entries); println!("requested value: {}", int_entries[0]); } fn all_operations(o: &mut Vec<i32>) { let mut head = 0; while perform_op(o, head).is_some() { head += 4; } } // "Nothing" returned means we're done fn perform_op(o: &mut Vec<i32>, head: usize) -> Option<()> { match o[head] { 1 => { let dest = o[head + 3] as usize; let src1 = o[head + 1] as usize; let src2 = o[head + 2] as usize; o[dest] = o[src1] + o[src2]; Some(()) } 2 => { let dest = o[head + 3] as usize; let src1 = o[head + 1] as usize; let src2 = o[head + 2] as usize; o[dest] = o[src1] * o[src2]; Some(()) } 99 => None, // done _ => panic!("bad opcode"), // shouldn't happen } } #[cfg(test)] mod tests { use super::*; #[test] fn test_opcodes_1() { let mut opcode = vec![1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]; all_operations(&mut opcode); let expected = vec![3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50]; assert_eq!(opcode, expected); } #[test] fn test_opcodes_2() { let mut opcode = vec![1, 0, 0, 0, 99]; all_operations(&mut opcode); let expected = vec![2, 0, 0, 0, 99]; assert_eq!(opcode, expected); } #[test] fn test_opcodes_3() { let mut opcode = vec![2, 3, 0, 3, 99]; all_operations(&mut opcode); let expected = vec![2, 3, 0, 6, 99]; assert_eq!(opcode, expected); } #[test] fn test_opcodes_4() { let mut opcode = vec![2, 4, 4, 5, 99, 0]; all_operations(&mut opcode); let expected = vec![2, 4, 4, 5, 99, 9801]; assert_eq!(opcode, expected); } #[test] fn test_opcodes_5() { let mut opcode = vec![1, 1, 1, 4, 99, 5, 6, 0, 99]; all_operations(&mut opcode); let expected = vec![30, 1, 1, 4, 2, 5, 6, 0, 99]; assert_eq!(opcode, expected); } } const DAYS_INPUT: &str = r#"1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,9,19,1,19,5,23,2,6,23,27,1,6,27,31,2,31,9,35,1,35,6,39,1,10,39,43,2,9,43,47,1,5,47,51,2,51,6,55,1,5,55,59,2,13,59,63,1,63,5,67,2,67,13,71,1,71,9,75,1,75,6,79,2,79,6,83,1,83,5,87,2,87,9,91,2,9,91,95,1,5,95,99,2,99,13,103,1,103,5,107,1,2,107,111,1,111,5,0,99,2,14,0,0"#;
//! CoIo creation error use std::{error, fmt, io}; /// CoIo creation error type pub struct Error<T> { err: io::Error, data: T, } impl<T> Error<T> { /// create error from io::Error and data pub fn new(err: io::Error, data: T) -> Error<T> { Error { err, data } } /// convert to inner data pub fn into_data(self) -> T { self.data } } impl<T> fmt::Display for Error<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.err.fmt(f) } } impl<T> fmt::Debug for Error<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.err.fmt(f) } } impl<T> From<Error<T>> for io::Error { fn from(err: Error<T>) -> Self { err.err } } impl<T> error::Error for Error<T> { fn cause(&self) -> Option<&dyn error::Error> { self.err.source() } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - TZSC control register"] pub cr: CR, _reserved1: [u8; 0x0c], #[doc = "0x10 - TZSC security configuration register"] pub seccfgr1: SECCFGR1, _reserved2: [u8; 0x0c], #[doc = "0x20 - TZSC privilege configuration register 1"] pub privcfgr1: PRIVCFGR1, _reserved3: [u8; 0x010c], #[doc = "0x130 - Unprivileged Water Mark 1 register"] pub mpcwm1_upwmr: MPCWM1_UPWMR, #[doc = "0x134 - Unprivileged Writable Water Mark 1 register"] pub mpcwm1_upwwmr: MPCWM1_UPWWMR, #[doc = "0x138 - Unprivileged Water Mark 2 register"] pub mpcwm2_upwmr: MPCWM2_UPWMR, _reserved6: [u8; 0x04], #[doc = "0x140 - Unprivileged Water Mark 3 register"] pub mpcwm3_upwmr: MPCWM3_UPWMR, } #[doc = "CR (rw) register accessor: TZSC control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`] module"] pub type CR = crate::Reg<cr::CR_SPEC>; #[doc = "TZSC control register"] pub mod cr; #[doc = "SECCFGR1 (rw) register accessor: TZSC security configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`seccfgr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`seccfgr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`seccfgr1`] module"] pub type SECCFGR1 = crate::Reg<seccfgr1::SECCFGR1_SPEC>; #[doc = "TZSC security configuration register"] pub mod seccfgr1; #[doc = "PRIVCFGR1 (rw) register accessor: TZSC privilege configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privcfgr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`privcfgr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`privcfgr1`] module"] pub type PRIVCFGR1 = crate::Reg<privcfgr1::PRIVCFGR1_SPEC>; #[doc = "TZSC privilege configuration register 1"] pub mod privcfgr1; #[doc = "MPCWM1_UPWMR (rw) register accessor: Unprivileged Water Mark 1 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mpcwm1_upwmr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`mpcwm1_upwmr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mpcwm1_upwmr`] module"] pub type MPCWM1_UPWMR = crate::Reg<mpcwm1_upwmr::MPCWM1_UPWMR_SPEC>; #[doc = "Unprivileged Water Mark 1 register"] pub mod mpcwm1_upwmr; #[doc = "MPCWM1_UPWWMR (rw) register accessor: Unprivileged Writable Water Mark 1 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mpcwm1_upwwmr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`mpcwm1_upwwmr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mpcwm1_upwwmr`] module"] pub type MPCWM1_UPWWMR = crate::Reg<mpcwm1_upwwmr::MPCWM1_UPWWMR_SPEC>; #[doc = "Unprivileged Writable Water Mark 1 register"] pub mod mpcwm1_upwwmr; #[doc = "MPCWM2_UPWMR (rw) register accessor: Unprivileged Water Mark 2 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mpcwm2_upwmr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`mpcwm2_upwmr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mpcwm2_upwmr`] module"] pub type MPCWM2_UPWMR = crate::Reg<mpcwm2_upwmr::MPCWM2_UPWMR_SPEC>; #[doc = "Unprivileged Water Mark 2 register"] pub mod mpcwm2_upwmr; #[doc = "MPCWM3_UPWMR (rw) register accessor: Unprivileged Water Mark 3 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mpcwm3_upwmr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`mpcwm3_upwmr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mpcwm3_upwmr`] module"] pub type MPCWM3_UPWMR = crate::Reg<mpcwm3_upwmr::MPCWM3_UPWMR_SPEC>; #[doc = "Unprivileged Water Mark 3 register"] pub mod mpcwm3_upwmr;
extern crate bitpacker; use std::collections::HashMap; use bitpacker::{BitPacker, BitUnpacker}; #[derive(Debug)] pub struct HuffmanNode { pub key: Option<char>, pub value: usize, left: Option<Box<HuffmanNode>>, right: Option<Box<HuffmanNode>>, } impl HuffmanNode { fn new_leaf(key: char, value: usize) -> HuffmanNode { HuffmanNode { key: Some(key), value: value, left: None, right: None, } } fn new_node(left: Box<HuffmanNode>, right: Box<HuffmanNode>) -> HuffmanNode { HuffmanNode { key: None, value: left.value + right.value, left: Some(left), right: Some(right), } } fn is_leaf(&self) -> bool { self.key.is_some() } } fn find_smallest_node(nodes: &Vec<Box<HuffmanNode>>) -> usize { let mut pos: usize = 0; for i in 0..nodes.len() { if nodes[pos].value > nodes[i].value { pos = i; } } pos } fn count_chars(original: &str) -> HashMap<char, usize> { let mut map = HashMap::new(); for key in original.chars() { *map.entry(key).or_insert(0) += 1; } map } pub fn build_tree(original: &str) -> Box<HuffmanNode> { let hash = count_chars(original); let mut nodes : Vec<Box<HuffmanNode>> = hash.into_iter().map(|t| Box::new(HuffmanNode::new_leaf(t.0, t.1))).collect(); while nodes.len() > 1 { let idx_left = find_smallest_node(&nodes); let left = nodes.remove(idx_left); let idx_right = find_smallest_node(&nodes); let right = nodes.remove(idx_right); nodes.push(Box::new(HuffmanNode::new_node(left, right))); } nodes.remove(0) } struct HuffmanDictionnary { table: HashMap<char, Vec<u8>> } impl HuffmanDictionnary { fn new () -> HuffmanDictionnary { HuffmanDictionnary { table: HashMap::new() } } fn build_table (&mut self, root: &Option<Box<HuffmanNode>>) { let v:Vec<u8> = Vec::new(); self.navigate(&root, v); println!("Built table:\n{:#?}", self.table); } fn navigate (&mut self, node_option: &Option<Box<HuffmanNode>>, v:Vec<u8>) { match *node_option { Some(ref node) => { if node.is_leaf() { self.table.entry(node.key.unwrap()).or_insert(v); } else { let mut vl = v.clone(); vl.push(0); let mut vr = v.clone(); vr.push(1); self.navigate(&node.left, vl); self.navigate(&node.right, vr); } } None => {} } } } pub fn compress(original:&String) -> Vec<u8> { let root = build_tree(&original); let mut table = HuffmanDictionnary::new(); table.build_table(&Some(root)); let mut packer = BitPacker::new(); // First, store the table packer.pack_i8(table.table.keys().len() as u8); // is u8 enough ? for key in table.table.keys() { packer.pack_i8(*key as u8); packer.pack_i8(table.table[&key].len() as u8); packer.pack_bits(&table.table[&key]); } // Then, store the message packer.pack_i32(original.len() as u32); for c in original.chars() { let ref v = table.table[&c]; packer.pack_bits(v); } packer.debug(); packer.flush() } pub fn decompress(compressed: Vec<u8>) -> String { let mut unpacker = BitUnpacker::new(compressed); let table_size = unpacker.read_i8(); let mut map: HashMap<char, Vec<u8>> = HashMap::new(); for _ in 0..table_size { let curr_char = unpacker.read_i8() as u8; let encoding_len = unpacker.read_i8(); let encoded_values = unpacker.read_bits(encoding_len as i32); map.insert(curr_char as char, encoded_values); } let message_length = unpacker.read_i32(); let mut message:String = String::from(""); println!("Decompressed table:\n {:#?}", map); println!("Uncompressed message length: {}", message_length); for _ in 0..message_length { for k in map.keys() { let ref curr_bits = map[k]; let peeked = unpacker.peek(curr_bits.len() as i32); if peeked.len() == curr_bits.len() && peeked.iter().zip(curr_bits).all(|(a,b)| { a == b}) { // println!("{}", *k); message.push(*k); unpacker.read_bits(curr_bits.len() as i32); break; } } } message } #[cfg(test)] mod tests { use super::*; #[test] fn test_count_chars(){ let s = String::from("abbcccc"); let counts = count_chars(&s); assert_eq!(3, counts.keys().len()); assert_eq!(1, counts[&'a']); assert_eq!(2, counts[&'b']); assert_eq!(4, counts[&'c']); } #[test] fn test_building_table(){ let a = HuffmanNode::new_leaf('a', 1); let b = HuffmanNode::new_leaf('b', 2); let c = HuffmanNode::new_leaf('c', 4); let ab = HuffmanNode::new_node(Box::new(a), Box::new(b)); let root = HuffmanNode::new_node(Box::new(ab), Box::new(c)); let mut table = HuffmanDictionnary::new(); table.build_table(&Some(Box::new(root))); assert_eq!(3, table.table.keys().len()); assert_eq!(vec![0, 0], table.table[&'a']); assert_eq!(vec![0, 1], table.table[&'b']); assert_eq!(vec![1], table.table[&'c']); } #[test] fn test_building_tree (){ let tree = build_tree("abbcccc"); assert_eq!(&tree.left.as_ref().unwrap().left.as_ref().unwrap().key, &Some('a')); assert_eq!(&tree.left.as_ref().unwrap().right.as_ref().unwrap().key, &Some('b')); assert_eq!(&tree.right.as_ref().unwrap().key, &Some('c')); } #[test] fn test_compress_decompress (){ let abbcccc = String::from("abbcccc"); let plop = String::from("plop"); assert_eq!(abbcccc, decompress(compress(&abbcccc))); assert_eq!(plop, decompress(compress(&plop))); } }
use crate::SizeError; use std::{fmt, str::FromStr}; #[cfg(feature = "serde_de")] use serde::{de, Deserialize, Deserializer, Serialize}; #[derive(Debug, PartialEq, Copy, Clone, Default)] #[cfg_attr(feature = "serde_de", derive(Serialize))] pub enum Size { Large, Medium, #[default] Small, } impl fmt::Display for Size { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s = match self { Size::Large => "Large", Size::Medium => "Medium", Size::Small => "Small", }; write!(f, "{}", s) } } #[cfg(feature = "serde_de")] impl<'de> Deserialize<'de> for Size { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; Size::from_str(s.as_str()).map_err(de::Error::custom) } } impl FromStr for Size { type Err = SizeError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_lowercase().as_ref() { "large" | "l" => Ok(Size::Large), "medium" | "m" => Ok(Size::Medium), "small" | "s" => Ok(Size::Small), _ => Err(SizeError {}), } } }
use winit::event::{Event, VirtualKeyCode, MouseButton, WindowEvent, DeviceEvent, KeyboardInput, ElementState}; use winit::dpi::PhysicalPosition; use serde::{Serialize, Deserialize}; use crate::geometry2d::Point; use crate::impl_ron_asset; use crate::event; // ------------------------------------------------------------------------------------------------- #[derive(Copy, Clone, PartialEq, Default, Debug)] pub struct Axis2 { pub x: f32, pub y: f32, } pub trait InputActions { fn end_frame(&mut self); fn set_action_state(&mut self, target: &str, state: ActionState); } #[derive(Copy, Clone, PartialEq, Debug)] pub enum InputState { Button(bool), Axis1(f32), Axis2(Axis2), } impl InputState { fn to_button(self) -> bool { match self { InputState::Button(b) => b, InputState::Axis1(v) => v.abs() >= 0.5, InputState::Axis2(_) => panic!("axis2 input can't be bound to button action"), } } fn to_axis1(self) -> f32 { match self { InputState::Button(b) => if b { 1.0 } else { 0.0 }, InputState::Axis1(v) => v, InputState::Axis2(_) => panic!("axis2 input can't be bound to axis1 action"), } } fn to_axis2(self) -> Axis2 { match self { InputState::Button(_) => panic!("button input can't be bound to axis2 action"), InputState::Axis1(v) => Axis2 { x: v, y: 0.0 }, InputState::Axis2(v) => v, } } } #[derive(Clone)] pub struct ActionState { state: InputState, mouse_position: Option<Point>, } impl ActionState { fn new(state: InputState) -> ActionState { ActionState { state, mouse_position: None } } fn new_button() -> ActionState { Self::new(InputState::Button(false)) } fn set_mouse_position(&mut self, mouse_position: PhysicalPosition<f64>) { let point = Point::nearest(mouse_position.x as f32, mouse_position.y as f32); self.mouse_position = Some(point); } } pub struct Action<T> { state: T, changed: bool, } impl<T> Action<T> { pub fn end_frame(&mut self) { self.changed = false; } } impl<T> Action<T> where T: Copy { pub fn get(&self) -> T { self.state } } impl<T> Action<T> where T: PartialEq { fn set_state_value(&mut self, state: T) { if self.state != state { self.state = state; self.changed = true; } } } impl<T> Default for Action<T> where T: Default { fn default() -> Action<T> { Action { state: T::default(), changed: false } } } impl Action<bool> { pub fn set_state(&mut self, state: ActionState) { self.set_state_value(state.state.to_button()); } pub fn pressed(&self) -> bool { self.state && self.changed } pub fn released(&self) -> bool { !self.state && self.changed } } impl Action<f32> { pub fn set_state(&mut self, state: ActionState) { self.set_state_value(state.state.to_axis1()); } } impl Action<Axis2> { pub fn set_state(&mut self, state: ActionState) { self.set_state_value(state.state.to_axis2()); } } #[derive(Default)] pub struct CursorAction { button: Action<bool>, position: Point, } impl CursorAction { pub fn get(&self) -> bool { self.button.get() } pub fn pressed(&self) -> bool { self.button.pressed() } pub fn released(&self) -> bool { self.button.released() } pub fn position(&self) -> Point { self.position } pub fn end_frame(&mut self) { self.button.end_frame(); } pub fn set_state(&mut self, state: ActionState) { self.position = state.mouse_position.expect("only mouse buttons can be bound to CursorAction"); self.button.set_state(state); } } // ------------------------------------------------------------------------------------------------- trait Binding { fn event(&mut self, event: &Event<()>) -> bool; fn state(&self) -> ActionState; } #[derive(Serialize, Deserialize)] pub struct KeyboardBinding { key: VirtualKeyCode, #[serde(skip)] pressed: bool, } impl Binding for KeyboardBinding { fn event(&mut self, event: &Event<()>) -> bool { if let Event::WindowEvent { event: WindowEvent::KeyboardInput { input: KeyboardInput { state, virtual_keycode, .. }, .. }, .. } = event { if *virtual_keycode == Some(self.key) { self.pressed = *state == ElementState::Pressed; return true; } } false } fn state(&self) -> ActionState { ActionState::new(InputState::Button(self.pressed)) } } #[derive(Copy, Clone, Eq, PartialEq, Debug)] enum CompositeDirection { Up, Down, Left, Right, } impl CompositeDirection { fn to_index(self) -> usize { match self { CompositeDirection::Up => 0, CompositeDirection::Down => 1, CompositeDirection::Left => 2, CompositeDirection::Right => 3, } } } #[derive(Serialize, Deserialize)] pub struct KeyboardCompositeBinding { directions: [KeyboardBinding; 4], } impl Binding for KeyboardCompositeBinding { fn event(&mut self, event: &Event<()>) -> bool { let mut changed = false; for binding in self.directions.iter_mut() { changed |= binding.event(event); } changed } fn state(&self) -> ActionState { let mut x = 0.; let mut y = 0.; if self.directions[CompositeDirection::Up.to_index()].pressed { y += 1.0; } if self.directions[CompositeDirection::Down.to_index()].pressed { y -= 1.0; } if self.directions[CompositeDirection::Left.to_index()].pressed { x -= 1.0; } if self.directions[CompositeDirection::Right.to_index()].pressed { x += 1.0; } ActionState::new(InputState::Axis2(Axis2 { x, y })) } } #[derive(Serialize, Deserialize)] pub struct MouseButtonBinding { button: MouseButton, #[serde(skip, default="ActionState::new_button")] state: ActionState, } impl Binding for MouseButtonBinding { fn event(&mut self, event: &Event<()>) -> bool { if let Event::WindowEvent { event: WindowEvent::CursorMoved { position, .. }, .. } = event { self.state.set_mouse_position(*position); return true; } else if let Event::WindowEvent { event: WindowEvent::MouseInput { state, button, .. }, .. } = event { if *button == self.button { self.state.state = InputState::Button(*state == ElementState::Pressed); return true; } } false } fn state(&self) -> ActionState { self.state.clone() } } #[derive(Serialize, Deserialize)] pub struct MouseMotionBinding { sensitivity: f32, #[serde(skip)] motion: Axis2, } impl Binding for MouseMotionBinding { fn event(&mut self, event: &Event<()>) -> bool { if let Event::DeviceEvent { event: DeviceEvent::MouseMotion { delta }, .. } = event { self.motion.x += delta.0 as f32 * self.sensitivity; self.motion.y += delta.1 as f32 * self.sensitivity; } false } fn state(&self) -> ActionState { ActionState::new(InputState::Axis2(self.motion)) } } #[derive(Serialize, Deserialize)] enum BindingEnum { // Button Keyboard(KeyboardBinding), MouseButton(MouseButtonBinding), // Axis2 KeyboardComposite(KeyboardCompositeBinding), MouseMotion(MouseMotionBinding), } impl Binding for BindingEnum { fn event(&mut self, event: &Event<()>) -> bool { match self { BindingEnum::Keyboard(binding) => binding.event(event), BindingEnum::MouseButton(binding) => binding.event(event), BindingEnum::KeyboardComposite(binding) => binding.event(event), BindingEnum::MouseMotion(binding) => binding.event(event), } } fn state(&self) -> ActionState { match self { BindingEnum::Keyboard(binding) => binding.state(), BindingEnum::MouseButton(binding) => binding.state(), BindingEnum::KeyboardComposite(binding) => binding.state(), BindingEnum::MouseMotion(binding) => binding.state(), } } } #[derive(Serialize, Deserialize)] pub struct InputBindings { bindings: Vec<(String, BindingEnum)>, } impl_ron_asset!(InputBindings, Config); impl InputBindings { pub fn len(&self) -> usize { self.bindings.len() } } pub struct InputSystem { bindings: InputBindings, event_system: event::EventSystem<InputEvent>, has_dispatched: bool, } impl InputSystem { pub(crate) fn new(bindings: InputBindings) -> InputSystem { InputSystem { bindings, event_system: event::EventSystem::new(), has_dispatched: false } } pub(crate) fn start_frame(&mut self) { // MouseMotionBindings work differently than others. The values are accumulated over each frame, then reset. for (index, (_, binding)) in self.bindings.bindings.iter_mut().enumerate() { if let BindingEnum::MouseMotion(binding) = binding { self.event_system.fire_event(InputEvent::new(index)); binding.motion = Axis2::default(); } } } pub fn dispatch_queue<T: InputActions>(&mut self, actions: &mut T) { actions.end_frame(); let bindings = &self.bindings; self.event_system.dispatch_queue(move |event| { let (target, binding) = &bindings.bindings[event.binding_index]; actions.set_action_state(target, binding.state()); }); self.has_dispatched = true; } pub(crate) fn end_frame(&mut self) { if self.has_dispatched { self.has_dispatched = false; } else { self.event_system.discard_queue(); } } pub(crate) fn input_event(&mut self, event: Event<()>) { // TODO do some matching so we're not checking every event against every binding for (index, (_, binding)) in self.bindings.bindings.iter_mut().enumerate() { if binding.event(&event) { self.event_system.fire_event(InputEvent::new(index)); } } } } pub struct InputEvent { binding_index: usize } impl InputEvent { fn new(binding_index: usize) -> InputEvent { InputEvent { binding_index } } } impl event::Event for InputEvent {}
use anyhow::Error; use fehler::throws; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; use std::fs; use std::io::prelude::*; #[throws(_)] fn main() { println!("cargo:rerun-if-changed=tests/"); let mut stream = TokenStream::new(); for entry in fs::read_dir("tests/")? { let entry = entry?; let path = entry.path(); if let Some(ext) = path.extension() { if ext == "md" { let name = path.file_stem().unwrap().to_str().unwrap(); let test_fn_name = Ident::new(&name, Span::call_site()); let tokens = quote! { #[test] fn #test_fn_name() -> Result<(), crate::Error> { crate::document::test(#name)?; Ok(()) } }; stream.extend(tokens); } } } let mut f = fs::File::create("src/tests.rs")?; f.write_all(stream.to_string().as_bytes())?; }
// 无重复字符的最长子串 // 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 // // 示例 1: // // 输入: "abcabcbb" // 输出: 3 // 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 // 示例 2: // // 输入: "bbbbb" // 输出: 1 // 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 // 示例 3: // // 输入: "pwwkew" // 输出: 3 // 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 // 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串 use crate::string::Solution; impl Solution { pub fn length_of_longest_substring(s: String) -> i32 { use std::cmp::max; if s.len() <= 1 { return s.len() as i32; } let s = s.as_bytes(); let mut ans: i32 = 0; for i in 0..s.len() - 1 { if ((s.len() - i) as i32) < ans { break; } let mut cur_set = [false; 256]; let mut cur_ans = 0; for j in i..s.len() { let cur_char = s[j] as usize; if cur_set[cur_char] { break; } else { cur_ans += 1; cur_set[cur_char] = true; } } ans = max(ans, cur_ans); }; ans } } #[cfg(test)] mod tests { use super::*; #[test] fn test() { assert_eq!(Solution::length_of_longest_substring("abcabcbb".into()), 3); assert_eq!(Solution::length_of_longest_substring("".into()), 0); assert_eq!(Solution::length_of_longest_substring("av".into()), 2); assert_eq!(Solution::length_of_longest_substring("abcbdef".into()), 5); assert_eq!(Solution::length_of_longest_substring("bbbbb".into()), 1); assert_eq!(Solution::length_of_longest_substring("pwwkew".into()), 3); } }
//pub mod full_name; //pub mod email_address; //pub mod telephone; //pub mod postal_address; //pub mod contact_information; //pub mod tenant_id; //pub mod enablement; //pub mod person; pub mod user;
pub(crate) mod chain_rows; pub(crate) mod from_sqlite_rows;
extern crate num_bigint; extern crate num_traits; use std::any; use std::fmt; use std::ops; use crate::token::Token; use num_bigint::BigInt; use num_traits::ToPrimitive; ////////////////////////////////////////////////////////////////////// /// Number ////////////////////////////////////////////////////////////////////// #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum NumberBase { BIN = 2, OCT = 8, DEC = 10, HEX = 16, } impl NumberBase { pub fn to_string(&self) -> &str { match self { Self::BIN => return "BIN", Self::OCT => return "OCT", Self::DEC => return "DEC", Self::HEX => return "HEX", } } } impl std::str::FromStr for NumberBase { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "bin" | "2" => Ok(Self::BIN), "oct" | "8" => Ok(Self::OCT), "dec" | "10" => Ok(Self::DEC), "hex" | "16" => Ok(Self::HEX), _ => Err("Error parsing".to_owned()), } } } #[derive(Clone)] pub struct Number { value: BigInt, base: NumberBase, } impl Number { pub fn from_slice(slice: &[u8], base: &NumberBase) -> Result<Number, String> { if let Some(result) = BigInt::parse_bytes(slice, *base as u32) { Ok(Number { value: result, base: *base, }) } else { Err("Error parsing number from slice".to_owned()) } } pub fn set_base(&mut self, base: &NumberBase) -> &Number { self.base = *base; self } } impl Token for Number { fn to_string(&self) -> String { self.value.to_string() } fn as_any(&self) -> &dyn any::Any { self } } impl ops::Add<Number> for Number { type Output = Number; fn add(self, rhs: Number) -> Number { Number { value: self.value + rhs.value, base: self.base, } } } impl ops::Sub<Number> for Number { type Output = Number; fn sub(self, rhs: Number) -> Number { Number { value: self.value - rhs.value, base: self.base, } } } impl ops::Mul<Number> for Number { type Output = Number; fn mul(self, rhs: Number) -> Number { Number { value: self.value * rhs.value, base: self.base, } } } impl ops::Div<Number> for Number { type Output = Number; fn div(self, rhs: Number) -> Number { Number { value: self.value / rhs.value, base: self.base, } } } impl ops::Shl<Number> for Number { type Output = Number; fn shl(self, rhs: Number) -> Number { Number { value: self.value << rhs.value.to_usize().unwrap(), base: self.base, } } } impl ops::Shr<Number> for Number { type Output = Number; fn shr(self, rhs: Number) -> Number { Number { value: self.value >> rhs.value.to_usize().unwrap(), base: self.base, } } } impl ops::BitAnd<Number> for Number { type Output = Number; fn bitand(self, rhs: Number) -> Number { Number { value: self.value & rhs.value, base: self.base, } } } impl ops::BitXor<Number> for Number { type Output = Number; fn bitxor(self, rhs: Number) -> Number { Number { value: self.value ^ rhs.value, base: self.base, } } } impl ops::BitOr<Number> for Number { type Output = Number; fn bitor(self, rhs: Number) -> Number { Number { value: self.value | rhs.value, base: self.base, } } } impl fmt::Display for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.base { NumberBase::BIN => fmt::Binary::fmt(&self.value, f), NumberBase::OCT => fmt::Octal::fmt(&self.value, f), NumberBase::DEC => fmt::Display::fmt(&self.value, f), NumberBase::HEX => fmt::UpperHex::fmt(&self.value, f), } } } impl fmt::Debug for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self, f) } } impl fmt::Binary for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Binary::fmt(&self.value, f) } } impl fmt::Octal for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.value, f) } } impl fmt::LowerHex for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.value, f) } } impl fmt::UpperHex for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::UpperHex::fmt(&self.value, f) } }
#![allow(dead_code)] use crate::utils::*; use std::ops; #[derive(Debug, Copy, Clone)] pub struct Vec3 { e: [f64; 3], } impl Vec3 { pub fn new() -> Self { Self { e: [0.0, 0.0, 0.0] } } pub fn from(e0: f64, e1: f64, e2: f64) -> Self { Self { e: [e0, e1, e2] } } pub fn random() -> Self { Self { e: [ random_double(0., 1.), random_double(0., 1.), random_double(0., 1.), ], } } pub fn random_from(min: f64, max: f64) -> Self { Self { e: [ random_double(min, max), random_double(min, max), random_double(min, max), ], } } pub fn random_in_unit_sphere() -> Self { loop { let p = Vec3::random_from(-1., 1.); if p.length_squared() >= 1. { continue; } return p; } } pub fn random_unit_vector() -> Self { unit_vector(Vec3::random_in_unit_sphere()) } pub fn random_in_hemisphere(normal: &Vec3) -> Self { let in_unit_sphere = Vec3::random_in_unit_sphere(); if dot(in_unit_sphere, *normal) > 0.0 { return in_unit_sphere; } else { return -in_unit_sphere; } } pub fn x(&self) -> f64 { self.e[0] } pub fn y(&self) -> f64 { self.e[1] } pub fn z(&self) -> f64 { self.e[2] } pub fn length_squared(&self) -> f64 { self.e[0] * self.e[0] + self.e[1] * self.e[1] + self.e[2] * self.e[2] } pub fn length(&self) -> f64 { self.length_squared().sqrt() } } pub fn dot(u: Vec3, v: Vec3) -> f64 { u[0] * v[0] + u[1] * v[1] + u[2] * v[2] } pub fn cross(u: Vec3, v: Vec3) -> Vec3 { Vec3::from( u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0], ) } pub fn unit_vector(v: Vec3) -> Vec3 { v / v.length() } impl ops::Neg for Vec3 { type Output = Self; fn neg(self) -> Self { Self::from(-self.e[0], -self.e[1], -self.e[2]) } } impl ops::Index<usize> for Vec3 { type Output = f64; fn index(&self, idx: usize) -> &Self::Output { &self.e[idx] } } impl ops::IndexMut<usize> for Vec3 { fn index_mut(&mut self, idx: usize) -> &mut Self::Output { &mut self.e[idx] } } impl ops::Add for Vec3 { type Output = Self; fn add(self, other: Self) -> Self { Self::from( self.e[0] + other.e[0], self.e[1] + other.e[1], self.e[2] + other.e[2], ) } } impl ops::Sub for Vec3 { type Output = Self; fn sub(self, other: Self) -> Self { Self::from( self.e[0] - other.e[0], self.e[1] - other.e[1], self.e[2] - other.e[2], ) } } impl ops::Mul for Vec3 { type Output = Self; fn mul(self, other: Self) -> Self { Vec3::from( self.e[0] * other.e[0], self.e[1] * other.e[1], self.e[2] * other.e[2], ) } } impl ops::Mul<f64> for Vec3 { type Output = Self; fn mul(self, other: f64) -> Self { Vec3::from(self.e[0] * other, self.e[1] * other, self.e[2] * other) } } impl ops::Mul<Vec3> for f64 { type Output = Vec3; fn mul(self, other: Vec3) -> Vec3 { other * self } } impl ops::Div<f64> for Vec3 { type Output = Self; fn div(self, other: f64) -> Self { (1.0 / other) * self } } impl ops::AddAssign for Vec3 { fn add_assign(&mut self, other: Self) { *self = Self::from( self.e[0] + other.e[0], self.e[1] + other.e[1], self.e[2] + other.e[2], ) } } impl ops::MulAssign<f64> for Vec3 { fn mul_assign(&mut self, other: f64) { *self = Self::from(self.e[0] * other, self.e[1] * other, self.e[2] * other) } } pub type Point3 = Vec3; pub type Color = Vec3;
pub(crate) mod message; pub(crate) mod input_message; pub(crate) mod slsk_buffer; pub(crate) mod packet; pub(crate) trait Looper { fn loop_forever(&mut self); }
mod protos; use log::info; use std::sync::Arc; use structopt::StructOpt; use grpcio::{ChannelBuilder, EnvBuilder}; use protos::bank_account::{ OpenBankAccountRequest, UpdateBankAccountRequest, DepositBankAccountRequest, WithdrawBankAccountRequest, CloseBankAccountRequest, }; use protos::bank_account_grpc::BankAccountServiceClient; fn main() { dotenv::dotenv().ok(); env_logger::init(); let args = Args::from_args(); let env = Arc::new(EnvBuilder::new().build()); let ch = ChannelBuilder::new(env).connect(&format!("{}:{}", args.host, args.port)); let client = BankAccountServiceClient::new(ch); match args.cmd { Command::Open{ name } => open_bank_account(&client, name), Command::Update{ bank_account_id, name } => update_bank_account(&client, bank_account_id, name), Command::Deposit{ bank_account_id, deposit } => deposit_bank_account(&client, bank_account_id, deposit), Command::Withdraw{ bank_account_id, withdraw } => withdraw_bank_account(&client, bank_account_id, withdraw), Command::Close{ bank_account_id } => close_bank_account(&client, bank_account_id), }; } #[derive(StructOpt, Debug)] #[structopt(name = "grpc_client")] pub struct Args { #[structopt(long, default_value="127.0.0.1")] pub host: String, #[structopt(long, default_value="8080")] pub port: u16, #[structopt(subcommand)] cmd: Command, } #[derive(StructOpt, Debug)] pub enum Command { Open { name: String, }, Update { bank_account_id: String, name: String, }, Deposit { bank_account_id: String, deposit: i32, }, Withdraw { bank_account_id: String, withdraw: i32, }, Close { bank_account_id: String, }, } fn open_bank_account(client: &BankAccountServiceClient, name: String) { let mut req = OpenBankAccountRequest::default(); req.set_name(name); info!("Send request: {:?}", &req); let reply = client.open(&req).expect("rpc"); info!("Response received: {:?}", &reply); } fn update_bank_account(client: &BankAccountServiceClient, bank_account_id: String, name: String) { let mut req = UpdateBankAccountRequest::default(); req.set_bank_account_id(bank_account_id); req.set_name(name); info!("Send request: {:?}", &req); let reply = client.update(&req).expect("rpc"); info!("Response received: {:?}", &reply); } fn deposit_bank_account(client: &BankAccountServiceClient, bank_account_id: String, deposit: i32) { let mut req = DepositBankAccountRequest::default(); req.set_bank_account_id(bank_account_id); req.set_deposit(deposit); info!("Send request: {:?}", &req); let reply = client.deposit(&req).expect("rpc"); info!("Response received: {:?}", &reply); } fn withdraw_bank_account(client: &BankAccountServiceClient, bank_account_id: String, withdraw: i32) { let mut req = WithdrawBankAccountRequest::default(); req.set_bank_account_id(bank_account_id); req.set_withdraw(withdraw); info!("Send request: {:?}", &req); let reply = client.withdraw(&req).expect("rpc"); info!("Response received: {:?}", &reply); } fn close_bank_account(client: &BankAccountServiceClient, bank_account_id: String) { let mut req = CloseBankAccountRequest::default(); req.set_bank_account_id(bank_account_id); info!("Send request: {:?}", &req); let reply = client.close(&req).expect("rpc"); info!("Response received: {:?}", &reply); }
use std::io::prelude::*; use std::io; use structopt::StructOpt; use std::path::PathBuf; use rpassword; use reqwest::Url; use std::thread; use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use std::sync::Arc; use std::fs::File; use log::error; mod logger; mod config; use config::{Config, State}; mod authenticator; use authenticator::{Authenticator, bitwarden::Bitwarden}; mod resolver; use resolver::{Resolver, phpipam::PhpIpam}; // TODO: // - update while waiting // - add timeout to yaml // - check ssh agent running // - ssh key added // - limit processes // - add dependecies of server // - alternative file structure with just a list of hosts/tasks // - catch all unnesessary unwraps in log // - implement own error // - change logger to writer // - show task number in log #[derive(Debug, StructOpt)] #[structopt(name = "tui-patch", about = "Run SSH commands from a YAML script file in parallel.")] struct Opt { #[structopt(parse(from_os_str), help = "YAML script file, for format details see in examples folder.")] config: PathBuf, #[structopt(default_value = "./log", short, long, help = "Specify the log output directory, the directory will be created if it does not exist. Each logfile will be created with hostname and timestamp.")] log: String, #[structopt(short, long, help = "Pass your Bitwarden master password to unlock the vault. Specify '-' to get prompt to enter hidden password. Setup bitwarden-cli before use (bw login).")] bitwarden: Option<String>, #[structopt(short, long, help = "Provide the URL to your PhpIpam and the PhpIpam App Name and App Code. Make sure you use 'SSL with App code token' in PhpIpam with 'Read' permission.")] phpipam: Option<String>, } fn main() { // read parameters let args = Opt::from_args(); // open config file let mut config_file = match File::open(args.config) { Ok(file) => file, Err(error) => panic!("{}", error) }; // read config file let mut raw_config = String::new(); match config_file.read_to_string(&mut raw_config) { Ok(string) => string, Err(error) => panic!("{}", error) }; let config: Config = serde_yaml::from_str(&raw_config).unwrap(); // setup log let log_directory: Arc<String> = Arc::new(args.log); // let log = log_directory.clone(); // logger::init(&*log, "main"); // check if bitwarden password should be read by user input let bitwarden_secret = match args.bitwarden { Some(secret) => { match secret == "-" { true => rpassword::read_password_from_tty(Some("Bitwarden Master Password: ")).ok(), false => Some(secret) }}, None => None }; // check if ipam password should be read by user input let ipam_url = match args.phpipam { Some(u) => { // use url for app name and app code let mut url = Url::parse(&u).unwrap(); if url.username() == "" { let stdin = io::stdin(); let mut app = String::new(); println!("PHPIpam API Name: "); stdin.read_line(&mut app).unwrap(); url.set_username(&app[..&app.len()-1]).unwrap(); } if url.password() == None { let code = rpassword::read_password_from_tty(Some("PHPIpam API Code: ")).unwrap(); url.set_password(Some(&code)).unwrap(); } Some(url) }, None => None, }; let resolver = Arc::new(match ipam_url { Some(u) => PhpIpam::new(u).ok(), None => None }); // load bitwarden let bitwarden = match &bitwarden_secret { // exit if password is wrong Some(path) => Arc::new( match Bitwarden::new(path) { Ok(bw) => Some(bw), Err(e) => { error!("{}", e); None }, } ), None => Arc::new(None) }; // create multithreaded progress bar let multi_progress = MultiProgress::new(); let style = ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}").progress_chars("##-"); for target in config.targets { // add progress bar for thread let count = target.tasks.len(); let progress = multi_progress.add(ProgressBar::new(count as u64)); progress.set_style(style.clone()); // create a read only copy for each thread let authenticator = bitwarden.clone(); let resolver = resolver.clone(); // copy path for logs let log = log_directory.clone(); let _ = thread::spawn(move || { progress.set_message(target.host.clone()); // create a logfile let _ = logger::init(&*log, &target.host); let mut worst_sate = State::Ok; match target.connect( &*authenticator, &*resolver) { Ok(c) => { for task in target.tasks { match task.run(&c) { Ok(State::Ok) => { progress.inc(1); }, Ok(State::Warning) => { worst_sate = State::Warning; progress.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:40.magenta/red} {pos:>7}/{len:7} {msg}").progress_chars("##-")); progress.set_message(format!("{}: warning.", &target.host)); progress.inc(1); }, Ok(State::Failed) => { progress.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:40.magenta/red} {pos:>7}/{len:7} {msg}").progress_chars("##-")); progress.set_message(format!("{}: command failed.", &target.host)); progress.finish_at_current_pos(); return }, Err(e) => { progress.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:40.red/red} {pos:>7}/{len:7} {msg}").progress_chars("XX-")); progress.finish_at_current_pos(); error!("{}", &e); return } } } }, Err(e) => { progress.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:40.red/red} {pos:>7}/{len:7} {msg}").progress_chars("XX-")); progress.set_message(format!("{}: connection failed.", &target.host)); progress.finish_at_current_pos(); error!("{}", &e); return } } // execution finished for a target match worst_sate { State::Ok => { progress.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:40.green/green} {pos:>7}/{len:7} {msg}").progress_chars("##-")); progress.finish_with_message(format!("{}: done.", &target.host)); }, State::Warning => { progress.finish_with_message(format!("{}: done with warnings.", &target.host)); }, // unreachable State::Failed => {} } }); } // wait for threads to be finished multi_progress.join().unwrap(); }
use super::*; use db::{Database, Pod}; use event::obj::{Dispatch, Listener}; use file::FileReaderWriter; use rocket::config::{Config, Environment}; use rocket::State; use rocket::{get, post, routes}; use rocket_contrib::json::{Json, JsonValue}; use scan::{AutoScanner, ScannerRecvArgument}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread; pub struct Harvest { scanner: AutoScanner, database: Arc<Mutex<Database>>, file_reader_writer: Arc<Mutex<FileReaderWriter>>, // jh: Option<JoinHandle<Result<()>>>, db_handles: HashMap<String, Box<dyn Listener<Pod> + 'static>>, scanner_handles: Arc<Mutex<HashMap<String, Box<dyn Listener<ScannerRecvArgument> + Send + 'static>>>>, } impl Harvest { pub fn new(namespace: String, dir: String) -> Self { let db_event_handler = Dispatch::<Pod>::new(); let database = Arc::new(Mutex::new(Database::new(db_event_handler))); let file_reader_db = database.clone(); Self { scanner: AutoScanner::new(namespace, dir, database.clone()), database, file_reader_writer: Arc::new(Mutex::new(FileReaderWriter::new(file_reader_db))), // jh: None, db_handles: HashMap::new(), scanner_handles: Arc::new(Mutex::new(HashMap::new())), } } pub fn start(&mut self) -> Result<()> { let cfg = Config::build(Environment::Development) .address("0.0.0.0") .port(8080) .unwrap(); let database = self.database.clone(); // registry db event handle let db_update_handle_arc_clone = self.database.clone(); let fwr_update_handle_arc_clone = self.file_reader_writer.clone(); self.db_handles.insert( db::Event::Update.as_ref().to_owned(), Box::new(DBUpdateEvent( db_update_handle_arc_clone, fwr_update_handle_arc_clone, )), ); let db_delete_handle_arc_clone = self.database.clone(); let fwr_delete_handle_arc_clone = self.file_reader_writer.clone(); self.db_handles.insert( db::Event::Delete.as_ref().to_owned(), Box::new(DBDeleteEvent( db_delete_handle_arc_clone, fwr_delete_handle_arc_clone, )), ); let db_add_handle_arc_clone = self.database.clone(); let fwr_add_handle_arc_clone = self.file_reader_writer.clone(); self.db_handles.insert( db::Event::Add.as_ref().to_owned(), Box::new(DBAddEvent( db_add_handle_arc_clone, fwr_add_handle_arc_clone, )), ); let scanner_clone = self.scanner.clone(); let self_scanner_handles_registry = self.scanner_handles.clone(); match self_scanner_handles_registry.lock() { Ok(mut scanner_event_handler) => { // registry scanner event handle let scanner_need_update_handler_db_arc = database.clone(); let scanner_need_update_handler_frw_arc = self.file_reader_writer.clone(); scanner_event_handler.insert( scan::PathEvent::NeedClose.as_ref().to_owned(), Box::new(ScannerCloseEvent( scanner_need_update_handler_db_arc, scanner_need_update_handler_frw_arc, )), ); let scanner_need_open_handler_db_arc = database.clone(); let scanner_need_open_handler_frw_arc = self.file_reader_writer.clone(); scanner_event_handler.insert( scan::PathEvent::NeedOpen.as_ref().to_owned(), Box::new(ScannerOpenEvent( scanner_need_open_handler_db_arc, scanner_need_open_handler_frw_arc, )), ); let scanner_need_write_handler_db_arc = database.clone(); let scanner_need_write_handler_frw_arc = self.file_reader_writer.clone(); scanner_event_handler.insert( scan::PathEvent::NeedWrite.as_ref().to_owned(), Box::new(ScannerWriteEvent( scanner_need_write_handler_db_arc, scanner_need_write_handler_frw_arc, )), ); } Err(e) => { panic!("registry scanner handle error: {:?}", e) } } let self_scanner_handles = self.scanner_handles.clone(); // start auto scanner with a new thread let _jh = thread::spawn(move || scanner_clone.start(self_scanner_handles)); rocket::custom(cfg) .mount("/", routes![post_pod, query_pod]) .register(catchers![not_found]) .manage(database) .launch(); if let Err(e) = _jh.join().unwrap() { eprintln!("{}", e) } Ok(()) } } #[derive(Serialize, Deserialize, Debug)] struct Request { namespace: String, pod: String, filter: String, output: String, upload: bool, } // /pod/collect list ns.pod start collect to output #[post("/pod", format = "json", data = "<req>")] fn post_pod(req: Json<Request>, db: State<'_, Arc<Mutex<Database>>>) -> JsonValue { if req.0.namespace == "" || req.0.pod == "" { return json!({ "status": "error", "reason": format!("namespace {} or pod {} maybe is empty",req.namespace,req.pod), }); } match db.lock() { Ok(mut db) => { for item in db.get_by_namespace_pod(req.0.namespace, req.0.pod).iter() { if let Some((uuid, pod)) = item { let mut pod = pod.to_owned(); pod.upload = req.0.upload; pod.filter = req.0.filter.clone(); pod.output = req.0.output.clone(); match db.update(uuid.to_owned(), pod) { Ok(_) => {} Err(e) => { eprintln!("{}", e); return json!({"status":"error","reason":format!("{}",e)}); } } } } json!({"status":"ok"}) } Err(e) => { json!({ "status":"error", "reason":format!("DB Lock Failure error {}",e) }) } } } #[get("/pod")] fn query_pod(db: State<'_, Arc<Mutex<Database>>>) -> JsonValue { match db.lock() { Ok(_db) => { json!({"status":"ok","reason":format!("{:?}",_db.all().to_json())}) } Err(e) => { json!({"status":"error","reason":format!("{}",e)}) } } } #[catch(404)] fn not_found() -> JsonValue { json!({ "status": "error", "reason": "Resource was not found." }) } #[cfg(test)] mod tests { #[test] fn it_works() {} }
use std::path::PathBuf; fn main() { println!("cargo:rerun-if-changed=src"); rust_sitter_tool::build_parsers(&PathBuf::from("src/lib.rs")); }
pub const DEFAULT_POINT_SIZE: i32 = 5; pub const DEFAULT_FONT_COLOR: &str = "#080808"; pub const DEFAULT_FONT_FAMILY: &str = "sans-serif"; pub const DEFAULT_DY: &str = ".35em"; pub const DEFAULT_STROKE_WIDTH: i32 = 1; pub const DEFAULT_STROKE_COLOR: &str = "#bbbbbb"; pub const X_ATTR: &str = "x"; pub const X1_ATTR: &str = "x1"; pub const X2_ATTR: &str = "x2"; pub const Y_ATTR: &str = "y"; pub const Y1_ATTR: &str = "y1"; pub const Y2_ATTR: &str = "y2"; pub const CX_ATTR: &str = "cx"; pub const CY_ATTR: &str = "cy"; pub const R_ATTR: &str = "r"; pub const D_ATTR: &str = "d"; pub const DY_ATTR: &str = "dy"; pub const WIDTH_ATTR: &str = "width"; pub const HEIGHT_ATTR: &str = "height"; pub const STROKE_ATTR: &str = "stroke"; pub const STROKE_WIDTH_ATTR: &str = "stroke-width"; pub const FILL_ATTR: &str = "fill"; pub const TRANSFORM_ATTR: &str = "transform"; pub const TEXT_ANCHOR_ATTR: &str = "text-anchor"; pub const TEXT_ANCHOR_START: &str = "start"; pub const TEXT_ANCHOR_MIDDLE: &str = "middle"; pub const TEXT_ANCHOR_END: &str = "end"; pub const FONT_SIZE_ATTR: &str = "font-size"; pub const FONT_FAMILY_ATTR: &str = "font-family"; pub const SHAPE_RENDERING_ATTR: &str = "shape-rendering"; pub const SHAPE_RENDERING_CRISP_EDGES: &str = "crispEdges"; pub const CLASS_ATTR: &str = "class"; pub const CLASS_AREA: &str = "area"; pub const CLASS_BAR: &str = "bar"; pub const CLASS_CHART: &str = "chart"; pub const CLASS_VIEWS: &str = "views"; pub const CLASS_X_AXIS: &str = "x-axis"; pub const CLASS_Y_AXIS: &str = "y-axis"; pub const CLASS_TICK: &str = "tick"; pub const CLASS_TITLE: &str = "title"; pub const CLASS_POINT: &str = "point"; pub const CLASS_LINE: &str = "line"; pub const VIEW_BOX_ATTR: &str = "viewBox"; pub const START: f32 = 0_f32; pub const FILL_NONE: &str = "none"; pub fn translate_x_y<T: std::fmt::Display>(x: T, y: T) -> String { format!("translate({},{})", x, y) } pub fn rotate_a_x_y<T: std::fmt::Display>(a: T, x: T, y: T) -> String { format!("rotate({},{},{})", a, x, y) } pub fn rotate_a<T: std::fmt::Display>(a: T) -> String { format!("rotate({})", a) } pub fn pair_x_y<T: std::fmt::Display>(x: T, y: T) -> String { format!("({},{})", x, y) } #[cfg(test)] mod tests { use super::*; #[test] fn translate() { let translated = translate_x_y(1_f32, 2_f32); assert_eq!(translated, "translate(1,2)"); } #[test] fn rotate() { let rotated_1 = rotate_a_x_y(1_f32, 2_f32, 3_f32); assert_eq!(rotated_1, "rotate(1,2,3)"); let rotated_2 = rotate_a(45_f32); assert_eq!(rotated_2, "rotate(45)"); } #[test] fn pair() { let paired = pair_x_y(12.1_f32, 21.1_f32); assert_eq!(paired, "(12.1,21.1)"); } }
mod states; pub use states::{Accepted, Calling, Completed, Errored, Proceeding, Terminated}; use crate::Error; use crate::SipManager; use common::{ rsip::{self, prelude::*}, tokio::time::Instant, }; use models::{ transport::{RequestMsg, ResponseMsg}, RequestExt, }; use std::sync::Arc; //should come from config pub static TIMER_T1: u64 = 500; pub static TIMER_B: u64 = 64 * TIMER_T1; pub static TIMER_M: u64 = 64 * TIMER_T1; pub static TIMER_D: u64 = 32000; #[allow(dead_code)] #[derive(Debug)] pub struct TrxStateMachine { pub id: String, pub state: TrxState, pub msg: RequestMsg, pub created_at: Instant, sip_manager: Arc<SipManager>, } #[derive(Debug)] pub enum TrxState { Calling(Calling), Proceeding(Proceeding), Completed(Completed), Accepted(Accepted), Terminated(Terminated), Errored(Errored), } impl std::fmt::Display for TrxState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Calling(_) => write!(f, "TrxState::Calling"), Self::Proceeding(_) => write!(f, "TrxState::Proceeding"), Self::Completed(_) => write!(f, "TrxState::Completed"), Self::Accepted(_) => write!(f, "TrxState::Accepted"), Self::Terminated(_) => write!(f, "TrxState::Terminated"), Self::Errored(_) => write!(f, "TrxState::Errored"), } } } impl TrxStateMachine { pub fn new(sip_manager: Arc<SipManager>, msg: RequestMsg) -> Result<Self, Error> { Ok(Self { id: msg.sip_request.transaction_id()?, state: TrxState::Calling(Default::default()), msg, created_at: Instant::now(), sip_manager, }) } pub async fn next(&mut self, response: Option<rsip::Response>) { let result = match response { Some(response) => self.next_step_with(response).await, None => self.next_step().await, }; match result { Ok(()) => (), Err(error) => self.error( format!("transaction {} errored: {}", self.id, error.to_string()), None, ), }; } pub fn is_active(&self) -> bool { !matches!(self.state, TrxState::Errored(_) | TrxState::Terminated(_)) } async fn next_step(&mut self) -> Result<(), Error> { match &self.state { TrxState::Calling(calling) => { match (calling.has_timedout(), calling.should_retransmit()) { (true, _) => self.terminate(), (false, true) => { self.sip_manager .transport .send(self.msg.clone().into()) .await?; self.state = TrxState::Calling(calling.retransmit()); } (false, false) => (), } } TrxState::Completed(completed) => { if completed.should_terminate() { self.terminate(); } } TrxState::Accepted(accepted) => { if accepted.should_terminate() { self.terminate(); } } _ => (), }; Ok(()) } async fn next_step_with(&mut self, response: rsip::Response) -> Result<(), Error> { use rsip::common::StatusCodeKind; match (&self.state, response.status_code.kind()) { (TrxState::Calling(_), StatusCodeKind::Provisional) => { self.sip_manager .core .process_incoming_message(self.response_msg_from(response.clone()).into()) .await; self.proceed(response); } (TrxState::Calling(_), StatusCodeKind::Successful) => { self.sip_manager .core .process_incoming_message(self.response_msg_from(response.clone()).into()) .await; self.accept(response); } (TrxState::Calling(_), _) => { self.sip_manager .core .process_incoming_message(self.response_msg_from(response.clone()).into()) .await; self.complete(response); } (TrxState::Proceeding(_), StatusCodeKind::Provisional) => { self.sip_manager .core .process_incoming_message(self.response_msg_from(response.clone()).into()) .await; self.update_response(response); } (TrxState::Proceeding(_), StatusCodeKind::Successful) => { self.sip_manager .core .process_incoming_message(self.response_msg_from(response.clone()).into()) .await; self.accept(response); } (TrxState::Proceeding(_), _) => { self.sip_manager .core .process_incoming_message(self.response_msg_from(response.clone()).into()) .await; self.send_ack_request_from(response.clone()).await?; self.complete(response); } (TrxState::Accepted(_), StatusCodeKind::Successful) => { self.sip_manager .core .process_incoming_message(self.response_msg_from(response.clone()).into()) .await; self.update_response(response); } (TrxState::Completed(_), kind) if kind > StatusCodeKind::Successful => { self.complete(response.clone()); self.send_ack_request_from(response.clone()).await?; self.complete(response); } (_, _) => { self.error( format!( "unknown match: {}, {} for transaction {}", response.status_code, self.state, self.id ), Some(response), ); } }; Ok(()) } fn proceed(&mut self, response: rsip::Response) { self.state = TrxState::Proceeding(Proceeding { response, entered_at: Instant::now(), }); } fn update_response(&mut self, response: rsip::Response) { match &self.state { TrxState::Proceeding(state) => { self.state = TrxState::Proceeding(Proceeding { response, entered_at: state.entered_at, }) } TrxState::Completed(state) => { self.state = TrxState::Completed(Completed { response, entered_at: state.entered_at, }) } TrxState::Accepted(state) => { self.state = TrxState::Accepted(Accepted { response, entered_at: state.entered_at, }) } TrxState::Errored(state) => { self.state = TrxState::Errored(Errored { response: Some(response), entered_at: state.entered_at, error: state.error.clone(), }) } _ => self.error( format!("Asking to update response when state is {}", self.state), Some(response), ), }; } fn complete(&mut self, response: rsip::Response) { self.state = TrxState::Completed(Completed { response, entered_at: Instant::now(), }); } fn accept(&mut self, response: rsip::Response) { self.state = TrxState::Accepted(Accepted { response, entered_at: Instant::now(), }); } fn terminate(&mut self) { let response: Option<rsip::Response> = match &self.state { TrxState::Accepted(accepted) => Some(accepted.clone().response), TrxState::Completed(completed) => Some(completed.clone().response), _ => None, }; self.state = TrxState::Terminated(Terminated { response, entered_at: Instant::now(), }); } fn error(&mut self, error: String, response: Option<rsip::Response>) { self.state = TrxState::Errored(Errored { entered_at: Instant::now(), response, error, }); } fn response_msg_from(&self, response: rsip::Response) -> ResponseMsg { ResponseMsg { sip_response: response, peer: self.msg.peer, transport: self.msg.transport, } } fn request_msg_from(&self, request: rsip::Request) -> RequestMsg { RequestMsg { sip_request: request, peer: self.msg.peer, transport: self.msg.transport, } } async fn send_ack_request_from(&self, response: rsip::Response) -> Result<(), Error> { Ok(self .sip_manager .transport .send( self.request_msg_from(self.msg.sip_request.ack_request_with(response)) .into(), ) .await?) } //format!("transaction {} errored: {:?}", self.id, error); }
pub mod standard; pub mod ngram; use serde_json; use serde_json::value::ToJson; use kite::token::Token; use analysis::ngram_generator::Edge; use analysis::tokenizers::standard::StandardTokenizer; use analysis::tokenizers::ngram::NGramTokenizer; /// Defines a tokenizer /// /// You can use this to define a tokenizer before having to bind it to any data /// /// # Examples /// /// ``` /// use kite::{Term, Token}; /// use kite::analysis::tokenizers::TokenizerSpec; /// /// let standard_tokenizer = TokenizerSpec::Standard; /// let token_stream = standard_tokenizer.initialise("Hello, world!"); /// /// let tokens = token_stream.collect::<Vec<Token>>(); /// /// assert_eq!(tokens, vec![ /// Token { term: Term::from_string("Hello"), position: 1 }, /// Token { term: Term::from_string("world"), position: 2 }, /// ]); /// ``` #[derive(Debug, Clone, PartialEq)] pub enum TokenizerSpec { Standard, NGram { min_size: usize, max_size: usize, edge: Edge, } } impl TokenizerSpec { pub fn initialise<'a>(&self, input: &'a str) -> Box<Iterator<Item=Token> + 'a> { match *self { TokenizerSpec::Standard => { Box::new(StandardTokenizer::new(input)) } TokenizerSpec::NGram{min_size, max_size, edge} => { Box::new(NGramTokenizer::new(input, min_size, max_size, edge)) } } } } impl ToJson for TokenizerSpec { fn to_json(&self) -> Result<serde_json::Value, serde_json::Error> { match *self { TokenizerSpec::Standard => { Ok(json!({ "type": "standard", })) } TokenizerSpec::NGram{min_size, max_size, edge} => { match edge { Edge::Left => { Ok(json!({ "type": "edgeNGram", "side": "front", "min_gram": min_size, "max_gram": max_size, })) } Edge::Right => { Ok(json!({ "type": "edgeNGram", "side": "back", "min_gram": min_size, "max_gram": max_size, })) } Edge::Neither => { Ok(json!({ "type": "ngram", "min_gram": min_size, "max_gram": max_size, })) } } } } } }
mod fixtures; use fixtures::{server, Error, TestServer, DIRECTORIES, FILES}; use rstest::rstest; use select::predicate::Attr; use select::{document::Document, node::Node}; use std::fs::{remove_file, File}; use std::io::Write; use std::path::PathBuf; /// Do not show readme contents by default #[rstest] fn no_readme_contents(server: TestServer) -> Result<(), Error> { let body = reqwest::blocking::get(server.url())?.error_for_status()?; let parsed = Document::from_read(body)?; // Check that the regular file listing still works. for &file in FILES { assert!(parsed.find(|x: &Node| x.text() == file).next().is_some()); } for &dir in DIRECTORIES { assert!(parsed.find(|x: &Node| x.text() == dir).next().is_some()); } // Check that there is no readme stuff here. assert!(parsed.find(Attr("id", "readme")).next().is_none()); assert!(parsed.find(Attr("id", "readme-filename")).next().is_none()); assert!(parsed.find(Attr("id", "readme-contents")).next().is_none()); Ok(()) } /// Show readme contents when told to if there is a readme file in the root #[rstest( readme_name, case("Readme.md"), case("readme.md"), case("README.md"), case("README.MD"), case("ReAdMe.Md") )] fn show_root_readme_contents( #[with(&["--readme"])] server: TestServer, readme_name: &str, ) -> Result<(), Error> { let readme_path = write_readme_contents(server.path().to_path_buf(), readme_name); let body = reqwest::blocking::get(server.url())?.error_for_status()?; let parsed = Document::from_read(body)?; // All the files are still getting listed... for &file in FILES { assert!(parsed.find(|x: &Node| x.text() == file).next().is_some()); } // ...in addition to the readme contents below the file listing. assert_readme_contents(&parsed, readme_name); remove_file(readme_path).unwrap(); Ok(()) } /// Show readme contents when told to if there is a readme file in any of the directories #[rstest( readme_name, case("Readme.md"), case("readme.md"), case("README.md"), case("README.MD"), case("ReAdMe.Md"), case("Readme.txt"), case("README.txt"), case("README"), case("ReAdMe") )] fn show_nested_readme_contents( #[with(&["--readme"])] server: TestServer, readme_name: &str, ) -> Result<(), Error> { for dir in DIRECTORIES { let readme_path = write_readme_contents(server.path().join(dir), readme_name); let body = reqwest::blocking::get(server.url().join(dir)?)?.error_for_status()?; let parsed = Document::from_read(body)?; // All the files are still getting listed... for &file in FILES { assert!(parsed.find(|x: &Node| x.text() == file).next().is_some()); } // ...in addition to the readme contents below the file listing. assert_readme_contents(&parsed, readme_name); remove_file(readme_path).unwrap(); } Ok(()) } fn write_readme_contents(path: PathBuf, filename: &str) -> PathBuf { let readme_path = path.join(filename); let mut readme_file = File::create(&readme_path).unwrap(); readme_file .write_all(format!("Contents of {filename}").as_bytes()) .expect("Couldn't write readme"); readme_path } fn assert_readme_contents(parsed_dom: &Document, filename: &str) { assert!(parsed_dom.find(Attr("id", "readme")).next().is_some()); assert!(parsed_dom .find(Attr("id", "readme-filename")) .next() .is_some()); assert!( parsed_dom .find(Attr("id", "readme-filename")) .next() .unwrap() .text() == filename ); assert!(parsed_dom .find(Attr("id", "readme-contents")) .next() .is_some()); assert!(parsed_dom .find(Attr("id", "readme-contents")) .next() .unwrap() .text() .trim() .contains(&format!("Contents of {filename}"))); }
use rand::{prelude::random, rngs::SmallRng, Rng, SeedableRng}; use structopt::StructOpt; use std::{collections::BTreeMap, time}; #[macro_export] macro_rules! pp { ($($arg:expr),+ => $val:expr) => { println!("{:<30} : {:?}", format!($($arg),+), $val) }; } /// Command line options. #[derive(Clone, StructOpt)] pub struct Opt { #[structopt(long = "seed")] seed: Option<u128>, #[structopt(long = "loads", default_value = "1000000")] // default 1M loads: usize, #[structopt(long = "ops", default_value = "1000000")] // default 1M ops: usize, #[structopt(long = "im")] im: bool, #[structopt(long = "std-vec")] std_vec: bool, #[structopt(long = "leaf-size")] leaf_size: Option<usize>, } fn main() { use std::iter::repeat; let opts = Opt::from_args(); let mut rng = { let seed = opts.seed.unwrap_or_else(random); // let seed: u128 = 89704735013013664095413923566273445973; SmallRng::from_seed(seed.to_le_bytes()) }; let arrs = if opts.im { vec![(Array::<u64>::new_im(), "im::Vector")] } else if opts.std_vec { vec![(Array::<u64>::new_vec(), "std::vec::Vec")] } else { let one = Array::new_vector(opts.leaf_size.unwrap_or(ppar::LEAF_CAP), true); let two = Array::new_vector_safe(opts.leaf_size.unwrap_or(ppar::LEAF_CAP), true); vec![(one, "ppar::rc::Vector"), (two, "ppar::arc::Vector")] }; for (opts, (arr, log)) in repeat(opts).take(arrs.len()).zip(arrs.into_iter()) { let mut perf = Perf::new(arr, opts); println!("Performance report for {}", log); println!("--------------------------------------"); perf.load(&mut rng); perf.run(&mut rng); perf.rebalance(true); perf.pretty_print(); println!() } } fn mem_ratio<T>(mem: usize, n: usize) -> f64 { let s = std::mem::size_of::<T>(); ((((mem as f64) / (n as f64)) - (s as f64)) / s as f64) * 100_f64 } #[derive(Clone)] enum Array<T> where T: Clone, { Vector(ppar::rc::Vector<T>), VectorSafe(ppar::arc::Vector<T>), Vec(Vec<T>), Im(im::Vector<T>), } impl<T> Array<T> where T: Clone, rand::distributions::Standard: rand::distributions::Distribution<T>, { fn new_vector(leaf_size: usize, auto_rebalance: bool) -> Self { let mut arr = ppar::rc::Vector::<T>::default(); arr.set_leaf_size(leaf_size) .set_auto_rebalance(auto_rebalance); Array::Vector(arr) } fn new_vector_safe(leaf_size: usize, auto_rebalance: bool) -> Self { let mut arr = ppar::arc::Vector::<T>::default(); arr.set_leaf_size(leaf_size) .set_auto_rebalance(auto_rebalance); Array::VectorSafe(arr) } fn new_vec() -> Self { Array::<T>::Vec(vec![]) } fn new_im() -> Self { Array::Im(im::Vector::<T>::new()) } #[allow(clippy::needless_collect)] fn load(&mut self, n: usize, rng: &mut SmallRng) -> (time::Duration, usize) { let offs: Vec<usize> = (1..=n).map(|i| rng.gen::<usize>() % i).collect(); let vals: Vec<T> = (0..n).map(|_| rng.gen::<T>()).collect(); let start = time::Instant::now(); for (off, val) in offs.into_iter().zip(vals.into_iter()) { match self { Array::Vector(arr) => arr.insert(off, val).unwrap(), Array::VectorSafe(arr) => arr.insert(off, val).unwrap(), Array::Vec(arr) => arr.insert(off, val), Array::Im(arr) => arr.insert(off, val), } } let elapsed = start.elapsed(); (elapsed, n) } fn len(&self) -> usize { match self { Array::Vector(arr) => arr.len(), Array::VectorSafe(arr) => arr.len(), Array::Vec(arr) => arr.len(), Array::Im(arr) => arr.len(), } } fn rebalance(&self, packed: bool) -> Option<Self> { match self { Array::Vector(arr) => Some(Array::Vector(arr.rebalance(packed).unwrap())), Array::VectorSafe(arr) => { Some(Array::VectorSafe(arr.rebalance(packed).unwrap())) } Array::Vec(_) => None, Array::Im(_) => None, } } } struct Perf<T> where T: Clone, { opts: Opt, val: Array<T>, stats: BTreeMap<&'static str, (time::Duration, usize)>, } impl<T> Perf<T> where T: Clone, rand::distributions::Standard: rand::distributions::Distribution<T>, { fn new(val: Array<T>, opts: Opt) -> Self { let stats = BTreeMap::new(); Perf { opts, val, stats } } fn len(&self) -> usize { match &self.val { Array::Vector(val) => val.len(), Array::VectorSafe(val) => val.len(), Array::Vec(val) => val.len(), Array::Im(val) => val.len(), } } fn rebalance(&mut self, packed: bool) { if let Some(val) = self.val.rebalance(packed) { self.val = val } } fn load(&mut self, rng: &mut SmallRng) { self.stats .insert("load", self.val.load(self.opts.loads, rng)); } fn run(&mut self, rng: &mut SmallRng) { self.op_clone(self.opts.ops); self.op_insert(self.opts.ops, rng); self.op_insert_mut(self.opts.ops, rng); self.op_remove(self.opts.ops, rng); self.op_remove_mut(self.opts.ops, rng); self.op_update(self.opts.ops, rng); self.op_update_mut(self.opts.ops, rng); self.op_get(self.opts.ops, rng); self.op_iter(self.opts.ops); self.op_split_append(self.opts.ops, rng); } fn pretty_print(&self) { for (k, (elapsed, n)) in self.stats.iter() { println!("{:14} {:?}", k, *elapsed / (*n as u32)); } let fp = match &self.val { Array::Vector(val) => Some((val.footprint(), val.len())), Array::VectorSafe(val) => Some((val.footprint(), val.len())), _ => None, }; if let Some((mem, n)) = fp { let ratio = mem_ratio::<T>(mem, n); println!("{:14} {}% {:?}", "mem-ratio", ratio, (mem, n)); } } fn op_clone(&mut self, n_ops: usize) -> usize { let start = time::Instant::now(); let mut acc = vec![]; for _i in 0..n_ops { acc.push(self.val.clone().len()); } let elapsed = start.elapsed(); self.stats.insert("clone", (elapsed, n_ops)); acc.len() } #[allow(clippy::needless_collect)] fn op_insert(&mut self, n_ops: usize, rng: &mut SmallRng) { let len = self.len(); let offs: Vec<usize> = (0..n_ops).map(|_| rng.gen::<usize>() % len).collect(); let vals: Vec<T> = (0..n_ops).map(|_| rng.gen::<T>()).collect(); let start = time::Instant::now(); for (off, val) in offs.into_iter().zip(vals.into_iter()) { match &mut self.val { Array::Vector(arr) => arr.insert(off, val).unwrap(), Array::VectorSafe(arr) => arr.insert(off, val).unwrap(), Array::Vec(arr) => arr.insert(off, val), Array::Im(arr) => arr.insert(off, val), }; } let elapsed = start.elapsed(); self.stats.insert("insert", (elapsed, n_ops)); } #[allow(clippy::needless_collect)] fn op_insert_mut(&mut self, n_ops: usize, rng: &mut SmallRng) { let len = self.len(); let offs: Vec<usize> = (0..n_ops).map(|_| rng.gen::<usize>() % len).collect(); let vals: Vec<T> = (0..n_ops).map(|_| rng.gen::<T>()).collect(); let start = time::Instant::now(); for (off, val) in offs.into_iter().zip(vals.into_iter()) { match &mut self.val { Array::Vector(arr) => arr.insert_mut(off, val).unwrap(), Array::VectorSafe(arr) => arr.insert_mut(off, val).unwrap(), Array::Vec(arr) => arr.insert(off, val), Array::Im(arr) => arr.insert(off, val), }; } let elapsed = start.elapsed(); self.stats.insert("insert_mut", (elapsed, n_ops)); } #[allow(clippy::needless_collect)] fn op_remove(&mut self, n_ops: usize, rng: &mut SmallRng) { let len = self.len(); let offs: Vec<usize> = (0..n_ops).map(|_| rng.gen::<usize>() % len).collect(); let vals: Vec<T> = (0..n_ops).map(|_| rng.gen::<T>()).collect(); for (off, val) in offs.into_iter().zip(vals.into_iter()) { match &mut self.val { Array::Vector(arr) => arr.insert(off, val).unwrap(), Array::VectorSafe(arr) => arr.insert(off, val).unwrap(), Array::Vec(arr) => arr.insert(off, val), Array::Im(arr) => arr.insert(off, val), }; } let len = self.len(); let offs = (0..n_ops).map(|i| rng.gen::<usize>() % (len - i)); let start = time::Instant::now(); for off in offs { match &mut self.val { Array::Vector(arr) => arr.remove(off).unwrap(), Array::VectorSafe(arr) => arr.remove(off).unwrap(), Array::Vec(arr) => arr.remove(off), Array::Im(arr) => arr.remove(off), }; } let elapsed = start.elapsed(); self.stats.insert("remove", (elapsed, n_ops)); } #[allow(clippy::needless_collect)] fn op_remove_mut(&mut self, n_ops: usize, rng: &mut SmallRng) { let len = self.len(); let offs: Vec<usize> = (0..n_ops).map(|_| rng.gen::<usize>() % len).collect(); let vals: Vec<T> = (0..n_ops).map(|_| rng.gen::<T>()).collect(); for (off, val) in offs.into_iter().zip(vals.into_iter()) { match &mut self.val { Array::Vector(arr) => arr.insert(off, val).unwrap(), Array::VectorSafe(arr) => arr.insert(off, val).unwrap(), Array::Vec(arr) => arr.insert(off, val), Array::Im(arr) => arr.insert(off, val), }; } let len = self.len(); let offs = (0..n_ops).map(|i| rng.gen::<usize>() % (len - i)); let start = time::Instant::now(); for off in offs { match &mut self.val { Array::Vector(arr) => { arr.remove_mut(off).unwrap(); } Array::VectorSafe(arr) => { arr.remove_mut(off).unwrap(); } Array::Vec(arr) => { arr.remove(off); } Array::Im(arr) => { arr.remove(off); } }; } let elapsed = start.elapsed(); self.stats.insert("remove_mut", (elapsed, n_ops)); } #[allow(clippy::needless_collect)] fn op_update(&mut self, n_ops: usize, rng: &mut SmallRng) { let len = self.len(); let offs: Vec<usize> = (0..n_ops).map(|_| rng.gen::<usize>() % len).collect(); let vals: Vec<T> = (0..n_ops).map(|_| rng.gen::<T>()).collect(); let start = time::Instant::now(); for (off, val) in offs.into_iter().zip(vals.into_iter()) { match &mut self.val { Array::Vector(arr) => { arr.update(off, val).unwrap(); } Array::VectorSafe(arr) => { arr.update(off, val).unwrap(); } Array::Vec(arr) => arr[off] = val, Array::Im(arr) => arr[off] = val, }; } let elapsed = start.elapsed(); self.stats.insert("update", (elapsed, n_ops)); } #[allow(clippy::needless_collect)] fn op_update_mut(&mut self, n_ops: usize, rng: &mut SmallRng) { let len = self.len(); let offs: Vec<usize> = (0..n_ops).map(|_| rng.gen::<usize>() % len).collect(); let vals = (0..n_ops).map(|_| rng.gen::<T>()); let start = time::Instant::now(); for (off, val) in offs.into_iter().zip(vals) { match &mut self.val { Array::Vector(arr) => { arr.update_mut(off, val).unwrap(); } Array::VectorSafe(arr) => { arr.update_mut(off, val).unwrap(); } Array::Vec(arr) => arr[off] = val, Array::Im(arr) => arr[off] = val, }; } let elapsed = start.elapsed(); self.stats.insert("update_mut", (elapsed, n_ops)); } fn op_get(&mut self, n_ops: usize, rng: &mut SmallRng) { let len = self.len(); let offs = (0..n_ops).map(|_| rng.gen::<usize>() % len); let start = time::Instant::now(); for off in offs { match &mut self.val { Array::Vector(val) => val.get(off).unwrap(), Array::VectorSafe(val) => val.get(off).unwrap(), Array::Vec(val) => val.get(off).unwrap(), Array::Im(val) => val.get(off).unwrap(), }; } let elapsed = start.elapsed(); self.stats.insert("get", (elapsed, n_ops)); } fn op_iter(&mut self, n_ops: usize) -> usize { let start = time::Instant::now(); let mut count = 0_usize; for _i in 0..n_ops { let v: Vec<&T> = match &mut self.val { Array::Vector(val) => val.iter().collect(), Array::VectorSafe(val) => val.iter().collect(), Array::Vec(val) => val.iter().collect(), Array::Im(val) => val.iter().collect(), }; count += v.len(); } let elapsed = start.elapsed(); self.stats.insert("iter", (elapsed, count)); count } fn op_split_append(&mut self, n_ops: usize, rng: &mut SmallRng) { let len = self.len(); let offs = (0..n_ops).map(|_| rng.gen::<usize>() % len); let mut split_off_dur = time::Duration::default(); let mut append_dur = time::Duration::default(); for off in offs { match &mut self.val { Array::Vector(val) => { let start = time::Instant::now(); let a = val.split_off(off).unwrap(); split_off_dur += start.elapsed(); let start = time::Instant::now(); val.append(a); append_dur += start.elapsed(); *val = val.rebalance(true).unwrap(); } Array::VectorSafe(val) => { let start = time::Instant::now(); let a = val.split_off(off).unwrap(); split_off_dur += start.elapsed(); let start = time::Instant::now(); val.append(a); append_dur += start.elapsed(); *val = val.rebalance(true).unwrap(); } Array::Vec(val) => { let start = time::Instant::now(); let mut a = val.split_off(off); split_off_dur += start.elapsed(); let start = time::Instant::now(); val.append(&mut a); append_dur += start.elapsed(); } Array::Im(val) => { let start = time::Instant::now(); let a = val.split_off(off); split_off_dur += start.elapsed(); let start = time::Instant::now(); val.append(a); append_dur += start.elapsed(); } } } self.stats.insert("split_off", (split_off_dur, n_ops)); self.stats.insert("append", (append_dur, n_ops)); } }
use std::panic; use rocket::{self, http::{Header, Status}, local::Client}; use diesel::connection::SimpleConnection; use serde_json; use horus_server::{self, routes::key::*}; use test::{run_test, sql::*}; #[test] fn issue() { run(|| { let client = get_client(); let req = client .post("/key/issue/999") .header(Header::new("x-api-test", USER_ID.to_string() + "/1")); // higher priv let mut response = req.dispatch(); assert_eq!(response.status(), Status::Created); assert!( response .body_string() .unwrap() .contains(USER_ID.to_string().as_str()) ); }); } #[test] fn issue_fails() { run(|| { let client = get_client(); let req = client.post("/key/issue/999"); let response = req.dispatch(); assert_eq!(response.status(), Status::Unauthorized); }); } #[test] fn validity_check() { run(|| { let client = get_client(); let req = client.get(format!("/key/{}/validity-check", API_KEY)); let mut response = req.dispatch(); assert_eq!(response.status(), Status::Ok); assert!(response.body_string().unwrap().contains(API_KEY)); }); } #[test] #[should_panic] fn validity_check_fails() { run(|| { let client = get_client(); let req = client.get("/key/invalidkey/validity-check"); let mut response = req.dispatch(); assert_eq!(response.status(), Status::Ok); assert!(response.body_string().unwrap().contains(API_KEY)); }); } fn run<T>(test: T) -> () where T: FnOnce() -> () + panic::UnwindSafe, { run_test(test, setup_db, unsetup_db); } fn setup_db() { let conn = horus_server::dbtools::get_db_conn_requestless().unwrap(); let mut setup_sql = String::new(); setup_sql.push_str(sql_insert_user().as_str()); setup_sql.push_str(sql_insert_license().as_str()); conn.batch_execute(&setup_sql).unwrap(); } fn unsetup_db() { let conn = horus_server::dbtools::get_db_conn_requestless().unwrap(); let unsetup_sql = sql_delete_user(); conn.batch_execute(&unsetup_sql).unwrap(); } fn get_client() -> Client { let rocket = rocket::ignite() .mount("/key", routes![validity_check, issue]) .manage(horus_server::dbtools::init_pool()); Client::new(rocket).expect("valid rocket instance") }
use super::triangle::Triangle; use super::mdl::MDL; #[derive(Debug)] pub struct Model { pub triangles: Vec<Triangle>, } impl Model { pub fn new (triangles: Vec<Triangle>) -> Model { Model{ triangles } } pub fn from_mdl(file_path: &str) -> Model { let mdl = MDL::open(file_path); Model { triangles: mdl.triangles, } } }
use gfx; use gfx::Bundle; use gfx_app; use gfx_app::ColorFormat; use winit::{Event, ElementState, VirtualKeyCode}; use state::{State, Visible, PREVIEW_WIDTH}; use state::template::DeltaPos; use state::color::Color; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "pos", } pipeline pipe { color: gfx::Global<[f32; 3]> = "u_color", center: gfx::Global<[f32; 2]> = "u_center", vbuf: gfx::VertexBuffer<Vertex> = (), out_color: gfx::RenderTarget<ColorFormat> = "target", clear_color: gfx::Global<[f32; 4]> = "color", } } pub struct App<R: gfx::Resources>{ bundle: Bundle<R, pipe::Data<R>>, state: State, } impl<R: gfx::Resources> gfx_app::Application<R> for App<R> { fn new<F: gfx::Factory<R>>(factory: &mut F, backend: gfx_app::shade::Backend, window_targets: gfx_app::WindowTargets<R>) -> Self { use gfx::traits::FactoryExt; let vs = gfx_app::shade::Source { glsl_150: include_bytes!("shader/tetris_150.glslv"), .. gfx_app::shade::Source::empty() }; let ps = gfx_app::shade::Source { glsl_150: include_bytes!("shader/tetris_150.glslf"), .. gfx_app::shade::Source::empty() }; let state = State::new(); let width = state.box_width(); let height = state.box_height(); let vertices = [ Vertex { pos: [-width, -height] }, Vertex { pos: [-width, height] }, Vertex { pos: [ width, -height] }, Vertex { pos: [ width, height] }, ]; let indices = [0u16, 1, 2, 1, 2, 3]; let (vertex_buffer, slice) = factory.create_vertex_buffer_with_slice(&vertices, &indices as &[u16]); let data = pipe::Data { color: Color::default().into(), center: [-2.0, -2.0], vbuf: vertex_buffer, out_color: window_targets.color, clear_color: [0.1, 0.1, 0.1, 1.0], }; let pso = factory.create_pipeline_simple( vs.select(backend).unwrap(), ps.select(backend).unwrap(), pipe::new() ).unwrap(); App { bundle: Bundle::new(slice, pso, data), state: state, } } fn render<C: gfx::CommandBuffer<R>>(&mut self, encoder: &mut gfx::Encoder<R, C>) { if !self.state.is_gameover && self.state.timer.is_up() { self.state.draw_piece(Visible::No); if self.state.move_piece(DeltaPos { dx: 0, dy: 1 }).is_err() { self.state.draw_piece(Visible::Yes); self.state.collapse_rows(); if self.state.spawn_piece().is_err() { println!("Game over\nYour score: {}", self.state.score); } else { self.state.draw_piece(Visible::Yes); } } else { self.state.draw_piece(Visible::Yes); } } let mut data = self.bundle.data.clone(); let box_width = self.state.box_width(); let box_height = self.state.box_height(); let middle_y = self.state.dim().h as f32 / 2.0 - 0.5; let middle_x = self.state.dim().w as f32 / 2.0 - 0.5; encoder.clear(&data.out_color, data.clear_color); for pos in self.state.main.get_iter() { let x = (pos.x as f32 / middle_x - 1.0) * (1.0 - box_width); let y = - (pos.y as f32 / middle_y - 1.0) * (1.0 - box_height); data.center = [x, y]; data.color = self.state.main.tile(pos).into(); encoder.draw(&self.bundle.slice, &self.bundle.pso, &data); } let offset = self.state.dim().w - PREVIEW_WIDTH; for pos in self.state.preview.get_iter() { let x = ((pos.x + offset) as f32 / middle_x - 1.0) * (1.0 - box_width); let y = - (pos.y as f32 / middle_y - 1.0) * (1.0 - box_height); data.center = [x, y]; data.color = self.state.preview.tile(pos).into(); encoder.draw(&self.bundle.slice, &self.bundle.pso, &data); } self.bundle.encode(encoder); } fn on(&mut self, event: Event) { if self.state.is_gameover { return; } match event { Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Left)) => { self.state.draw_piece(Visible::No); let _ = self.state.move_piece(DeltaPos { dx: -1, dy: 0 }); self.state.draw_piece(Visible::Yes); }, Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Right)) => { self.state.draw_piece(Visible::No); let _ = self.state.move_piece(DeltaPos { dx: 1, dy: 0 }); self.state.draw_piece(Visible::Yes); }, Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Down)) => { self.state.draw_piece(Visible::No); let _ = self.state.move_piece(DeltaPos { dx: 0, dy: 1 }); self.state.draw_piece(Visible::Yes); }, Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Up)) => { self.state.draw_piece(Visible::No); self.state.rotate_piece(); self.state.draw_piece(Visible::Yes); } Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Space)) => { self.state.draw_piece(Visible::No); self.state.hard_drop(); self.state.draw_piece(Visible::Yes); self.state.collapse_rows(); if self.state.spawn_piece().is_err() { println!("Game over\nYour score: {}", self.state.score); } else { self.state.draw_piece(Visible::Yes); } } _ => (), } } }
use std::env; use std::error::Error; use std::fs::File; use std::path::Path; use std::io::Read; fn main() { println!("Rusty Brainfuck Interpreter"); let args: Vec<String> = env::args().collect(); let path = Path::new(&args[1]); let mut file = match File::open(&path) { Err(why) => panic!("{}", why.description()), Ok(file) => file, // if no error, return fd }; let mut content = String::new(); match file.read_to_string(&mut content) { Err(why) => panic!("{}", why.description()), Ok(_) => {}, }; let mut register_pointer = 0usize; let mut code_pointer = 0usize; #[derive(Debug)] let mut code = Vec::new(); let mut inloop_vec: Vec<usize> = Vec::new(); let mut register = vec![0;1]; for c in content.chars() { match c { '<' | '>' | '+' | '-' | '.' | '[' | ']' => code.push(c), _ => { }, } } println!("{:?}", code); loop { if args.len() > 2 { if args[2] == "fullprint" { print!("\n{:?} p_loc {}", register, register_pointer); } } match code[code_pointer] { '<' => if register_pointer != 0 { register_pointer -= 1; }, '>' => { if register.len() -1 == register_pointer { register.push(0); } register_pointer += 1; }, '+' => register[register_pointer] += 1, '-' => register[register_pointer] -= 1, '.' => print!("{}", to_ascii(&register[register_pointer])), '[' => inloop_vec.push(code_pointer), ']' => { if register[register_pointer] != 0 { code_pointer = *inloop_vec.last().unwrap(); } else { inloop_vec.pop(); } }, _ => { }, } code_pointer += 1; if code_pointer == code.len() { return } } } fn to_ascii(i: &i32) -> String { match *i { x@0...127 => format!("{:?}", x as u8 as char), _ => "".into(), } }
use crate::device::Device; use crate::sys; #[allow(dead_code)] pub struct Swapchain { swapchain: sys::dxgi::Swapchain, backbuffer: sys::dxgi::BackbufferRaw, render_target: sys::direct2d::Bitmap, } impl Swapchain { pub fn create_from_hwnd(device: &Device, hwnd: winapi::shared::windef::HWND) -> Self { let swapchain = sys::dxgi::Swapchain::create_from_hwnd(&device.d3d11_device, hwnd); let backbuffer = swapchain.get_backbuffer(); let render_target = device.create_bitmap_from_backbuffer(&backbuffer); device.set_target(&render_target); Swapchain { swapchain, backbuffer, render_target, } } pub fn present(&self) { self.swapchain.present(); } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorDetails>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorDetails { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ManagementGroupInfo>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ManagementGroupInfoProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupInfoProperties { #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroup { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ManagementGroupProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupProperties { #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub details: Option<ManagementGroupDetailsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupDetailsProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<f64>, #[serde(rename = "updatedTime", default, skip_serializing_if = "Option::is_none")] pub updated_time: Option<String>, #[serde(rename = "updatedBy", default, skip_serializing_if = "Option::is_none")] pub updated_by: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub parent: Option<ParentGroupInfo>, #[serde(rename = "managementGroupType", default, skip_serializing_if = "Option::is_none")] pub management_group_type: Option<ManagementGroupType>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ParentGroupInfo { #[serde(rename = "parentId", default, skip_serializing_if = "Option::is_none")] pub parent_id: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ManagementGroupType { Enrollment, Department, Account, Subscription, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupWithChildren { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ManagementGroupPropertiesWithChildren>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupPropertiesWithChildren { #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub details: Option<ManagementGroupDetailsProperties>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub children: Vec<ManagementGroupChildInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupChildInfo { #[serde(rename = "childType", default, skip_serializing_if = "Option::is_none")] pub child_type: Option<ManagementGroupType>, #[serde(rename = "childId", default, skip_serializing_if = "Option::is_none")] pub child_id: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupWithHierarchy { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ManagementGroupPropertiesWithHierarchy>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupPropertiesWithHierarchy { #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub details: Option<ManagementGroupDetailsProperties>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub children: Vec<ManagementGroupRecursiveChildInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagementGroupRecursiveChildInfo { #[serde(rename = "childType", default, skip_serializing_if = "Option::is_none")] pub child_type: Option<ManagementGroupType>, #[serde(rename = "childId", default, skip_serializing_if = "Option::is_none")] pub child_id: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub children: Vec<ManagementGroupRecursiveChildInfo>, }
//! Shibboleth SP authentication plugin for Gotham web applications extern crate futures; extern crate gotham; #[macro_use] extern crate gotham_derive; extern crate hyper; #[macro_use] extern crate log; #[macro_use] extern crate percent_encoding; extern crate serde; #[macro_use] extern crate serde_derive; #[cfg(test)] extern crate serde_bytes; mod authenticated_session; mod headers; mod middleware; mod receiver; mod router; pub use authenticated_session::*; pub use middleware::*; pub use receiver::*; pub use router::*;
use futures::future::Future; use std::net::IpAddr; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Arc; #[derive(PartialEq, Clone)] pub enum SocketType { RawIpv4, RawIpv6, ICMP, TCP, UDP, } #[derive(Debug)] pub enum SocketSendError { SocketNotReady, Exhausted, Unknown(String), } #[derive(Debug)] pub enum SocketReceiveError { SocketNotReady, Unknown(String), } #[derive(Debug)] pub enum SocketConnectionError { Exhausted, Unknown(String), } pub type OnTcpSocketData = Arc<dyn Fn(&[u8]) -> Result<usize, SocketReceiveError>>; pub type OnUdpSocketData = Arc<dyn Fn(&[u8], IpAddr, u16) -> Result<usize, SocketReceiveError>>; pub trait Socket { fn tcp_socket_send(&mut self, data: &[u8]) -> Result<usize, SocketSendError>; fn udp_socket_send(&mut self, data: &[u8], addr: SocketAddr) -> Result<usize, SocketSendError>; fn tcp_connect(&mut self, addr: SocketAddr, port: u16) -> Result<(), SocketConnectionError>; fn tcp_receive(&mut self, f: &dyn Fn(&[u8])) -> Result<usize, SocketReceiveError>; fn udp_receive( &mut self, f: &dyn Fn(&[u8], SocketAddr, u16), ) -> Result<usize, SocketReceiveError>; } #[cfg(feature = "async")] pub trait AsyncSocket { fn tcp_socket_send<'a>( &'a mut self, data: &'a [u8], ) -> Pin<Box<dyn Future<Output = Result<usize, SocketSendError>> + Send + 'a>>; fn tcp_connect<'a>( &'a mut self, addr: SocketAddr, src_port: u16, ) -> Pin<Box<dyn Future<Output = Result<(), SocketConnectionError>> + Send + 'a>>; fn tcp_receive<'a>( &'a mut self, f: &'a dyn Fn(&[u8]), ) -> Pin<Box<dyn Future<Output = Result<usize, SocketReceiveError>> + Send + 'a>>; fn udp_socket_send<'a>( &'a mut self, data: &'a [u8], addr: SocketAddr, ) -> Pin<Box<dyn Future<Output = Result<usize, SocketSendError>> + Send + 'a>>; fn udp_receive<'a>( &'a mut self, f: &'a dyn Fn(&[u8], SocketAddr, u16), ) -> Pin<Box<dyn Future<Output = Result<usize, SocketReceiveError>> + Send + 'a>>; }
mod DJKey; use crate::DJKey::DJKey::CamelotKey; use std::env; fn main() { println!("Hello, world!"); let args: Vec<String> = env::args().collect(); // first argument is switch to indicate what type of key we are inputting // 1. --camelot -c // 2. --key -k let switch = &args[1]; // second argument is the key value to parse // either of the form // 1. [1-12]{AB} // 2. [A-G]{#b} let key = &args[2]; println!("first argument is {}", switch); println!("second arg is {}", key); let key = key.parse::<CamelotKey>(); }
use crate::figure::IndexedMesh; use crate::figure::MeshPoint; use crate::figure::RegularMesh; use crate::figure::RenderableMesh; use gltf::mesh::util::ReadIndices::{U16, U32, U8}; use nalgebra::Vector3; use nalgebra_glm::cross; use nalgebra_glm::length; use nalgebra_glm::normalize; pub enum LoadingError { Ooops, } impl From<gltf::Error> for LoadingError { fn from(_: gltf::Error) -> Self { LoadingError::Ooops } } pub fn load_figures(path: &str) -> Result<Vec<RenderableMesh>, LoadingError> { let mut figures: Vec<RenderableMesh> = Vec::new(); let (gltf, buffers, _) = gltf::import(path)?; for mesh in gltf.meshes() { for primitive in mesh.primitives() { let mut points: Vec<MeshPoint> = Vec::new(); let reader = primitive.reader(|buffer| Some(&buffers[buffer.index()])); let norm_iter = reader.read_normals(); let vert_iter = reader.read_positions(); let tangents_iter = reader.read_tangents(); match (vert_iter, norm_iter, tangents_iter) { (Some(verts), Some(norms), Some(tangents)) => { let iter = verts.zip(norms).zip(tangents); for ((vert, norm), tang) in iter { points.push(MeshPoint::new( vert, [1.0, 1.0, 1.0], norm, [tang[0], tang[1], tang[2]], )) } } (Some(verts), Some(norms), None) => { let iter = verts.zip(norms); for (vert, norm) in iter { let tangent = calc_tangent(norm); points.push(MeshPoint::new(vert, [1.0, 1.0, 1.0], norm, tangent)) } } (_, _, _) => {} } let o_indices = reader.read_indices().map(|indcs| { let indices: Vec<u32> = match indcs { U8(iter) => iter.map(|i| i as u32).collect(), U16(iter) => iter.map(|i| i as u32).collect(), U32(iter) => iter.map(|i| i as u32).collect(), }; indices }); let mesh = match o_indices { Some(indices) => RenderableMesh::Indexed(IndexedMesh { points, indices }), None => RenderableMesh::Regular(RegularMesh { points }), }; figures.push(mesh); } } Ok(figures) } pub fn calc_tangent(norm: [f32; 3]) -> [f32; 3] { let v1 = Vector3::new(0.0, 0.0, 1.0); let v2 = Vector3::new(0.0, 1.0, 0.0); let v_norm = Vector3::new(norm[0], norm[1], norm[2]); let c1: Vector3<f32> = cross(&v_norm, &v1); let c2: Vector3<f32> = cross(&v_norm, &v2); let mut tang = if length(&c1) > length(&c2) { c1 } else { c2 }; tang = normalize(&tang); tang.into() }
use crate::search::request::{boost_request::RequestBoostPart, snippet_info::SnippetInfo}; use core::cmp::Ordering; use ordered_float::OrderedFloat; /// Internal and External structure for defining the search requests tree. #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "lowercase")] pub enum SearchRequest { Or(SearchTree), And(SearchTree), /// Search on a field Search(RequestSearchPart), } #[derive(Serialize, Deserialize, Default, Clone, Debug)] pub struct SearchTree { /// list of subqueries pub queries: Vec<SearchRequest>, #[serde(default)] #[serde(skip_serializing_if = "Option::is_none")] /// Options which should be applied on the subqueries pub options: Option<SearchRequestOptions>, } impl SearchRequest { pub fn simplify(&mut self) { match self { // Pull up Or Conditions SearchRequest::Or(subtree) => { // move the tree down first, to do a complete simplify for sub_query in &mut subtree.queries { sub_query.simplify(); } let mut sub_ors = Vec::new(); for i in (0..subtree.queries.len()).rev() { match &subtree.queries[i] { // We can only simplify if options are none SearchRequest::Or(req) if req.options.is_none() => match subtree.queries.remove(i) { SearchRequest::Or(search_tree) => sub_ors.extend(search_tree.queries), _ => unreachable!(), }, _ => {} } } subtree.queries.extend(sub_ors.into_iter()); } // Pull up And Conditions SearchRequest::And(subtree) => { // move the tree down first, to do a complete simplify for sub_query in &mut subtree.queries { sub_query.simplify(); } let mut sub_ands = Vec::new(); for i in (0..subtree.queries.len()).rev() { match &subtree.queries[i] { // We can only simplify if options are none SearchRequest::And(req) if req.options.is_none() => match subtree.queries.remove(i) { SearchRequest::And(search_tree) => sub_ands.extend(search_tree.queries), _ => unreachable!(), }, _ => {} } } subtree.queries.extend(sub_ands.into_iter()); } SearchRequest::Search(_req) => {} } } pub fn get_options(&self) -> &Option<SearchRequestOptions> { match self { SearchRequest::Or(SearchTree { options, .. }) => options, SearchRequest::And(SearchTree { options, .. }) => options, SearchRequest::Search(el) => &el.options, } } pub fn get_options_mut(&mut self) -> &mut Option<SearchRequestOptions> { match self { SearchRequest::Or(SearchTree { options, .. }) => options, SearchRequest::And(SearchTree { options, .. }) => options, SearchRequest::Search(el) => &mut el.options, } } pub fn as_request_search_part(&self) -> &RequestSearchPart { match self { SearchRequest::Search(el) => el, _ => panic!("as_request_search_part"), } } pub fn get_boost(&self) -> Option<&[RequestBoostPart]> { self.get_options().as_ref().and_then(|opt| opt.boost.as_deref()) } } #[derive(Serialize, Deserialize, Default, Clone, Debug, Hash, PartialEq, Eq, PartialOrd)] pub struct SearchRequestOptions { #[serde(skip_serializing)] #[serde(default)] //TODO explain on part of query tree not yet supported, fix and enable on pub(crate) explain: bool, #[serde(skip_serializing_if = "Option::is_none")] pub top: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] pub skip: Option<usize>, // TODO check conceptual location of RequestBoostPart, how is it used /// Not working currently when used in RequestSearchPart, use Toplevel request.boost #[serde(skip_serializing_if = "Option::is_none")] pub boost: Option<Vec<RequestBoostPart>>, } fn is_false(val: &bool) -> bool { !(*val) } /// Searching on a field, TODO rename #[derive(Serialize, Deserialize, Default, Clone, Debug, Hash, PartialEq, Eq)] pub struct RequestSearchPart { pub path: String, pub terms: Vec<String>, //TODO only first term used currently #[serde(skip_serializing_if = "Option::is_none")] pub levenshtein_distance: Option<u32>, #[serde(skip_serializing_if = "is_false")] #[serde(default)] pub starts_with: bool, #[serde(skip_serializing_if = "is_false")] #[serde(default)] pub is_regex: bool, /// TODO document #[serde(skip_serializing_if = "Option::is_none")] pub token_value: Option<RequestBoostPart>, /// boosts the search part with this value /// /// Note: You can also boost with a boost query via options #[serde(skip_serializing_if = "Option::is_none")] pub boost: Option<OrderedFloat<f32>>, // TODO Move to SearchRequestOptions, to boost whole subtrees /// Matches terms cases insensitive /// /// default is to ignore case /// /// e.g. "Term" would match "terM" with `ignore_case` true #[serde(skip_serializing_if = "Option::is_none")] pub ignore_case: Option<bool>, /// return the snippet hit #[serde(skip_serializing_if = "Option::is_none")] pub snippet: Option<bool>, /// Override default SnippetInfo #[serde(skip_serializing_if = "Option::is_none")] pub snippet_info: Option<SnippetInfo>, //TODO REMOVE, AND MOVE TO SearchRequestOptions #[serde(skip_serializing_if = "Option::is_none")] pub top: Option<usize>, //TODO REMOVE, AND MOVE TO SearchRequestOptions #[serde(skip_serializing_if = "Option::is_none")] pub skip: Option<usize>, #[serde(default)] #[serde(skip_serializing_if = "Option::is_none")] pub options: Option<SearchRequestOptions>, } impl RequestSearchPart { pub fn is_explain(&self) -> bool { self.options.as_ref().map(|o| o.explain).unwrap_or_default() } pub fn short_dbg_info(&self) -> String { format!("{:?} in {:?} (isRegex:{},starts_with:{})", self.terms[0], self.path, self.is_regex, self.starts_with) } } impl Ord for RequestSearchPart { fn cmp(&self, other: &RequestSearchPart) -> Ordering { format!("{:?}", self).cmp(&format!("{:?}", other)) } } impl PartialOrd for RequestSearchPart { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { format!("{:?}", self).partial_cmp(&format!("{:?}", other)) } }
pub fn run() { println!("Print Statemet"); println!("Number {}", 1); //Basic Formatting println!("{} is from {}", "Rajeevalochan", "Veppampattu"); //Positional Arguments println!( "{0} is from {1} and {0} Loves to {2}", "Rajeevalochan", "Veppampatu", "Code" ); //Named Arguments println!( "{hisName} loves {herName}", hisName = "Rajeevalochan", herName = "Buji" ); //Placeholder Traits println!("Binary: {:b} Hex: {:x} Octal: {:o}", 10, 10, 10); println!("{:?}", (12, true, "Hola")); }
#![cfg(test)] use super::*; use crate::physics::single_chain::test::Parameters; mod base { use super::*; use rand::Rng; #[test] fn init() { let parameters = Parameters::default(); let _ = FJC::init(parameters.number_of_links_minimum, parameters.link_length_reference, parameters.hinge_mass_reference); } #[test] fn number_of_links() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); assert_eq!(number_of_links, FJC::init(number_of_links, parameters.link_length_reference, parameters.hinge_mass_reference).number_of_links); } } #[test] fn link_length() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); assert_eq!(link_length, FJC::init(parameters.number_of_links_minimum, link_length, parameters.hinge_mass_reference).link_length); } } #[test] fn hinge_mass() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); assert_eq!(hinge_mass, FJC::init(parameters.number_of_links_minimum, parameters.link_length_reference, hinge_mass).hinge_mass); } } #[test] fn all_parameters() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); assert_eq!(number_of_links, model.number_of_links); assert_eq!(link_length, model.link_length); assert_eq!(hinge_mass, model.hinge_mass); } } } mod nondimensional { use super::*; use rand::Rng; #[test] fn end_to_end_length() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_end_to_end_length = model.nondimensional_end_to_end_length(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let end_to_end_length = model.end_to_end_length(&potential_distance, &potential_stiffness, &temperature); let residual_abs = &end_to_end_length/link_length - &nondimensional_end_to_end_length; let residual_rel = &residual_abs/&nondimensional_end_to_end_length; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn end_to_end_length_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_end_to_end_length = model.nondimensional_end_to_end_length_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let end_to_end_length = model.end_to_end_length_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = &end_to_end_length/link_length - &nondimensional_end_to_end_length; let residual_rel = &residual_abs/&nondimensional_end_to_end_length; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn force() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_force = model.nondimensional_force(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let force = model.force(&potential_distance, &potential_stiffness, &temperature); let residual_abs = &force/BOLTZMANN_CONSTANT/temperature*link_length - &nondimensional_force; let residual_rel = &residual_abs/&nondimensional_force; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_helmholtz_free_energy = model.nondimensional_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let helmholtz_free_energy = model.helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature); let residual_abs = helmholtz_free_energy/BOLTZMANN_CONSTANT/temperature - nondimensional_helmholtz_free_energy; let residual_rel = residual_abs/nondimensional_helmholtz_free_energy; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn helmholtz_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_helmholtz_free_energy_per_link = model.nondimensional_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let helmholtz_free_energy_per_link = model.helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = helmholtz_free_energy_per_link/BOLTZMANN_CONSTANT/temperature - nondimensional_helmholtz_free_energy_per_link; let residual_rel = residual_abs/nondimensional_helmholtz_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn relative_helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_relative_helmholtz_free_energy = model.nondimensional_relative_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let relative_helmholtz_free_energy = model.relative_helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature); let residual_abs = relative_helmholtz_free_energy/BOLTZMANN_CONSTANT/temperature - nondimensional_relative_helmholtz_free_energy; let residual_rel = residual_abs/nondimensional_relative_helmholtz_free_energy; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn relative_helmholtz_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_relative_helmholtz_free_energy_per_link = model.nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let relative_helmholtz_free_energy_per_link = model.relative_helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = relative_helmholtz_free_energy_per_link/BOLTZMANN_CONSTANT/temperature - nondimensional_relative_helmholtz_free_energy_per_link; let residual_rel = residual_abs/nondimensional_relative_helmholtz_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_gibbs_free_energy = model.nondimensional_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let gibbs_free_energy = model.gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature); let residual_abs = gibbs_free_energy/BOLTZMANN_CONSTANT/temperature - nondimensional_gibbs_free_energy; let residual_rel = residual_abs/nondimensional_gibbs_free_energy; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn gibbs_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_gibbs_free_energy_per_link = model.nondimensional_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let gibbs_free_energy_per_link = model.gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = gibbs_free_energy_per_link/BOLTZMANN_CONSTANT/temperature - nondimensional_gibbs_free_energy_per_link; let residual_rel = residual_abs/nondimensional_gibbs_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn relative_gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_relative_gibbs_free_energy = model.nondimensional_relative_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let relative_gibbs_free_energy = model.relative_gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature); let residual_abs = relative_gibbs_free_energy/BOLTZMANN_CONSTANT/temperature - nondimensional_relative_gibbs_free_energy; let residual_rel = residual_abs/nondimensional_relative_gibbs_free_energy; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn relative_gibbs_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_relative_gibbs_free_energy_per_link = model.nondimensional_relative_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let relative_gibbs_free_energy_per_link = model.relative_gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = relative_gibbs_free_energy_per_link/BOLTZMANN_CONSTANT/temperature - nondimensional_relative_gibbs_free_energy_per_link; let residual_rel = residual_abs/nondimensional_relative_gibbs_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } } mod per_link { use super::*; use rand::Rng; #[test] fn end_to_end_length() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let end_to_end_length = model.end_to_end_length(&potential_distance, &potential_stiffness, &temperature); let end_to_end_length_per_link = model.end_to_end_length_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = end_to_end_length/(number_of_links as f64) - end_to_end_length_per_link; let residual_rel = residual_abs/end_to_end_length_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn nondimensional_end_to_end_length() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let nondimensional_end_to_end_length = model.nondimensional_end_to_end_length(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let nondimensional_end_to_end_length_per_link = model.nondimensional_end_to_end_length_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let residual_abs = nondimensional_end_to_end_length/(number_of_links as f64) - nondimensional_end_to_end_length_per_link; let residual_rel = residual_abs/nondimensional_end_to_end_length_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let helmholtz_free_energy = model.helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature); let helmholtz_free_energy_per_link = model.helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = helmholtz_free_energy/(number_of_links as f64) - helmholtz_free_energy_per_link; let residual_rel = residual_abs/helmholtz_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn relative_helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let relative_helmholtz_free_energy = model.relative_helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature); let relative_helmholtz_free_energy_per_link = model.relative_helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = relative_helmholtz_free_energy/(number_of_links as f64) - relative_helmholtz_free_energy_per_link; let residual_rel = residual_abs/relative_helmholtz_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn nondimensional_helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_helmholtz_free_energy = model.nondimensional_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let nondimensional_helmholtz_free_energy_per_link = model.nondimensional_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let residual_abs = nondimensional_helmholtz_free_energy/(number_of_links as f64) - nondimensional_helmholtz_free_energy_per_link; let residual_rel = residual_abs/nondimensional_helmholtz_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn nondimensional_relative_helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let nondimensional_relative_helmholtz_free_energy = model.nondimensional_relative_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let nondimensional_relative_helmholtz_free_energy_per_link = model.nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let residual_abs = nondimensional_relative_helmholtz_free_energy/(number_of_links as f64) - nondimensional_relative_helmholtz_free_energy_per_link; let residual_rel = residual_abs/nondimensional_relative_helmholtz_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let gibbs_free_energy = model.gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature); let gibbs_free_energy_per_link = model.gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = gibbs_free_energy/(number_of_links as f64) - gibbs_free_energy_per_link; let residual_rel = residual_abs/gibbs_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn relative_gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let relative_gibbs_free_energy = model.relative_gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature); let relative_gibbs_free_energy_per_link = model.relative_gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = relative_gibbs_free_energy/(number_of_links as f64) - relative_gibbs_free_energy_per_link; let residual_rel = residual_abs/relative_gibbs_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn nondimensional_gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_gibbs_free_energy = model.nondimensional_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let nondimensional_gibbs_free_energy_per_link = model.nondimensional_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let residual_abs = nondimensional_gibbs_free_energy/(number_of_links as f64) - nondimensional_gibbs_free_energy_per_link; let residual_rel = residual_abs/nondimensional_gibbs_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn nondimensional_relative_gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let nondimensional_relative_gibbs_free_energy = model.nondimensional_relative_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let nondimensional_relative_gibbs_free_energy_per_link = model.nondimensional_relative_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let residual_abs = nondimensional_relative_gibbs_free_energy/(number_of_links as f64) - nondimensional_relative_gibbs_free_energy_per_link; let residual_rel = residual_abs/nondimensional_relative_gibbs_free_energy_per_link; assert!(residual_abs.abs() <= parameters.abs_tol); assert!(residual_rel.abs() <= parameters.rel_tol); } } } mod relative { use super::*; use rand::Rng; #[test] fn helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let helmholtz_free_energy = model.helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature); let helmholtz_free_energy_0 = model.helmholtz_free_energy(&ZERO, &potential_stiffness, &temperature); let relative_helmholtz_free_energy = model.relative_helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature); let residual_abs = &helmholtz_free_energy - &helmholtz_free_energy_0 - &relative_helmholtz_free_energy; let residual_rel = &residual_abs/&helmholtz_free_energy_0; assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn helmholtz_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let helmholtz_free_energy_per_link = model.helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let helmholtz_free_energy_per_link_0 = model.helmholtz_free_energy_per_link(&ZERO, &potential_stiffness, &temperature); let relative_helmholtz_free_energy_per_link = model.relative_helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = &helmholtz_free_energy_per_link - &helmholtz_free_energy_per_link_0 - &relative_helmholtz_free_energy_per_link; let residual_rel = &residual_abs/&helmholtz_free_energy_per_link_0; assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn nondimensional_helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_helmholtz_free_energy = model.nondimensional_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let nondimensional_helmholtz_free_energy_0 = model.nondimensional_helmholtz_free_energy(&ZERO, &nondimensional_potential_stiffness, &temperature); let nondimensional_relative_helmholtz_free_energy = model.nondimensional_relative_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let residual_abs = &nondimensional_helmholtz_free_energy - &nondimensional_helmholtz_free_energy_0 - &nondimensional_relative_helmholtz_free_energy; let residual_rel = &residual_abs/&nondimensional_helmholtz_free_energy_0; assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn nondimensional_helmholtz_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_helmholtz_free_energy_per_link = model.nondimensional_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let nondimensional_helmholtz_free_energy_per_link_0 = model.nondimensional_helmholtz_free_energy_per_link(&ZERO, &nondimensional_potential_stiffness, &temperature); let nondimensional_relative_helmholtz_free_energy_per_link = model.nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let residual_abs = &nondimensional_helmholtz_free_energy_per_link - &nondimensional_helmholtz_free_energy_per_link_0 - &nondimensional_relative_helmholtz_free_energy_per_link; let residual_rel = &residual_abs/&nondimensional_helmholtz_free_energy_per_link_0; assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let gibbs_free_energy = model.gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature); let gibbs_free_energy_0 = model.gibbs_free_energy(&ZERO, &potential_stiffness, &temperature); let relative_gibbs_free_energy = model.relative_gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature); let residual_abs = &gibbs_free_energy - &gibbs_free_energy_0 - &relative_gibbs_free_energy; let residual_rel = &residual_abs/&gibbs_free_energy_0; assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn gibbs_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let gibbs_free_energy_per_link = model.gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let gibbs_free_energy_per_link_0 = model.gibbs_free_energy_per_link(&ZERO, &potential_stiffness, &temperature); let relative_gibbs_free_energy_per_link = model.relative_gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature); let residual_abs = &gibbs_free_energy_per_link - &gibbs_free_energy_per_link_0 - &relative_gibbs_free_energy_per_link; let residual_rel = &residual_abs/&gibbs_free_energy_per_link_0; assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn nondimensional_gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_gibbs_free_energy = model.nondimensional_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let nondimensional_gibbs_free_energy_0 = model.nondimensional_gibbs_free_energy(&ZERO, &nondimensional_potential_stiffness, &temperature); let nondimensional_relative_gibbs_free_energy = model.nondimensional_relative_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let residual_abs = &nondimensional_gibbs_free_energy - &nondimensional_gibbs_free_energy_0 - &nondimensional_relative_gibbs_free_energy; let residual_rel = &residual_abs/&nondimensional_gibbs_free_energy_0; assert!(residual_rel.abs() <= parameters.rel_tol); } } #[test] fn nondimensional_gibbs_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let nondimensional_gibbs_free_energy_per_link = model.nondimensional_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature); let nondimensional_gibbs_free_energy_per_link_0 = model.nondimensional_gibbs_free_energy_per_link(&ZERO, &nondimensional_potential_stiffness, &temperature); let nondimensional_relative_gibbs_free_energy_per_link = model.nondimensional_relative_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let residual_abs = &nondimensional_gibbs_free_energy_per_link - &nondimensional_gibbs_free_energy_per_link_0 - &nondimensional_relative_gibbs_free_energy_per_link; let residual_rel = &residual_abs/&nondimensional_gibbs_free_energy_per_link_0; assert!(residual_rel.abs() <= parameters.rel_tol); } } } mod zero { use super::*; use rand::Rng; #[test] fn relative_helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let relative_helmholtz_free_energy_0 = model.relative_helmholtz_free_energy(&(ZERO*(number_of_links as f64)*link_length), &potential_stiffness, &temperature); assert!(relative_helmholtz_free_energy_0.abs() <= BOLTZMANN_CONSTANT*temperature*(number_of_links as f64)*ZERO); } } #[test] fn relative_helmholtz_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let relative_helmholtz_free_energy_per_link_0 = model.relative_helmholtz_free_energy_per_link(&(ZERO*(number_of_links as f64)*link_length), &potential_stiffness, &temperature); assert!(relative_helmholtz_free_energy_per_link_0.abs() <= BOLTZMANN_CONSTANT*temperature*ZERO); } } #[test] fn nondimensional_relative_helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let nondimensional_relative_helmholtz_free_energy_0 = model.nondimensional_relative_helmholtz_free_energy(&ZERO, &nondimensional_potential_stiffness); assert!(nondimensional_relative_helmholtz_free_energy_0.abs() <= (number_of_links as f64)*ZERO); } } #[test] fn nondimensional_relative_helmholtz_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let nondimensional_relative_helmholtz_free_energy_per_link_0 = model.nondimensional_relative_helmholtz_free_energy_per_link(&ZERO, &nondimensional_potential_stiffness); assert!(nondimensional_relative_helmholtz_free_energy_per_link_0.abs() <= ZERO); } } #[test] fn relative_gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let relative_gibbs_free_energy_0 = model.relative_gibbs_free_energy(&ZERO, &potential_stiffness, &temperature); assert!(relative_gibbs_free_energy_0.abs() <= BOLTZMANN_CONSTANT*temperature*(number_of_links as f64)*ZERO); } } #[test] fn relative_gibbs_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let relative_gibbs_free_energy_per_link_0 = model.relative_gibbs_free_energy_per_link(&ZERO, &potential_stiffness, &temperature); assert!(relative_gibbs_free_energy_per_link_0.abs() <= BOLTZMANN_CONSTANT*temperature*ZERO); } } #[test] fn nondimensional_relative_gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let nondimensional_relative_gibbs_free_energy_0 = model.nondimensional_relative_gibbs_free_energy(&ZERO, &nondimensional_potential_stiffness); assert!(nondimensional_relative_gibbs_free_energy_0.abs() <= (number_of_links as f64)*ZERO); } } #[test] fn nondimensional_relative_gibbs_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let nondimensional_relative_gibbs_free_energy_per_link_0 = model.nondimensional_relative_gibbs_free_energy_per_link(&ZERO, &nondimensional_potential_stiffness); assert!(nondimensional_relative_gibbs_free_energy_per_link_0.abs() <= ZERO); } } } mod connection { use super::*; use rand::Rng; #[test] fn force() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + 0.5*parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let force = model.force(&potential_distance, &potential_stiffness, &temperature); let h = parameters.rel_tol*(number_of_links as f64)*link_length; let force_from_derivative = (model.relative_helmholtz_free_energy(&(potential_distance + 0.5*h), &potential_stiffness, &temperature) - model.relative_helmholtz_free_energy(&(potential_distance - 0.5*h), &potential_stiffness, &temperature))/h; let residual_abs = &force - &force_from_derivative; let residual_rel = &residual_abs/&force; assert!(residual_rel.abs() <= h); } } #[test] fn nondimensional_force() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + 0.5*parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let nondimensional_force = model.nondimensional_force(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let h = parameters.rel_tol; let nondimensional_force_from_derivative = (model.nondimensional_relative_helmholtz_free_energy_per_link(&(nondimensional_potential_distance + 0.5*h), &nondimensional_potential_stiffness) - model.nondimensional_relative_helmholtz_free_energy_per_link(&(nondimensional_potential_distance - 0.5*h), &nondimensional_potential_stiffness))/h; let residual_abs = &nondimensional_force - &nondimensional_force_from_derivative; let residual_rel = &residual_abs/&nondimensional_force; assert!(residual_rel.abs() <= h); } } #[test] fn end_to_end_length() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + 0.5*parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + 0.5*parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let end_to_end_length = model.end_to_end_length(&potential_distance, &potential_stiffness, &temperature); let h = parameters.rel_tol*(number_of_links as f64)*link_length; let end_to_end_length_from_derivative = -1.0/potential_stiffness*(model.relative_gibbs_free_energy(&(potential_distance + 0.5*h), &potential_stiffness, &temperature) - model.relative_gibbs_free_energy(&(potential_distance - 0.5*h), &potential_stiffness, &temperature))/h; let residual_abs = &end_to_end_length - &end_to_end_length_from_derivative; let residual_rel = &residual_abs/&end_to_end_length; assert!(residual_rel.abs() <= h); } } #[test] fn end_to_end_length_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + 0.5*parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + 0.5*parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let end_to_end_length_per_link = model.end_to_end_length_per_link(&potential_distance, &potential_stiffness, &temperature); let h = parameters.rel_tol*(number_of_links as f64)*link_length; let end_to_end_length_per_link_from_derivative = -1.0/potential_stiffness*(model.relative_gibbs_free_energy_per_link(&(potential_distance + 0.5*h), &potential_stiffness, &temperature) - model.relative_gibbs_free_energy_per_link(&(potential_distance - 0.5*h), &potential_stiffness, &temperature))/h; let residual_abs = &end_to_end_length_per_link - &end_to_end_length_per_link_from_derivative; let residual_rel = &residual_abs/&end_to_end_length_per_link; assert!(residual_rel.abs() <= h); } } #[test] fn nondimensional_end_to_end_length() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + 0.5*parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + 0.5*parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let nondimensional_end_to_end_length = model.nondimensional_end_to_end_length(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let h = parameters.rel_tol; let nondimensional_end_to_end_length_from_derivative = -1.0/nondimensional_potential_stiffness/(number_of_links as f64)*(model.nondimensional_relative_gibbs_free_energy(&(nondimensional_potential_distance + 0.5*h), &nondimensional_potential_stiffness) - model.nondimensional_relative_gibbs_free_energy(&(nondimensional_potential_distance - 0.5*h), &nondimensional_potential_stiffness))/h; let residual_abs = &nondimensional_end_to_end_length - &nondimensional_end_to_end_length_from_derivative; let residual_rel = &residual_abs/&nondimensional_end_to_end_length; assert!(residual_rel.abs() <= h); } } #[test] fn nondimensional_end_to_end_length_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum); let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + 0.5*parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>()); let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + 0.5*parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>()); let nondimensional_end_to_end_length_per_link = model.nondimensional_end_to_end_length_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness); let h = parameters.rel_tol; let nondimensional_end_to_end_length_per_link_from_derivative = -1.0/nondimensional_potential_stiffness/(number_of_links as f64)*(model.nondimensional_relative_gibbs_free_energy_per_link(&(nondimensional_potential_distance + 0.5*h), &nondimensional_potential_stiffness) - model.nondimensional_relative_gibbs_free_energy_per_link(&(nondimensional_potential_distance - 0.5*h), &nondimensional_potential_stiffness))/h; let residual_abs = &nondimensional_end_to_end_length_per_link - &nondimensional_end_to_end_length_per_link_from_derivative; let residual_rel = &residual_abs/&nondimensional_end_to_end_length_per_link; assert!(residual_rel.abs() <= h); } } } mod strong_potential { use super::*; use rand::Rng; use crate::math::integrate_1d; use crate::physics::single_chain:: { ZERO, POINTS }; #[test] fn force() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |potential_distance: &f64| { (model.force(&potential_distance, &potential_stiffness, &temperature) - model.asymptotic.strong_potential.force(&potential_distance, &potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |potential_distance: &f64| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; (model.force(&potential_distance, &potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &(ZERO*(number_of_links as f64)*link_length), &(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &POINTS); let denominator = integrate_1d(&integrand_denominator, &(ZERO*(number_of_links as f64)*link_length), &(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_large); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_large*parameters.log_log_scale); let log_log_slope = (residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!((log_log_slope/2.0 + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_force() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_force(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.asymptotic.strong_potential.nondimensional_force(&nondimensional_potential_distance, &nondimensional_potential_stiffness)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { (model.nondimensional_force(&nondimensional_potential_distance, &nondimensional_potential_stiffness)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &ZERO, &parameters.nondimensional_potential_distance_small, &POINTS); let denominator = integrate_1d(&integrand_denominator, &ZERO, &parameters.nondimensional_potential_distance_small, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_large); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_large*parameters.log_log_scale); let log_log_slope = (residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!((log_log_slope/2.0 + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |potential_distance: &f64| { (model.helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature) - model.helmholtz_free_energy(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature) - model.asymptotic.strong_potential.helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature) + model.asymptotic.strong_potential.helmholtz_free_energy(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature)).powi(2) }; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_denominator = |potential_distance: &f64| { (model.helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature) - model.helmholtz_free_energy(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &(ZERO*(number_of_links as f64)*link_length), &(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &POINTS); let denominator = integrate_1d(&integrand_denominator, &(ZERO*(number_of_links as f64)*link_length), &(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_large); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_large*parameters.log_log_scale); let log_log_slope = (residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!((log_log_slope/2.0 + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn helmholtz_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |potential_distance: &f64| { (model.helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) - model.helmholtz_free_energy_per_link(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature) - model.asymptotic.strong_potential.helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) + model.asymptotic.strong_potential.helmholtz_free_energy_per_link(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature)).powi(2) }; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_denominator = |potential_distance: &f64| { (model.helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) - model.helmholtz_free_energy_per_link(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &(ZERO*(number_of_links as f64)*link_length), &(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &POINTS); let denominator = integrate_1d(&integrand_denominator, &(ZERO*(number_of_links as f64)*link_length), &(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_large); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_large*parameters.log_log_scale); let log_log_slope = (residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!((log_log_slope/2.0 + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn relative_helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |potential_distance: &f64| { (model.relative_helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature) - model.relative_helmholtz_free_energy(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature) - model.asymptotic.strong_potential.relative_helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature) + model.asymptotic.strong_potential.relative_helmholtz_free_energy(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature)).powi(2) }; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_denominator = |potential_distance: &f64| { (model.relative_helmholtz_free_energy(&potential_distance, &potential_stiffness, &temperature) - model.relative_helmholtz_free_energy(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &(ZERO*(number_of_links as f64)*link_length), &(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &POINTS); let denominator = integrate_1d(&integrand_denominator, &(ZERO*(number_of_links as f64)*link_length), &(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_large); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_large*parameters.log_log_scale); let log_log_slope = (residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!((log_log_slope/2.0 + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn relative_helmholtz_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |potential_distance: &f64| { (model.relative_helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) - model.relative_helmholtz_free_energy_per_link(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature) - model.asymptotic.strong_potential.relative_helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) + model.asymptotic.strong_potential.relative_helmholtz_free_energy_per_link(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature)).powi(2) }; let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_denominator = |potential_distance: &f64| { (model.relative_helmholtz_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) - model.relative_helmholtz_free_energy_per_link(&(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &(ZERO*(number_of_links as f64)*link_length), &(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &POINTS); let denominator = integrate_1d(&integrand_denominator, &(ZERO*(number_of_links as f64)*link_length), &(parameters.nondimensional_potential_distance_small*(number_of_links as f64)*link_length), &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_large); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_large*parameters.log_log_scale); let log_log_slope = (residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!((log_log_slope/2.0 + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) - model.nondimensional_helmholtz_free_energy(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness, &temperature) - model.asymptotic.strong_potential.nondimensional_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) + model.asymptotic.strong_potential.nondimensional_helmholtz_free_energy(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { (model.nondimensional_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) - model.nondimensional_helmholtz_free_energy(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &ZERO, &parameters.nondimensional_potential_distance_small, &POINTS); let denominator = integrate_1d(&integrand_denominator, &ZERO, &parameters.nondimensional_potential_distance_small, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_large); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_large*parameters.log_log_scale); let log_log_slope = (residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!((log_log_slope/2.0 + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_helmholtz_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) - model.nondimensional_helmholtz_free_energy_per_link(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness, &temperature) - model.asymptotic.strong_potential.nondimensional_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) + model.asymptotic.strong_potential.nondimensional_helmholtz_free_energy_per_link(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { (model.nondimensional_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) - model.nondimensional_helmholtz_free_energy_per_link(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &ZERO, &parameters.nondimensional_potential_distance_small, &POINTS); let denominator = integrate_1d(&integrand_denominator, &ZERO, &parameters.nondimensional_potential_distance_small, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_large); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_large*parameters.log_log_scale); let log_log_slope = (residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!((log_log_slope/2.0 + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_relative_helmholtz_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_relative_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.nondimensional_relative_helmholtz_free_energy(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness) - model.asymptotic.strong_potential.nondimensional_relative_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness) + model.asymptotic.strong_potential.nondimensional_relative_helmholtz_free_energy(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { (model.nondimensional_relative_helmholtz_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.nondimensional_relative_helmholtz_free_energy(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &ZERO, &parameters.nondimensional_potential_distance_small, &POINTS); let denominator = integrate_1d(&integrand_denominator, &ZERO, &parameters.nondimensional_potential_distance_small, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_large); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_large*parameters.log_log_scale); let log_log_slope = (residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!((log_log_slope/2.0 + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_relative_helmholtz_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.nondimensional_relative_helmholtz_free_energy_per_link(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness) - model.asymptotic.strong_potential.nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness) + model.asymptotic.strong_potential.nondimensional_relative_helmholtz_free_energy_per_link(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { (model.nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.nondimensional_relative_helmholtz_free_energy_per_link(&parameters.nondimensional_potential_distance_small, &nondimensional_potential_stiffness)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &ZERO, &parameters.nondimensional_potential_distance_small, &POINTS); let denominator = integrate_1d(&integrand_denominator, &ZERO, &parameters.nondimensional_potential_distance_small, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_large); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_large*parameters.log_log_scale); let log_log_slope = (residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!((log_log_slope/2.0 + 1.0).abs() <= parameters.log_log_tol); } } } mod weak_potential { use super::*; use rand::Rng; use crate::math::integrate_1d; #[test] fn end_to_end_length() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; (model.end_to_end_length(&potential_distance, &potential_stiffness, &temperature) - model.asymptotic.weak_potential.end_to_end_length(&potential_distance, &potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; model.end_to_end_length(&potential_distance, &potential_stiffness, &temperature).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn end_to_end_length_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; (model.end_to_end_length_per_link(&potential_distance, &potential_stiffness, &temperature) - model.asymptotic.weak_potential.end_to_end_length_per_link(&potential_distance, &potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; model.end_to_end_length_per_link(&potential_distance, &potential_stiffness, &temperature).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_end_to_end_length() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_end_to_end_length(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.asymptotic.weak_potential.nondimensional_end_to_end_length(&nondimensional_potential_distance, &nondimensional_potential_stiffness)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { model.nondimensional_end_to_end_length(&nondimensional_potential_distance, &nondimensional_potential_stiffness).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_end_to_end_length_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_end_to_end_length_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.asymptotic.weak_potential.nondimensional_end_to_end_length_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { model.nondimensional_end_to_end_length_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; (model.gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature) - model.gibbs_free_energy(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature) - model.asymptotic.weak_potential.gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature) + model.asymptotic.weak_potential.gibbs_free_energy(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; (model.gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature) - model.gibbs_free_energy(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn gibbs_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; (model.gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) - model.gibbs_free_energy_per_link(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature) - model.asymptotic.weak_potential.gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) + model.asymptotic.weak_potential.gibbs_free_energy_per_link(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; (model.gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) - model.gibbs_free_energy_per_link(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn relative_gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; (model.relative_gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature) - model.relative_gibbs_free_energy(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature) - model.asymptotic.weak_potential.relative_gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature) + model.asymptotic.weak_potential.relative_gibbs_free_energy(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; (model.relative_gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature) - model.relative_gibbs_free_energy(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn relative_gibbs_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature; let integrand_numerator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; (model.relative_gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) - model.relative_gibbs_free_energy_per_link(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature) - model.asymptotic.weak_potential.relative_gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) + model.asymptotic.weak_potential.relative_gibbs_free_energy_per_link(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { let potential_distance = (number_of_links as f64)*link_length*nondimensional_potential_distance; (model.relative_gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature) - model.relative_gibbs_free_energy_per_link(&((number_of_links as f64)*link_length*parameters.nondimensional_potential_distance_large_1), &potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) - model.nondimensional_gibbs_free_energy(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness, &temperature) - model.asymptotic.weak_potential.nondimensional_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) + model.asymptotic.weak_potential.nondimensional_gibbs_free_energy(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { (model.nondimensional_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) - model.nondimensional_gibbs_free_energy(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_gibbs_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>()); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) - model.nondimensional_gibbs_free_energy_per_link(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness, &temperature) - model.asymptotic.weak_potential.nondimensional_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) + model.asymptotic.weak_potential.nondimensional_gibbs_free_energy_per_link(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness, &temperature)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { (model.nondimensional_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature) - model.nondimensional_gibbs_free_energy_per_link(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness, &temperature)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_relative_gibbs_free_energy() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_relative_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.nondimensional_relative_gibbs_free_energy(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness) - model.asymptotic.weak_potential.nondimensional_relative_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness) + model.asymptotic.weak_potential.nondimensional_relative_gibbs_free_energy(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { (model.nondimensional_relative_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.nondimensional_relative_gibbs_free_energy(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } #[test] fn nondimensional_relative_gibbs_free_energy_per_link() { let mut rng = rand::thread_rng(); let parameters = Parameters::default(); for _ in 0..parameters.number_of_loops { let number_of_links: u8 = parameters.number_of_links_maximum - parameters.number_of_links_minimum; let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>()); let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>()); let model = FJC::init(number_of_links, link_length, hinge_mass); let residual_rel = |nondimensional_potential_stiffness| { let integrand_numerator = |nondimensional_potential_distance: &f64| { (model.nondimensional_relative_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.nondimensional_relative_gibbs_free_energy_per_link(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness) - model.asymptotic.weak_potential.nondimensional_relative_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness) + model.asymptotic.weak_potential.nondimensional_relative_gibbs_free_energy_per_link(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness)).powi(2) }; let integrand_denominator = |nondimensional_potential_distance: &f64| { (model.nondimensional_relative_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness) - model.nondimensional_relative_gibbs_free_energy_per_link(&parameters.nondimensional_potential_distance_large_1, &nondimensional_potential_stiffness)).powi(2) }; let numerator = integrate_1d(&integrand_numerator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); let denominator = integrate_1d(&integrand_denominator, &parameters.nondimensional_potential_distance_large_1, &parameters.nondimensional_potential_distance_large_2, &POINTS); (numerator/denominator).sqrt() }; let residual_rel_1 = residual_rel(parameters.nondimensional_potential_stiffness_small); let residual_rel_2 = residual_rel(parameters.nondimensional_potential_stiffness_small*parameters.log_log_scale); let log_log_slope = -(residual_rel_2/residual_rel_1).ln()/(parameters.log_log_scale).ln(); assert!(residual_rel_1.abs() <= parameters.nondimensional_potential_stiffness_small); assert!(residual_rel_2.abs() <= parameters.nondimensional_potential_stiffness_small/parameters.log_log_scale); assert!((log_log_slope + 1.0).abs() <= parameters.log_log_tol); } } }
#[doc = "Register `JOFR%s` reader"] pub type R = crate::R<JOFR_SPEC>; #[doc = "Register `JOFR%s` writer"] pub type W = crate::W<JOFR_SPEC>; #[doc = "Field `JOFFSET` reader - Data offset for injected channel x"] pub type JOFFSET_R = crate::FieldReader<u16>; #[doc = "Field `JOFFSET` writer - Data offset for injected channel x"] pub type JOFFSET_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 12, O, u16>; impl R { #[doc = "Bits 0:11 - Data offset for injected channel x"] #[inline(always)] pub fn joffset(&self) -> JOFFSET_R { JOFFSET_R::new((self.bits & 0x0fff) as u16) } } impl W { #[doc = "Bits 0:11 - Data offset for injected channel x"] #[inline(always)] #[must_use] pub fn joffset(&mut self) -> JOFFSET_W<JOFR_SPEC, 0> { JOFFSET_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "injected channel data offset register x\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`jofr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`jofr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct JOFR_SPEC; impl crate::RegisterSpec for JOFR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`jofr::R`](R) reader structure"] impl crate::Readable for JOFR_SPEC {} #[doc = "`write(|w| ..)` method takes [`jofr::W`](W) writer structure"] impl crate::Writable for JOFR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets JOFR%s to value 0"] impl crate::Resettable for JOFR_SPEC { const RESET_VALUE: Self::Ux = 0; }
/// An enum to represent all characters in the PauCinHau block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum PauCinHau { /// \u{11ac0}: '𑫀' LetterPa, /// \u{11ac1}: '𑫁' LetterKa, /// \u{11ac2}: '𑫂' LetterLa, /// \u{11ac3}: '𑫃' LetterMa, /// \u{11ac4}: '𑫄' LetterDa, /// \u{11ac5}: '𑫅' LetterZa, /// \u{11ac6}: '𑫆' LetterVa, /// \u{11ac7}: '𑫇' LetterNga, /// \u{11ac8}: '𑫈' LetterHa, /// \u{11ac9}: '𑫉' LetterGa, /// \u{11aca}: '𑫊' LetterKha, /// \u{11acb}: '𑫋' LetterSa, /// \u{11acc}: '𑫌' LetterBa, /// \u{11acd}: '𑫍' LetterCa, /// \u{11ace}: '𑫎' LetterTa, /// \u{11acf}: '𑫏' LetterTha, /// \u{11ad0}: '𑫐' LetterNa, /// \u{11ad1}: '𑫑' LetterPha, /// \u{11ad2}: '𑫒' LetterRa, /// \u{11ad3}: '𑫓' LetterFa, /// \u{11ad4}: '𑫔' LetterCha, /// \u{11ad5}: '𑫕' LetterA, /// \u{11ad6}: '𑫖' LetterE, /// \u{11ad7}: '𑫗' LetterI, /// \u{11ad8}: '𑫘' LetterO, /// \u{11ad9}: '𑫙' LetterU, /// \u{11ada}: '𑫚' LetterUa, /// \u{11adb}: '𑫛' LetterIa, /// \u{11adc}: '𑫜' LetterFinalP, /// \u{11add}: '𑫝' LetterFinalK, /// \u{11ade}: '𑫞' LetterFinalT, /// \u{11adf}: '𑫟' LetterFinalM, /// \u{11ae0}: '𑫠' LetterFinalN, /// \u{11ae1}: '𑫡' LetterFinalL, /// \u{11ae2}: '𑫢' LetterFinalW, /// \u{11ae3}: '𑫣' LetterFinalNg, /// \u{11ae4}: '𑫤' LetterFinalY, /// \u{11ae5}: '𑫥' RisingToneLong, /// \u{11ae6}: '𑫦' RisingTone, /// \u{11ae7}: '𑫧' SandhiGlottalStop, /// \u{11ae8}: '𑫨' RisingToneLongFinal, /// \u{11ae9}: '𑫩' RisingToneFinal, /// \u{11aea}: '𑫪' SandhiGlottalStopFinal, /// \u{11aeb}: '𑫫' SandhiToneLong, /// \u{11aec}: '𑫬' SandhiTone, /// \u{11aed}: '𑫭' SandhiToneLongFinal, /// \u{11aee}: '𑫮' SandhiToneFinal, /// \u{11aef}: '𑫯' MidDashLevelTone, /// \u{11af0}: '𑫰' GlottalStopVariant, /// \u{11af1}: '𑫱' MidDashLevelToneLongFinal, /// \u{11af2}: '𑫲' MidDashLevelToneFinal, /// \u{11af3}: '𑫳' LowDashFallingToneLong, /// \u{11af4}: '𑫴' LowDashFallingTone, /// \u{11af5}: '𑫵' GlottalStop, /// \u{11af6}: '𑫶' LowDashFallingToneLongFinal, /// \u{11af7}: '𑫷' LowDashFallingToneFinal, /// \u{11af8}: '𑫸' GlottalStopFinal, } impl Into<char> for PauCinHau { fn into(self) -> char { match self { PauCinHau::LetterPa => '𑫀', PauCinHau::LetterKa => '𑫁', PauCinHau::LetterLa => '𑫂', PauCinHau::LetterMa => '𑫃', PauCinHau::LetterDa => '𑫄', PauCinHau::LetterZa => '𑫅', PauCinHau::LetterVa => '𑫆', PauCinHau::LetterNga => '𑫇', PauCinHau::LetterHa => '𑫈', PauCinHau::LetterGa => '𑫉', PauCinHau::LetterKha => '𑫊', PauCinHau::LetterSa => '𑫋', PauCinHau::LetterBa => '𑫌', PauCinHau::LetterCa => '𑫍', PauCinHau::LetterTa => '𑫎', PauCinHau::LetterTha => '𑫏', PauCinHau::LetterNa => '𑫐', PauCinHau::LetterPha => '𑫑', PauCinHau::LetterRa => '𑫒', PauCinHau::LetterFa => '𑫓', PauCinHau::LetterCha => '𑫔', PauCinHau::LetterA => '𑫕', PauCinHau::LetterE => '𑫖', PauCinHau::LetterI => '𑫗', PauCinHau::LetterO => '𑫘', PauCinHau::LetterU => '𑫙', PauCinHau::LetterUa => '𑫚', PauCinHau::LetterIa => '𑫛', PauCinHau::LetterFinalP => '𑫜', PauCinHau::LetterFinalK => '𑫝', PauCinHau::LetterFinalT => '𑫞', PauCinHau::LetterFinalM => '𑫟', PauCinHau::LetterFinalN => '𑫠', PauCinHau::LetterFinalL => '𑫡', PauCinHau::LetterFinalW => '𑫢', PauCinHau::LetterFinalNg => '𑫣', PauCinHau::LetterFinalY => '𑫤', PauCinHau::RisingToneLong => '𑫥', PauCinHau::RisingTone => '𑫦', PauCinHau::SandhiGlottalStop => '𑫧', PauCinHau::RisingToneLongFinal => '𑫨', PauCinHau::RisingToneFinal => '𑫩', PauCinHau::SandhiGlottalStopFinal => '𑫪', PauCinHau::SandhiToneLong => '𑫫', PauCinHau::SandhiTone => '𑫬', PauCinHau::SandhiToneLongFinal => '𑫭', PauCinHau::SandhiToneFinal => '𑫮', PauCinHau::MidDashLevelTone => '𑫯', PauCinHau::GlottalStopVariant => '𑫰', PauCinHau::MidDashLevelToneLongFinal => '𑫱', PauCinHau::MidDashLevelToneFinal => '𑫲', PauCinHau::LowDashFallingToneLong => '𑫳', PauCinHau::LowDashFallingTone => '𑫴', PauCinHau::GlottalStop => '𑫵', PauCinHau::LowDashFallingToneLongFinal => '𑫶', PauCinHau::LowDashFallingToneFinal => '𑫷', PauCinHau::GlottalStopFinal => '𑫸', } } } impl std::convert::TryFrom<char> for PauCinHau { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { '𑫀' => Ok(PauCinHau::LetterPa), '𑫁' => Ok(PauCinHau::LetterKa), '𑫂' => Ok(PauCinHau::LetterLa), '𑫃' => Ok(PauCinHau::LetterMa), '𑫄' => Ok(PauCinHau::LetterDa), '𑫅' => Ok(PauCinHau::LetterZa), '𑫆' => Ok(PauCinHau::LetterVa), '𑫇' => Ok(PauCinHau::LetterNga), '𑫈' => Ok(PauCinHau::LetterHa), '𑫉' => Ok(PauCinHau::LetterGa), '𑫊' => Ok(PauCinHau::LetterKha), '𑫋' => Ok(PauCinHau::LetterSa), '𑫌' => Ok(PauCinHau::LetterBa), '𑫍' => Ok(PauCinHau::LetterCa), '𑫎' => Ok(PauCinHau::LetterTa), '𑫏' => Ok(PauCinHau::LetterTha), '𑫐' => Ok(PauCinHau::LetterNa), '𑫑' => Ok(PauCinHau::LetterPha), '𑫒' => Ok(PauCinHau::LetterRa), '𑫓' => Ok(PauCinHau::LetterFa), '𑫔' => Ok(PauCinHau::LetterCha), '𑫕' => Ok(PauCinHau::LetterA), '𑫖' => Ok(PauCinHau::LetterE), '𑫗' => Ok(PauCinHau::LetterI), '𑫘' => Ok(PauCinHau::LetterO), '𑫙' => Ok(PauCinHau::LetterU), '𑫚' => Ok(PauCinHau::LetterUa), '𑫛' => Ok(PauCinHau::LetterIa), '𑫜' => Ok(PauCinHau::LetterFinalP), '𑫝' => Ok(PauCinHau::LetterFinalK), '𑫞' => Ok(PauCinHau::LetterFinalT), '𑫟' => Ok(PauCinHau::LetterFinalM), '𑫠' => Ok(PauCinHau::LetterFinalN), '𑫡' => Ok(PauCinHau::LetterFinalL), '𑫢' => Ok(PauCinHau::LetterFinalW), '𑫣' => Ok(PauCinHau::LetterFinalNg), '𑫤' => Ok(PauCinHau::LetterFinalY), '𑫥' => Ok(PauCinHau::RisingToneLong), '𑫦' => Ok(PauCinHau::RisingTone), '𑫧' => Ok(PauCinHau::SandhiGlottalStop), '𑫨' => Ok(PauCinHau::RisingToneLongFinal), '𑫩' => Ok(PauCinHau::RisingToneFinal), '𑫪' => Ok(PauCinHau::SandhiGlottalStopFinal), '𑫫' => Ok(PauCinHau::SandhiToneLong), '𑫬' => Ok(PauCinHau::SandhiTone), '𑫭' => Ok(PauCinHau::SandhiToneLongFinal), '𑫮' => Ok(PauCinHau::SandhiToneFinal), '𑫯' => Ok(PauCinHau::MidDashLevelTone), '𑫰' => Ok(PauCinHau::GlottalStopVariant), '𑫱' => Ok(PauCinHau::MidDashLevelToneLongFinal), '𑫲' => Ok(PauCinHau::MidDashLevelToneFinal), '𑫳' => Ok(PauCinHau::LowDashFallingToneLong), '𑫴' => Ok(PauCinHau::LowDashFallingTone), '𑫵' => Ok(PauCinHau::GlottalStop), '𑫶' => Ok(PauCinHau::LowDashFallingToneLongFinal), '𑫷' => Ok(PauCinHau::LowDashFallingToneFinal), '𑫸' => Ok(PauCinHau::GlottalStopFinal), _ => Err(()), } } } impl Into<u32> for PauCinHau { fn into(self) -> u32 { let c: char = self.into(); let hex = c .escape_unicode() .to_string() .replace("\\u{", "") .replace("}", ""); u32::from_str_radix(&hex, 16).unwrap() } } impl std::convert::TryFrom<u32> for PauCinHau { type Error = (); fn try_from(u: u32) -> Result<Self, Self::Error> { if let Ok(c) = char::try_from(u) { Self::try_from(c) } else { Err(()) } } } impl Iterator for PauCinHau { type Item = Self; fn next(&mut self) -> Option<Self> { let index: u32 = (*self).into(); use std::convert::TryFrom; Self::try_from(index + 1).ok() } } impl PauCinHau { /// The character with the lowest index in this unicode block pub fn new() -> Self { PauCinHau::LetterPa } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("PauCinHau{:#?}", self); string_morph::to_sentence_case(&s) } }
use std::f32::consts; use cgmath::Point3; use crate::high_level_fighter::HighLevelSubaction; /// Uses spherical coordinates to represent the cameras location relative to a target. /// https://en.wikipedia.org/wiki/Spherical_coordinate_system /// https://threejs.org/docs/#api/en/math/Spherical pub(crate) struct Camera { pub target: Point3<f32>, /// radius from the target to the camera pub radius: f32, /// polar angle from the y (up) axis pub phi: f32, /// equator angle around the y (up) axis. pub theta: f32, } impl Camera { pub fn new(subaction: &HighLevelSubaction, width: u16, height: u16) -> Camera { let mut subaction_extent = subaction.hurt_box_extent(); subaction_extent.extend(&subaction.hit_box_extent()); subaction_extent.extend(&subaction.ledge_grab_box_extent()); let extent_middle_y = (subaction_extent.up + subaction_extent.down) / 2.0; let extent_middle_z = (subaction_extent.left + subaction_extent.right) / 2.0; let extent_height = subaction_extent.up - subaction_extent.down; let extent_width = subaction_extent.right - subaction_extent.left; let extent_aspect = extent_width / extent_height; let aspect = width as f32 / height as f32; let radius = (subaction_extent.up - extent_middle_y).max(subaction_extent.right - extent_middle_z); let fov = 40.0; let fov_rad = fov * consts::PI / 180.0; let mut camera_distance = radius / (fov_rad / 2.0).tan(); // This logic probably only works because this.pixel_width >= this.pixel_height is always true if extent_aspect > aspect { camera_distance /= aspect; } else if extent_width > extent_height { camera_distance /= extent_aspect; } let target = Point3::new(0.0, extent_middle_y, extent_middle_z); Camera { target, radius: camera_distance, phi: std::f32::consts::PI / 2.0, theta: std::f32::consts::PI * 3.0 / 2.0, } } }
pub enum Event { KeyPress, KeyRelease, OwnerGrabButton, ButtonPress, ButtonRelease, EnterWindow, LeaveWindow, PointerMotion, PointerMotionHint, Button1Motion, Button2Motion, Button3Motion, Button4Motion, Button5Motion, ButtonMotion, Exposure, VisibilityChange, StructureNotify, ResizeRedirect, SubstructureNotify, SubstructureRedirect, FocusChange, PropertyChange, ColormapChange, KeymapState, }
use proconio::input; fn main() { input! {} unimplemented!(); }
#![allow(non_camel_case_types)] use crate::mbc::rom::Rom; use crate::mbc::{mbc1::Mbc1, Mbc, MbcError}; use crate::spec::cartridge_header::CartridgeType; use crate::spec::hardware_registers::{HardwareRegister, HardwareRegisterError, Interrupt}; use crate::spec::memory_region::MemoryRegion; use std::convert::TryFrom; use std::ops::Range; #[derive(Debug)] pub enum Error { CreateError, ReadError, WriteError, MBCError(MbcError), HWError(HardwareRegisterError), UnusableWriteRegion, InvalidInterruptFlagState, } impl From<MbcError> for Error { fn from(e: MbcError) -> Self { Error::MBCError(e) } } impl From<HardwareRegisterError> for Error { fn from(e: HardwareRegisterError) -> Self { Error::HWError(e) } } pub enum MbcType { Rom, Mbc1, Mbc2, Mbc3, Mbc4, Mbc5, Mbc5Rumble, Mmm, } impl From<&CartridgeType> for MbcType { fn from(cart_type: &CartridgeType) -> Self { match cart_type { CartridgeType::ROM | CartridgeType::ROM_RAM | CartridgeType::ROM_RAM_BAT => { MbcType::Rom } CartridgeType::MBC1 | CartridgeType::MBC1_RAM | CartridgeType::MBC1_RAM_BAT => { MbcType::Mbc1 } CartridgeType::MBC2 | CartridgeType::MBC2_BAT => MbcType::Mbc2, CartridgeType::MMM_01 | CartridgeType::MMM_01_RAM | CartridgeType::MMM_01_RAM_BAT => { MbcType::Mmm } CartridgeType::MBC3 | CartridgeType::MBC3_TIMER_BAT | CartridgeType::MBC3_RAM_TIMER_BAT | CartridgeType::MBC3_RAM | CartridgeType::MBC3_RAM_BAT => MbcType::Mbc3, CartridgeType::MBC4 | CartridgeType::MBC4_RAM | CartridgeType::MBC4_RAM_BAT => { MbcType::Mbc4 } CartridgeType::MBC5 | CartridgeType::MBC5_RAM | CartridgeType::MBC5_RAM_BAT => { MbcType::Mbc5 } } } } pub struct MMU { mbc: Box<dyn Mbc>, pub enable_interrupts: bool, interrupt_enable: u8, pub internal_ram: Box<[u8]>, hi_ram: Box<[u8]>, hw_registers: HardwareRegister, } impl MMU { pub fn new(game_data: &[u8], cart_type: &CartridgeType) -> Result<MMU, Error> { Ok(MMU { mbc: Self::create_mbc_from_type(cart_type, game_data), enable_interrupts: false, interrupt_enable: 0, internal_ram: Box::from([0; 0xE000 - 0xC000]), hi_ram: Box::from([0; 0xFFFF - 0xFF80]), hw_registers: HardwareRegister::default(), }) } pub fn read_byte(&self, address: u16) -> Result<u8, Error> { match address { 0x8000..=0x9FFF => { // VIDEO RAM Ok(0) } 0xC000..=0xFDFF => { // Internal work ram // Note 0xE000-0xFDFF is mirror ram let mirrored_address = if address >= 0xE000 { address - (0xE000 - 0xC000) } else { address }; Ok(self.internal_ram[(mirrored_address - 0xC000) as usize]) } 0xFEA0..=0xFEFF => Ok(0), 0xFF00..=0xFF7F => Ok(self.hw_registers.map_read(address)?), 0xFF80..=0xFFFE => Ok(self.hi_ram[(address - 0xFF80) as usize]), 0xFFFF => Ok(self.interrupt_enable), _ => self .mbc .map_read(address) .or_else(|_| panic!("Attempt to read from an unknown address {:X}", address)), } } pub fn write_byte(&mut self, address: u16, value: u8) -> Result<(), Error> { match address { 0x8000..=0x9FFF => { // VIDEO RAM unimplemented Ok(()) } 0xC000..=0xFDFF => { // Internal work ram // Note 0xE000-0xFDFF is mirror ram let mirrored_address = if address >= 0xE000 { address - (0xE000 - 0xC000) } else { address }; self.internal_ram[(mirrored_address - 0xC000) as usize] = value; Ok(()) } 0xFEA0..=0xFEFF => Ok(()), 0xFF00..=0xFF7F => Ok(self.hw_registers.map_write(address, value)?), 0xFF80..=0xFFFE => { self.hi_ram[(address - 0xFF80) as usize] = value; Ok(()) } 0xFFFF => { self.interrupt_enable = value; Ok(()) } _ => self.mbc.map_write(address, value).or_else(|_| { panic!( "Attempt to write to an unknown address {:X} <- {:X}", address, value ) }), } } pub fn read_word(&self, address: u16) -> Result<u16, Error> { let rhs = self.read_byte(address)? as u16; let lhs = self.read_byte(address + 1)? as u16; let value = (lhs << 8) | rhs; Ok(value) } pub fn write_word(&mut self, address: u16, value: u16) -> Result<(), Error> { let rhs = value & 0xFF; let lhs = (value & 0xFF00) >> 8; self.write_byte(address, rhs as u8)?; self.write_byte(address + 1, lhs as u8) } pub fn write_interrupt_enable_reg(&mut self, value: bool) { self.enable_interrupts = value; } pub fn interrupts_enabled(&self) -> Result<Option<Interrupt>, Error> { let interrupt_enable = self.read_byte(0xFFFF)?; let interrupt_flag = self.read_byte(0xFF0F)?; if self.enable_interrupts && (interrupt_enable & interrupt_flag) != 0 { return Ok(Interrupt::try_from(interrupt_enable & interrupt_flag).ok()); } Ok(None) } pub fn interrupts_scheduled(&self) -> Result<bool, Error> { let interrupt_enable = self.read_byte(0xFFFF)?; let interrupt_flag = self.read_byte(0xFF0F)?; Ok((interrupt_enable & interrupt_flag) != 0) } pub fn set_interrupt_bit(&mut self, int: Interrupt, state: bool) -> Result<(), Error> { let interrupt_flag = self.read_byte(0xFF0F)?; let bit = int.get_position(); let next_value = if state { interrupt_flag | bit } else { interrupt_flag & !bit }; self.write_byte(0xFF0F, next_value) } fn create_mbc_from_type(cart_type: &CartridgeType, data: &[u8]) -> Box<dyn Mbc> { match MbcType::from(cart_type) { MbcType::Rom => Box::new(Rom::new(data)), MbcType::Mbc1 => Box::new(Mbc1::new(data)), MbcType::Mbc2 => unimplemented!("MBC2"), MbcType::Mbc3 => unimplemented!("MBC3"), MbcType::Mbc4 => unimplemented!("MBC4"), MbcType::Mbc5 => unimplemented!("MBC5"), MbcType::Mbc5Rumble => unimplemented!("MBC5Rumble"), MbcType::Mmm => unimplemented!("MMM"), } } #[cfg(debug_assertions)] pub fn debug_print_range(&self, range: Range<u16>) { let mut chunk = vec![]; let x = range.clone(); for address in range { chunk.push(format!( "{:X}: {:X}", address, self.read_byte(address).unwrap() )) } println!("Chunk between {:X?}: {:?}", x, chunk); } }
use std::collections::BTreeMap; use std::io::{self, BufRead}; fn counts(table: &mut BTreeMap<char, u32>, input: &str) -> (bool, bool) { table.clear(); for ch in input.chars() { *table.entry(ch).or_insert(0) += 1; } let mut has_doubles = false; let mut has_triples = false; for count in table.values() { match count { 2 => has_doubles = true, 3 => has_triples = true, _ => (), } } (has_doubles, has_triples) } fn checksum(lines: &[String]) -> u32 { let mut table = BTreeMap::new(); let mut double_counts = 0; let mut triple_counts = 0; for line in lines.iter() { let (has_doubles, has_triples) = counts(&mut table, line); if has_doubles { double_counts += 1; } if has_triples { triple_counts += 1; } } return double_counts * triple_counts; } fn number_of_differing_chars(s1: &str, s2: &str) -> u32 { s1.chars() .zip(s2.chars()) .map(|(ch1, ch2)| if ch1 != ch2 { 1 } else { 0 }) .sum() } fn similar_strings(lines: &[String]) -> Option<(String, String)> { for (i, s1) in lines.iter().enumerate() { for s2 in lines[i + 1..].iter() { if number_of_differing_chars(s1, s2) == 1 { return Some((s1.clone(), s2.clone())); } } } None } fn print_common_chars(s1: &str, s2: &str) { for (ch1, ch2) in s1.chars().zip(s2.chars()) { if ch1 == ch2 { print!("{}", ch1); } } } fn main() { let stdin = io::stdin(); let lines = stdin.lock().lines().flat_map(|x| x).collect::<Vec<_>>(); println!("part 1: {}", checksum(&lines)); print!("part 2: "); match similar_strings(&lines) { Some((s1, s2)) => print_common_chars(&s1, &s2), None => print!("No similar strings found"), } println!(""); }
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::PADREGH { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `PAD31FNCSEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD31FNCSELR { #[doc = "Configure as the analog input for ADC single ended input 3 value."] ADCSE3, #[doc = "IOM/MSPI nCE group 31 value."] NCE31, #[doc = "CTIMER connection 13 value."] CT13, #[doc = "Configure as GPIO31 value."] GPIO31, #[doc = "Configure as the UART0 RX input signal value."] UART0RX, #[doc = "SCARD serial clock output value."] SCCCLK, #[doc = "Configure as UART1 RTS output signal value."] UA1RTS, #[doc = r" Reserved"] _Reserved(u8), } impl PAD31FNCSELR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { PAD31FNCSELR::ADCSE3 => 0, PAD31FNCSELR::NCE31 => 1, PAD31FNCSELR::CT13 => 2, PAD31FNCSELR::GPIO31 => 3, PAD31FNCSELR::UART0RX => 4, PAD31FNCSELR::SCCCLK => 5, PAD31FNCSELR::UA1RTS => 7, PAD31FNCSELR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> PAD31FNCSELR { match value { 0 => PAD31FNCSELR::ADCSE3, 1 => PAD31FNCSELR::NCE31, 2 => PAD31FNCSELR::CT13, 3 => PAD31FNCSELR::GPIO31, 4 => PAD31FNCSELR::UART0RX, 5 => PAD31FNCSELR::SCCCLK, 7 => PAD31FNCSELR::UA1RTS, i => PAD31FNCSELR::_Reserved(i), } } #[doc = "Checks if the value of the field is `ADCSE3`"] #[inline] pub fn is_adcse3(&self) -> bool { *self == PAD31FNCSELR::ADCSE3 } #[doc = "Checks if the value of the field is `NCE31`"] #[inline] pub fn is_nce31(&self) -> bool { *self == PAD31FNCSELR::NCE31 } #[doc = "Checks if the value of the field is `CT13`"] #[inline] pub fn is_ct13(&self) -> bool { *self == PAD31FNCSELR::CT13 } #[doc = "Checks if the value of the field is `GPIO31`"] #[inline] pub fn is_gpio31(&self) -> bool { *self == PAD31FNCSELR::GPIO31 } #[doc = "Checks if the value of the field is `UART0RX`"] #[inline] pub fn is_uart0rx(&self) -> bool { *self == PAD31FNCSELR::UART0RX } #[doc = "Checks if the value of the field is `SCCCLK`"] #[inline] pub fn is_sccclk(&self) -> bool { *self == PAD31FNCSELR::SCCCLK } #[doc = "Checks if the value of the field is `UA1RTS`"] #[inline] pub fn is_ua1rts(&self) -> bool { *self == PAD31FNCSELR::UA1RTS } } #[doc = "Possible values of the field `PAD31STRNG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD31STRNGR { #[doc = "Low drive strength value."] LOW, #[doc = "High drive strength value."] HIGH, } impl PAD31STRNGR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD31STRNGR::LOW => false, PAD31STRNGR::HIGH => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD31STRNGR { match value { false => PAD31STRNGR::LOW, true => PAD31STRNGR::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline] pub fn is_low(&self) -> bool { *self == PAD31STRNGR::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline] pub fn is_high(&self) -> bool { *self == PAD31STRNGR::HIGH } } #[doc = "Possible values of the field `PAD31INPEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD31INPENR { #[doc = "Pad input disabled value."] DIS, #[doc = "Pad input enabled value."] EN, } impl PAD31INPENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD31INPENR::DIS => false, PAD31INPENR::EN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD31INPENR { match value { false => PAD31INPENR::DIS, true => PAD31INPENR::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == PAD31INPENR::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == PAD31INPENR::EN } } #[doc = "Possible values of the field `PAD31PULL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD31PULLR { #[doc = "Pullup disabled value."] DIS, #[doc = "Pullup enabled value."] EN, } impl PAD31PULLR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD31PULLR::DIS => false, PAD31PULLR::EN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD31PULLR { match value { false => PAD31PULLR::DIS, true => PAD31PULLR::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == PAD31PULLR::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == PAD31PULLR::EN } } #[doc = "Possible values of the field `PAD30FNCSEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD30FNCSELR { #[doc = "Configure as the ANATEST1 I/O signal value."] ANATEST1, #[doc = "IOM/MSPI nCE group 30 value."] NCE30, #[doc = "CTIMER connection 11 value."] CT11, #[doc = "Configure as GPIO30 value."] GPIO30, #[doc = "Configure as UART0 TX output signal value."] UART0TX, #[doc = "Configure as UART1 RTS output signal value."] UA1RTS, #[doc = "Configure as the PDM I2S Data output signal value."] I2S_DAT, #[doc = r" Reserved"] _Reserved(u8), } impl PAD30FNCSELR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { PAD30FNCSELR::ANATEST1 => 0, PAD30FNCSELR::NCE30 => 1, PAD30FNCSELR::CT11 => 2, PAD30FNCSELR::GPIO30 => 3, PAD30FNCSELR::UART0TX => 4, PAD30FNCSELR::UA1RTS => 5, PAD30FNCSELR::I2S_DAT => 7, PAD30FNCSELR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> PAD30FNCSELR { match value { 0 => PAD30FNCSELR::ANATEST1, 1 => PAD30FNCSELR::NCE30, 2 => PAD30FNCSELR::CT11, 3 => PAD30FNCSELR::GPIO30, 4 => PAD30FNCSELR::UART0TX, 5 => PAD30FNCSELR::UA1RTS, 7 => PAD30FNCSELR::I2S_DAT, i => PAD30FNCSELR::_Reserved(i), } } #[doc = "Checks if the value of the field is `ANATEST1`"] #[inline] pub fn is_anatest1(&self) -> bool { *self == PAD30FNCSELR::ANATEST1 } #[doc = "Checks if the value of the field is `NCE30`"] #[inline] pub fn is_nce30(&self) -> bool { *self == PAD30FNCSELR::NCE30 } #[doc = "Checks if the value of the field is `CT11`"] #[inline] pub fn is_ct11(&self) -> bool { *self == PAD30FNCSELR::CT11 } #[doc = "Checks if the value of the field is `GPIO30`"] #[inline] pub fn is_gpio30(&self) -> bool { *self == PAD30FNCSELR::GPIO30 } #[doc = "Checks if the value of the field is `UART0TX`"] #[inline] pub fn is_uart0tx(&self) -> bool { *self == PAD30FNCSELR::UART0TX } #[doc = "Checks if the value of the field is `UA1RTS`"] #[inline] pub fn is_ua1rts(&self) -> bool { *self == PAD30FNCSELR::UA1RTS } #[doc = "Checks if the value of the field is `I2S_DAT`"] #[inline] pub fn is_i2s_dat(&self) -> bool { *self == PAD30FNCSELR::I2S_DAT } } #[doc = "Possible values of the field `PAD30STRNG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD30STRNGR { #[doc = "Low drive strength value."] LOW, #[doc = "High drive strength value."] HIGH, } impl PAD30STRNGR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD30STRNGR::LOW => false, PAD30STRNGR::HIGH => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD30STRNGR { match value { false => PAD30STRNGR::LOW, true => PAD30STRNGR::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline] pub fn is_low(&self) -> bool { *self == PAD30STRNGR::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline] pub fn is_high(&self) -> bool { *self == PAD30STRNGR::HIGH } } #[doc = "Possible values of the field `PAD30INPEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD30INPENR { #[doc = "Pad input disabled value."] DIS, #[doc = "Pad input enabled value."] EN, } impl PAD30INPENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD30INPENR::DIS => false, PAD30INPENR::EN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD30INPENR { match value { false => PAD30INPENR::DIS, true => PAD30INPENR::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == PAD30INPENR::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == PAD30INPENR::EN } } #[doc = "Possible values of the field `PAD30PULL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD30PULLR { #[doc = "Pullup disabled value."] DIS, #[doc = "Pullup enabled value."] EN, } impl PAD30PULLR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD30PULLR::DIS => false, PAD30PULLR::EN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD30PULLR { match value { false => PAD30PULLR::DIS, true => PAD30PULLR::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == PAD30PULLR::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == PAD30PULLR::EN } } #[doc = "Possible values of the field `PAD29FNCSEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD29FNCSELR { #[doc = "Configure as the analog input for ADC single ended input 1 value."] ADCSE1, #[doc = "IOM/MSPI nCE group 29 value."] NCE29, #[doc = "CTIMER connection 9 value."] CT9, #[doc = "Configure as GPIO29 value."] GPIO29, #[doc = "Configure as the UART0 CTS input signal value."] UA0CTS, #[doc = "Configure as the UART1 CTS input signal value."] UA1CTS, #[doc = "Configure as the UART0 RX input signal value."] UART0RX, #[doc = "Configure as PDM DATA input value."] PDM_DATA, } impl PAD29FNCSELR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { PAD29FNCSELR::ADCSE1 => 0, PAD29FNCSELR::NCE29 => 1, PAD29FNCSELR::CT9 => 2, PAD29FNCSELR::GPIO29 => 3, PAD29FNCSELR::UA0CTS => 4, PAD29FNCSELR::UA1CTS => 5, PAD29FNCSELR::UART0RX => 6, PAD29FNCSELR::PDM_DATA => 7, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> PAD29FNCSELR { match value { 0 => PAD29FNCSELR::ADCSE1, 1 => PAD29FNCSELR::NCE29, 2 => PAD29FNCSELR::CT9, 3 => PAD29FNCSELR::GPIO29, 4 => PAD29FNCSELR::UA0CTS, 5 => PAD29FNCSELR::UA1CTS, 6 => PAD29FNCSELR::UART0RX, 7 => PAD29FNCSELR::PDM_DATA, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `ADCSE1`"] #[inline] pub fn is_adcse1(&self) -> bool { *self == PAD29FNCSELR::ADCSE1 } #[doc = "Checks if the value of the field is `NCE29`"] #[inline] pub fn is_nce29(&self) -> bool { *self == PAD29FNCSELR::NCE29 } #[doc = "Checks if the value of the field is `CT9`"] #[inline] pub fn is_ct9(&self) -> bool { *self == PAD29FNCSELR::CT9 } #[doc = "Checks if the value of the field is `GPIO29`"] #[inline] pub fn is_gpio29(&self) -> bool { *self == PAD29FNCSELR::GPIO29 } #[doc = "Checks if the value of the field is `UA0CTS`"] #[inline] pub fn is_ua0cts(&self) -> bool { *self == PAD29FNCSELR::UA0CTS } #[doc = "Checks if the value of the field is `UA1CTS`"] #[inline] pub fn is_ua1cts(&self) -> bool { *self == PAD29FNCSELR::UA1CTS } #[doc = "Checks if the value of the field is `UART0RX`"] #[inline] pub fn is_uart0rx(&self) -> bool { *self == PAD29FNCSELR::UART0RX } #[doc = "Checks if the value of the field is `PDM_DATA`"] #[inline] pub fn is_pdm_data(&self) -> bool { *self == PAD29FNCSELR::PDM_DATA } } #[doc = "Possible values of the field `PAD29STRNG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD29STRNGR { #[doc = "Low drive strength value."] LOW, #[doc = "High drive strength value."] HIGH, } impl PAD29STRNGR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD29STRNGR::LOW => false, PAD29STRNGR::HIGH => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD29STRNGR { match value { false => PAD29STRNGR::LOW, true => PAD29STRNGR::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline] pub fn is_low(&self) -> bool { *self == PAD29STRNGR::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline] pub fn is_high(&self) -> bool { *self == PAD29STRNGR::HIGH } } #[doc = "Possible values of the field `PAD29INPEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD29INPENR { #[doc = "Pad input disabled value."] DIS, #[doc = "Pad input enabled value."] EN, } impl PAD29INPENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD29INPENR::DIS => false, PAD29INPENR::EN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD29INPENR { match value { false => PAD29INPENR::DIS, true => PAD29INPENR::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == PAD29INPENR::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == PAD29INPENR::EN } } #[doc = "Possible values of the field `PAD29PULL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD29PULLR { #[doc = "Pullup disabled value."] DIS, #[doc = "Pullup enabled value."] EN, } impl PAD29PULLR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD29PULLR::DIS => false, PAD29PULLR::EN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD29PULLR { match value { false => PAD29PULLR::DIS, true => PAD29PULLR::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == PAD29PULLR::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == PAD29PULLR::EN } } #[doc = "Possible values of the field `PAD28FNCSEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD28FNCSELR { #[doc = "Configure as the PDM I2S Word Clock input value."] I2S_WCLK, #[doc = "IOM/MSPI nCE group 28 value."] NCE28, #[doc = "CTIMER connection 7 value."] CT7, #[doc = "Configure as GPIO28 value."] GPIO28, #[doc = "Configure as the IOMSTR2 SPI MOSI output signal value."] M2MOSI, #[doc = "Configure as the UART0 TX output signal value."] UART0TX, #[doc = r" Reserved"] _Reserved(u8), } impl PAD28FNCSELR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { PAD28FNCSELR::I2S_WCLK => 0, PAD28FNCSELR::NCE28 => 1, PAD28FNCSELR::CT7 => 2, PAD28FNCSELR::GPIO28 => 3, PAD28FNCSELR::M2MOSI => 5, PAD28FNCSELR::UART0TX => 6, PAD28FNCSELR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> PAD28FNCSELR { match value { 0 => PAD28FNCSELR::I2S_WCLK, 1 => PAD28FNCSELR::NCE28, 2 => PAD28FNCSELR::CT7, 3 => PAD28FNCSELR::GPIO28, 5 => PAD28FNCSELR::M2MOSI, 6 => PAD28FNCSELR::UART0TX, i => PAD28FNCSELR::_Reserved(i), } } #[doc = "Checks if the value of the field is `I2S_WCLK`"] #[inline] pub fn is_i2s_wclk(&self) -> bool { *self == PAD28FNCSELR::I2S_WCLK } #[doc = "Checks if the value of the field is `NCE28`"] #[inline] pub fn is_nce28(&self) -> bool { *self == PAD28FNCSELR::NCE28 } #[doc = "Checks if the value of the field is `CT7`"] #[inline] pub fn is_ct7(&self) -> bool { *self == PAD28FNCSELR::CT7 } #[doc = "Checks if the value of the field is `GPIO28`"] #[inline] pub fn is_gpio28(&self) -> bool { *self == PAD28FNCSELR::GPIO28 } #[doc = "Checks if the value of the field is `M2MOSI`"] #[inline] pub fn is_m2mosi(&self) -> bool { *self == PAD28FNCSELR::M2MOSI } #[doc = "Checks if the value of the field is `UART0TX`"] #[inline] pub fn is_uart0tx(&self) -> bool { *self == PAD28FNCSELR::UART0TX } } #[doc = "Possible values of the field `PAD28STRNG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD28STRNGR { #[doc = "Low drive strength value."] LOW, #[doc = "High drive strength value."] HIGH, } impl PAD28STRNGR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD28STRNGR::LOW => false, PAD28STRNGR::HIGH => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD28STRNGR { match value { false => PAD28STRNGR::LOW, true => PAD28STRNGR::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline] pub fn is_low(&self) -> bool { *self == PAD28STRNGR::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline] pub fn is_high(&self) -> bool { *self == PAD28STRNGR::HIGH } } #[doc = "Possible values of the field `PAD28INPEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD28INPENR { #[doc = "Pad input disabled value."] DIS, #[doc = "Pad input enabled value."] EN, } impl PAD28INPENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD28INPENR::DIS => false, PAD28INPENR::EN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD28INPENR { match value { false => PAD28INPENR::DIS, true => PAD28INPENR::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == PAD28INPENR::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == PAD28INPENR::EN } } #[doc = "Possible values of the field `PAD28PULL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PAD28PULLR { #[doc = "Pullup disabled value."] DIS, #[doc = "Pullup enabled value."] EN, } impl PAD28PULLR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PAD28PULLR::DIS => false, PAD28PULLR::EN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PAD28PULLR { match value { false => PAD28PULLR::DIS, true => PAD28PULLR::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == PAD28PULLR::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == PAD28PULLR::EN } } #[doc = "Values that can be written to the field `PAD31FNCSEL`"] pub enum PAD31FNCSELW { #[doc = "Configure as the analog input for ADC single ended input 3 value."] ADCSE3, #[doc = "IOM/MSPI nCE group 31 value."] NCE31, #[doc = "CTIMER connection 13 value."] CT13, #[doc = "Configure as GPIO31 value."] GPIO31, #[doc = "Configure as the UART0 RX input signal value."] UART0RX, #[doc = "SCARD serial clock output value."] SCCCLK, #[doc = "Configure as UART1 RTS output signal value."] UA1RTS, } impl PAD31FNCSELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { PAD31FNCSELW::ADCSE3 => 0, PAD31FNCSELW::NCE31 => 1, PAD31FNCSELW::CT13 => 2, PAD31FNCSELW::GPIO31 => 3, PAD31FNCSELW::UART0RX => 4, PAD31FNCSELW::SCCCLK => 5, PAD31FNCSELW::UA1RTS => 7, } } } #[doc = r" Proxy"] pub struct _PAD31FNCSELW<'a> { w: &'a mut W, } impl<'a> _PAD31FNCSELW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD31FNCSELW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Configure as the analog input for ADC single ended input 3 value."] #[inline] pub fn adcse3(self) -> &'a mut W { self.variant(PAD31FNCSELW::ADCSE3) } #[doc = "IOM/MSPI nCE group 31 value."] #[inline] pub fn nce31(self) -> &'a mut W { self.variant(PAD31FNCSELW::NCE31) } #[doc = "CTIMER connection 13 value."] #[inline] pub fn ct13(self) -> &'a mut W { self.variant(PAD31FNCSELW::CT13) } #[doc = "Configure as GPIO31 value."] #[inline] pub fn gpio31(self) -> &'a mut W { self.variant(PAD31FNCSELW::GPIO31) } #[doc = "Configure as the UART0 RX input signal value."] #[inline] pub fn uart0rx(self) -> &'a mut W { self.variant(PAD31FNCSELW::UART0RX) } #[doc = "SCARD serial clock output value."] #[inline] pub fn sccclk(self) -> &'a mut W { self.variant(PAD31FNCSELW::SCCCLK) } #[doc = "Configure as UART1 RTS output signal value."] #[inline] pub fn ua1rts(self) -> &'a mut W { self.variant(PAD31FNCSELW::UA1RTS) } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; const OFFSET: u8 = 27; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD31STRNG`"] pub enum PAD31STRNGW { #[doc = "Low drive strength value."] LOW, #[doc = "High drive strength value."] HIGH, } impl PAD31STRNGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD31STRNGW::LOW => false, PAD31STRNGW::HIGH => true, } } } #[doc = r" Proxy"] pub struct _PAD31STRNGW<'a> { w: &'a mut W, } impl<'a> _PAD31STRNGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD31STRNGW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Low drive strength value."] #[inline] pub fn low(self) -> &'a mut W { self.variant(PAD31STRNGW::LOW) } #[doc = "High drive strength value."] #[inline] pub fn high(self) -> &'a mut W { self.variant(PAD31STRNGW::HIGH) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 26; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD31INPEN`"] pub enum PAD31INPENW { #[doc = "Pad input disabled value."] DIS, #[doc = "Pad input enabled value."] EN, } impl PAD31INPENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD31INPENW::DIS => false, PAD31INPENW::EN => true, } } } #[doc = r" Proxy"] pub struct _PAD31INPENW<'a> { w: &'a mut W, } impl<'a> _PAD31INPENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD31INPENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Pad input disabled value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(PAD31INPENW::DIS) } #[doc = "Pad input enabled value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(PAD31INPENW::EN) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 25; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD31PULL`"] pub enum PAD31PULLW { #[doc = "Pullup disabled value."] DIS, #[doc = "Pullup enabled value."] EN, } impl PAD31PULLW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD31PULLW::DIS => false, PAD31PULLW::EN => true, } } } #[doc = r" Proxy"] pub struct _PAD31PULLW<'a> { w: &'a mut W, } impl<'a> _PAD31PULLW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD31PULLW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Pullup disabled value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(PAD31PULLW::DIS) } #[doc = "Pullup enabled value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(PAD31PULLW::EN) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD30FNCSEL`"] pub enum PAD30FNCSELW { #[doc = "Configure as the ANATEST1 I/O signal value."] ANATEST1, #[doc = "IOM/MSPI nCE group 30 value."] NCE30, #[doc = "CTIMER connection 11 value."] CT11, #[doc = "Configure as GPIO30 value."] GPIO30, #[doc = "Configure as UART0 TX output signal value."] UART0TX, #[doc = "Configure as UART1 RTS output signal value."] UA1RTS, #[doc = "Configure as the PDM I2S Data output signal value."] I2S_DAT, } impl PAD30FNCSELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { PAD30FNCSELW::ANATEST1 => 0, PAD30FNCSELW::NCE30 => 1, PAD30FNCSELW::CT11 => 2, PAD30FNCSELW::GPIO30 => 3, PAD30FNCSELW::UART0TX => 4, PAD30FNCSELW::UA1RTS => 5, PAD30FNCSELW::I2S_DAT => 7, } } } #[doc = r" Proxy"] pub struct _PAD30FNCSELW<'a> { w: &'a mut W, } impl<'a> _PAD30FNCSELW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD30FNCSELW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Configure as the ANATEST1 I/O signal value."] #[inline] pub fn anatest1(self) -> &'a mut W { self.variant(PAD30FNCSELW::ANATEST1) } #[doc = "IOM/MSPI nCE group 30 value."] #[inline] pub fn nce30(self) -> &'a mut W { self.variant(PAD30FNCSELW::NCE30) } #[doc = "CTIMER connection 11 value."] #[inline] pub fn ct11(self) -> &'a mut W { self.variant(PAD30FNCSELW::CT11) } #[doc = "Configure as GPIO30 value."] #[inline] pub fn gpio30(self) -> &'a mut W { self.variant(PAD30FNCSELW::GPIO30) } #[doc = "Configure as UART0 TX output signal value."] #[inline] pub fn uart0tx(self) -> &'a mut W { self.variant(PAD30FNCSELW::UART0TX) } #[doc = "Configure as UART1 RTS output signal value."] #[inline] pub fn ua1rts(self) -> &'a mut W { self.variant(PAD30FNCSELW::UA1RTS) } #[doc = "Configure as the PDM I2S Data output signal value."] #[inline] pub fn i2s_dat(self) -> &'a mut W { self.variant(PAD30FNCSELW::I2S_DAT) } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; const OFFSET: u8 = 19; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD30STRNG`"] pub enum PAD30STRNGW { #[doc = "Low drive strength value."] LOW, #[doc = "High drive strength value."] HIGH, } impl PAD30STRNGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD30STRNGW::LOW => false, PAD30STRNGW::HIGH => true, } } } #[doc = r" Proxy"] pub struct _PAD30STRNGW<'a> { w: &'a mut W, } impl<'a> _PAD30STRNGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD30STRNGW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Low drive strength value."] #[inline] pub fn low(self) -> &'a mut W { self.variant(PAD30STRNGW::LOW) } #[doc = "High drive strength value."] #[inline] pub fn high(self) -> &'a mut W { self.variant(PAD30STRNGW::HIGH) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD30INPEN`"] pub enum PAD30INPENW { #[doc = "Pad input disabled value."] DIS, #[doc = "Pad input enabled value."] EN, } impl PAD30INPENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD30INPENW::DIS => false, PAD30INPENW::EN => true, } } } #[doc = r" Proxy"] pub struct _PAD30INPENW<'a> { w: &'a mut W, } impl<'a> _PAD30INPENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD30INPENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Pad input disabled value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(PAD30INPENW::DIS) } #[doc = "Pad input enabled value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(PAD30INPENW::EN) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 17; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD30PULL`"] pub enum PAD30PULLW { #[doc = "Pullup disabled value."] DIS, #[doc = "Pullup enabled value."] EN, } impl PAD30PULLW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD30PULLW::DIS => false, PAD30PULLW::EN => true, } } } #[doc = r" Proxy"] pub struct _PAD30PULLW<'a> { w: &'a mut W, } impl<'a> _PAD30PULLW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD30PULLW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Pullup disabled value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(PAD30PULLW::DIS) } #[doc = "Pullup enabled value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(PAD30PULLW::EN) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD29FNCSEL`"] pub enum PAD29FNCSELW { #[doc = "Configure as the analog input for ADC single ended input 1 value."] ADCSE1, #[doc = "IOM/MSPI nCE group 29 value."] NCE29, #[doc = "CTIMER connection 9 value."] CT9, #[doc = "Configure as GPIO29 value."] GPIO29, #[doc = "Configure as the UART0 CTS input signal value."] UA0CTS, #[doc = "Configure as the UART1 CTS input signal value."] UA1CTS, #[doc = "Configure as the UART0 RX input signal value."] UART0RX, #[doc = "Configure as PDM DATA input value."] PDM_DATA, } impl PAD29FNCSELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { PAD29FNCSELW::ADCSE1 => 0, PAD29FNCSELW::NCE29 => 1, PAD29FNCSELW::CT9 => 2, PAD29FNCSELW::GPIO29 => 3, PAD29FNCSELW::UA0CTS => 4, PAD29FNCSELW::UA1CTS => 5, PAD29FNCSELW::UART0RX => 6, PAD29FNCSELW::PDM_DATA => 7, } } } #[doc = r" Proxy"] pub struct _PAD29FNCSELW<'a> { w: &'a mut W, } impl<'a> _PAD29FNCSELW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD29FNCSELW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Configure as the analog input for ADC single ended input 1 value."] #[inline] pub fn adcse1(self) -> &'a mut W { self.variant(PAD29FNCSELW::ADCSE1) } #[doc = "IOM/MSPI nCE group 29 value."] #[inline] pub fn nce29(self) -> &'a mut W { self.variant(PAD29FNCSELW::NCE29) } #[doc = "CTIMER connection 9 value."] #[inline] pub fn ct9(self) -> &'a mut W { self.variant(PAD29FNCSELW::CT9) } #[doc = "Configure as GPIO29 value."] #[inline] pub fn gpio29(self) -> &'a mut W { self.variant(PAD29FNCSELW::GPIO29) } #[doc = "Configure as the UART0 CTS input signal value."] #[inline] pub fn ua0cts(self) -> &'a mut W { self.variant(PAD29FNCSELW::UA0CTS) } #[doc = "Configure as the UART1 CTS input signal value."] #[inline] pub fn ua1cts(self) -> &'a mut W { self.variant(PAD29FNCSELW::UA1CTS) } #[doc = "Configure as the UART0 RX input signal value."] #[inline] pub fn uart0rx(self) -> &'a mut W { self.variant(PAD29FNCSELW::UART0RX) } #[doc = "Configure as PDM DATA input value."] #[inline] pub fn pdm_data(self) -> &'a mut W { self.variant(PAD29FNCSELW::PDM_DATA) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; const OFFSET: u8 = 11; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD29STRNG`"] pub enum PAD29STRNGW { #[doc = "Low drive strength value."] LOW, #[doc = "High drive strength value."] HIGH, } impl PAD29STRNGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD29STRNGW::LOW => false, PAD29STRNGW::HIGH => true, } } } #[doc = r" Proxy"] pub struct _PAD29STRNGW<'a> { w: &'a mut W, } impl<'a> _PAD29STRNGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD29STRNGW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Low drive strength value."] #[inline] pub fn low(self) -> &'a mut W { self.variant(PAD29STRNGW::LOW) } #[doc = "High drive strength value."] #[inline] pub fn high(self) -> &'a mut W { self.variant(PAD29STRNGW::HIGH) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 10; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD29INPEN`"] pub enum PAD29INPENW { #[doc = "Pad input disabled value."] DIS, #[doc = "Pad input enabled value."] EN, } impl PAD29INPENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD29INPENW::DIS => false, PAD29INPENW::EN => true, } } } #[doc = r" Proxy"] pub struct _PAD29INPENW<'a> { w: &'a mut W, } impl<'a> _PAD29INPENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD29INPENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Pad input disabled value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(PAD29INPENW::DIS) } #[doc = "Pad input enabled value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(PAD29INPENW::EN) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 9; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD29PULL`"] pub enum PAD29PULLW { #[doc = "Pullup disabled value."] DIS, #[doc = "Pullup enabled value."] EN, } impl PAD29PULLW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD29PULLW::DIS => false, PAD29PULLW::EN => true, } } } #[doc = r" Proxy"] pub struct _PAD29PULLW<'a> { w: &'a mut W, } impl<'a> _PAD29PULLW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD29PULLW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Pullup disabled value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(PAD29PULLW::DIS) } #[doc = "Pullup enabled value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(PAD29PULLW::EN) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD28FNCSEL`"] pub enum PAD28FNCSELW { #[doc = "Configure as the PDM I2S Word Clock input value."] I2S_WCLK, #[doc = "IOM/MSPI nCE group 28 value."] NCE28, #[doc = "CTIMER connection 7 value."] CT7, #[doc = "Configure as GPIO28 value."] GPIO28, #[doc = "Configure as the IOMSTR2 SPI MOSI output signal value."] M2MOSI, #[doc = "Configure as the UART0 TX output signal value."] UART0TX, } impl PAD28FNCSELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { PAD28FNCSELW::I2S_WCLK => 0, PAD28FNCSELW::NCE28 => 1, PAD28FNCSELW::CT7 => 2, PAD28FNCSELW::GPIO28 => 3, PAD28FNCSELW::M2MOSI => 5, PAD28FNCSELW::UART0TX => 6, } } } #[doc = r" Proxy"] pub struct _PAD28FNCSELW<'a> { w: &'a mut W, } impl<'a> _PAD28FNCSELW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD28FNCSELW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Configure as the PDM I2S Word Clock input value."] #[inline] pub fn i2s_wclk(self) -> &'a mut W { self.variant(PAD28FNCSELW::I2S_WCLK) } #[doc = "IOM/MSPI nCE group 28 value."] #[inline] pub fn nce28(self) -> &'a mut W { self.variant(PAD28FNCSELW::NCE28) } #[doc = "CTIMER connection 7 value."] #[inline] pub fn ct7(self) -> &'a mut W { self.variant(PAD28FNCSELW::CT7) } #[doc = "Configure as GPIO28 value."] #[inline] pub fn gpio28(self) -> &'a mut W { self.variant(PAD28FNCSELW::GPIO28) } #[doc = "Configure as the IOMSTR2 SPI MOSI output signal value."] #[inline] pub fn m2mosi(self) -> &'a mut W { self.variant(PAD28FNCSELW::M2MOSI) } #[doc = "Configure as the UART0 TX output signal value."] #[inline] pub fn uart0tx(self) -> &'a mut W { self.variant(PAD28FNCSELW::UART0TX) } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; const OFFSET: u8 = 3; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD28STRNG`"] pub enum PAD28STRNGW { #[doc = "Low drive strength value."] LOW, #[doc = "High drive strength value."] HIGH, } impl PAD28STRNGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD28STRNGW::LOW => false, PAD28STRNGW::HIGH => true, } } } #[doc = r" Proxy"] pub struct _PAD28STRNGW<'a> { w: &'a mut W, } impl<'a> _PAD28STRNGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD28STRNGW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Low drive strength value."] #[inline] pub fn low(self) -> &'a mut W { self.variant(PAD28STRNGW::LOW) } #[doc = "High drive strength value."] #[inline] pub fn high(self) -> &'a mut W { self.variant(PAD28STRNGW::HIGH) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD28INPEN`"] pub enum PAD28INPENW { #[doc = "Pad input disabled value."] DIS, #[doc = "Pad input enabled value."] EN, } impl PAD28INPENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD28INPENW::DIS => false, PAD28INPENW::EN => true, } } } #[doc = r" Proxy"] pub struct _PAD28INPENW<'a> { w: &'a mut W, } impl<'a> _PAD28INPENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD28INPENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Pad input disabled value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(PAD28INPENW::DIS) } #[doc = "Pad input enabled value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(PAD28INPENW::EN) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PAD28PULL`"] pub enum PAD28PULLW { #[doc = "Pullup disabled value."] DIS, #[doc = "Pullup enabled value."] EN, } impl PAD28PULLW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PAD28PULLW::DIS => false, PAD28PULLW::EN => true, } } } #[doc = r" Proxy"] pub struct _PAD28PULLW<'a> { w: &'a mut W, } impl<'a> _PAD28PULLW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PAD28PULLW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Pullup disabled value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(PAD28PULLW::DIS) } #[doc = "Pullup enabled value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(PAD28PULLW::EN) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 27:29 - Pad 31 function select"] #[inline] pub fn pad31fncsel(&self) -> PAD31FNCSELR { PAD31FNCSELR::_from({ const MASK: u8 = 7; const OFFSET: u8 = 27; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 26 - Pad 31 drive strength"] #[inline] pub fn pad31strng(&self) -> PAD31STRNGR { PAD31STRNGR::_from({ const MASK: bool = true; const OFFSET: u8 = 26; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 25 - Pad 31 input enable"] #[inline] pub fn pad31inpen(&self) -> PAD31INPENR { PAD31INPENR::_from({ const MASK: bool = true; const OFFSET: u8 = 25; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 24 - Pad 31 pullup enable"] #[inline] pub fn pad31pull(&self) -> PAD31PULLR { PAD31PULLR::_from({ const MASK: bool = true; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 19:21 - Pad 30 function select"] #[inline] pub fn pad30fncsel(&self) -> PAD30FNCSELR { PAD30FNCSELR::_from({ const MASK: u8 = 7; const OFFSET: u8 = 19; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 18 - Pad 30 drive strength"] #[inline] pub fn pad30strng(&self) -> PAD30STRNGR { PAD30STRNGR::_from({ const MASK: bool = true; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 17 - Pad 30 input enable"] #[inline] pub fn pad30inpen(&self) -> PAD30INPENR { PAD30INPENR::_from({ const MASK: bool = true; const OFFSET: u8 = 17; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 16 - Pad 30 pullup enable"] #[inline] pub fn pad30pull(&self) -> PAD30PULLR { PAD30PULLR::_from({ const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 11:13 - Pad 29 function select"] #[inline] pub fn pad29fncsel(&self) -> PAD29FNCSELR { PAD29FNCSELR::_from({ const MASK: u8 = 7; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 10 - Pad 29 drive strength"] #[inline] pub fn pad29strng(&self) -> PAD29STRNGR { PAD29STRNGR::_from({ const MASK: bool = true; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 9 - Pad 29 input enable"] #[inline] pub fn pad29inpen(&self) -> PAD29INPENR { PAD29INPENR::_from({ const MASK: bool = true; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 8 - Pad 29 pullup enable"] #[inline] pub fn pad29pull(&self) -> PAD29PULLR { PAD29PULLR::_from({ const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 3:5 - Pad 28 function select"] #[inline] pub fn pad28fncsel(&self) -> PAD28FNCSELR { PAD28FNCSELR::_from({ const MASK: u8 = 7; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 2 - Pad 28 drive strength"] #[inline] pub fn pad28strng(&self) -> PAD28STRNGR { PAD28STRNGR::_from({ const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 1 - Pad 28 input enable"] #[inline] pub fn pad28inpen(&self) -> PAD28INPENR { PAD28INPENR::_from({ const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 0 - Pad 28 pullup enable"] #[inline] pub fn pad28pull(&self) -> PAD28PULLR { PAD28PULLR::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 404232216 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 27:29 - Pad 31 function select"] #[inline] pub fn pad31fncsel(&mut self) -> _PAD31FNCSELW { _PAD31FNCSELW { w: self } } #[doc = "Bit 26 - Pad 31 drive strength"] #[inline] pub fn pad31strng(&mut self) -> _PAD31STRNGW { _PAD31STRNGW { w: self } } #[doc = "Bit 25 - Pad 31 input enable"] #[inline] pub fn pad31inpen(&mut self) -> _PAD31INPENW { _PAD31INPENW { w: self } } #[doc = "Bit 24 - Pad 31 pullup enable"] #[inline] pub fn pad31pull(&mut self) -> _PAD31PULLW { _PAD31PULLW { w: self } } #[doc = "Bits 19:21 - Pad 30 function select"] #[inline] pub fn pad30fncsel(&mut self) -> _PAD30FNCSELW { _PAD30FNCSELW { w: self } } #[doc = "Bit 18 - Pad 30 drive strength"] #[inline] pub fn pad30strng(&mut self) -> _PAD30STRNGW { _PAD30STRNGW { w: self } } #[doc = "Bit 17 - Pad 30 input enable"] #[inline] pub fn pad30inpen(&mut self) -> _PAD30INPENW { _PAD30INPENW { w: self } } #[doc = "Bit 16 - Pad 30 pullup enable"] #[inline] pub fn pad30pull(&mut self) -> _PAD30PULLW { _PAD30PULLW { w: self } } #[doc = "Bits 11:13 - Pad 29 function select"] #[inline] pub fn pad29fncsel(&mut self) -> _PAD29FNCSELW { _PAD29FNCSELW { w: self } } #[doc = "Bit 10 - Pad 29 drive strength"] #[inline] pub fn pad29strng(&mut self) -> _PAD29STRNGW { _PAD29STRNGW { w: self } } #[doc = "Bit 9 - Pad 29 input enable"] #[inline] pub fn pad29inpen(&mut self) -> _PAD29INPENW { _PAD29INPENW { w: self } } #[doc = "Bit 8 - Pad 29 pullup enable"] #[inline] pub fn pad29pull(&mut self) -> _PAD29PULLW { _PAD29PULLW { w: self } } #[doc = "Bits 3:5 - Pad 28 function select"] #[inline] pub fn pad28fncsel(&mut self) -> _PAD28FNCSELW { _PAD28FNCSELW { w: self } } #[doc = "Bit 2 - Pad 28 drive strength"] #[inline] pub fn pad28strng(&mut self) -> _PAD28STRNGW { _PAD28STRNGW { w: self } } #[doc = "Bit 1 - Pad 28 input enable"] #[inline] pub fn pad28inpen(&mut self) -> _PAD28INPENW { _PAD28INPENW { w: self } } #[doc = "Bit 0 - Pad 28 pullup enable"] #[inline] pub fn pad28pull(&mut self) -> _PAD28PULLW { _PAD28PULLW { w: self } } }
use crate::sender::Sender; use std::error::Error; pub struct PrintSender {} impl Sender for PrintSender { fn init(&mut self) { } fn send(&self, msg: &str) -> Result<(), Box<dyn Error>> { println!("MSG: {}", msg); Ok(()) } fn name(&self) -> &'static str { "print" } }
#[doc = "Register `HWCFGR` reader"] pub type R = crate::R<HWCFGR_SPEC>; #[doc = "Register `HWCFGR` writer"] pub type W = crate::W<HWCFGR_SPEC>; #[doc = "Field `ALARMB` reader - ALARMB"] pub type ALARMB_R = crate::FieldReader; #[doc = "Field `ALARMB` writer - ALARMB"] pub type ALARMB_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `WAKEUP` reader - WAKEUP"] pub type WAKEUP_R = crate::FieldReader; #[doc = "Field `WAKEUP` writer - WAKEUP"] pub type WAKEUP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `SMOOTH_CALIB` reader - SMOOTH_CALIB"] pub type SMOOTH_CALIB_R = crate::FieldReader; #[doc = "Field `SMOOTH_CALIB` writer - SMOOTH_CALIB"] pub type SMOOTH_CALIB_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `TIMESTAMP` reader - TIMESTAMP"] pub type TIMESTAMP_R = crate::FieldReader; #[doc = "Field `TIMESTAMP` writer - TIMESTAMP"] pub type TIMESTAMP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `OPTIONREG_OUT` reader - OPTIONREG_OUT"] pub type OPTIONREG_OUT_R = crate::FieldReader; #[doc = "Field `OPTIONREG_OUT` writer - OPTIONREG_OUT"] pub type OPTIONREG_OUT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `TRUST_ZONE` reader - TRUST_ZONE"] pub type TRUST_ZONE_R = crate::FieldReader; #[doc = "Field `TRUST_ZONE` writer - TRUST_ZONE"] pub type TRUST_ZONE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; impl R { #[doc = "Bits 0:3 - ALARMB"] #[inline(always)] pub fn alarmb(&self) -> ALARMB_R { ALARMB_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - WAKEUP"] #[inline(always)] pub fn wakeup(&self) -> WAKEUP_R { WAKEUP_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:11 - SMOOTH_CALIB"] #[inline(always)] pub fn smooth_calib(&self) -> SMOOTH_CALIB_R { SMOOTH_CALIB_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - TIMESTAMP"] #[inline(always)] pub fn timestamp(&self) -> TIMESTAMP_R { TIMESTAMP_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 16:23 - OPTIONREG_OUT"] #[inline(always)] pub fn optionreg_out(&self) -> OPTIONREG_OUT_R { OPTIONREG_OUT_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bits 24:27 - TRUST_ZONE"] #[inline(always)] pub fn trust_zone(&self) -> TRUST_ZONE_R { TRUST_ZONE_R::new(((self.bits >> 24) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - ALARMB"] #[inline(always)] #[must_use] pub fn alarmb(&mut self) -> ALARMB_W<HWCFGR_SPEC, 0> { ALARMB_W::new(self) } #[doc = "Bits 4:7 - WAKEUP"] #[inline(always)] #[must_use] pub fn wakeup(&mut self) -> WAKEUP_W<HWCFGR_SPEC, 4> { WAKEUP_W::new(self) } #[doc = "Bits 8:11 - SMOOTH_CALIB"] #[inline(always)] #[must_use] pub fn smooth_calib(&mut self) -> SMOOTH_CALIB_W<HWCFGR_SPEC, 8> { SMOOTH_CALIB_W::new(self) } #[doc = "Bits 12:15 - TIMESTAMP"] #[inline(always)] #[must_use] pub fn timestamp(&mut self) -> TIMESTAMP_W<HWCFGR_SPEC, 12> { TIMESTAMP_W::new(self) } #[doc = "Bits 16:23 - OPTIONREG_OUT"] #[inline(always)] #[must_use] pub fn optionreg_out(&mut self) -> OPTIONREG_OUT_W<HWCFGR_SPEC, 16> { OPTIONREG_OUT_W::new(self) } #[doc = "Bits 24:27 - TRUST_ZONE"] #[inline(always)] #[must_use] pub fn trust_zone(&mut self) -> TRUST_ZONE_W<HWCFGR_SPEC, 24> { TRUST_ZONE_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "hardware configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hwcfgr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`hwcfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct HWCFGR_SPEC; impl crate::RegisterSpec for HWCFGR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`hwcfgr::R`](R) reader structure"] impl crate::Readable for HWCFGR_SPEC {} #[doc = "`write(|w| ..)` method takes [`hwcfgr::W`](W) writer structure"] impl crate::Writable for HWCFGR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets HWCFGR to value 0"] impl crate::Resettable for HWCFGR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::error; use std::fmt; #[derive(Debug)] pub enum AppError { // Config related NeedOutputError, NeedRowsError, ParseRowsError, NeedColsError, ParseColsError, NeedHeightError, ParseHeightError, NeedWidthError, ParseWidthError, NeedBackgroundColorError, ParseBackgroundColorError, NeedImagesError, ParseImageError, InvalidRowsColsError, // Image resize and combine related LoadImageError, SaveImageError, } impl fmt::Display for AppError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { AppError::NeedOutputError => write!(f, "Need OUTPUT in config"), AppError::NeedRowsError => write!(f, "Need ROWS in config"), AppError::ParseRowsError => write!(f, "Failed to parse ROWS"), AppError::NeedColsError => write!(f, "Need COL in config"), AppError::ParseColsError => write!(f, "Failed to parse COLS"), AppError::NeedHeightError => write!(f, "Need HEIGHT in config"), AppError::ParseHeightError => write!(f, "Failed to parse HEIGHT"), AppError::NeedWidthError => write!(f, "Need WIDTH in config"), AppError::ParseWidthError => write!(f, "Failed to parse WIDTH"), AppError::NeedBackgroundColorError => write!(f, "Need BACKGROUND_COLOR in config"), AppError::ParseBackgroundColorError => write!(f, "BACKGROUND_COLOR needs to be in format <red,green,blue,alpha>"), AppError::NeedImagesError => write!(f, "Need IMAGE in config"), AppError::ParseImageError => write!(f, "IMAGE needs to be in format <row,col,path_to_image>"), AppError::InvalidRowsColsError => write!(f, "ROWS or COLS cannot be lesser than 1"), AppError::LoadImageError => write!(f, "Failed to load image"), AppError::SaveImageError => write!(f, "Failed to save image"), } } } impl error::Error for AppError { fn cause(&self) -> Option<&error::Error> { None } }
extern crate time; use std::time::{Duration, Instant}; use log::error; use winit::dpi::LogicalSize; use winit::window::WindowBuilder; use winit_input_helper::WinitInputHelper; use winit::event::{Event, VirtualKeyCode}; use winit::event_loop::{ControlFlow, EventLoop}; use pixels::{Error, Pixels, SurfaceTexture}; use std::fs; use std::env; use std::process; use rs_emu::Emu; fn main() -> Result<(), Error> { let args: Vec<String> = env::args().collect(); if args.len() != 2 { println!("No input file given"); process::exit(1); } // Reading ROM file let buffer = fs::read_to_string(&args[1]) .expect("File doesn't exist"); let mut emu = Emu::new(); emu.load_rom(&buffer); // ------------------------ Game loop -------------------------- // env_logger::init(); let event_loop = EventLoop::new(); let mut input = WinitInputHelper::new(); let window = { let size = LogicalSize::new(512 as f64, 256 as f64); WindowBuilder::new() .with_title("rs_emu") .with_inner_size(size) .with_min_inner_size(size) .build(&event_loop) .unwrap() }; let mut pixels = { let window_size = window.inner_size(); let surface_texture = SurfaceTexture::new(window_size.width, window_size.height, &window); Pixels::new(512, 256, surface_texture)? }; let mut time = Instant::now(); event_loop.run(move |event, _, control_flow| { emu.ticks(1000); if let Event::RedrawRequested(_) = event { emu.draw(pixels.get_frame()); if pixels .render() .map_err(|e| error!("pixels.render() failed: {}", e)) .is_err() { *control_flow = ControlFlow::Exit; return; } } let now = Instant::now(); let dt = now.duration_since(time); let one_frame = Duration::new(0,10_000_000); if dt > one_frame { time = now; window.request_redraw(); } if input.update(event) { if input.key_pressed(VirtualKeyCode::Escape) || input.quit() { *control_flow = ControlFlow::Exit; return; } if let Some(size) = input.window_resized() { pixels.resize(size.width, size.height); } /* if input.key_pressed(VirtualKeyCode::Left) { self.emu.store_ram(24576, ASCII_CODE); } if input.key_released(VirtualKeyCode::Left) { self.emu.store_ram(24576, 0); } */ } }); }
use std::collections::HashMap; use itertools::Itertools; pub fn run() { let system = BagSystem::build_from_rules(include_str!("input.txt")); let can_contain_shiny_gold = system.count_contains("shiny gold"); let shiny_gold_requires_contain = system.count_required_bags("shiny gold"); println!("Day07 - Part 1: {}", can_contain_shiny_gold); println!("Day07 - Part 2: {}", shiny_gold_requires_contain); } struct BagSystem<'a> { contains: HashMap<&'a str, Vec<(&'a str, u32)>>, contained_in: HashMap<&'a str, Vec<&'a str>> } impl<'a> BagSystem<'a> { fn new() -> Self { Self { contains: HashMap::new(), contained_in: HashMap::new() } } fn count_required_bags(&self, key: &str) -> u32 { match self.contains.get(key) { Some (b) => { b.iter().fold(0, |sum, bag| sum + bag.1 + (bag.1* self.count_required_bags(bag.0))) }, None => 0 } } fn count_contains(&self, key: &str) -> usize { let mut all = self.get_all_contains(key); all.sort(); all.dedup(); all.len() } fn get_all_contains(&self, key: &str) -> Vec<&str> { match self.contained_in.get(key) { Some(b) => { let mut res = b.to_vec(); for contained in b { res.append(&mut BagSystem::get_all_contains(self, contained)); } res }, None => Vec::new() } } fn build_from_rules(input: &'a str) -> Self { let mut sys = Self::new(); for line in input.lines() { sys.add_bag_rule(line); } sys } fn add_bag_rule(&mut self, rule_str: &'a str) { let (bag, rules) = rule_str.split(" bags contain ").collect_tuple().unwrap(); let contained_bags: Vec<(&str, u32)> = if rules != "no other bags." { rules.split(", ").map(|c| { let end = c.find(" bag").unwrap(); let n = c[0..1].parse().expect("Not a number"); (&c[2..end], n) }).collect() } else { Vec::new() }; self.add_bag(bag, contained_bags); } fn add_bag(&mut self, bag: &'a str, contained: Vec<(&'a str, u32)>) { for con_bag in &contained { let contained_in = self.contained_in .entry(con_bag.0) .or_insert(Vec::new()); contained_in.push(bag); } self.contains.insert(bag, contained); } } #[cfg(test)] mod tests { use super::*; static TEST_INPUT: &str = "light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags."; #[test] fn test_add_bag_to_system() { let mut system = BagSystem::new(); let bags = vec![("shiny magenta",1), ("wavy teal",2)]; system.add_bag("light red", bags); assert_eq!(2, system.contained_in.len()); } #[test] fn test_add_empty_bag_rule_to_system() { let mut system = BagSystem::new(); system.add_bag_rule("striped tomato bags contain no other bags."); assert_eq!(0, system.contained_in.len()); } #[test] fn test_add_two_bag_rule_to_system() { let mut system = BagSystem::new(); system.add_bag_rule("dark orange bags contain 3 bright white bags, 4 muted yellow bags."); assert_eq!(2, system.contained_in.len()); } #[test] fn test_build_rule_to_system_from_input() { let system = BagSystem::build_from_rules(TEST_INPUT); assert_eq!(7, system.contained_in.len()); } #[test] fn test_get_all_bag_contains() { let system = BagSystem::build_from_rules(TEST_INPUT); let res = system.get_all_contains("shiny gold"); assert_eq!(6, res.len()); } #[test] fn test_count_contains() { let system = BagSystem::build_from_rules(TEST_INPUT); let res = system.count_contains("shiny gold"); assert_eq!(4, res); } #[test] fn test_count_required_bags() { let system = BagSystem::build_from_rules(TEST_INPUT); let res = system.count_required_bags("shiny gold"); assert_eq!(32, res); } }
use crate::properties; use serde::Deserialize; #[derive(Debug, Deserialize)] pub struct RoundedCorners { #[serde(rename = "mn")] pub match_name: String, #[serde(rename = "nm")] pub name: String, #[serde(rename = "r")] pub radius: properties::EitherValue, }
use x11::xlib::{ Atom as XAtom, False as XFalse, XGetWindowProperty, }; use std::{ os::raw::{ c_int, c_uchar, c_ulong, }, ptr::null_mut, }; use crate::{ Atom, Display, NotSupported, Window, }; /// An export of [XGetWindowProperty]. /// Make sure to [x11::xlib::XFree] the pointer, when you're done with it. /// /// An example of how to handle the response can be found in the [GetWindowPropertyResponse] docs. pub unsafe fn get_window_property( display: &Display, window: Window, property: Atom, expected_type: XAtom ) -> Result<GetWindowPropertyResponse, NotSupported> { let mut response = GetWindowPropertyResponse::default(); if XGetWindowProperty( display.0, window.0, property.0, 0, 4096 / 4, XFalse, expected_type, &mut response.actual_type_return, &mut response.actual_format_return, &mut response.nitems_return, &mut response.bytes_after_return, &mut response.proper_return ) == 0 { return Ok(response) } Err(NotSupported) } /// A response to [get_window_property]. /// /// A slice should be made from this. /// /// **NOTE:** Remember to use XFree on the pointer. /// /// # Example: /// ```ignore /// let response: GetWindowPropertyResponse = get_window_property(...); /// if response.actual_format_return == 8 { /// slice::from_raw_parts(response.proper_return as *const u8, response.nitems_return as usize) /// .iter() /// .for_each(|x| println!("{}", x)); /// XFree(response.proper_return) /// } /// ``` pub struct GetWindowPropertyResponse { /// The type of the return. pub actual_type_return: XAtom, /// The formate of the return whether it is 8, 16 or 32 bytes. /// If the architecture is 64-bits and the format is 32, /// then the return type wil be 64 bits. pub actual_format_return: c_int, /// The number of items returned in the lsit. pub nitems_return: c_ulong, /// The number of bytes that are returned. /// /// This crate ignores this field. pub bytes_after_return: c_ulong, /// The pointer that is returned. pub proper_return: *mut c_uchar, } impl Default for GetWindowPropertyResponse { fn default() -> Self { Self { actual_type_return: 0, actual_format_return: 0, nitems_return: 0, bytes_after_return: 0, proper_return: null_mut(), } } }
// Test parenthesis fn foo() { let very_long_variable_name = (a + first + simple + test); let very_long_variable_name = (a + first + simple + test + AAAAAAAAAAAAA + BBBBBBBBBBBBBBBBBB + b + c); }
use std::fs::File; use std::io::{self, Read}; use std::num; use std::path::Path; #[derive(Debug)] enum CustomError { Io(io::Error), // we could add more meaningful data Parse(num::ParseIntError), } fn file_parse_verbose<P: AsRef<Path>>(file_path: P) -> Result<i32, CustomError> { let mut file = File::open(file_path).map_err(CustomError::Io).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).map_err(CustomError::Io).unwrap(); let n: i32 = contents.trim().parse().map_err(CustomError::Parse).unwrap(); Ok(n) } // provide an implemention for converting a io::Error to a CustomError impl From<io::Error> for CustomError { fn from(err: io::Error) -> CustomError { CustomError::Io(err) } } impl From<num::ParseIntError> for CustomError { fn from(err: num::ParseIntError) -> CustomError { CustomError::Parse(err) } } fn file_parse<P: AsRef<Path>>(file_path: P) -> Result<i32, CustomError> { let mut file = File::open(file_path)?; // here can have a io::Error let mut contents = String::new(); file.read_to_string(&mut contents)?; // here can have a io::Error let n: i32 = contents.trim().parse()?; // here can have a num::ParseIntError Ok(n) } fn main() { let n: i32 = file_parse("/home/pietro/Desktop/Emerging Programming Paradigms/rust_projects/presentation/resources/3_number.txt").unwrap_or(0); println!("parsed number is {}", n) }
#[doc = "Reader of register MMMS_CONN_STATUS"] pub type R = crate::R<u32, super::MMMS_CONN_STATUS>; #[doc = "Reader of field `CURR_CONN_INDEX`"] pub type CURR_CONN_INDEX_R = crate::R<u8, u8>; #[doc = "Reader of field `CURR_CONN_TYPE`"] pub type CURR_CONN_TYPE_R = crate::R<bool, bool>; #[doc = "Reader of field `SN_CURR`"] pub type SN_CURR_R = crate::R<bool, bool>; #[doc = "Reader of field `NESN_CURR`"] pub type NESN_CURR_R = crate::R<bool, bool>; #[doc = "Reader of field `LAST_UNMAPPED_CHANNEL`"] pub type LAST_UNMAPPED_CHANNEL_R = crate::R<u8, u8>; #[doc = "Reader of field `PKT_MISS`"] pub type PKT_MISS_R = crate::R<bool, bool>; #[doc = "Reader of field `ANCHOR_PT_STATE`"] pub type ANCHOR_PT_STATE_R = crate::R<bool, bool>; impl R { #[doc = "Bits 0:4 - Connection Index that was serviced. Legal values are 0,1,2,3."] #[inline(always)] pub fn curr_conn_index(&self) -> CURR_CONN_INDEX_R { CURR_CONN_INDEX_R::new((self.bits & 0x1f) as u8) } #[doc = "Bit 5 - Connection type 1 - Master Connection 0 - Slave Connection"] #[inline(always)] pub fn curr_conn_type(&self) -> CURR_CONN_TYPE_R { CURR_CONN_TYPE_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Sequence Number of Packets exchanged"] #[inline(always)] pub fn sn_curr(&self) -> SN_CURR_R { SN_CURR_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - Next Sequence Number"] #[inline(always)] pub fn nesn_curr(&self) -> NESN_CURR_R { NESN_CURR_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bits 8:13 - Last Unmapped Channel"] #[inline(always)] pub fn last_unmapped_channel(&self) -> LAST_UNMAPPED_CHANNEL_R { LAST_UNMAPPED_CHANNEL_R::new(((self.bits >> 8) & 0x3f) as u8) } #[doc = "Bit 14 - 1 - Packet Missed 0 - Connection exchanged packets"] #[inline(always)] pub fn pkt_miss(&self) -> PKT_MISS_R { PKT_MISS_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - Anchor Point State 0 - Anchor point missed 1 - Anchor point established"] #[inline(always)] pub fn anchor_pt_state(&self) -> ANCHOR_PT_STATE_R { ANCHOR_PT_STATE_R::new(((self.bits >> 15) & 0x01) != 0) } }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// LogsExclusion : Represents the index exclusion filter object from configuration API. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LogsExclusion { #[serde(rename = "filter", skip_serializing_if = "Option::is_none")] pub filter: Option<Box<crate::models::LogsExclusionFilter>>, /// Whether or not the exclusion filter is active. #[serde(rename = "is_enabled", skip_serializing_if = "Option::is_none")] pub is_enabled: Option<bool>, /// Name of the index exclusion filter. #[serde(rename = "name")] pub name: String, } impl LogsExclusion { /// Represents the index exclusion filter object from configuration API. pub fn new(name: String) -> LogsExclusion { LogsExclusion { filter: None, is_enabled: None, name, } } }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::schema::ensure_slice_len_eq; use anyhow::{format_err, Result}; use byteorder::{BigEndian, ReadBytesExt}; use schemadb::{ define_schema, schema::{KeyCodec, ValueCodec}, DEFAULT_CF_NAME, }; use sgtypes::ledger_info::LedgerInfo; use std::mem::size_of; define_schema!( LedgerInfoSchema, u64, /* epoch num */ LedgerInfo, DEFAULT_CF_NAME ); impl KeyCodec<LedgerInfoSchema> for u64 { fn encode_key(&self) -> Result<Vec<u8>> { Ok(self.to_be_bytes().to_vec()) } fn decode_key(data: &[u8]) -> Result<Self> { ensure_slice_len_eq(data, size_of::<Self>())?; Ok((&data[..]).read_u64::<BigEndian>()?) } } impl ValueCodec<LedgerInfoSchema> for LedgerInfo { fn encode_value(&self) -> Result<Vec<u8>> { lcs::to_bytes(self).map_err(|e| format_err!("{:?}", e)) } fn decode_value(data: &[u8]) -> Result<Self> { lcs::from_bytes(data).map_err(|e| format_err!("{:?}", e)) } }
mod serve; use serve::api::v1::API; use serve::authorizer::Authorizer; use serve::configuration::ConfigWrapper; use serve::database::DatabaseController; use serve::emailer::Emailer; use serve::oauth::Oauth; use serve::server::Server; use std::fs; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::Path; use std::process::Command; use std::sync::{Arc, Mutex}; use std::time::SystemTime; use warp::filters::log::Info; use warp::Filter; #[tokio::main] async fn main() { let mut config = ConfigWrapper::new("settings").unwrap(); match Server::instance(&config.clone().configuration) { Ok(server) => { let mut authorizer = Authorizer::new(); let emailer = Emailer::new(20); let mailer = Arc::new(Mutex::new(emailer)); let serve = Arc::new(Mutex::new(server.clone())); let conf = Arc::new(Mutex::new(config.clone().configuration.clone())); let con = Arc::clone(&conf.clone()); let mut auths: Vec<String> = Vec::new(); for i in 0..config.clone().configuration.oauth.auths.len() { let auth = config.configuration.oauth.auths[i].clone(); let serve = Arc::clone(&serve); let server = serve.lock().unwrap(); match DatabaseController::get_oauth_record(&server.clone(), auth.clone().name) { Ok(conf) => { config.configuration.oauth.auths[i] = conf; } Err(_) => { let aut = Oauth::new(auth.clone(), server.clone()); authorizer = authorizer.add_oauth(aut); auths.push(auth.clone().name); } } } for prov in auths { authorizer.init_authorize(prov); } let log = warp::log::custom(move |info: Info| { // Use a log macro, or slog, or println, or whatever! let mut usr_agnt = info.user_agent(); if usr_agnt.is_none() { usr_agnt = Some("None"); } let out: String; let con = con.lock().unwrap(); let path = Path::new(&con.server.access_log); let mut file_obj: File; if path.exists() { file_obj = OpenOptions::new().append(true).open(path).unwrap(); } else { file_obj = File::create(path).unwrap(); } match info.remote_addr() { Some(addr) => { out = format!( "{} => [{} {} {} {} {} {}]\n", SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_millis(), addr, info.method(), info.path(), info.status(), info.elapsed().as_nanos().to_string(), usr_agnt.unwrap() ); } None => { out = format!( "{} => [{} {} {} {} {}]\n", SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_millis(), info.method(), info.path(), info.status(), info.elapsed().as_nanos().to_string(), usr_agnt.unwrap() ); } } file_obj.write(out.as_bytes()).unwrap(); }); let base = warp::path::end().and(warp::fs::dir("www")); let assets = warp::path("assets").and(warp::fs::dir("www/assets")); let stat = warp::path("static").and(warp::fs::dir("www/static")); let api_routing = API::setup(mailer, serve, conf); let oauth = authorizer.clone().route(); let robots = warp::path("robots.txt").map(|| fs::read_to_string("www/robots.txt").unwrap()); let base_files = warp::path!(String) .map(|_| warp::reply::html(fs::read_to_string("www/index.html").unwrap())); let routes = robots .or(base) .or(assets) .or(stat) .or(api_routing) .or(oauth) .or(base_files) .with(log); println!( "Running at {}:{}", config.clone().configuration.server.address, server.clone().port ); println!("Database: {}", server.clone().database.database.name()); Command::new("./qamaits-redirect") .arg("-host") .arg(config.clone().configuration.server.hostname) .arg("-address") .arg(config.clone().configuration.server.address) .spawn() .unwrap(); warp::serve(routes) .tls() .key_path(config.clone().configuration.clone().server.tls_key) .cert_path(config.clone().configuration.clone().server.tls_cert) .run((server.clone().address, server.clone().port)) .await; } Err(e) => { println!("{:?}", e); return; } } }
use crate::scorecard::{DieCountScores, Scorecard}; pub fn score_roll(roll: &Vec<u8>) -> Scorecard{ let mut aces:u8 = 0; let mut twos:u8 = 0; let mut threes:u8 = 0; let mut fours:u8 = 0; let mut fives:u8 = 0; let mut sixes:u8 = 0; let mut die_total:u8 = 0; let mut sorted_vec = vec![0, 0, 0, 0, 0]; for i in 0..roll.len() { let v = roll[i]; sorted_vec[i] = v; if v == 1 { aces += v; } else if v == 2 { twos += v; } else if v == 3 { threes += v; } else if v == 4 { fours += v; } else if v == 5 { fives += v; } else if v == 6 { sixes += v; } die_total += v; } sorted_vec.sort(); let die_count = get_die_count(aces, twos, threes, fours, fives, sixes); let die_count_scores = get_die_count_based_scores(&die_count); Scorecard{ aces, twos, threes, fours, fives, sixes, three_of_a_kind: if die_count_scores.is_three_of_a_kind { die_total } else { 0 }, four_of_a_kind: if die_count_scores.is_four_of_a_kind { die_total } else { 0 }, full_house: die_count_scores.is_full_house, sm_straight: is_small_straight(&sorted_vec), lg_straight: is_large_straight(&sorted_vec), yahtzee: die_count_scores.is_five_of_a_kind, chance: die_total, yahtzee_bonus_count: 0 } } fn is_small_straight(sorted_vec: &Vec<u8>) -> bool{ let mut vec_no_dups: Vec<u8> = sorted_vec.to_vec(); vec_no_dups.dedup(); if vec_no_dups.len() < 4 { return false; } let first_vale = vec_no_dups[0]; for i in 1..vec_no_dups.len(){ let iu8: u8 = i as u8; if vec_no_dups[i] != first_vale + iu8{ return false; } } true } fn is_large_straight(sorted_vec: &Vec<u8>) -> bool{ for i in 0..sorted_vec.len() { let loop_i: u8 = i as u8; if loop_i + 1 != sorted_vec[i] { return false; } } true } fn get_die_count(aces: u8, twos: u8, threes: u8, fours: u8, fives: u8, sixes: u8) -> [u8; 6] { [aces, twos / 2, threes / 3, fours / 4, fives / 5, sixes / 6] } fn get_die_count_based_scores(die_count:&[u8; 6]) -> DieCountScores{ let mut is_two_of_a_kind = false; let mut is_three_of_a_kind = false; let mut is_four_of_a_kind = false; let mut is_five_of_a_kind = false; for i in 0..die_count.len(){ let v: u8 = die_count[i]; if v == 2 { is_two_of_a_kind = true; } if v == 3{ is_three_of_a_kind = true; } if v == 4{ is_four_of_a_kind = true; } if v == 5 { is_five_of_a_kind = true; } } DieCountScores {is_two_of_a_kind, is_three_of_a_kind, is_four_of_a_kind, is_five_of_a_kind, is_full_house: is_two_of_a_kind && is_three_of_a_kind} }
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; #[derive(Hash)] struct SessionData<'a> { user_name: &'a str, extra_data: &'a str, password: &'a str, } fn calculate_hash<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } pub fn hash(user_name: &str, extra_data: &str, password: &str) -> u64 { calculate_hash(&SessionData { user_name: user_name, extra_data: extra_data, password: password, }) }
// use std::collections::HashMap; use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender}; use std::thread; use std::time::{Duration, Instant}; use log::*; use raft::{self, RawNode}; use raft::eraftpb::{ConfChange, ConfState, Entry, EntryType, Message, MessageType}; use raft::storage::MemStorage; use crate::server::util; pub enum PeerMessage { Propose(Vec<u8>), Message(Message), ConfChange(ConfChange), } pub struct Peer { pub raw_node: RawNode<MemStorage>, last_apply_index: u64, // last_compacted_idx: u64, conf_state: Option<ConfState>, apply_ch: SyncSender<Entry>, // peers_addr: HashMap<u64, (String, u32)>, // id, (host, port) } impl Peer { pub fn new(id: u64, apply_ch: SyncSender<Entry>, peers: Vec<u64>) -> Peer { let cfg = util::default_raft_config(id, peers); let storge = MemStorage::new(); let peer = Peer { raw_node: RawNode::new(&cfg, storge, vec![]).unwrap(), last_apply_index: 0, // last_compacted_idx: 0, conf_state: None, apply_ch, // peers_addr: HashMap::new(), }; peer } pub fn activate(mut peer: Peer, sender: SyncSender<Message>, receiver: Receiver<PeerMessage>) { thread::spawn(move || { peer.listen_message(sender, receiver); }); } fn listen_message(&mut self, sender: SyncSender<Message>, receiver: Receiver<PeerMessage>) { debug!("start listening message"); let mut t = Instant::now(); let mut timeout = Duration::from_millis(100); loop { match receiver.recv_timeout(timeout) { Ok(PeerMessage::Propose(p)) => match self.raw_node.propose(vec![], p.clone()) { Ok(_) => info!("proposal succeeded: {:?}", p), Err(_) => { warn!("proposal failed: {:?}", p); self.apply_message(Entry::new()); } }, Ok(PeerMessage::ConfChange(cc)) => { match self.raw_node.propose_conf_change(vec![], cc.clone()) { Ok(_) => info!("proposed configuration change succeeded: {:?}", cc), Err(_) => warn!("proposed configuration change failed: {:?}", cc), } } Ok(PeerMessage::Message(m)) => self.raw_node.step(m).unwrap(), Err(RecvTimeoutError::Timeout) => (), Err(RecvTimeoutError::Disconnected) => return, } let d = t.elapsed(); if d >= timeout { t = Instant::now(); timeout = Duration::from_millis(200); self.raw_node.tick(); } else { timeout -= d; } self.on_ready(sender.clone()); } } fn is_leader(&self) -> bool { self.raw_node.raft.leader_id == self.raw_node.raft.id } fn on_ready(&mut self, sender: SyncSender<Message>) { if !self.raw_node.has_ready() { return; } let mut ready = self.raw_node.ready(); let is_leader = self.is_leader(); // leader if is_leader { let msgs = ready.messages.drain(..); for msg in msgs { Self::send_message(sender.clone(), msg.clone()); } } if !raft::is_empty_snap(&ready.snapshot) { self.raw_node .mut_store() .wl() .apply_snapshot(ready.snapshot.clone()) .unwrap() } if !ready.entries.is_empty() { self.raw_node .mut_store() .wl() .append(&ready.entries) .unwrap(); } if let Some(ref hs) = ready.hs { self.raw_node.mut_store().wl().set_hardstate(hs.clone()); } // not leader if !is_leader { let msgs = ready.messages.drain(..); for msg in msgs { Self::send_message(sender.clone(), msg.clone()); } } if let Some(committed_entries) = ready.committed_entries.take() { for entry in committed_entries { // Mostly, you need to save the last apply index to resume applying // after restart. Here we just ignore this because we use a Memory storage. self.last_apply_index = entry.get_index(); if entry.get_data().is_empty() { // Emtpy entry, when the peer becomes Leader it will send an empty entry. continue; } match entry.get_entry_type() { EntryType::EntryNormal => self.apply_message(entry.clone()), EntryType::EntryConfChange => { let cc = util::parse_data(&entry.data); info!("apply config change: {:?}", cc); self.raw_node.apply_conf_change(&cc); self.apply_message(entry.clone()); self.conf_state = Some(self.raw_node.apply_conf_change(&cc)); } } } // if last_apply_index > 0 { // info!("last apply index: {}", last_apply_index); // let data = b"data".to_vec(); // match self.raw_node.mut_store().wl().create_snapshot( // last_apply_index, // conf_state, // data, // ) { // Ok(_s) => (), // Err(e) => error!("creating snapshot failed: {:?}", e), // } // } } // Advance the Raft self.raw_node.advance(ready); // let raft_applied = self.raw_node.raft.raft_log.get_applied(); // info!("raft_applied: {}", raft_applied); // match self.raw_node.mut_store().wl().compact(raft_applied) { // Ok(_) => (), // Err(e) => error!("compaction failed: {:?}", e), // } } fn send_message(sender: SyncSender<Message>, msg: Message) { thread::spawn(move || { // for entry in msg.mut_entries().iter() { // debug!("leader: {:?}", entry); // } match msg.msg_type { MessageType::MsgHeartbeat => debug!("send message: {:?}", msg), MessageType::MsgHeartbeatResponse => debug!("send message: {:?}", msg), _ => info!("send message: {:?}", msg), } sender.send(msg).unwrap_or_else(|e| { panic!("error sending message: {:?}", e); }); }); } fn apply_message(&self, entry: Entry) { let sender = self.apply_ch.clone(); thread::spawn(move || { info!("apply entry: {:?}", entry); sender.send(entry).unwrap_or_else(|e| { panic!("error sending apply entry: {:?}", e); }); }); } }