text
stringlengths
8
4.13M
/// Abstract Syntax for F-terms and F-types use std::fmt; // The trees themselves #[derive(Clone, Debug, PartialEq, Eq)] pub enum FType { Var(String), Arr(Box<FType>, Box<FType>), Forall(String, Box<FType>), } #[derive(Clone, Debug, PartialEq, Eq)] pub enum FTermChurch { Var(String), Lam(String, Box<FType>, Box<FTermChurch>), App(Box<FTermChurch>, Box<FTermChurch>), TLam(String, Box<FTermChurch>), TApp(Box<FTermChurch>, Box<FType>), } #[derive(Clone, Debug, PartialEq, Eq)] pub enum FOmegaKind { Star, Arr(Box<FOmegaKind>, Box<FOmegaKind>), } // smart constructors that handle boxing/string allocation pub fn tvar<S: Into<String>>(x: S) -> FType { FType::Var(x.into()) } pub fn arr(x: FType, y: FType) -> FType { FType::Arr(Box::new(x), Box::new(y)) } pub fn forall<S: Into<String>>(x: S, y: FType) -> FType { FType::Forall(x.into(), Box::new(y)) } pub fn var<S: Into<String>>(x: S) -> FTermChurch { FTermChurch::Var(x.into()) } pub fn lam<S: Into<String>>(x: S, y: FType, z: FTermChurch) -> FTermChurch { FTermChurch::Lam(x.into(), Box::new(y), Box::new(z)) } pub fn app(x: FTermChurch, y: FTermChurch) -> FTermChurch { FTermChurch::App(Box::new(x), Box::new(y)) } pub fn tlam<S: Into<String>>(x: S, y: FTermChurch) -> FTermChurch { FTermChurch::TLam(x.into(), Box::new(y)) } pub fn tapp(x: FTermChurch, y: FType) -> FTermChurch { FTermChurch::TApp(Box::new(x), Box::new(y)) } // shorthand for inspecting the tags of the trees impl FType { pub fn is_var(&self) -> bool { if let FType::Var(_) = self { true } else { false } } pub fn is_forall(&self) -> bool { if let FType::Forall(_, _) = self { true } else { false } } } impl FTermChurch { pub fn is_var(&self) -> bool { if let FTermChurch::Var(_) = self { true } else { false } } pub fn is_lam(&self) -> bool { match self { FTermChurch::Lam(_, _, _) | FTermChurch::TLam(_, _) => true, _ => false, } } pub fn is_app(&self) -> bool { if let FTermChurch::App(_, _) = self { true } else { false } } pub fn is_tapp(&self) -> bool { if let FTermChurch::TApp(_, _) = self { true } else { false } } pub fn is_value(&self) -> bool { self.is_lam() } } impl FOmegaKind { pub fn is_star(&self) -> bool { if let FOmegaKind::Star = self { true } else { false } } } // pretty printing and printing machinery pub fn parens_if<X: fmt::Display>(x: X, use_parens: bool) -> String { if use_parens { format!("({})", x) } else { format!("{}", x) } } impl fmt::Display for FType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::FType::*; match self { Var(x) => write!(f, "{}", x), Arr(x, y) => write!(f, "{} -> {}", parens_if(x, !x.is_var()), y), Forall(x, y) => write!(f, "forall {}, {}", x, y), } } } impl fmt::Display for FTermChurch { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::FTermChurch::*; match self { Var(x) => write!(f, "{}", x), Lam(x, y, z) => write!(f, "lam {} : {} => {}", x, y, z), App(x, y) => write!(f, "{} {}", parens_if(x, !x.is_var()), parens_if(y, !y.is_var())), TLam(x, y) => write!(f, "tlam {} => {}", x, y), TApp(x, y) => write!(f, "{} [{}]", parens_if(x, x.is_lam()), y), } } } impl fmt::Display for FOmegaKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::FOmegaKind::*; match self { Star => write!(f, "*"), Arr(x, y) => write!(f, "{} -> {}", parens_if(x, !x.is_star()), y), } } }
use { crate::model::*, cm_rust::{ self, CapabilityPath, ComponentDecl, ExposeDecl, ExposeDirectoryDecl, ExposeLegacyServiceDecl, ExposeServiceDecl, OfferDecl, OfferDirectoryDecl, OfferLegacyServiceDecl, OfferServiceDecl, OfferTarget, StorageDecl, UseDecl, UseDirectoryDecl, UseLegacyServiceDecl, }, fidl_fuchsia_sys2 as fsys, std::collections::HashSet, }; /// A capability being routed, which is represented by one of `use`, `offer`, or `expose`, /// or `storage`. #[derive(Debug)] pub enum RoutedCapability { Use(UseDecl), Expose(ExposeDecl), Offer(OfferDecl), Storage(StorageDecl), } impl RoutedCapability { /// Returns the source path of the capability, if one exists. pub fn source_path(&self) -> Option<&CapabilityPath> { match self { RoutedCapability::Use(use_) => match use_ { UseDecl::LegacyService(UseLegacyServiceDecl { source_path, .. }) => { Some(source_path) } UseDecl::Directory(UseDirectoryDecl { source_path, .. }) => Some(source_path), _ => None, }, RoutedCapability::Expose(expose) => match expose { ExposeDecl::LegacyService(ExposeLegacyServiceDecl { source_path, .. }) => { Some(source_path) } ExposeDecl::Directory(ExposeDirectoryDecl { source_path, .. }) => Some(source_path), _ => None, }, RoutedCapability::Offer(offer) => match offer { OfferDecl::LegacyService(OfferLegacyServiceDecl { source_path, .. }) => { Some(source_path) } OfferDecl::Directory(OfferDirectoryDecl { source_path, .. }) => Some(source_path), _ => None, }, RoutedCapability::Storage(_) => None, } } /// Returns the `ExposeDecl` that exposes the capability, if it exists. pub fn find_expose_source<'a>(&self, decl: &'a ComponentDecl) -> Option<&'a ExposeDecl> { decl.exposes.iter().find(|&expose| match (self, expose) { // LegacyService exposed to me that has a matching `expose` or `offer`. ( RoutedCapability::Offer(OfferDecl::LegacyService(parent_offer)), ExposeDecl::LegacyService(expose), ) => parent_offer.source_path == expose.target_path, ( RoutedCapability::Expose(ExposeDecl::LegacyService(parent_expose)), ExposeDecl::LegacyService(expose), ) => parent_expose.source_path == expose.target_path, // Directory exposed to me that matches a directory `expose` or `offer`. ( RoutedCapability::Offer(OfferDecl::Directory(parent_offer)), ExposeDecl::Directory(expose), ) => parent_offer.source_path == expose.target_path, ( RoutedCapability::Expose(ExposeDecl::Directory(parent_expose)), ExposeDecl::Directory(expose), ) => parent_expose.source_path == expose.target_path, // Directory exposed to me that matches a `storage` declaration which consumes it. (RoutedCapability::Storage(parent_storage), ExposeDecl::Directory(expose)) => { parent_storage.source_path == expose.target_path } _ => false, }) } /// Returns the set of `ExposeServiceDecl`s that expose the service capability, if they exist. pub fn find_expose_service_sources<'a>( &self, decl: &'a ComponentDecl, ) -> Vec<&'a ExposeServiceDecl> { let paths: HashSet<_> = match self { RoutedCapability::Offer(OfferDecl::Service(parent_offer)) => { parent_offer.sources.iter().map(|s| &s.source_path).collect() } RoutedCapability::Expose(ExposeDecl::Service(parent_expose)) => { parent_expose.sources.iter().map(|s| &s.source_path).collect() } _ => panic!("Expected an offer or expose of a service capability, found: {:?}", self), }; decl.exposes .iter() .filter_map(|expose| match expose { ExposeDecl::Service(expose) if paths.contains(&expose.target_path) => Some(expose), _ => None, }) .collect() } /// Returns the `OfferDecl` that offers the capability in `child_offer` to `child_name`, if it /// exists. pub fn find_offer_source<'a>( &self, decl: &'a ComponentDecl, child_moniker: &ChildMoniker, ) -> Option<&'a OfferDecl> { decl.offers.iter().find(|&offer| match (self, offer) { // LegacyService offered to me that matches a service `use` or `offer` declaration. ( RoutedCapability::Use(UseDecl::LegacyService(child_use)), OfferDecl::LegacyService(offer), ) => Self::is_offer_legacy_service_or_directory_match( child_moniker, &child_use.source_path, &offer.target, &offer.target_path, ), ( RoutedCapability::Offer(OfferDecl::LegacyService(child_offer)), OfferDecl::LegacyService(offer), ) => Self::is_offer_legacy_service_or_directory_match( child_moniker, &child_offer.source_path, &offer.target, &offer.target_path, ), // Directory offered to me that matches a directory `use` or `offer` declaration. (RoutedCapability::Use(UseDecl::Directory(child_use)), OfferDecl::Directory(offer)) => { Self::is_offer_legacy_service_or_directory_match( child_moniker, &child_use.source_path, &offer.target, &offer.target_path, ) } ( RoutedCapability::Offer(OfferDecl::Directory(child_offer)), OfferDecl::Directory(offer), ) => Self::is_offer_legacy_service_or_directory_match( child_moniker, &child_offer.source_path, &offer.target, &offer.target_path, ), // Directory offered to me that matches a `storage` declaration which consumes it. (RoutedCapability::Storage(child_storage), OfferDecl::Directory(offer)) => { Self::is_offer_legacy_service_or_directory_match( child_moniker, &child_storage.source_path, &offer.target, &offer.target_path, ) } // Storage offered to me. (RoutedCapability::Use(UseDecl::Storage(child_use)), OfferDecl::Storage(offer)) => { Self::is_offer_storage_match( child_moniker, child_use.type_(), offer.target(), offer.type_(), ) } ( RoutedCapability::Offer(OfferDecl::Storage(child_offer)), OfferDecl::Storage(offer), ) => Self::is_offer_storage_match( child_moniker, child_offer.type_(), offer.target(), offer.type_(), ), _ => false, }) } /// Returns the set of `OfferServiceDecl`s that offer the service capability, if they exist. pub fn find_offer_service_sources<'a>( &self, decl: &'a ComponentDecl, child_moniker: &ChildMoniker, ) -> Vec<&'a OfferServiceDecl> { let paths: HashSet<_> = match self { RoutedCapability::Use(UseDecl::Service(child_use)) => { vec![&child_use.source_path].into_iter().collect() } RoutedCapability::Offer(OfferDecl::Service(child_offer)) => { child_offer.sources.iter().map(|s| &s.source_path).collect() } _ => panic!("Expected a use or offer of a service capability, found: {:?}", self), }; decl.offers .iter() .filter_map(|offer| match offer { OfferDecl::Service(offer) if Self::is_offer_service_match( child_moniker, &paths, &offer.target, &offer.target_path, ) => { Some(offer) } _ => None, }) .collect() } fn is_offer_service_match( child_moniker: &ChildMoniker, paths: &HashSet<&CapabilityPath>, target: &OfferTarget, target_path: &CapabilityPath, ) -> bool { match target { OfferTarget::Child(target_child_name) => match child_moniker.collection() { Some(_) => false, None => target_child_name == child_moniker.name() && paths.contains(target_path), }, OfferTarget::Collection(target_collection_name) => match child_moniker.collection() { Some(collection) => { target_collection_name == collection && paths.contains(target_path) } None => false, }, } } fn is_offer_legacy_service_or_directory_match( child_moniker: &ChildMoniker, path: &CapabilityPath, target: &OfferTarget, target_path: &CapabilityPath, ) -> bool { match target { OfferTarget::Child(target_child_name) => match child_moniker.collection() { Some(_) => false, None => target_path == path && target_child_name == child_moniker.name(), }, OfferTarget::Collection(target_collection_name) => match child_moniker.collection() { Some(collection) => target_path == path && target_collection_name == collection, None => false, }, } } fn is_offer_storage_match( child_moniker: &ChildMoniker, child_type: fsys::StorageType, parent_target: &OfferTarget, parent_type: fsys::StorageType, ) -> bool { // The types must match... parent_type == child_type && // ...and the child/collection names must match. match (parent_target, child_moniker.collection()) { (OfferTarget::Child(target_child_name), None) => target_child_name == child_moniker.name(), (OfferTarget::Collection(target_collection_name), Some(collection)) => target_collection_name == collection, _ => false } } } #[cfg(test)] mod tests { use { super::*, cm_rust::{ ExposeSource, ExposeTarget, OfferServiceSource, ServiceSource, StorageDirectorySource, }, }; #[test] fn find_expose_service_sources() { let capability = RoutedCapability::Expose(ExposeDecl::Service(ExposeServiceDecl { sources: vec![ ServiceSource { source: ExposeSource::Self_, source_path: CapabilityPath { dirname: "/svc".to_string(), basename: "net".to_string(), }, }, ServiceSource { source: ExposeSource::Self_, source_path: CapabilityPath { dirname: "/svc".to_string(), basename: "log".to_string(), }, }, ServiceSource { source: ExposeSource::Self_, source_path: CapabilityPath { dirname: "/svc".to_string(), basename: "unmatched-source".to_string(), }, }, ], target: ExposeTarget::Realm, target_path: CapabilityPath { dirname: "".to_string(), basename: "".to_string() }, })); let net_service = ExposeServiceDecl { sources: vec![], target: ExposeTarget::Realm, target_path: CapabilityPath { dirname: "/svc".to_string(), basename: "net".to_string(), }, }; let log_service = ExposeServiceDecl { sources: vec![], target: ExposeTarget::Realm, target_path: CapabilityPath { dirname: "/svc".to_string(), basename: "log".to_string(), }, }; let unmatched_service = ExposeServiceDecl { sources: vec![], target: ExposeTarget::Realm, target_path: CapabilityPath { dirname: "/svc".to_string(), basename: "unmatched-target".to_string(), }, }; let decl = ComponentDecl { program: None, uses: vec![], exposes: vec![ ExposeDecl::Service(net_service.clone()), ExposeDecl::Service(log_service.clone()), ExposeDecl::Service(unmatched_service.clone()), ], offers: vec![], children: vec![], collections: vec![], storage: vec![], facets: None, runners: vec![], }; let sources = capability.find_expose_service_sources(&decl); assert_eq!(sources, vec![&net_service, &log_service]) } #[test] #[should_panic] fn find_expose_service_sources_with_unexpected_capability() { let capability = RoutedCapability::Storage(StorageDecl { name: "".to_string(), source: StorageDirectorySource::Realm, source_path: CapabilityPath { dirname: "".to_string(), basename: "".to_string() }, }); let decl = ComponentDecl { program: None, uses: vec![], exposes: vec![], offers: vec![], children: vec![], collections: vec![], storage: vec![], facets: None, runners: vec![], }; capability.find_expose_service_sources(&decl); } #[test] fn find_offer_service_sources() { let capability = RoutedCapability::Offer(OfferDecl::Service(OfferServiceDecl { sources: vec![ ServiceSource { source: OfferServiceSource::Self_, source_path: CapabilityPath { dirname: "/svc".to_string(), basename: "net".to_string(), }, }, ServiceSource { source: OfferServiceSource::Self_, source_path: CapabilityPath { dirname: "/svc".to_string(), basename: "log".to_string(), }, }, ServiceSource { source: OfferServiceSource::Self_, source_path: CapabilityPath { dirname: "/svc".to_string(), basename: "unmatched-source".to_string(), }, }, ], target: OfferTarget::Child("".to_string()), target_path: CapabilityPath { dirname: "".to_string(), basename: "".to_string() }, })); let net_service = OfferServiceDecl { sources: vec![], target: OfferTarget::Child("child".to_string()), target_path: CapabilityPath { dirname: "/svc".to_string(), basename: "net".to_string(), }, }; let log_service = OfferServiceDecl { sources: vec![], target: OfferTarget::Child("child".to_string()), target_path: CapabilityPath { dirname: "/svc".to_string(), basename: "log".to_string(), }, }; let unmatched_service = OfferServiceDecl { sources: vec![], target: OfferTarget::Child("child".to_string()), target_path: CapabilityPath { dirname: "/svc".to_string(), basename: "unmatched-target".to_string(), }, }; let decl = ComponentDecl { program: None, uses: vec![], exposes: vec![], offers: vec![ OfferDecl::Service(net_service.clone()), OfferDecl::Service(log_service.clone()), OfferDecl::Service(unmatched_service.clone()), ], children: vec![], collections: vec![], storage: vec![], facets: None, runners: vec![], }; let moniker = ChildMoniker::new("child".to_string(), None, 0); let sources = capability.find_offer_service_sources(&decl, &moniker); assert_eq!(sources, vec![&net_service, &log_service]) } #[test] #[should_panic] fn find_offer_service_sources_with_unexpected_capability() { let capability = RoutedCapability::Storage(StorageDecl { name: "".to_string(), source: StorageDirectorySource::Realm, source_path: CapabilityPath { dirname: "".to_string(), basename: "".to_string() }, }); let decl = ComponentDecl { program: None, uses: vec![], exposes: vec![], offers: vec![], children: vec![], collections: vec![], storage: vec![], facets: None, runners: vec![], }; let moniker = ChildMoniker::new("".to_string(), None, 0); capability.find_offer_service_sources(&decl, &moniker); } }
use log::*; use num_derive::FromPrimitive; use serde_derive::{Deserialize, Serialize}; use morgan_interface::account::KeyedAccount; use morgan_interface::instruction_processor_utils::DecodeError; use morgan_interface::pubkey::Pubkey; use morgan_helper::logHelper::*; #[derive(Serialize, Debug, PartialEq, FromPrimitive)] pub enum TokenError { InvalidArgument, InsufficentFunds, NotOwner, } impl<T> DecodeError<T> for TokenError { fn type_of(&self) -> &'static str { "TokenError" } } impl std::fmt::Display for TokenError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "error") } } impl std::error::Error for TokenError {} pub type Result<T> = std::result::Result<T, TokenError>; #[derive(Debug, Default, Serialize, Deserialize, PartialEq)] pub struct TokenInfo { /// Total supply of tokens supply: u64, /// Number of base 10 digits to the right of the decimal place in the total supply decimals: u8, /// Descriptive name of this token name: String, /// Symbol for this token symbol: String, } #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)] pub struct TokenAccountDelegateInfo { /// The source account for the tokens source: Pubkey, /// The original amount that this delegate account was authorized to spend up to original_amount: u64, } #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)] pub struct TokenAccountInfo { /// The kind of token this account holds token: Pubkey, /// Owner of this account owner: Pubkey, /// Amount of tokens this account holds amount: u64, /// If `delegate` None, `amount` belongs to this account. /// If `delegate` is Option<_>, `amount` represents the remaining allowance /// of tokens that may be transferred from the `source` account. delegate: Option<TokenAccountDelegateInfo>, } #[derive(Debug, Serialize, Deserialize, PartialEq)] enum TokenInstruction { NewToken(TokenInfo), NewTokenAccount, Transfer(u64), Approve(u64), SetOwner, } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub enum TokenState { Unallocated, Token(TokenInfo), Account(TokenAccountInfo), Invalid, } impl Default for TokenState { fn default() -> TokenState { TokenState::Unallocated } } impl TokenState { #[allow(clippy::needless_pass_by_value)] fn map_to_invalid_args(err: std::boxed::Box<bincode::ErrorKind>) -> TokenError { // warn!("invalid argument: {:?}", err); println!( "{}", Warn( format!("invalid argument: {:?}", err).to_string(), module_path!().to_string() ) ); TokenError::InvalidArgument } pub fn deserialize(input: &[u8]) -> Result<TokenState> { if input.is_empty() { Err(TokenError::InvalidArgument)?; } match input[0] { 0 => Ok(TokenState::Unallocated), 1 => Ok(TokenState::Token( bincode::deserialize(&input[1..]).map_err(Self::map_to_invalid_args)?, )), 2 => Ok(TokenState::Account( bincode::deserialize(&input[1..]).map_err(Self::map_to_invalid_args)?, )), _ => Err(TokenError::InvalidArgument), } } fn serialize(self: &TokenState, output: &mut [u8]) -> Result<()> { if output.is_empty() { // warn!("serialize fail: ouput.len is 0"); println!( "{}", Warn( format!("serialize fail: ouput.len is 0").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } match self { TokenState::Unallocated | TokenState::Invalid => Err(TokenError::InvalidArgument), TokenState::Token(token_info) => { output[0] = 1; let writer = std::io::BufWriter::new(&mut output[1..]); bincode::serialize_into(writer, &token_info).map_err(Self::map_to_invalid_args) } TokenState::Account(account_info) => { output[0] = 2; let writer = std::io::BufWriter::new(&mut output[1..]); bincode::serialize_into(writer, &account_info).map_err(Self::map_to_invalid_args) } } } #[allow(dead_code)] pub fn amount(&self) -> Result<u64> { if let TokenState::Account(account_info) = self { Ok(account_info.amount) } else { Err(TokenError::InvalidArgument) } } #[allow(dead_code)] pub fn only_owner(&self, key: &Pubkey) -> Result<()> { if *key != Pubkey::default() { if let TokenState::Account(account_info) = self { if account_info.owner == *key { return Ok(()); } } } // warn!("TokenState: non-owner rejected"); println!( "{}", Warn( format!("TokenState: non-owner rejected").to_string(), module_path!().to_string() ) ); Err(TokenError::NotOwner) } pub fn process_newtoken( info: &mut [KeyedAccount], token_info: TokenInfo, input_accounts: &[TokenState], output_accounts: &mut Vec<(usize, TokenState)>, ) -> Result<()> { if input_accounts.len() != 2 { // error!("{}", Error(format!("Expected 2 accounts").to_string())); println!( "{}", Error( format!("Expected 2 accounts").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if let TokenState::Account(dest_account) = &input_accounts[1] { if info[0].signer_key().unwrap() != &dest_account.token { // error!("{}", Error(format!("account 1 token mismatch").to_string())); println!( "{}", Error( format!("account 1 token mismatch").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if dest_account.delegate.is_some() { // error!("{}", Error(format!("account 1 is a delegate and cannot accept tokens").to_string())); println!( "{}", Error( format!("account 1 is a delegate and cannot accept tokens").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } let mut output_dest_account = dest_account.clone(); output_dest_account.amount = token_info.supply; output_accounts.push((1, TokenState::Account(output_dest_account))); } else { // error!("{}", Error(format!("account 1 invalid").to_string())); println!( "{}", Error( format!("account 1 invalid").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if input_accounts[0] != TokenState::Unallocated { // error!("{}", Error(format!("account 0 not available").to_string())); println!( "{}", Error( format!("account 0 not available").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } output_accounts.push((0, TokenState::Token(token_info))); Ok(()) } pub fn process_newaccount( info: &mut [KeyedAccount], input_accounts: &[TokenState], output_accounts: &mut Vec<(usize, TokenState)>, ) -> Result<()> { // key 0 - Destination new token account // key 1 - Owner of the account // key 2 - Token this account is associated with // key 3 - Source account that this account is a delegate for (optional) if input_accounts.len() < 3 { // error!("{}", Error(format!("Expected 3 accounts").to_string())); println!( "{}", Error( format!("Expected 3 accounts").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if input_accounts[0] != TokenState::Unallocated { // error!("{}", Error(format!("account 0 is already allocated").to_string())); println!( "{}", Error( format!("account 0 is already allocated").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } let mut token_account_info = TokenAccountInfo { token: *info[2].unsigned_key(), owner: *info[1].unsigned_key(), amount: 0, delegate: None, }; if input_accounts.len() >= 4 { token_account_info.delegate = Some(TokenAccountDelegateInfo { source: *info[3].unsigned_key(), original_amount: 0, }); } output_accounts.push((0, TokenState::Account(token_account_info))); Ok(()) } pub fn process_transfer( info: &mut [KeyedAccount], amount: u64, input_accounts: &[TokenState], output_accounts: &mut Vec<(usize, TokenState)>, ) -> Result<()> { if input_accounts.len() < 3 { // error!("{}", Error(format!("Expected 3 accounts").to_string())); println!( "{}", Error( format!("Expected 3 accounts").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if let (TokenState::Account(source_account), TokenState::Account(dest_account)) = (&input_accounts[1], &input_accounts[2]) { if source_account.token != dest_account.token { // error!("{}", Error(format!("account 1/2 token mismatch").to_string())); println!( "{}", Error( format!("account 1/2 token mismatch").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if dest_account.delegate.is_some() { // error!("{}", Error(format!("account 2 is a delegate and cannot accept tokens").to_string())); println!( "{}", Error( format!("account 2 is a delegate and cannot accept tokens").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if info[0].signer_key().unwrap() != &source_account.owner { // error!("{}", Error(format!("owner of account 1 not present").to_string())); println!( "{}", Error( format!("owner of account 1 not present").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if source_account.amount < amount { Err(TokenError::InsufficentFunds)?; } let mut output_source_account = source_account.clone(); output_source_account.amount -= amount; output_accounts.push((1, TokenState::Account(output_source_account))); if let Some(ref delegate_info) = source_account.delegate { if input_accounts.len() != 4 { // error!("{}", Error(format!("Expected 4 accounts").to_string())); println!( "{}", Error( format!("Expected 4 accounts").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } let delegate_account = source_account; if let TokenState::Account(source_account) = &input_accounts[3] { if source_account.token != delegate_account.token { // error!("{}", Error(format!("account 1/3 token mismatch").to_string())); println!( "{}", Error( format!("account 1/3 token mismatch").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if info[3].unsigned_key() != &delegate_info.source { // error!("{}", Error(format!("Account 1 is not a delegate of account 3").to_string())); println!( "{}", Error( format!("Account 1 is not a delegate of account 3").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if source_account.amount < amount { Err(TokenError::InsufficentFunds)?; } let mut output_source_account = source_account.clone(); output_source_account.amount -= amount; output_accounts.push((3, TokenState::Account(output_source_account))); } else { // error!("{}", Error(format!("account 3 is an invalid account").to_string())); println!( "{}", Error( format!("account 3 is an invalid account").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } } let mut output_dest_account = dest_account.clone(); output_dest_account.amount += amount; output_accounts.push((2, TokenState::Account(output_dest_account))); } else { // error!("{}", Error(format!("account 1 and/or 2 are invalid accounts").to_string())); println!( "{}", Error( format!("account 1 and/or 2 are invalid accounts").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } Ok(()) } pub fn process_approve( info: &mut [KeyedAccount], amount: u64, input_accounts: &[TokenState], output_accounts: &mut Vec<(usize, TokenState)>, ) -> Result<()> { if input_accounts.len() != 3 { // error!("{}", Error(format!("Expected 3 accounts").to_string())); println!( "{}", Error( format!("Expected 3 accounts").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if let (TokenState::Account(source_account), TokenState::Account(delegate_account)) = (&input_accounts[1], &input_accounts[2]) { if source_account.token != delegate_account.token { // error!("{}", Error(format!("account 1/2 token mismatch").to_string())); println!( "{}", Error( format!("account 1/2 token mismatch").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if info[0].signer_key().unwrap() != &source_account.owner { // error!("{}", Error(format!("owner of account 1 not present").to_string())); println!( "{}", Error( format!("owner of account 1 not present").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if source_account.delegate.is_some() { // error!("{}", Error(format!("account 1 is a delegate").to_string())); println!( "{}", Error( format!("account 1 is a delegate").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } match &delegate_account.delegate { None => { // error!("{}", Error(format!("account 2 is not a delegate").to_string())); println!( "{}", Error( format!("account 2 is not a delegate").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } Some(delegate_info) => { if info[1].unsigned_key() != &delegate_info.source { // error!("{}", Error(format!("account 2 is not a delegate of account 1").to_string())); println!( "{}", Error( format!("account 2 is not a delegate of account 1").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } let mut output_delegate_account = delegate_account.clone(); output_delegate_account.amount = amount; output_delegate_account.delegate = Some(TokenAccountDelegateInfo { source: delegate_info.source, original_amount: amount, }); output_accounts.push((2, TokenState::Account(output_delegate_account))); } } } else { // error!("{}", Error(format!("account 1 and/or 2 are invalid accounts").to_string())); println!( "{}", Error( format!("account 1 and/or 2 are invalid accounts").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } Ok(()) } pub fn process_setowner( info: &mut [KeyedAccount], input_accounts: &[TokenState], output_accounts: &mut Vec<(usize, TokenState)>, ) -> Result<()> { if input_accounts.len() < 3 { // error!("{}", Error(format!("Expected 3 accounts").to_string())); println!( "{}", Error( format!("Expected 3 accounts").to_string(), module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } if let TokenState::Account(source_account) = &input_accounts[1] { if info[0].signer_key().unwrap() != &source_account.owner { // info!("{}", Info(format!("owner of account 1 not present").to_string())); let info:String = format!("owner of account 1 not present").to_string(); println!("{}", printLn( info, module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } let mut output_source_account = source_account.clone(); output_source_account.owner = *info[2].unsigned_key(); output_accounts.push((1, TokenState::Account(output_source_account))); } else { // info!("{}", Info(format!("account 1 is invalid").to_string())); let info:String = format!("account 1 is invalid").to_string(); println!("{}", printLn( info, module_path!().to_string() ) ); Err(TokenError::InvalidArgument)?; } Ok(()) } pub fn process(program_id: &Pubkey, info: &mut [KeyedAccount], input: &[u8]) -> Result<()> { let command = bincode::deserialize::<TokenInstruction>(input).map_err(Self::map_to_invalid_args)?; // info!("{}", Info(format!("process_transaction: command={:?}", command).to_string())); let loginfo:String = format!("process_transaction: command={:?}", command).to_string(); println!("{}", printLn( loginfo, module_path!().to_string() ) ); if info[0].signer_key().is_none() { Err(TokenError::InvalidArgument)?; } let input_accounts: Vec<TokenState> = info .iter() .map(|keyed_account| { let account = &keyed_account.account; if account.owner == *program_id { match Self::deserialize(&account.data) { Ok(token_state) => token_state, Err(err) => { // error!("{}", Error(format!("deserialize failed: {:?}", err).to_string())); println!( "{}", Error( format!("deserialize failed: {:?}", err).to_string(), module_path!().to_string() ) ); TokenState::Invalid } } } else { TokenState::Invalid } }) .collect(); for account in &input_accounts { // info!("{}", Info(format!("input_account: data={:?}", account).to_string())); let loginfo:String = format!("input_account: data={:?}", account).to_string(); println!("{}", printLn( loginfo, module_path!().to_string() ) ); } let mut output_accounts: Vec<(_, _)> = vec![]; match command { TokenInstruction::NewToken(token_info) => { Self::process_newtoken(info, token_info, &input_accounts, &mut output_accounts)? } TokenInstruction::NewTokenAccount => { Self::process_newaccount(info, &input_accounts, &mut output_accounts)? } TokenInstruction::Transfer(amount) => { Self::process_transfer(info, amount, &input_accounts, &mut output_accounts)? } TokenInstruction::Approve(amount) => { Self::process_approve(info, amount, &input_accounts, &mut output_accounts)? } TokenInstruction::SetOwner => { Self::process_setowner(info, &input_accounts, &mut output_accounts)? } } for (index, account) in &output_accounts { // info!("{}", Info(format!("output_account: index={} data={:?}", index, account).to_string())); let loginfo:String = format!("output_account: index={} data={:?}", index, account).to_string(); println!("{}", printLn( loginfo, module_path!().to_string() ) ); Self::serialize(account, &mut info[*index].account.data)?; } Ok(()) } } #[cfg(test)] mod test { use super::*; #[test] pub fn serde() { assert_eq!(TokenState::deserialize(&[0]), Ok(TokenState::default())); let mut data = vec![0; 256]; let account = TokenState::Account(TokenAccountInfo { token: Pubkey::new(&[1; 32]), owner: Pubkey::new(&[2; 32]), amount: 123, delegate: None, }); account.serialize(&mut data).unwrap(); assert_eq!(TokenState::deserialize(&data), Ok(account)); let account = TokenState::Token(TokenInfo { supply: 12345, decimals: 2, name: "A test token".to_string(), symbol: "TEST".to_string(), }); account.serialize(&mut data).unwrap(); assert_eq!(TokenState::deserialize(&data), Ok(account)); } #[test] pub fn serde_expect_fail() { let mut data = vec![0; 256]; // Certain TokenState's may not be serialized let account = TokenState::default(); assert_eq!(account, TokenState::Unallocated); assert!(account.serialize(&mut data).is_err()); assert!(account.serialize(&mut data).is_err()); let account = TokenState::Invalid; assert!(account.serialize(&mut data).is_err()); // Bad deserialize data assert!(TokenState::deserialize(&[]).is_err()); assert!(TokenState::deserialize(&[1]).is_err()); assert!(TokenState::deserialize(&[1, 2]).is_err()); assert!(TokenState::deserialize(&[2, 2]).is_err()); assert!(TokenState::deserialize(&[3]).is_err()); } // Note: business logic tests are located in the @morgan/web3.js test suite }
const EXAMPLE: &str = include_str!(r"../../resources/day13-example.txt"); const INPUT: &str = include_str!(r"../../resources/day13-input.txt"); fn part1(_input: &str) -> u64 { 0 } fn part2(_input: &str) -> u64 { 0 } fn main() { rustaoc2022::run_matrix(part1, part2, EXAMPLE, INPUT); } #[cfg(test)] mod test { use crate::{part1, part2, EXAMPLE, INPUT}; #[test] #[ignore] fn test_example() { assert_eq!(31, part1(EXAMPLE)); assert_eq!(29, part2(EXAMPLE)); } #[test] #[ignore] fn test_input() { assert_eq!(456, part1(INPUT)); assert_eq!(454, part2(INPUT)); } }
use neon::prelude::*; use neon::register_module; use num_cpus; fn thread_count(mut cx: FunctionContext) -> JsResult<JsNumber> { Ok(cx.number(num_cpus::get() as f64)) } fn thread_count_cb(mut cx: FunctionContext) -> JsResult<JsUndefined> { let prefix = cx.argument::<JsString>(0)?.value(); let f = cx.argument::<JsFunction>(1)?; // function(result) {console.log(result);} let result = format!("{}:{}", prefix, num_cpus::get()); let args = vec![cx.string(result)]; let null = cx.null(); f.call(&mut cx, null, args)? .downcast::<JsUndefined>() .or_throw(&mut cx) } register_module!(mut m, { m.export_function("threadCount", thread_count)?; m.export_function("threadCountCb", thread_count_cb)?; Ok(()) });
use std::collections::BTreeSet; pub type NumType = u32; #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Range { min: NumType, max: NumType } impl Range { pub fn new(min: NumType, max: NumType) -> Range { Range { min: min, max: max } } } pub struct RangeSet { available_ranges: BTreeSet<Range> } impl RangeSet { pub fn new(initial_range: Range) -> RangeSet { let mut rs = RangeSet { available_ranges: BTreeSet::new() }; rs.available_ranges.insert(initial_range); rs } pub fn take_any_one(&mut self) -> Option<NumType> { if let Some(range) = self.next_range() { self.available_ranges.remove(&range); if range.min == range.max { Some(range.min) } else { self.available_ranges.insert(Range::new(1 + range.min, range.max)); Some(range.min) } } else { None } } fn next_range(&self) -> Option<Range> { if let Some(&range) = self.available_ranges.iter().next() { Some(range) } else { None } } pub fn release_one(&mut self, _: NumType) { // TODO(nicholasbishop): implement this } }
pub use VkSurfaceTransformFlagsKHR::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkSurfaceTransformFlagsKHR { VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR = 0x00000001, VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR = 0x00000002, VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR = 0x00000004, VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR = 0x00000008, VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR = 0x00000010, VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR = 0x00000020, VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR = 0x00000040, VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR = 0x00000080, VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR = 0x00000100, } use crate::SetupVkFlags; #[repr(C)] #[derive(Clone, Copy, Eq, PartialEq, Hash)] pub struct VkSurfaceTransformFlagBitsKHR(u32); SetupVkFlags!(VkSurfaceTransformFlagsKHR, VkSurfaceTransformFlagBitsKHR); impl Default for VkSurfaceTransformFlagBitsKHR { fn default() -> Self { VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR.into() } }
table! { clients (id) { id -> Nullable<Int4>, email -> Varchar, first_name -> Nullable<Varchar>, last_name -> Nullable<Varchar>, } } table! { users (id) { id -> Nullable<Int4>, email -> Varchar, first_name -> Nullable<Varchar>, last_name -> Nullable<Varchar>, } } allow_tables_to_appear_in_same_query!( clients, users, );
use std::collections::VecDeque; use std::convert::TryFrom; use std::io; use crate::error::Error; /// Used to read input for the program. /// /// Mainly used to allow easier testing. pub trait ProgInput { fn read(&mut self) -> Result<String, Error>; } /// Used to write output from the program. /// /// Mainly used to allow easier testing. pub trait ProgOutput { fn write(&mut self, output: &str) -> Result<(), Error>; } impl ProgInput for VecDeque<String> { fn read(&mut self) -> Result<String, Error> { if let Some(value) = self.pop_front() { Ok(value) } else { Err(Error::NoAvailableInput) } } } impl ProgOutput for VecDeque<String> { fn write(&mut self, output: &str) -> Result<(), Error> { self.push_back(output.to_string()); Ok(()) } } /// Reads in program input from stdin. #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] pub struct StdInProgInput {} impl StdInProgInput { pub fn new() -> Self { StdInProgInput {} } } impl ProgInput for StdInProgInput { fn read(&mut self) -> Result<String, Error> { let mut input = String::new(); let _ = io::stdin().read_line(&mut input)?; Ok(input) } } /// Writes program output to stdout. #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] pub struct StdOutProgOutput {} impl StdOutProgOutput { pub fn new() -> Self { StdOutProgOutput {} } } impl ProgOutput for StdOutProgOutput { fn write(&mut self, output: &str) -> Result<(), Error> { println!("{}", output); Ok(()) } } /// Parse a string into memory state. pub fn parse_mem_state(input: &str) -> Result<Vec<i64>, std::num::ParseIntError> { input .split(',') .map(|s| s.trim().parse::<i64>()) .collect::<Result<Vec<i64>, std::num::ParseIntError>>() } #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] enum ParamMode { Position, Immediate, Relative, } /// The operation as well as the parameter modes for operands. #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] enum OpCode { Add, Mul, Input, Output, JumpIfTrue, JumpIfFalse, LessThan, Equals, AdjustsRelativeBase, Halt, } fn param_mode(param: u32, op: i64) -> ParamMode { match (op % 10i64.pow(param + 3)) / 10i64.pow(param + 2) { 0 => ParamMode::Position, 1 => ParamMode::Immediate, 2 => ParamMode::Relative, _ => panic!("unexpected parameter mode"), } } fn decode_op_code(op: i64) -> OpCode { let op_code = op % 100; match op_code { 1 => OpCode::Add, 2 => OpCode::Mul, 3 => OpCode::Input, 4 => OpCode::Output, 5 => OpCode::JumpIfTrue, 6 => OpCode::JumpIfFalse, 7 => OpCode::LessThan, 8 => OpCode::Equals, 9 => OpCode::AdjustsRelativeBase, 99 => OpCode::Halt, _ => panic!("unexpected op"), } } #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] pub enum ProgState { NotStarted, Halt, NeedInput, } #[derive(Clone, Debug, Hash, Eq, PartialEq)] pub struct Prog { mem_state: Vec<i64>, pc: usize, relative_base: isize, state: ProgState, } impl Prog { pub fn new(init_mem_state: &[i64]) -> Self { let mut mem_state = vec![0; init_mem_state.len()]; mem_state.copy_from_slice(init_mem_state); Prog { mem_state, pc: 0, relative_base: 0, state: ProgState::NotStarted, } } pub fn state(&self) -> ProgState { self.state } } impl Prog { fn get_operand(&mut self, param_num: usize, op_code: i64) -> Result<i64, Error> { match param_mode(u32::try_from(param_num)?, op_code) { ParamMode::Position => { let index = usize::try_from(self.mem_state[self.pc + (param_num + 1)])?; if index >= self.mem_state.len() { self.mem_state.resize(index + 1, 0); } Ok(self.mem_state[index]) } ParamMode::Immediate => Ok(self.mem_state[self.pc + (param_num + 1)]), ParamMode::Relative => { let index = usize::try_from( isize::try_from(self.mem_state[self.pc + (param_num + 1)])? + self.relative_base, )?; if index >= self.mem_state.len() { self.mem_state.resize(index + 1, 0); } Ok(self.mem_state[index]) } } } fn store_value(&mut self, value: i64, param_num: usize, op_code: i64) -> Result<(), Error> { match param_mode(u32::try_from(param_num)?, op_code) { ParamMode::Position => { let index = usize::try_from(self.mem_state[self.pc + (param_num + 1)])?; if index >= self.mem_state.len() { self.mem_state.resize(index + 1, 0); } self.mem_state[index] = value; Ok(()) } ParamMode::Immediate => unreachable!(), ParamMode::Relative => { let index = usize::try_from( isize::try_from(self.mem_state[self.pc + (param_num + 1)])? + self.relative_base, )?; if index >= self.mem_state.len() { self.mem_state.resize(index + 1, 0); } self.mem_state[index] = value; Ok(()) } } } /// Runs a program given an initial memory state. pub fn run<T, S>(&mut self, input: &mut T, output: &mut S) -> Result<(), Error> where T: ProgInput, S: ProgOutput, { loop { let op_code = self.mem_state[self.pc]; match decode_op_code(op_code) { OpCode::Add => { let operand_0 = self.get_operand(0, op_code)?; let operand_1 = self.get_operand(1, op_code)?; self.store_value(operand_0 + operand_1, 2, op_code)?; self.pc += 4; } OpCode::Mul => { let operand_0 = self.get_operand(0, op_code)?; let operand_1 = self.get_operand(1, op_code)?; self.store_value(operand_0 * operand_1, 2, op_code)?; self.pc += 4; } OpCode::Input => { let input = match input.read() { Ok(v) => v, Err(Error::NoAvailableInput) => { self.state = ProgState::NeedInput; return Ok(()); } Err(e) => return Err(e), }; let input = input.trim().parse::<i64>()?; self.store_value(input, 0, op_code)?; self.pc += 2; } OpCode::Output => { let operand_0 = self.get_operand(0, op_code)?; output.write(&format!("{}", operand_0))?; self.pc += 2; } OpCode::JumpIfTrue => { let operand_0 = self.get_operand(0, op_code)?; if operand_0 != 0 { let operand_1 = self.get_operand(1, op_code)?; self.pc = usize::try_from(operand_1)?; } else { self.pc += 3; } } OpCode::JumpIfFalse => { let operand_0 = self.get_operand(0, op_code)?; if operand_0 == 0 { let operand_1 = self.get_operand(1, op_code)?; self.pc = usize::try_from(operand_1)?; } else { self.pc += 3; } } OpCode::LessThan => { let operand_0 = self.get_operand(0, op_code)?; let operand_1 = self.get_operand(1, op_code)?; self.store_value(if operand_0 < operand_1 { 1 } else { 0 }, 2, op_code)?; self.pc += 4; } OpCode::Equals => { let operand_0 = self.get_operand(0, op_code)?; let operand_1 = self.get_operand(1, op_code)?; self.store_value(if operand_0 == operand_1 { 1 } else { 0 }, 2, op_code)?; self.pc += 4; } OpCode::AdjustsRelativeBase => { let operand_0 = self.get_operand(0, op_code)?; self.relative_base = isize::try_from(i64::try_from(self.relative_base)? + operand_0)?; self.pc += 2; } OpCode::Halt => { self.state = ProgState::Halt; return Ok(()); } } } } } #[cfg(test)] mod tests { use super::*; use crate::tests::*; #[test] fn param_mode_0() { assert_eq!(param_mode(0, 101), ParamMode::Immediate); assert_eq!(param_mode(0, 1), ParamMode::Position); assert_eq!(param_mode(0, 201), ParamMode::Relative); } #[test] fn param_mode_1() { assert_eq!(param_mode(1, 1101), ParamMode::Immediate); assert_eq!(param_mode(1, 1001), ParamMode::Immediate); assert_eq!(param_mode(1, 101), ParamMode::Position); assert_eq!(param_mode(1, 1), ParamMode::Position); assert_eq!(param_mode(1, 2101), ParamMode::Relative); assert_eq!(param_mode(1, 2001), ParamMode::Relative); } #[test] fn param_mode_2() { assert_eq!(param_mode(2, 1101), ParamMode::Position); assert_eq!(param_mode(2, 1001), ParamMode::Position); assert_eq!(param_mode(2, 101), ParamMode::Position); assert_eq!(param_mode(2, 1), ParamMode::Position); assert_eq!(param_mode(2, 20001), ParamMode::Relative); assert_eq!(param_mode(2, 21001), ParamMode::Relative); assert_eq!(param_mode(2, 22001), ParamMode::Relative); } fn run_prog_no_input_or_output(mem_state: &[i64]) -> Prog { let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run(&mut TestInput::new(vec![]), &mut test_output) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert!(test_output.output.is_empty()); prog } #[test] fn day2_ex1() { let mem_state = vec![1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]; let prog = run_prog_no_input_or_output(&mem_state); assert_eq!( vec![3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50], prog.mem_state ); } #[test] fn day2_ex2() { let mem_state = vec![1, 0, 0, 0, 99]; let prog = run_prog_no_input_or_output(&mem_state); assert_eq!(vec![2, 0, 0, 0, 99], prog.mem_state); } #[test] fn day2_ex3() { let mem_state = vec![2, 3, 0, 3, 99]; let prog = run_prog_no_input_or_output(&mem_state); assert_eq!(vec![2, 3, 0, 6, 99], prog.mem_state); } #[test] fn day2_ex4() { let mem_state = vec![2, 4, 4, 5, 99, 0]; let prog = run_prog_no_input_or_output(&mem_state); assert_eq!(vec![2, 4, 4, 5, 99, 9801], prog.mem_state); } #[test] fn day2_ex5() { let mem_state = vec![1, 1, 1, 4, 99, 5, 6, 0, 99]; let prog = run_prog_no_input_or_output(&mem_state); assert_eq!(vec![30, 1, 1, 4, 2, 5, 6, 0, 99], prog.mem_state); } #[test] fn day5_ex1() { let mem_state = vec![3, 0, 4, 0, 99]; let mut test_output = TestOutput::new(); let x = String::from("42"); let mut prog = Prog::new(&mem_state); prog.run(&mut TestInput::new(vec![x.clone()]), &mut test_output) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec![x], test_output.output); assert_eq!(vec![42, 0, 4, 0, 99], prog.mem_state); } #[test] fn day5_ex2() { let mem_state = vec![1002, 4, 3, 4, 33]; let prog = run_prog_no_input_or_output(&mem_state); assert_eq!(vec![1002, 4, 3, 4, 99], prog.mem_state); } #[test] fn day5_ex3() { let mem_state = vec![3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("8")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["1"], test_output.output); assert_eq!(vec![3, 9, 8, 9, 10, 9, 4, 9, 99, 1, 8], prog.mem_state); } #[test] fn day5_ex5() { let mem_state = vec![3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("7")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["0"], test_output.output); assert_eq!(vec![3, 9, 8, 9, 10, 9, 4, 9, 99, 0, 8], prog.mem_state); } #[test] fn day5_ex6() { let mem_state = vec![3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("8")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["0"], test_output.output); assert_eq!(vec![3, 9, 7, 9, 10, 9, 4, 9, 99, 0, 8], prog.mem_state); } #[test] fn day5_ex7() { let mem_state = vec![3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("7")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["1"], test_output.output); assert_eq!(vec![3, 9, 7, 9, 10, 9, 4, 9, 99, 1, 8], prog.mem_state); } #[test] fn day5_ex8() { let mem_state = vec![3, 3, 1108, -1, 8, 3, 4, 3, 99]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("8")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["1"], test_output.output); assert_eq!(vec![3, 3, 1108, 1, 8, 3, 4, 3, 99], prog.mem_state); } #[test] fn day5_ex9() { let mem_state = vec![3, 3, 1108, -1, 8, 3, 4, 3, 99]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("7")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["0"], test_output.output); assert_eq!(vec![3, 3, 1108, 0, 8, 3, 4, 3, 99], prog.mem_state); } #[test] fn day5_ex10() { let mem_state = vec![3, 3, 1107, -1, 8, 3, 4, 3, 99]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("8")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["0"], test_output.output); assert_eq!(vec![3, 3, 1107, 0, 8, 3, 4, 3, 99], prog.mem_state); } #[test] fn day5_ex11() { let mem_state = vec![3, 3, 1107, -1, 8, 3, 4, 3, 99]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("7")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["1"], test_output.output); assert_eq!(vec![3, 3, 1107, 1, 8, 3, 4, 3, 99], prog.mem_state); } #[test] fn day5_ex12() { let mem_state = vec![3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("0")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["0"], test_output.output); assert_eq!( vec![3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, 0, 0, 1, 9], prog.mem_state ); } #[test] fn day5_ex13() { let mem_state = vec![3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("1")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["1"], test_output.output); assert_eq!( vec![3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, 1, 1, 1, 9], prog.mem_state ); } #[test] fn day5_ex14() { let mem_state = vec![3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("0")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["0"], test_output.output); assert_eq!( vec![3, 3, 1105, 0, 9, 1101, 0, 0, 12, 4, 12, 99, 0], prog.mem_state ); } #[test] fn day5_ex15() { let mem_state = vec![3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("1")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["1"], test_output.output); assert_eq!( vec![3, 3, 1105, 1, 9, 1101, 0, 0, 12, 4, 12, 99, 1], prog.mem_state ); } #[test] fn day5_ex16() { let mem_state = vec![ 3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99, ]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("7")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["999"], test_output.output); assert_eq!( vec![ 3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 7, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99 ], prog.mem_state ); } #[test] fn day5_ex17() { let mem_state = vec![ 3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99, ]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("8")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["1000"], test_output.output); assert_eq!( vec![ 3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 1000, 8, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99 ], prog.mem_state ); } #[test] fn day5_ex18() { let mem_state = vec![ 3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99, ]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run( &mut TestInput::new(vec![String::from("9")]), &mut test_output, ) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec!["1001"], test_output.output); assert_eq!( vec![ 3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 1001, 9, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99 ], prog.mem_state ); } #[test] fn day9_ex1() { let mem_state = vec![ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99, ]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run(&mut TestInput::new(vec![]), &mut test_output) .unwrap(); assert_eq!(ProgState::Halt, prog.state); let expected_output: Vec<String> = vec![ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99, ] .into_iter() .map(|i| i.to_string()) .collect(); assert_eq!(expected_output, test_output.output); } #[test] fn day9_ex2() { let mem_state = vec![1102, 34915192, 34915192, 7, 4, 7, 99, 0]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run(&mut TestInput::new(vec![]), &mut test_output) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec![1219_0706_3239_6864i64.to_string()], test_output.output); } #[test] fn day9_ex3() { let mem_state = vec![104, 1125899906842624, 99]; let mut test_output = TestOutput::new(); let mut prog = Prog::new(&mem_state); prog.run(&mut TestInput::new(vec![]), &mut test_output) .unwrap(); assert_eq!(ProgState::Halt, prog.state); assert_eq!(vec![1125899906842624i64.to_string()], test_output.output); } }
use ggez::graphics::Rect; use specs::World; pub fn add_camera_resource(world: &mut World, camera: Rect) { world.add_resource::<Camera>(Camera(camera)); } pub struct Camera(pub Rect);
use core::{Color, ColorComponent, FresnelIndex, RayIntersection, LightIntersection}; use defs::FloatType; use tools::CompareWithTolerance; #[derive(Debug, Copy, Clone)] struct FresnelData { pub n: FresnelIndex, pub n_inverse: FresnelIndex, pub n_avg: FloatType, pub n_imaginary: FresnelIndex, pub n_imaginary_inverse: FresnelIndex, pub n_imaginary_avg: FloatType, pub f0: FresnelIndex, pub f0_avg: FloatType, pub f0_inverse: FresnelIndex, pub f0_inverse_avg: FloatType } impl FresnelData { fn new(real: FresnelIndex, imaginary: FresnelIndex) -> Self { let mut f0 = ((real - FresnelIndex::one()) * (real - FresnelIndex::one())) + imaginary * imaginary; f0 *= (((real + FresnelIndex::one()) * (real + FresnelIndex::one())) + imaginary * imaginary).recip(); let mut f0_inverse = ((imaginary - FresnelIndex::one()) * (imaginary - FresnelIndex::one())) + imaginary * imaginary; f0_inverse *= (((imaginary + FresnelIndex::one()) * (imaginary + FresnelIndex::one())) + imaginary * imaginary).recip(); Self { n: real, n_inverse: real.recip(), n_avg: real.intensity_avg(), n_imaginary: imaginary, n_imaginary_inverse: imaginary.recip(), n_imaginary_avg: imaginary.intensity_avg(), f0: f0, f0_avg: f0.intensity_avg(), f0_inverse: f0_inverse, f0_inverse_avg: f0_inverse.intensity_avg() } } pub fn get_fresnel_reflect(&self, intersection: &RayIntersection) -> Option<Color> { let view_and_normal_angle_cosine = intersection.get_view_direction().dot(intersection.get_normal_vector()); if view_and_normal_angle_cosine.greater_eq_eps(&0.0) { let f = if !intersection.was_inside() { self.f0 } else { self.f0_inverse }; let f1 = (Color::one()-f) * Color::one().mul_scalar(&(1.0 - view_and_normal_angle_cosine).powi(5)); Some(f + f1) } else { None } } pub fn get_fresnel_refract(&self, intersection: &RayIntersection) -> Option<Color> { if let Some(color) = self.get_fresnel_reflect(intersection) { Some(Color::one() - color) } else { None } } } #[derive(Debug, Copy, Clone)] pub struct Material { ambient: Option<Color>, diffuse: Option<Color>, specular: Option<(Color, FloatType)>, fresnel: Option<FresnelData>, reflective: bool, refractive: bool, } impl Material { pub fn new_useless() -> Self { Self { ambient: None, diffuse: None, specular: None, fresnel: None, reflective: false, refractive: false } } pub fn new_diffuse(diffuse: Color, ambient: Option<Color>) -> Self { Self { diffuse: Some(diffuse), ambient: ambient, specular: None, fresnel: None, reflective: false, refractive: false} } pub fn new_shiny(diffuse: Color, specular: (Color, FloatType), ambient: Option<Color>) -> Self { Self { diffuse: Some(diffuse), ambient: ambient, specular: Some(specular), fresnel: None, reflective: false, refractive: false} } pub fn new_reflective(fresnel_real: FresnelIndex, fresnel_imagninary: FresnelIndex, diffuse: Option<Color>, specular: Option<(Color, FloatType)>, ambient: Option<Color>) -> Self { Self { diffuse: diffuse, ambient: ambient, specular: specular, fresnel: Some(FresnelData::new(fresnel_real, fresnel_imagninary)), reflective: true, refractive: false} } pub fn new_refractive(fresnel_real: FresnelIndex, fresnel_imagninary: FresnelIndex, diffuse: Option<Color>, specular: Option<(Color, FloatType)>, ambient: Option<Color>) -> Self { Self { diffuse: diffuse, ambient: ambient, specular: specular, fresnel: Some(FresnelData::new(fresnel_real, fresnel_imagninary)), reflective: false, refractive: true} } pub fn new_reflective_and_refractive(fresnel_real: FresnelIndex, fresnel_imagninary: FresnelIndex, diffuse: Option<Color>, specular: Option<(Color, FloatType)>, ambient: Option<Color>) -> Self { Self { diffuse: diffuse, ambient: ambient, specular: specular, fresnel: Some(FresnelData::new(fresnel_real, fresnel_imagninary)), reflective: true, refractive: true} } pub fn new_light_source(diffuse: Color, ambient: Option<Color>) -> Self { Self { diffuse: Some(diffuse), ambient: ambient, specular: None, fresnel: Some(FresnelData::new(FresnelIndex::one(), FresnelIndex::one())), reflective: false, refractive: true } } pub fn get_ambient_color(&self) -> Option<&Color> { self.ambient.as_ref() } pub fn get_diffuse_color(&self) -> Option<&Color> { self.diffuse.as_ref() } pub fn get_specular_color(&self) -> Option<&(Color, FloatType)> { self.specular.as_ref() } pub fn is_opaque(&self) -> bool { !self.refractive } pub fn is_transparent(&self) -> bool { !self.is_opaque() } pub fn is_reflective(&self) -> bool { self.reflective } pub fn is_refractive(&self) -> bool { self.refractive } pub fn get_transparency_to_light(&self) -> Option<Color> { if self.is_transparent() { match self.diffuse { None => Some(Color::one()), Some(color) => Some(color) } } else { None } } pub fn get_average_refractive_index(&self) -> Option<FloatType> { self.fresnel.and_then(|fresnel_data| { Some(fresnel_data.n_avg) }) } pub fn get_refractive_index_for_component(&self, component: ColorComponent) -> Option<FloatType> { self.fresnel.and_then(|fresnel_data| { Some(fresnel_data.n.get_component(component)) }) } fn get_fresnel_data(&self) -> Option<&FresnelData> { self.fresnel.as_ref() } pub fn get_diffuse_illumination(ray_intersection: &RayIntersection, light_intersection: &LightIntersection) -> Option<Color> { let material = ray_intersection.get_material(); material.get_diffuse_color().and_then(|color| { let surface_normal = ray_intersection.get_normal_vector(); let light_direction = light_intersection.get_light_direction(); let cosln = light_direction.dot(surface_normal).max(0.0); let illumination = light_intersection.get_illumination(); Some ((*color * *illumination).mul_scalar(&cosln)) }) } pub fn get_specular_illumination(ray_intersection: &RayIntersection, light_intersection: &LightIntersection) -> Option<Color> { let material = ray_intersection.get_material(); material.get_specular_color().and_then(|color_shiny| { let illumination = light_intersection.get_illumination(); let view_direction = ray_intersection.get_view_direction(); let surface_normal = ray_intersection.get_normal_vector(); let (color, shininess) = *color_shiny; let light_direction = light_intersection.get_light_direction(); let half_direction = (view_direction + light_direction).normalize(); let coshn = half_direction.dot(surface_normal).max(0.0).powf(shininess); Some((color * *illumination).mul_scalar(&coshn)) }) } pub fn get_fresnel_reflection(ray_intersection: &RayIntersection) -> Option<Color> { let material = ray_intersection.get_material(); material.get_fresnel_data().and_then(|fresnel_data| { fresnel_data.get_fresnel_reflect(ray_intersection) }) } pub fn get_fresnel_refraction(ray_intersection: &RayIntersection) -> Option<Color> { let material = ray_intersection.get_material(); material.get_fresnel_data().and_then(|fresnel_data| { fresnel_data.get_fresnel_refract(ray_intersection) }) } }
use std::fs::File; use std::io::BufReader; use std::io::Read; use std::collections::HashSet; use std::iter::FromIterator; fn main() { let file = File::open("input").expect("Failed to read file input"); let mut buf_reader = BufReader::new(file); let mut contents = String::new(); buf_reader.read_to_string(&mut contents) .expect("Failed to bufferize file input"); let lines = contents.lines(); let mut count : usize = 0; let mut reset : bool = true; let mut group = HashSet::new(); for line in lines { if line.is_empty() { count += group.len(); reset = true; } else { let h = HashSet::from_iter(line.chars()); if reset { group = h; reset = false; } else { group = HashSet::from_iter(group .intersection(&h).cloned()); } } } count += group.len(); println!("Count: {}", count); }
use criterion::{criterion_group, criterion_main, Criterion}; use day05::{part1, part2}; fn part1_benchmark(c: &mut Criterion) { let input = include_str!("../../input/2018/day5.txt").trim(); c.bench_function("part1", move |b| b.iter(|| part1(&input))); } fn part2_benchmark(c: &mut Criterion) { let input = include_str!("../../input/2018/day5.txt").trim(); c.bench_function("part2", move |b| b.iter(|| part2(&input))); } criterion_group!(benches, part1_benchmark, part2_benchmark); criterion_main!(benches);
fn main() { unreachable!(); }
extern crate winrt_notification; use winrt_notification::{ Duration, Sound, Toast, }; fn main() { Toast::new(Toast::POWERSHELL_APP_ID) .title("Look at this flip!") .text1("(╯°□°)╯︵ ┻━┻") .sound(Some(Sound::SMS)) .duration(Duration::Short) .show() .expect("unable to send notification"); }
mod board; mod ai; use ai::AI; pub use board::Board; mod humanplayer; mod pipeai; pub use pipeai::PipeAI; pub use humanplayer::HumanPlayer; use board::Player; use std::time::Instant; use std::collections::HashMap; /*#[derive(StructOpt)] struct Cli { #[structopt(parse(from_os_str))] o_ai_path: std::path::PathBuf, #[structopt(parse(from_os_str))] x_ai_path: std::path::PathBuf, }*/ fn main() { let ais: Vec<(String, Box<dyn Fn() -> Box<dyn AI>>)> = vec![ /*("javascript_10".to_string(), Box::new(move || Box::new( PipeAI::new("C:/Program Files/nodejs/node.exe".to_string(), vec!["uttt.js".to_string(), "10".to_string()]) )) ),*/ ("abriand_10".to_string(), Box::new(move || Box::new( PipeAI::new("C:/Users/atb88/Desktop/uttt-bot/target/release/uttt-bot.exe".to_string(), vec![]))) ), ("ggeng_10".to_string(), Box::new(move || Box::new( PipeAI::new("C:/ultimate-tictactoe/target/release/main.exe".to_string(), vec!["10".to_string()]))) ), ]; let mut games: HashMap<(String, String), Player> = HashMap::new(); let mut scores: Vec<f32> = vec![0.0; ais.len()]; for _i in 0..1 { for x_idx in 0..ais.len() { for o_idx in 0..ais.len() { if x_idx != o_idx { let (o_name, o_ctor) = &ais[o_idx]; let (x_name, x_ctor) = &ais[x_idx]; match play_game(&mut *x_ctor(), &mut *o_ctor()) { Player::X => { scores[x_idx] += 1.0; games.insert((x_name.clone(), o_name.clone() + " " + &_i.to_string()), Player::X); }, Player::O => { scores[o_idx] += 1.0; games.insert((x_name.clone(), o_name.clone() + " " + &_i.to_string()), Player::O); }, Player::DEAD => { scores[x_idx] += 0.5; scores[o_idx] += 0.5; games.insert((x_name.clone(), o_name.clone() + " " + &_i.to_string()), Player::DEAD); }, Player::NEITHER => panic!("NEITHER won"), }; } } } } for g in games { println!("{} vs {}: {:?}", (g.0).0, (g.0).1, g.1); } println!(""); for s_idx in 0..scores.len() { println!("{}: {}", ais[s_idx].0, scores[s_idx]); } } fn play_game(x_ai: &mut dyn AI, o_ai: &mut dyn AI) -> Player { let mut times_vec = Vec::new(); let mut now = Instant::now(); let mut last_move = x_ai.get_move(-1); times_vec.push(now.elapsed().as_millis()); let mut board = Board::new(2); loop { if last_move == -1 { println!("X forfeited"); board.winner = Player::O; break; } if !board.make_move(last_move as usize) { println!("X made an illegal move {}", last_move); board.winner = Player::O; break; } board.pretty_print(); println!(""); if board.winner != Player::NEITHER { break; } last_move = o_ai.get_move(last_move); if last_move == -1 { println!("O forfeited"); board.winner = Player::X; break; } if !board.make_move(last_move as usize) { println!("O made an illegal move {}", last_move); board.winner = Player::X; break; } board.pretty_print(); println!(""); if board.winner != Player::NEITHER { break; } now = Instant::now(); last_move = x_ai.get_move(last_move); times_vec.push(now.elapsed().as_millis()); } board.pretty_print(); println!("{:?}", board.move_history); println!("{:?}", times_vec); x_ai.cleanup(); o_ai.cleanup(); println!("{:?} wins", board.winner); return board.winner; }
use iron::prelude::*; use iron::status; use iron::typemap::Key; use persistent::Read; use std::sync::Arc; use crate::store::StatsStore; #[cfg(not(debug_assertions))] const DASHBOARD_SOURCE: &str = include_str!("../web/src/index.html"); #[cfg(not(debug_assertions))] const DASHBOARD_JS_SOURCE: &str = include_str!("../web/dist/index.js"); #[derive(Copy, Clone)] pub struct Stats; impl Key for Stats { type Value = Arc<StatsStore>; } pub fn total_msg_count(req: &mut Request) -> IronResult<Response> { let stats = req.get::<Read<Stats>>().unwrap(); Ok(match stats.get_msg_count() { Ok(count) => Response::with((status::Ok, count.to_string())), Err(_) => { eprintln!("Error getting message count"); Response::with((status::NoContent, "0".to_owned())) } }) } pub fn msg_count(req: &mut Request) -> IronResult<Response> { let stats = req.get::<Read<Stats>>().unwrap(); Ok(match stats.get_user_msg_count() { Ok(count) => Response::with((status::Ok, count.to_string())), Err(_) => { eprintln!("Error getting message count"); Response::with((status::NoContent, "0".to_owned())) } }) } pub fn edit_count(req: &mut Request) -> IronResult<Response> { let stats = req.get::<Read<Stats>>().unwrap(); Ok(match stats.get_edit_count() { Ok(count) => Response::with((status::Ok, count.to_string())), Err(e) => { eprintln!("Error getting message count: {:?}", e); Response::with((status::NoContent, "0".to_owned())) } }) } pub fn msg_count_per_day(req: &mut Request) -> IronResult<Response> { let stats = req.get::<Read<Stats>>().unwrap(); Ok(match stats.get_user_msgs_per_day() { Ok(count) => Response::with((status::Ok, serde_json::to_string(&count).unwrap())), Err(e) => { eprintln!("Error getting message count: {:#?}", e); Response::with((status::InternalServerError, "0".to_owned())) } }) } pub fn total_msg_count_per_day(req: &mut Request) -> IronResult<Response> { let stats = req.get::<Read<Stats>>().unwrap(); Ok(match stats.get_total_msgs_per_day() { Ok(count) => Response::with((status::Ok, serde_json::to_string(&count).unwrap())), Err(_) => { eprintln!("Error getting message count"); Response::with((status::InternalServerError, "0".to_owned())) } }) } pub fn get_channels(req: &mut Request) -> IronResult<Response> { let stats = req.get::<Read<Stats>>().unwrap(); Ok(match stats.get_channels() { Ok(ref channels) => Response::with((status::Ok, serde_json::to_string(channels).unwrap())), Err(_) => { eprintln!("Error getting channels"); Response::with((status::InternalServerError, "[]")) } }) } pub fn get_guilds(req: &mut Request) -> IronResult<Response> { let stats = req.get::<Read<Stats>>().unwrap(); Ok(match stats.get_guilds() { Ok(ref guilds) => Response::with((status::Ok, serde_json::to_string(guilds).unwrap())), Err(_) => { eprintln!("Error getting guilds"); Response::with((status::InternalServerError, "[]")) } }) } #[cfg(not(debug_assertions))] pub fn dashboard(_rq: &mut Request) -> IronResult<Response> { let mut resp = Response::with((status::Ok, DASHBOARD_SOURCE)); resp.headers.set(iron::headers::ContentType::html()); Ok(resp) } #[cfg(not(debug_assertions))] pub fn dashboard_js(_rq: &mut Request) -> IronResult<Response> { Ok(Response::with((status::Ok, DASHBOARD_JS_SOURCE))) } #[cfg(debug_assertions)] pub fn dashboard(_rq: &mut Request) -> IronResult<Response> { let mut resp = Response::with(( status::Ok, std::fs::read_to_string("web/dist/index.html").unwrap(), )); resp.headers.set(iron::headers::ContentType::html()); Ok(resp) } #[cfg(debug_assertions)] pub fn dashboard_js(_rq: &mut Request) -> IronResult<Response> { let mut resp = Response::with((status::MovedPermanently, "")); resp.headers.set(iron::headers::Location( "http://localhost:1234/index.js".into(), )); Ok(resp) }
pub mod dto; pub mod image_controller; pub mod status_controller;
/// Devices pub mod device; /// Global descriptor table pub mod gdt; // /// Interrupt descriptor table // pub mod idt; // /// Interrupt instructions // pub mod interrupt; // /// Paging // pub mod paging; // /// Initialization and start function // pub mod start; // /// Stop function // pub mod stop;
//! Display attributes /// Display rotation. /// /// Note that 90º and 270º rotations are not supported by // [`TerminalMode`](../mode/terminal/struct.TerminalMode.html). #[derive(Clone, Copy)] pub enum DisplayRotation { /// No rotation, normal display Rotate0, /// Rotate by 90 degress clockwise Rotate90, /// Rotate by 180 degress clockwise Rotate180, /// Rotate 270 degress clockwise Rotate270, } /// Display size enumeration #[derive(Clone, Copy)] pub enum DisplaySize { /// 128 by 128 pixels Display128x128, /// 128 by 96 pixels Display128x96, } impl DisplaySize { /// Get integral dimensions from DisplaySize // TODO: Use whatever vec2 impl I decide to use here pub fn dimensions(&self) -> (u8, u8) { match *self { DisplaySize::Display128x128 => (128, 128), DisplaySize::Display128x96 => (128, 96), } } }
use fuzzcheck::DefaultMutator; #[derive(Clone, DefaultMutator)] pub struct X(bool); #[derive(Clone, DefaultMutator)] pub struct Y { x: bool, } #[cfg(test)] mod test { use fuzzcheck::Mutator; use super::*; #[test] #[no_coverage] fn test_compile() { let _m = X::default_mutator(); let m = Y::default_mutator(); let (_y, _) = m.random_arbitrary(10.0); // assert!(false, "{}", y.x); } }
use std::error::Error; use std::thread; use std::time::Duration; use rainbow_hat_rs::lights::Lights; use rainbow_hat_rs::touch::Buttons; fn main() -> Result<(), Box<dyn Error>> { let mut lights = Lights::new()?; let mut buttons = Buttons::new()?; // Turn on the light when a touch is pressed. loop { thread::sleep(Duration::from_millis(50)); if buttons.a.is_pressed() { println!("Button A touched!"); lights.rgb(true, false, false); } else if buttons.b.is_pressed() { println!("Button B touched!"); lights.rgb(false, true, false); } else if buttons.c.is_pressed(){ println!("Button C touched!"); lights.rgb(false, false, true); } else { println!("Button release!"); lights.rgb(false, false, false); } } }
//! Server-side synchronous Postgres connection, as limited as we need. //! To use, create PostgresBackend and run() it, passing the Handler //! implementation determining how to process the queries. Currently its API //! is rather narrow, but we can extend it once required. use crate::pq_proto::{BeMessage, FeMessage, FeStartupMessage, StartupRequestCode}; use crate::sock_split::{BidiStream, ReadStream, WriteStream}; use anyhow::{anyhow, bail, ensure, Result}; use bytes::{Bytes, BytesMut}; use log::*; use rand::Rng; use serde::{Deserialize, Serialize}; use std::io::{self, Write}; use std::net::{Shutdown, SocketAddr, TcpStream}; use std::str::FromStr; use std::sync::Arc; pub trait Handler { /// Handle single query. /// postgres_backend will issue ReadyForQuery after calling this (this /// might be not what we want after CopyData streaming, but currently we don't /// care). fn process_query(&mut self, pgb: &mut PostgresBackend, query_string: Bytes) -> Result<()>; /// Called on startup packet receival, allows to process params. /// /// If Ok(false) is returned postgres_backend will skip auth -- that is needed for new users /// creation is the proxy code. That is quite hacky and ad-hoc solution, may be we could allow /// to override whole init logic in implementations. fn startup(&mut self, _pgb: &mut PostgresBackend, _sm: &FeStartupMessage) -> Result<()> { Ok(()) } /// Check auth md5 fn check_auth_md5(&mut self, _pgb: &mut PostgresBackend, _md5_response: &[u8]) -> Result<()> { bail!("MD5 auth failed") } /// Check auth jwt fn check_auth_jwt(&mut self, _pgb: &mut PostgresBackend, _jwt_response: &[u8]) -> Result<()> { bail!("JWT auth failed") } } /// PostgresBackend protocol state. /// XXX: The order of the constructors matters. #[derive(Clone, Copy, PartialEq, PartialOrd)] pub enum ProtoState { Initialization, Encrypted, Authentication, Established, } #[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)] pub enum AuthType { Trust, MD5, // This mimics postgres's AuthenticationCleartextPassword but instead of password expects JWT ZenithJWT, } impl FromStr for AuthType { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "Trust" => Ok(Self::Trust), "MD5" => Ok(Self::MD5), "ZenithJWT" => Ok(Self::ZenithJWT), _ => bail!("invalid value \"{}\" for auth type", s), } } } #[derive(Clone, Copy)] pub enum ProcessMsgResult { Continue, Break, } /// Always-writeable sock_split stream. /// May not be readable. See [`PostgresBackend::take_stream_in`] pub enum Stream { Bidirectional(BidiStream), WriteOnly(WriteStream), } impl Stream { fn shutdown(&mut self, how: Shutdown) -> io::Result<()> { match self { Self::Bidirectional(bidi_stream) => bidi_stream.shutdown(how), Self::WriteOnly(write_stream) => write_stream.shutdown(how), } } } impl io::Write for Stream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { match self { Self::Bidirectional(bidi_stream) => bidi_stream.write(buf), Self::WriteOnly(write_stream) => write_stream.write(buf), } } fn flush(&mut self) -> io::Result<()> { match self { Self::Bidirectional(bidi_stream) => bidi_stream.flush(), Self::WriteOnly(write_stream) => write_stream.flush(), } } } pub struct PostgresBackend { stream: Option<Stream>, // Output buffer. c.f. BeMessage::write why we are using BytesMut here. buf_out: BytesMut, pub state: ProtoState, md5_salt: [u8; 4], auth_type: AuthType, peer_addr: SocketAddr, pub tls_config: Option<Arc<rustls::ServerConfig>>, } pub fn query_from_cstring(query_string: Bytes) -> Vec<u8> { let mut query_string = query_string.to_vec(); if let Some(ch) = query_string.last() { if *ch == 0 { query_string.pop(); } } query_string } impl PostgresBackend { pub fn new( socket: TcpStream, auth_type: AuthType, tls_config: Option<Arc<rustls::ServerConfig>>, ) -> io::Result<Self> { let peer_addr = socket.peer_addr()?; Ok(Self { stream: Some(Stream::Bidirectional(BidiStream::from_tcp(socket))), buf_out: BytesMut::with_capacity(10 * 1024), state: ProtoState::Initialization, md5_salt: [0u8; 4], auth_type, tls_config, peer_addr, }) } pub fn into_stream(self) -> Stream { self.stream.unwrap() } /// Get direct reference (into the Option) to the read stream. fn get_stream_in(&mut self) -> Result<&mut BidiStream> { match &mut self.stream { Some(Stream::Bidirectional(stream)) => Ok(stream), _ => Err(anyhow!("reader taken")), } } pub fn get_peer_addr(&self) -> &SocketAddr { &self.peer_addr } pub fn take_stream_in(&mut self) -> Option<ReadStream> { let stream = self.stream.take(); match stream { Some(Stream::Bidirectional(bidi_stream)) => { let (read, write) = bidi_stream.split(); self.stream = Some(Stream::WriteOnly(write)); Some(read) } stream => { self.stream = stream; None } } } /// Read full message or return None if connection is closed. pub fn read_message(&mut self) -> Result<Option<FeMessage>> { let (state, stream) = (self.state, self.get_stream_in()?); use ProtoState::*; match state { Initialization | Encrypted => FeStartupMessage::read(stream), Authentication | Established => FeMessage::read(stream), } } /// Write message into internal output buffer. pub fn write_message_noflush(&mut self, message: &BeMessage) -> io::Result<&mut Self> { BeMessage::write(&mut self.buf_out, message)?; Ok(self) } /// Flush output buffer into the socket. pub fn flush(&mut self) -> io::Result<&mut Self> { let stream = self.stream.as_mut().unwrap(); stream.write_all(&self.buf_out)?; self.buf_out.clear(); Ok(self) } /// Write message into internal buffer and flush it. pub fn write_message(&mut self, message: &BeMessage) -> io::Result<&mut Self> { self.write_message_noflush(message)?; self.flush() } // Wrapper for run_message_loop() that shuts down socket when we are done pub fn run(mut self, handler: &mut impl Handler) -> Result<()> { let ret = self.run_message_loop(handler); if let Some(stream) = self.stream.as_mut() { let _ = stream.shutdown(Shutdown::Both); } ret } fn run_message_loop(&mut self, handler: &mut impl Handler) -> Result<()> { trace!("postgres backend to {:?} started", self.peer_addr); let mut unnamed_query_string = Bytes::new(); while let Some(msg) = self.read_message()? { trace!("got message {:?}", msg); match self.process_message(handler, msg, &mut unnamed_query_string)? { ProcessMsgResult::Continue => continue, ProcessMsgResult::Break => break, } } trace!("postgres backend to {:?} exited", self.peer_addr); Ok(()) } pub fn start_tls(&mut self) -> anyhow::Result<()> { match self.stream.take() { Some(Stream::Bidirectional(bidi_stream)) => { let session = rustls::ServerSession::new(&self.tls_config.clone().unwrap()); self.stream = Some(Stream::Bidirectional(bidi_stream.start_tls(session)?)); Ok(()) } stream => { self.stream = stream; bail!("can't start TLs without bidi stream"); } } } fn process_message( &mut self, handler: &mut impl Handler, msg: FeMessage, unnamed_query_string: &mut Bytes, ) -> Result<ProcessMsgResult> { // Allow only startup and password messages during auth. Otherwise client would be able to bypass auth // TODO: change that to proper top-level match of protocol state with separate message handling for each state if self.state < ProtoState::Established { ensure!( matches!( msg, FeMessage::PasswordMessage(_) | FeMessage::StartupMessage(_) ), "protocol violation" ); } match msg { FeMessage::StartupMessage(m) => { trace!("got startup message {:?}", m); match m.kind { StartupRequestCode::NegotiateSsl => { info!("SSL requested"); if self.tls_config.is_some() { self.write_message(&BeMessage::EncryptionResponse(true))?; self.start_tls()?; self.state = ProtoState::Encrypted; } else { self.write_message(&BeMessage::EncryptionResponse(false))?; } } StartupRequestCode::NegotiateGss => { info!("GSS requested"); self.write_message(&BeMessage::EncryptionResponse(false))?; } StartupRequestCode::Normal => { if self.tls_config.is_some() && !matches!(self.state, ProtoState::Encrypted) { self.write_message(&BeMessage::ErrorResponse( "must connect with TLS".to_string(), ))?; bail!("client did not connect with TLS"); } // NB: startup() may change self.auth_type -- we are using that in proxy code // to bypass auth for new users. handler.startup(self, &m)?; match self.auth_type { AuthType::Trust => { self.write_message_noflush(&BeMessage::AuthenticationOk)?; // psycopg2 will not connect if client_encoding is not // specified by the server self.write_message_noflush(&BeMessage::ParameterStatus)?; self.write_message(&BeMessage::ReadyForQuery)?; self.state = ProtoState::Established; } AuthType::MD5 => { rand::thread_rng().fill(&mut self.md5_salt); let md5_salt = self.md5_salt; self.write_message(&BeMessage::AuthenticationMD5Password( &md5_salt, ))?; self.state = ProtoState::Authentication; } AuthType::ZenithJWT => { self.write_message(&BeMessage::AuthenticationCleartextPassword)?; self.state = ProtoState::Authentication; } } } StartupRequestCode::Cancel => { return Ok(ProcessMsgResult::Break); } } } FeMessage::PasswordMessage(m) => { trace!("got password message '{:?}'", m); assert!(self.state == ProtoState::Authentication); match self.auth_type { AuthType::Trust => unreachable!(), AuthType::MD5 => { let (_, md5_response) = m .split_last() .ok_or_else(|| anyhow::Error::msg("protocol violation"))?; if let Err(e) = handler.check_auth_md5(self, md5_response) { self.write_message(&BeMessage::ErrorResponse(format!("{}", e)))?; bail!("auth failed: {}", e); } } AuthType::ZenithJWT => { let (_, jwt_response) = m .split_last() .ok_or_else(|| anyhow::Error::msg("protocol violation"))?; if let Err(e) = handler.check_auth_jwt(self, jwt_response) { self.write_message(&BeMessage::ErrorResponse(format!("{}", e)))?; bail!("auth failed: {}", e); } } } self.write_message_noflush(&BeMessage::AuthenticationOk)?; // psycopg2 will not connect if client_encoding is not // specified by the server self.write_message_noflush(&BeMessage::ParameterStatus)?; self.write_message(&BeMessage::ReadyForQuery)?; self.state = ProtoState::Established; } FeMessage::Query(m) => { trace!("got query {:?}", m.body); // xxx distinguish fatal and recoverable errors? if let Err(e) = handler.process_query(self, m.body.clone()) { let errmsg = format!("{}", e); // ":#" uses the alternate formatting style, which makes anyhow display the // full cause of the error, not just the top-level context. We don't want to // send that in the ErrorResponse though, because it's not relevant to the // compute node logs. warn!("query handler for {:?} failed: {:#}", m.body, e); self.write_message_noflush(&BeMessage::ErrorResponse(errmsg))?; } self.write_message(&BeMessage::ReadyForQuery)?; } FeMessage::Parse(m) => { *unnamed_query_string = m.query_string; self.write_message(&BeMessage::ParseComplete)?; } FeMessage::Describe(_) => { self.write_message_noflush(&BeMessage::ParameterDescription)? .write_message(&BeMessage::NoData)?; } FeMessage::Bind(_) => { self.write_message(&BeMessage::BindComplete)?; } FeMessage::Close(_) => { self.write_message(&BeMessage::CloseComplete)?; } FeMessage::Execute(_) => { handler.process_query(self, unnamed_query_string.clone())?; } FeMessage::Sync => { self.write_message(&BeMessage::ReadyForQuery)?; } FeMessage::Terminate => { return Ok(ProcessMsgResult::Break); } // We prefer explicit pattern matching to wildcards, because // this helps us spot the places where new variants are missing FeMessage::CopyData(_) | FeMessage::CopyDone | FeMessage::CopyFail => { bail!("unexpected message type: {:?}", msg); } } Ok(ProcessMsgResult::Continue) } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qtoolbutton.h // dst-file: /src/widgets/qtoolbutton.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::qabstractbutton::*; // 773 use std::ops::Deref; use super::qaction::*; // 773 use super::super::core::qobjectdefs::*; // 771 use super::super::core::qsize::*; // 771 use super::qmenu::*; // 773 use super::qwidget::*; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QToolButton_Class_Size() -> c_int; // proto: void QToolButton::setAutoRaise(bool enable); fn C_ZN11QToolButton12setAutoRaiseEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: QAction * QToolButton::defaultAction(); fn C_ZNK11QToolButton13defaultActionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: const QMetaObject * QToolButton::metaObject(); fn C_ZNK11QToolButton10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QSize QToolButton::minimumSizeHint(); fn C_ZNK11QToolButton15minimumSizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QToolButton::~QToolButton(); fn C_ZN11QToolButtonD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QToolButton::showMenu(); fn C_ZN11QToolButton8showMenuEv(qthis: u64 /* *mut c_void*/); // proto: QSize QToolButton::sizeHint(); fn C_ZNK11QToolButton8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QToolButton::autoRaise(); fn C_ZNK11QToolButton9autoRaiseEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QMenu * QToolButton::menu(); fn C_ZNK11QToolButton4menuEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QToolButton::setMenu(QMenu * menu); fn C_ZN11QToolButton7setMenuEP5QMenu(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QToolButton::QToolButton(QWidget * parent); fn C_ZN11QToolButtonC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: void QToolButton::setDefaultAction(QAction * ); fn C_ZN11QToolButton16setDefaultActionEP7QAction(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); fn QToolButton_SlotProxy_connect__ZN11QToolButton9triggeredEP7QAction(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QToolButton)=1 #[derive(Default)] pub struct QToolButton { qbase: QAbstractButton, pub qclsinst: u64 /* *mut c_void*/, pub _triggered: QToolButton_triggered_signal, } impl /*struct*/ QToolButton { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QToolButton { return QToolButton{qbase: QAbstractButton::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QToolButton { type Target = QAbstractButton; fn deref(&self) -> &QAbstractButton { return & self.qbase; } } impl AsRef<QAbstractButton> for QToolButton { fn as_ref(& self) -> & QAbstractButton { return & self.qbase; } } // proto: void QToolButton::setAutoRaise(bool enable); impl /*struct*/ QToolButton { pub fn setAutoRaise<RetType, T: QToolButton_setAutoRaise<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setAutoRaise(self); // return 1; } } pub trait QToolButton_setAutoRaise<RetType> { fn setAutoRaise(self , rsthis: & QToolButton) -> RetType; } // proto: void QToolButton::setAutoRaise(bool enable); impl<'a> /*trait*/ QToolButton_setAutoRaise<()> for (i8) { fn setAutoRaise(self , rsthis: & QToolButton) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QToolButton12setAutoRaiseEb()}; let arg0 = self as c_char; unsafe {C_ZN11QToolButton12setAutoRaiseEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QAction * QToolButton::defaultAction(); impl /*struct*/ QToolButton { pub fn defaultAction<RetType, T: QToolButton_defaultAction<RetType>>(& self, overload_args: T) -> RetType { return overload_args.defaultAction(self); // return 1; } } pub trait QToolButton_defaultAction<RetType> { fn defaultAction(self , rsthis: & QToolButton) -> RetType; } // proto: QAction * QToolButton::defaultAction(); impl<'a> /*trait*/ QToolButton_defaultAction<QAction> for () { fn defaultAction(self , rsthis: & QToolButton) -> QAction { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QToolButton13defaultActionEv()}; let mut ret = unsafe {C_ZNK11QToolButton13defaultActionEv(rsthis.qclsinst)}; let mut ret1 = QAction::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QToolButton::metaObject(); impl /*struct*/ QToolButton { pub fn metaObject<RetType, T: QToolButton_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QToolButton_metaObject<RetType> { fn metaObject(self , rsthis: & QToolButton) -> RetType; } // proto: const QMetaObject * QToolButton::metaObject(); impl<'a> /*trait*/ QToolButton_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QToolButton) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QToolButton10metaObjectEv()}; let mut ret = unsafe {C_ZNK11QToolButton10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QSize QToolButton::minimumSizeHint(); impl /*struct*/ QToolButton { pub fn minimumSizeHint<RetType, T: QToolButton_minimumSizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.minimumSizeHint(self); // return 1; } } pub trait QToolButton_minimumSizeHint<RetType> { fn minimumSizeHint(self , rsthis: & QToolButton) -> RetType; } // proto: QSize QToolButton::minimumSizeHint(); impl<'a> /*trait*/ QToolButton_minimumSizeHint<QSize> for () { fn minimumSizeHint(self , rsthis: & QToolButton) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QToolButton15minimumSizeHintEv()}; let mut ret = unsafe {C_ZNK11QToolButton15minimumSizeHintEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QToolButton::~QToolButton(); impl /*struct*/ QToolButton { pub fn free<RetType, T: QToolButton_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QToolButton_free<RetType> { fn free(self , rsthis: & QToolButton) -> RetType; } // proto: void QToolButton::~QToolButton(); impl<'a> /*trait*/ QToolButton_free<()> for () { fn free(self , rsthis: & QToolButton) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QToolButtonD2Ev()}; unsafe {C_ZN11QToolButtonD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QToolButton::showMenu(); impl /*struct*/ QToolButton { pub fn showMenu<RetType, T: QToolButton_showMenu<RetType>>(& self, overload_args: T) -> RetType { return overload_args.showMenu(self); // return 1; } } pub trait QToolButton_showMenu<RetType> { fn showMenu(self , rsthis: & QToolButton) -> RetType; } // proto: void QToolButton::showMenu(); impl<'a> /*trait*/ QToolButton_showMenu<()> for () { fn showMenu(self , rsthis: & QToolButton) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QToolButton8showMenuEv()}; unsafe {C_ZN11QToolButton8showMenuEv(rsthis.qclsinst)}; // return 1; } } // proto: QSize QToolButton::sizeHint(); impl /*struct*/ QToolButton { pub fn sizeHint<RetType, T: QToolButton_sizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sizeHint(self); // return 1; } } pub trait QToolButton_sizeHint<RetType> { fn sizeHint(self , rsthis: & QToolButton) -> RetType; } // proto: QSize QToolButton::sizeHint(); impl<'a> /*trait*/ QToolButton_sizeHint<QSize> for () { fn sizeHint(self , rsthis: & QToolButton) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QToolButton8sizeHintEv()}; let mut ret = unsafe {C_ZNK11QToolButton8sizeHintEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QToolButton::autoRaise(); impl /*struct*/ QToolButton { pub fn autoRaise<RetType, T: QToolButton_autoRaise<RetType>>(& self, overload_args: T) -> RetType { return overload_args.autoRaise(self); // return 1; } } pub trait QToolButton_autoRaise<RetType> { fn autoRaise(self , rsthis: & QToolButton) -> RetType; } // proto: bool QToolButton::autoRaise(); impl<'a> /*trait*/ QToolButton_autoRaise<i8> for () { fn autoRaise(self , rsthis: & QToolButton) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QToolButton9autoRaiseEv()}; let mut ret = unsafe {C_ZNK11QToolButton9autoRaiseEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QMenu * QToolButton::menu(); impl /*struct*/ QToolButton { pub fn menu<RetType, T: QToolButton_menu<RetType>>(& self, overload_args: T) -> RetType { return overload_args.menu(self); // return 1; } } pub trait QToolButton_menu<RetType> { fn menu(self , rsthis: & QToolButton) -> RetType; } // proto: QMenu * QToolButton::menu(); impl<'a> /*trait*/ QToolButton_menu<QMenu> for () { fn menu(self , rsthis: & QToolButton) -> QMenu { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QToolButton4menuEv()}; let mut ret = unsafe {C_ZNK11QToolButton4menuEv(rsthis.qclsinst)}; let mut ret1 = QMenu::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QToolButton::setMenu(QMenu * menu); impl /*struct*/ QToolButton { pub fn setMenu<RetType, T: QToolButton_setMenu<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setMenu(self); // return 1; } } pub trait QToolButton_setMenu<RetType> { fn setMenu(self , rsthis: & QToolButton) -> RetType; } // proto: void QToolButton::setMenu(QMenu * menu); impl<'a> /*trait*/ QToolButton_setMenu<()> for (&'a QMenu) { fn setMenu(self , rsthis: & QToolButton) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QToolButton7setMenuEP5QMenu()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN11QToolButton7setMenuEP5QMenu(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QToolButton::QToolButton(QWidget * parent); impl /*struct*/ QToolButton { pub fn new<T: QToolButton_new>(value: T) -> QToolButton { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QToolButton_new { fn new(self) -> QToolButton; } // proto: void QToolButton::QToolButton(QWidget * parent); impl<'a> /*trait*/ QToolButton_new for (Option<&'a QWidget>) { fn new(self) -> QToolButton { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QToolButtonC2EP7QWidget()}; let ctysz: c_int = unsafe{QToolButton_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN11QToolButtonC2EP7QWidget(arg0)}; let rsthis = QToolButton{qbase: QAbstractButton::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QToolButton::setDefaultAction(QAction * ); impl /*struct*/ QToolButton { pub fn setDefaultAction<RetType, T: QToolButton_setDefaultAction<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDefaultAction(self); // return 1; } } pub trait QToolButton_setDefaultAction<RetType> { fn setDefaultAction(self , rsthis: & QToolButton) -> RetType; } // proto: void QToolButton::setDefaultAction(QAction * ); impl<'a> /*trait*/ QToolButton_setDefaultAction<()> for (&'a QAction) { fn setDefaultAction(self , rsthis: & QToolButton) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QToolButton16setDefaultActionEP7QAction()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN11QToolButton16setDefaultActionEP7QAction(rsthis.qclsinst, arg0)}; // return 1; } } #[derive(Default)] // for QToolButton_triggered pub struct QToolButton_triggered_signal{poi:u64} impl /* struct */ QToolButton { pub fn triggered(&self) -> QToolButton_triggered_signal { return QToolButton_triggered_signal{poi:self.qclsinst}; } } impl /* struct */ QToolButton_triggered_signal { pub fn connect<T: QToolButton_triggered_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QToolButton_triggered_signal_connect { fn connect(self, sigthis: QToolButton_triggered_signal); } // triggered(class QAction *) extern fn QToolButton_triggered_signal_connect_cb_0(rsfptr:fn(QAction), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QAction::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QToolButton_triggered_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QAction)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QAction::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QToolButton_triggered_signal_connect for fn(QAction) { fn connect(self, sigthis: QToolButton_triggered_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QToolButton_triggered_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QToolButton_SlotProxy_connect__ZN11QToolButton9triggeredEP7QAction(arg0, arg1, arg2)}; } } impl /* trait */ QToolButton_triggered_signal_connect for Box<Fn(QAction)> { fn connect(self, sigthis: QToolButton_triggered_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QToolButton_triggered_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QToolButton_SlotProxy_connect__ZN11QToolButton9triggeredEP7QAction(arg0, arg1, arg2)}; } } // <= body block end
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. mod segments; mod transform; use crate::point::Point; use segments::PathSegments; use transform::Transform; #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum PathCommand { Line([Point<f32>; 2]), Quad([Point<f32>; 3]), RatQuad([(Point<f32>, f32); 3]), Cubic([Point<f32>; 4]), RatCubic([(Point<f32>, f32); 4]), Close, } /// A vector path containing one contour. #[derive(Clone, Debug, Default)] pub struct Path { commands: Vec<PathCommand>, } impl Path { /// Creates a new path. /// /// # Examples /// ``` /// # use crate::mold::Path; /// let path = Path::new(); /// ``` pub fn new() -> Self { Self { commands: vec![] } } /// Adds a line to the path from `p0` to `p1`. /// /// # Examples /// ``` /// # use crate::mold::{Path, Point}; /// let mut path = Path::new(); /// path.line( /// Point::new(1.0, 2.0), /// Point::new(1.0, 3.0), /// ); /// ``` pub fn line(&mut self, p0: Point<f32>, p1: Point<f32>) { self.commands.push(PathCommand::Line([p0, p1])); } /// Adds a quadratic Bézier from `p0` to `p2` with `p1` as control point. /// /// # Examples /// ``` /// # use crate::mold::{Path, Point}; /// let mut path = Path::new(); /// path.quad( /// Point::new(1.0, 2.0), /// Point::new(1.0, 3.0), /// Point::new(1.0, 4.0), /// ); /// ``` pub fn quad(&mut self, p0: Point<f32>, p1: Point<f32>, p2: Point<f32>) { self.commands.push(PathCommand::Quad([p0, p1, p2])); } /// Adds a rational quadratic Bézier from `p0` to `p2` with `p1` as control point. Each weighted /// point is represented by a tuple contining its point and its weight. /// /// # Examples /// ``` /// # use crate::mold::{Path, Point}; /// let mut path = Path::new(); /// path.rat_quad( /// (Point::new(1.0, 2.0), 1.0), /// (Point::new(1.0, 3.0), 1.0), /// (Point::new(1.0, 4.0), 1.0), /// ); /// ``` pub fn rat_quad( &mut self, p0: (Point<f32>, f32), p1: (Point<f32>, f32), p2: (Point<f32>, f32), ) { self.commands.push(PathCommand::RatQuad([p0, p1, p2])); } /// Adds a cubic Bézier from `p0` to `p3` with `p1` and `p2` as control points. /// /// # Examples /// ``` /// # use crate::mold::{Path, Point}; /// let mut path = Path::new(); /// path.cubic( /// Point::new(1.0, 2.0), /// Point::new(1.0, 3.0), /// Point::new(1.0, 4.0), /// Point::new(1.0, 5.0), /// ); /// ``` pub fn cubic(&mut self, p0: Point<f32>, p1: Point<f32>, p2: Point<f32>, p3: Point<f32>) { self.commands.push(PathCommand::Cubic([p0, p1, p2, p3])); } /// Adds a rational cubic Bézier from `p0` to `p3` with `p1` and `p2` as control points. Each /// weighted point is represented by a tuple contining its point and its weight. /// /// # Examples /// ``` /// # use crate::mold::{Path, Point}; /// let mut path = Path::new(); /// path.rat_cubic( /// (Point::new(1.0, 2.0), 1.0), /// (Point::new(1.0, 3.0), 1.0), /// (Point::new(1.0, 4.0), 1.0), /// (Point::new(1.0, 5.0), 1.0), /// ); /// ``` pub fn rat_cubic( &mut self, p0: (Point<f32>, f32), p1: (Point<f32>, f32), p2: (Point<f32>, f32), p3: (Point<f32>, f32), ) { self.commands.push(PathCommand::RatCubic([p0, p1, p2, p3])); } /// Closes the contour defined by the path. If the starting point and ending point of the /// contour don't match, a straight line is added between them that closes the contour. /// /// # Examples /// ``` /// # use crate::mold::{Path, Point}; /// let mut path = Path::new(); /// path.line( /// Point::new(0.0, 0.0), /// Point::new(1.0, 1.0), /// ); /// path.line( /// Point::new(1.0, 1.0), /// Point::new(2.0, 0.0), /// ); /// /// path.close(); /// // Equivalent to: /// // path.line( /// // Point::new(2.0, 0.0), /// // Point::new(0.0, 0.0), /// // ); /// ``` pub fn close(&mut self) { self.commands.push(PathCommand::Close); } pub(crate) fn segments(&self) -> PathSegments { PathSegments::new(&self.commands, None) } pub(crate) fn transformed(&self, transform: &[f32; 9]) -> PathSegments { PathSegments::new(&self.commands, Some(Transform::new(transform))) } } #[cfg(test)] mod tests { use super::*; use crate::segment::Segment; #[test] fn path_interface() { let mut path = Path::new(); path.line(Point::new(1.0, 1.0), Point::new(1.0, 1.0)); assert_eq!( path.commands.last(), Some(&PathCommand::Line([Point::new(1.0, 1.0), Point::new(1.0, 1.0),])) ); path.quad(Point::new(1.0, 1.0), Point::new(1.0, 1.0), Point::new(1.0, 1.0)); assert_eq!( path.commands.last(), Some(&PathCommand::Quad([ Point::new(1.0, 1.0), Point::new(1.0, 1.0), Point::new(1.0, 1.0), ])) ); path.rat_quad( (Point::new(1.0, 1.0), 1.0), (Point::new(1.0, 1.0), 1.0), (Point::new(1.0, 1.0), 1.0), ); assert_eq!( path.commands.last(), Some(&PathCommand::RatQuad([ (Point::new(1.0, 1.0), 1.0), (Point::new(1.0, 1.0), 1.0), (Point::new(1.0, 1.0), 1.0), ])) ); path.cubic( Point::new(1.0, 1.0), Point::new(1.0, 1.0), Point::new(1.0, 1.0), Point::new(1.0, 1.0), ); assert_eq!( path.commands.last(), Some(&PathCommand::Cubic([ Point::new(1.0, 1.0), Point::new(1.0, 1.0), Point::new(1.0, 1.0), Point::new(1.0, 1.0), ])) ); path.rat_cubic( (Point::new(1.0, 1.0), 1.0), (Point::new(1.0, 1.0), 1.0), (Point::new(1.0, 1.0), 1.0), (Point::new(1.0, 1.0), 1.0), ); assert_eq!( path.commands.last(), Some(&PathCommand::RatCubic([ (Point::new(1.0, 1.0), 1.0), (Point::new(1.0, 1.0), 1.0), (Point::new(1.0, 1.0), 1.0), (Point::new(1.0, 1.0), 1.0), ])) ); } #[test] fn close_open_path() { let mut path = Path::new(); path.line(Point::new(0.0, 0.0), Point::new(1.0, 1.0)); path.line(Point::new(1.0, 1.0), Point::new(2.0, 0.0)); path.close(); assert_eq!( path.segments().collect::<Vec<_>>(), vec![ Segment::new(Point::new(0.0, 0.0), Point::new(1.0, 1.0)), Segment::new(Point::new(1.0, 1.0), Point::new(2.0, 0.0)), Segment::new(Point::new(2.0, 0.0), Point::new(0.0, 0.0)), ], ); } #[test] fn close_closed_path() { let mut path = Path::new(); path.line(Point::new(0.0, 0.0), Point::new(1.0, 1.0)); path.line(Point::new(1.0, 1.0), Point::new(2.0, 0.0)); path.line(Point::new(2.0, 0.0), Point::new(0.0, 0.0)); path.close(); assert_eq!( path.segments().collect::<Vec<_>>(), vec![ Segment::new(Point::new(0.0, 0.0), Point::new(1.0, 1.0)), Segment::new(Point::new(1.0, 1.0), Point::new(2.0, 0.0)), Segment::new(Point::new(2.0, 0.0), Point::new(0.0, 0.0)), ], ); } #[test] fn scale_translate_quad() { let transform = Transform::new(&[2.0, 0.0, 2.0, 0.0, 2.0, 2.0, 0.0, 0.0, 1.0]); let command = PathCommand::Quad([Point::new(0.0, 0.0), Point::new(1.0, 1.0), Point::new(2.0, 0.0)]); assert_eq!( transform.transform(command), PathCommand::Quad([Point::new(2.0, 2.0), Point::new(4.0, 4.0), Point::new(6.0, 2.0),]) ); } #[test] fn perspective_transform_quad() { let transform = Transform::new(&[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.0, 1.0]); let command = PathCommand::Quad([Point::new(0.0, 0.0), Point::new(1.0, 1.0), Point::new(2.0, 0.0)]); assert_eq!( transform.transform(command), PathCommand::RatQuad([ (Point::new(0.0, 0.0), 1.0), (Point::new(1.0, 1.0), 1.5), (Point::new(2.0, 0.0), 2.0), ]) ); } #[test] fn scale_translate() { let mut path = Path::new(); path.quad(Point::new(0.0, 0.0), Point::new(1.0, 1.0), Point::new(2.0, 0.0)); let transformed: Vec<_> = path.transformed(&[2.0, 0.0, 2.0, 0.0, 2.0, 2.0, 0.0, 0.0, 1.0]).collect(); assert_eq!(transformed.first().unwrap().p0, Point::new(2.0, 2.0)); assert_eq!(transformed.last().unwrap().p1, Point::new(6.0, 2.0)); } #[test] fn scale_translate_t22_not_1() { let mut path = Path::new(); path.quad(Point::new(0.0, 0.0), Point::new(1.0, 1.0), Point::new(2.0, 0.0)); let transformed: Vec<_> = path.transformed(&[2.0, 0.0, 2.0, 0.0, 2.0, 2.0, 0.0, 0.0, 2.0]).collect(); assert_eq!(transformed.first().unwrap().p0, Point::new(1.0, 1.0)); assert_eq!(transformed.last().unwrap().p1, Point::new(3.0, 1.0)); } #[test] fn rational_bezier_with_weights_1() { let non_rational = Path { commands: vec![PathCommand::Quad([ Point::new(2.0, 0.0), Point::new(2.0, 2.0), Point::new(0.0, 2.0), ])], }; let rational = Path { commands: vec![PathCommand::RatQuad([ (Point::new(2.0, 0.0), 1.0), (Point::new(2.0, 2.0), 1.0), (Point::new(0.0, 2.0), 1.0), ])], }; assert_eq!( non_rational.segments().collect::<Vec<_>>(), rational.segments().collect::<Vec<_>>(), ); } #[test] fn circle_rational_bezier() { const RADIUS: f32 = 10.0; let path = Path { commands: vec![PathCommand::RatQuad([ (Point::new(RADIUS, 0.0), 1.0), (Point::new(RADIUS, RADIUS), 1.0 / RADIUS.sqrt()), (Point::new(0.0, RADIUS), 1.0), ])], }; let segments: Vec<_> = path.segments().collect(); for segment in &segments[1..] { assert!( segment.p0.x * segment.p0.x + segment.p0.y * segment.p0.y - RADIUS * RADIUS < std::f32::EPSILON ); } } #[test] fn quad_split_into_segments() { let mut path = Path::new(); path.quad(Point::new(0.0, 0.0), Point::new(1.0, 1.0), Point::new(2.0, 0.0)); assert_eq!(path.segments().count(), 3); } }
use chrono::{DateTime, NaiveDateTime, Utc}; pub mod map_lat_long; pub mod map_weather; pub mod digit_map; pub fn countdown(timestamp: String) -> TimeFrame { let scheduled_naive = NaiveDateTime::parse_from_str(timestamp.as_str(), "%Y-%m-%dT%H:%M:%SZ").unwrap(); let scheduled = DateTime::<Utc>::from_utc(scheduled_naive, Utc).signed_duration_since(Utc::now()); process_seconds(scheduled.num_seconds()) } pub fn countdown_news(timestamp: String) -> TimeFrame { let scheduled_naive = NaiveDateTime::parse_from_str(timestamp.as_str(), "%Y-%m-%dT%H:%M:%S%.3fZ").unwrap(); let scheduled = DateTime::<Utc>::from_utc(scheduled_naive, Utc).signed_duration_since(Utc::now()); process_seconds(scheduled.num_seconds()) } pub fn process_seconds(s: i64) -> TimeFrame { let days = s / (60 * 60 * 24); let hours = s % (60 * 60 * 24) / (60 * 60); let minutes = s % (60 * 60) / (60); let seconds = s % (60); TimeFrame::new(seconds, minutes, hours, days, s, s.is_negative()) } #[derive(Debug, Clone, Copy)] pub struct TimeFrame { pub seconds: u64, pub minutes: u64, pub hours: u64, pub days: u64, pub total_seconds: u64, pub has_passed: bool, } impl TimeFrame { pub fn new(s: i64, m: i64, h: i64, d: i64, total: i64, has_passed: bool) -> TimeFrame { let seconds = if s.is_negative() { (s * -1) as u64 } else { s as u64 }; let minutes = if m.is_negative() { (m * -1) as u64 } else { m as u64 }; let hours = if h.is_negative() { (h * -1) as u64 } else { h as u64 }; let days = if d.is_negative() { (d * -1) as u64 } else { d as u64 }; let total_seconds = if total.is_negative() { (total * -1) as u64 } else { total as u64 }; TimeFrame { seconds, minutes, hours, days, total_seconds, has_passed, } } }
#[macro_use] pub mod shared; pub mod blake2b; pub mod blake2s;
use futures::*; use std::io; use tokio_core; use tokio_io::{AsyncRead, AsyncWrite}; pub type PlaintextSocket = tokio_core::net::TcpStream; /// Abstracts a plaintext socket vs. a TLS decorated one. #[derive(Debug)] pub enum Connection { Plain(PlaintextSocket), } /// A connection handshake. /// /// Resolves to a connection ready to be used at the next layer. pub struct Handshake { plaintext_socket: Option<PlaintextSocket>, } // ===== impl Connection ===== impl Connection { /// Establish a connection backed by the provided `io`. pub fn handshake(io: PlaintextSocket) -> Handshake { Handshake { plaintext_socket: Some(io), } } } impl io::Read for Connection { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { use self::Connection::*; match *self { Plain(ref mut t) => t.read(buf), } } } // TODO: impl specialty functions impl AsyncRead for Connection {} impl io::Write for Connection { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { use self::Connection::*; match *self { Plain(ref mut t) => t.write(buf), } } fn flush(&mut self) -> io::Result<()> { use self::Connection::*; match *self { Plain(ref mut t) => t.flush(), } } } // TODO: impl specialty functions impl AsyncWrite for Connection { fn shutdown(&mut self) -> Poll<(), io::Error> { use self::Connection::*; match *self { Plain(ref mut t) => t.shutdown(), } } } // ===== impl Handshake ===== impl Future for Handshake { type Item = Connection; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, io::Error> { let plaintext_socket = self.plaintext_socket.take().expect("poll after complete"); Ok(Connection::Plain(plaintext_socket).into()) } }
use std::io; use std::fs; use std::path::Path; pub fn get_string<T: AsRef<Path>>(path: T) -> io::Result<String> { match fs::read_to_string(path) { Err(e) => Err(e), Ok(ref content) => { let trimmed = content.trim(); if trimmed.starts_with('\0') { Err(io::Error::from(io::ErrorKind::InvalidData)) } else { Ok(trimmed.to_string()) } } } } // TODO: Generic somehow? pub fn get_f32<T: AsRef<Path>>(path: T) -> io::Result<f32> { get_string(path).and_then(|value| { value.parse::<f32>().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) }) } pub fn get_u32<T: AsRef<Path>>(path: T) -> io::Result<u32> { get_string(path).and_then(|value| { value.parse::<u32>().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) }) }
//! Native loader use crate::message_processor::SymbolCache; use bincode::deserialize; #[cfg(unix)] use libloading::os::unix::*; #[cfg(windows)] use libloading::os::windows::*; use log::*; use morgan_interface::account::KeyedAccount; use morgan_interface::instruction::InstructionError; use morgan_interface::instruction_processor_utils; use morgan_interface::loader_instruction::LoaderInstruction; use morgan_interface::pubkey::Pubkey; use std::env; use std::path::PathBuf; use std::str; use morgan_helper::logHelper::*; /// Dynamic link library prefixes #[cfg(unix)] const PLATFORM_FILE_PREFIX_NATIVE: &str = "lib"; #[cfg(windows)] const PLATFORM_FILE_PREFIX_NATIVE: &str = ""; /// Dynamic link library file extension specific to the platform #[cfg(any(target_os = "macos", target_os = "ios"))] const PLATFORM_FILE_EXTENSION_NATIVE: &str = "dylib"; /// Dynamic link library file extension specific to the platform #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios"))))] const PLATFORM_FILE_EXTENSION_NATIVE: &str = "so"; /// Dynamic link library file extension specific to the platform #[cfg(windows)] const PLATFORM_FILE_EXTENSION_NATIVE: &str = "dll"; fn create_path(name: &str) -> PathBuf { let current_exe = env::current_exe() .unwrap_or_else(|e| panic!("create_path(\"{}\"): current exe not found: {:?}", name, e)); let current_exe_directory = PathBuf::from(current_exe.parent().unwrap_or_else(|| { panic!( "create_path(\"{}\"): no parent directory of {:?}", name, current_exe, ) })); let library_file_name = PathBuf::from(PLATFORM_FILE_PREFIX_NATIVE.to_string() + name) .with_extension(PLATFORM_FILE_EXTENSION_NATIVE); // Check the current_exe directory for the library as `cargo tests` are run // from the deps/ subdirectory let file_path = current_exe_directory.join(&library_file_name); if file_path.exists() { file_path } else { // `cargo build` places dependent libraries in the deps/ subdirectory current_exe_directory.join("deps").join(library_file_name) } } pub fn entrypoint( program_id: &Pubkey, keyed_accounts: &mut [KeyedAccount], ix_data: &[u8], tick_height: u64, symbol_cache: &SymbolCache, ) -> Result<(), InstructionError> { if keyed_accounts[0].account.executable { // dispatch it let (names, params) = keyed_accounts.split_at_mut(1); let name_vec = &names[0].account.data; if let Some(entrypoint) = symbol_cache.read().unwrap().get(name_vec) { unsafe { return entrypoint(program_id, params, ix_data, tick_height); } } let name = match str::from_utf8(name_vec) { Ok(v) => v, Err(e) => { // warn!("Invalid UTF-8 sequence: {}", e); println!("{}",Warn(format!("Invalid UTF-8 sequence: {}", e).to_string(),module_path!().to_string())); return Err(InstructionError::GenericError); } }; trace!("Call native {:?}", name); let path = create_path(&name); // TODO linux tls bug can cause crash on dlclose(), workaround by never unloading match Library::open(Some(&path), libc::RTLD_NODELETE | libc::RTLD_NOW) { Ok(library) => unsafe { let entrypoint: Symbol<instruction_processor_utils::Entrypoint> = match library.get(instruction_processor_utils::ENTRYPOINT.as_bytes()) { Ok(s) => s, Err(e) => { // warn!( // "{:?}: Unable to find {:?} in program", // e, // instruction_processor_utils::ENTRYPOINT // ); println!( "{}", Warn(format!("{:?}: Unable to find {:?} in program", e, instruction_processor_utils::ENTRYPOINT).to_string(), module_path!().to_string()) ); return Err(InstructionError::GenericError); } }; let ret = entrypoint(program_id, params, ix_data, tick_height); symbol_cache .write() .unwrap() .insert(name_vec.to_vec(), entrypoint); return ret; }, Err(e) => { // warn!("Unable to load: {:?}", e); println!( "{}", Warn(format!("Unable to load: {:?}", e).to_string(), module_path!().to_string()) ); return Err(InstructionError::GenericError); } } } else if let Ok(instruction) = deserialize(ix_data) { if keyed_accounts[0].signer_key().is_none() { // warn!("key[0] did not sign the transaction"); println!( "{}", Warn(format!("key[0] did not sign the transaction").to_string(), module_path!().to_string()) ); return Err(InstructionError::GenericError); } match instruction { LoaderInstruction::Write { offset, bytes } => { trace!("NativeLoader::Write offset {} bytes {:?}", offset, bytes); let offset = offset as usize; if keyed_accounts[0].account.data.len() < offset + bytes.len() { // warn!( // "Error: Overflow, {} < {}", // keyed_accounts[0].account.data.len(), // offset + bytes.len() // ); println!( "{}", Warn( format!("Error: Overflow, {} < {}", keyed_accounts[0].account.data.len(), offset + bytes.len()).to_string(), module_path!().to_string()) ); return Err(InstructionError::GenericError); } // native loader takes a name and we assume it all comes in at once keyed_accounts[0].account.data = bytes; } LoaderInstruction::Finalize => { keyed_accounts[0].account.executable = true; trace!( "NativeLoader::Finalize prog: {:?}", keyed_accounts[0].signer_key().unwrap() ); } } } else { // warn!("Invalid data in instruction: {:?}", ix_data); println!( "{}", Warn( format!("Invalid data in instruction: {:?}", ix_data).to_string(), module_path!().to_string()) ); return Err(InstructionError::GenericError); } Ok(()) }
use crate::{ protocol::{parts::AmRsCore, ServerUsage}, HdbError, HdbResult, }; use std::collections::VecDeque; #[cfg(feature = "async")] use super::fetch::async_fetch_a_lob_chunk; use crate::conn::AmConnCore; #[cfg(feature = "async")] use tokio::io::ReadBuf; #[cfg(feature = "sync")] use super::fetch::sync_fetch_a_lob_chunk; #[cfg(feature = "sync")] use std::io::Write; // `BLobHandle` is used for blobs that we receive from the database. // The data are often not transferred completely, so we carry internally // a database connection and the necessary controls to support fetching // remaining data on demand. #[derive(Clone, Debug)] pub(crate) struct BLobHandle { pub(crate) am_conn_core: AmConnCore, o_am_rscore: Option<AmRsCore>, is_data_complete: bool, total_byte_length: u64, locator_id: u64, data: VecDeque<u8>, acc_byte_length: usize, pub(crate) server_usage: ServerUsage, } impl BLobHandle { pub(crate) fn new( am_conn_core: &AmConnCore, o_am_rscore: &Option<AmRsCore>, is_data_complete: bool, total_byte_length: u64, locator_id: u64, data: Vec<u8>, ) -> Self { let data = VecDeque::from(data); Self { am_conn_core: am_conn_core.clone(), o_am_rscore: o_am_rscore.as_ref().cloned(), total_byte_length, is_data_complete, locator_id, acc_byte_length: data.len(), data, server_usage: ServerUsage::default(), } } #[cfg(feature = "sync")] pub(crate) fn sync_read_slice(&mut self, offset: u64, length: u32) -> HdbResult<Vec<u8>> { let (reply_data, _reply_is_last_data) = sync_fetch_a_lob_chunk( &mut self.am_conn_core, self.locator_id, offset, length, &mut self.server_usage, )?; debug!("read_slice(): got {} bytes", reply_data.len()); Ok(reply_data) } #[cfg(feature = "async")] pub(crate) async fn read_slice(&mut self, offset: u64, length: u32) -> HdbResult<Vec<u8>> { let (reply_data, _reply_is_last_data) = async_fetch_a_lob_chunk( &mut self.am_conn_core, self.locator_id, offset, length, &mut self.server_usage, ) .await?; debug!("read_slice(): got {} bytes", reply_data.len()); Ok(reply_data) } pub(crate) fn total_byte_length(&self) -> u64 { self.total_byte_length } pub(crate) fn cur_buf_len(&self) -> usize { self.data.len() } #[allow(clippy::cast_possible_truncation)] #[cfg(feature = "sync")] fn fetch_next_chunk(&mut self) -> HdbResult<()> { if self.is_data_complete { return Err(HdbError::Impl("fetch_next_chunk(): already complete")); } let read_length = std::cmp::min( self.am_conn_core.sync_lock()?.lob_read_length(), (self.total_byte_length - self.acc_byte_length as u64) as u32, ); let (reply_data, reply_is_last_data) = sync_fetch_a_lob_chunk( &mut self.am_conn_core, self.locator_id, self.acc_byte_length as u64, read_length, &mut self.server_usage, )?; self.acc_byte_length += reply_data.len(); self.data.append(&mut VecDeque::from(reply_data)); if reply_is_last_data { self.is_data_complete = true; self.o_am_rscore = None; } assert_eq!( self.is_data_complete, self.total_byte_length == self.acc_byte_length as u64 ); trace!( "fetch_next_chunk: is_data_complete = {}, data.len() = {}", self.is_data_complete, self.data.len() ); Ok(()) } #[allow(clippy::cast_possible_truncation)] #[cfg(feature = "async")] async fn async_fetch_next_chunk(&mut self) -> HdbResult<()> { if self.is_data_complete { return Err(HdbError::Impl("fetch_next_chunk(): already complete")); } let read_length = std::cmp::min( self.am_conn_core.async_lock().await.lob_read_length(), (self.total_byte_length - self.acc_byte_length as u64) as u32, ); let (reply_data, reply_is_last_data) = async_fetch_a_lob_chunk( &mut self.am_conn_core, self.locator_id, self.acc_byte_length as u64, read_length, &mut self.server_usage, ) .await?; self.acc_byte_length += reply_data.len(); self.data.append(&mut VecDeque::from(reply_data)); if reply_is_last_data { self.is_data_complete = true; self.o_am_rscore = None; } assert_eq!( self.is_data_complete, self.total_byte_length == self.acc_byte_length as u64 ); trace!( "fetch_next_chunk: is_data_complete = {}, data.len() = {}", self.is_data_complete, self.data.len() ); Ok(()) } #[cfg(feature = "sync")] pub(crate) fn sync_load_complete(&mut self) -> HdbResult<()> { trace!("load_complete()"); while !self.is_data_complete { self.fetch_next_chunk()?; } Ok(()) } #[cfg(feature = "async")] pub(crate) async fn async_load_complete(&mut self) -> HdbResult<()> { trace!("load_complete()"); while !self.is_data_complete { self.async_fetch_next_chunk().await?; } Ok(()) } // Converts a BLobHandle into a Vec<u8> containing its data. #[cfg(feature = "sync")] pub(crate) fn sync_into_bytes(mut self) -> HdbResult<Vec<u8>> { trace!("into_bytes()"); self.sync_load_complete()?; Ok(Vec::from(self.data)) } // Converts a BLobHandle into a Vec<u8> containing its data. #[cfg(feature = "async")] pub(crate) fn into_bytes_if_complete(self) -> HdbResult<Vec<u8>> { trace!("into_bytes_if_complete()"); if self.is_data_complete { Ok(Vec::from(self.data)) } else { Err(HdbError::Usage( "Can't convert BLob that is not not completely loaded", )) } } } // Support for streaming #[cfg(feature = "sync")] impl std::io::Read for BLobHandle { fn read(&mut self, mut buf: &mut [u8]) -> std::io::Result<usize> { let buf_len = buf.len(); trace!("BLobHandle::read() with buf of len {}", buf_len); while !self.is_data_complete && (buf_len > self.data.len()) { self.fetch_next_chunk().map_err(|e| { std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e.to_string()) })?; } let count = std::cmp::min(self.data.len(), buf_len); let (s1, s2) = self.data.as_slices(); if count <= s1.len() { // write count bytes from s1 buf.write_all(&s1[0..count])?; } else { // write s1 completely, then take the rest from s2 buf.write_all(s1)?; buf.write_all(&s2[0..(count - s1.len())])?; } self.data.drain(0..count); Ok(count) } } #[cfg(feature = "async")] impl<'a> BLobHandle { pub(crate) async fn async_read(&mut self, buf: &'a mut [u8]) -> HdbResult<usize> { let mut buf = ReadBuf::new(buf); let buf_len = buf.capacity(); debug_assert!(buf.filled().is_empty()); trace!("BLobHandle::read() with buf of len {}", buf_len); while !self.is_data_complete && (self.data.len() < buf_len) { self.async_fetch_next_chunk().await?; } let count = std::cmp::min(self.data.len(), buf_len); let (s1, s2) = self.data.as_slices(); if count <= s1.len() { // write count bytes from s1 buf.put_slice(&s1[0..count]); } else { // write s1 completely, then take the rest from s2 buf.put_slice(s1); buf.put_slice(&s2[0..(count - s1.len())]); } self.data.drain(0..count); Ok(count) } }
//! The device struct and implementation use pyo3::prelude::*; use pyo3::wrap_pyfunction; use crate::bindings::*; use crate::error_enum_or_value; use crate::types::HydraHarpError::*; use crate::types::{ CTCStatus, EdgeSelection, HydraHarpError, MeasurementControl, MeasurementMode, ReferenceSource, }; use crate::measurement::Measureable; /// Contains the information of the device - the number it is (0 -> 7) and the serial of it. #[pyclass] #[derive(Debug, PartialEq)] pub struct Device { pub id: i32, pub serial: [i8; 8], /// the length of the histograms returned by get_histogram in u32 pub histogram_length: Option<usize>, } impl Device { /// Try to open a device given a device id and return a result with either the opened device or an error pub fn open_device(id: i32) -> Result<Device, HydraHarpError> { let mut serial = [0i8; 8]; error_enum_or_value! { unsafe {HH_OpenDevice(id, serial.as_mut_ptr())}, Device {id, serial, histogram_length: None} } } /// Try to close this device pub fn close_device(&mut self) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_CloseDevice(self.id) }, () } } /// Initialise the device. Should be done before other functions are run pub fn initialise( &mut self, mode: MeasurementMode, ref_source: ReferenceSource, ) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_Initialize(self.id, num::ToPrimitive::to_i32(&mode).unwrap(), num::ToPrimitive::to_i32(&ref_source).unwrap()) }, () } } /// Get the base resolution of this device /// Returns a tuple (f64, i32) containing (resolution, bin steps) if successful pub fn get_base_resolution(&self) -> Result<(f64, i32), HydraHarpError> { let mut res = 0f64; let mut bin = 0i32; error_enum_or_value! {{ unsafe { HH_GetBaseResolution( self.id, &mut res as *mut f64, &mut bin as *mut i32 ) }}, (res, bin) } } /// Get the number of input channels to this device pub fn get_number_of_input_channels(&self) -> Result<i32, HydraHarpError> { let mut inputs = 0i32; error_enum_or_value! { unsafe { HH_GetNumOfInputChannels(self.id, &mut inputs as *mut i32) }, inputs } } /// Perform a device calibration pub fn calibrate(&mut self) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_Calibrate(self.id) }, () } } /// Set the sync divider pub fn set_sync_divider(&mut self, divisions: i32) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetSyncDiv( self.id, divisions ) }, () } } /// Modify the sync CFD settings. /// level sets the CFD discriminator level in millivolts with bounds (DISCRMIN, DISCRMAX) /// zerox sets the CFD zero cross level in millivolts with bounds (ZCMIN, ZCMAX) pub fn set_sync_CFD(&mut self, level: i32, zerox: i32) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetSyncCFD(self.id, level, zerox) }, () } } /// Set the sync timing offset in ps /// minimum is CHANOFFSMIN, maximum is CHANOFFSMAX pub fn set_sync_channel_offset(&mut self, offset: i32) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetSyncChannelOffset(self.id, offset) }, () } } /// Modify the input CFD. Bounds are the same as the `set_sync_CFD` pub fn set_input_CFD( &mut self, channel: i32, level: i32, zerox: i32, ) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetInputCFD(self.id, channel, level, zerox) }, () } } /// Set the timing offset on the given channel in picoseconds pub fn set_input_channel_offset( &mut self, channel: i32, offset: i32, ) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetInputChannelOffset(self.id, channel, offset) }, () } } /// Set the enabled state of the given channel pub fn set_input_channel_enabled( &mut self, channel: i32, enabled: bool, ) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetInputChannelEnable(self.id, channel, enabled as i32) }, () } } /// This setting determines if a measurement run will stop if any channel reaches the maximum set by `stopcount`. /// If `stop_ofl` is `false` the measurement will continue, but counts above `STOPCNTMAX` in any bin will be clipped. pub fn set_stop_overflow( &mut self, stop_ofl: bool, stopcount: u32, ) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetStopOverflow(self.id, stop_ofl as i32, stopcount) }, () } } /// Set the binning. The binning value corresponds to powers of 2*the base resolution. /// eg: `binning = 0 => 1*base_resolution` /// `binning = 1 => 2*base_resolution` /// `binning = 2 => 4*base_resolution` pub fn set_binning(&mut self, binning: i32) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetBinning(self.id, binning) }, () } } /// Set the histogram time offset in nanoseconds pub fn set_offset(&mut self, offset: i32) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetOffset(self.id, offset) }, () } } /// Set the histogram length. Returns the actual length calculated as `1024*(2^lencode)` pub fn set_histogram_length(&mut self, length: i32) -> Result<i32, HydraHarpError> { let mut actual_length: i32 = 0; let return_val = error_enum_or_value! { unsafe { HH_SetHistoLen(self.id, length, &mut actual_length as *mut i32) }, actual_length }; if let Ok(len) = return_val { self.histogram_length = Some(len as usize); } return_val } /// Clear the histogram memory pub fn clear_histogram_memory(&mut self) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_ClearHistMem(self.id) }, () } } /// Set the measurement control code and edges pub fn set_measurement_control( &mut self, control: MeasurementControl, start_edge: EdgeSelection, stop_edge: EdgeSelection, ) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetMeasControl(self.id, num::ToPrimitive::to_i32(&control).unwrap(), num::ToPrimitive::to_i32(&start_edge).unwrap(), num::ToPrimitive::to_i32(&stop_edge).unwrap()) }, () } } /// Stop a measurement. Can be used before the acquisition time expires pub fn stop_measurement(&mut self) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_StopMeas(self.id) }, () } } /// Get the histogram from the device. Returns the error `HistogramLengthNotKnown` if /// `self.histogram_length = None`. If clear is true then the acquisiton buffer is cleared upon reading, /// otherwise it isn't pub fn get_histogram(&mut self, channel: i32, clear: bool) -> Result<Vec<u32>, HydraHarpError> { if let Some(histogram_length) = self.histogram_length { // let mut histogram_data: Vec<u32> = Vec::with_capacity(histogram_length); let mut histogram_data: Vec<u32> = vec![0; histogram_length]; error_enum_or_value! { unsafe { HH_GetHistogram(self.id, histogram_data.as_mut_ptr(), channel, clear as i32) }, histogram_data } } else { Err(HydraHarpError::HistogramLengthNotKnown) } } /// get the resolution at the current histogram bin width in picoseconds pub fn get_resolution(&self) -> Result<f64, HydraHarpError> { let mut resolution: f64 = 0.0; error_enum_or_value! { unsafe { HH_GetResolution(self.id, &mut resolution as *mut f64) }, resolution } } /// get the current sync rate pub fn get_sync_rate(&self) -> Result<i32, HydraHarpError> { let mut sync_rate: i32 = 0; error_enum_or_value! { unsafe { HH_GetSyncRate(self.id, &mut sync_rate as *mut i32) }, sync_rate } } /// get the current count rate /// allow at least 100ms after initialise or set_sync_divider to get a stable meter reading /// wait at least 100ms to get a new reading. This is the gate time of the counters pub fn get_count_rate(&self, channel: i32) -> Result<i32, HydraHarpError> { let mut count_rate: i32 = 0; error_enum_or_value! { unsafe { HH_GetCountRate(self.id, channel, &mut count_rate as *mut i32) }, count_rate } } /// get the flags. Use the `FLAG_*` variables to extract the different flags pub fn get_flags(&self) -> Result<i32, HydraHarpError> { let mut flags: i32 = 0; error_enum_or_value! { unsafe { HH_GetFlags(self.id, &mut flags as *mut i32) }, flags } } /// get the elapsed measurement time in ms pub fn get_elapsed_measurement_time(&self) -> Result<f64, HydraHarpError> { let mut time: f64 = 0.0; error_enum_or_value! { unsafe { HH_GetElapsedMeasTime(self.id, &mut time as *mut f64) }, time } } /// get the warnings encoded bitwise pub fn get_warnings(&self) -> Result<i32, HydraHarpError> { let mut warnings: i32 = 0; error_enum_or_value! { unsafe { HH_GetWarnings(self.id, &mut warnings as *mut i32) }, warnings } } /// Use in TTTR mode /// set the marker edges pub fn set_marker_edges( &mut self, me1: EdgeSelection, me2: EdgeSelection, me3: EdgeSelection, me4: EdgeSelection, ) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetMarkerEdges(self.id, num::ToPrimitive::to_i32(&me1).unwrap(), num::ToPrimitive::to_i32(&me2).unwrap(), num::ToPrimitive::to_i32(&me3).unwrap(), num::ToPrimitive::to_i32(&me4).unwrap()) }, () } } /// Use in TTTR mode /// enable or disable the marker edges pub fn enable_marker_edges( &mut self, en1: bool, en2: bool, en3: bool, en4: bool, ) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetMarkerEnable(self.id, en1 as i32, en2 as i32, en3 as i32, en4 as i32)}, () } } /// Use in TTTR mode /// Set the marker holdoff time in ns pub fn set_marker_holdoff_time(&mut self, holdoff_time: i32) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_SetMarkerHoldoffTime(self.id, holdoff_time) }, () } } } impl Drop for Device { fn drop(&mut self) { self.close_device(); } } impl Measureable for Device { /// Start a measurement with acquisition time in milliseconds fn start_measurement(&mut self, acquisition_time: i32) -> Result<(), HydraHarpError> { error_enum_or_value! { unsafe { HH_StartMeas(self.id, acquisition_time) }, () } } /// use in TTTR mode /// `buffer` should be at least 128 records long /// `records_to_fetch` should be a multiple of 128, less than the length of `buffer` and no longer than `TTREADMAX` /// In the result, returns Ok(records_written), where records_written is the number of records actually written to the buffer fn read_fifo( &mut self, buffer: &mut [u32], records_to_fetch: i32, ) -> Result<i32, HydraHarpError> { let mut records_written: i32 = 0; error_enum_or_value! { unsafe { HH_ReadFiFo( self.id, buffer.as_mut_ptr(), records_to_fetch, &mut records_written as *mut i32 ) }, records_written } } /// Get the status of the device, whether the acquisiton time is still going, or if it has ended. fn get_CTC_status(&self) -> Result<CTCStatus, HydraHarpError> { let mut status: i32 = 0; error_enum_or_value! { unsafe { HH_CTCStatus(self.id, &mut status as *mut i32) }, num::FromPrimitive::from_i32(status).unwrap() } } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use kvm_ioctls::{Kvm, VmFd}; use kvm_bindings::{kvm_userspace_memory_region, KVM_CAP_X86_DISABLE_EXITS, kvm_enable_cap, KVM_X86_DISABLE_EXITS_HLT, KVM_X86_DISABLE_EXITS_MWAIT}; use spin::Mutex; use alloc::sync::Arc; use std::{thread}; use core::sync::atomic::AtomicI32; use core::sync::atomic::Ordering; use lazy_static::lazy_static; use std::os::unix::io::FromRawFd; use super::super::super::qlib::common::*; use super::super::super::qlib::pagetable::{PageTables}; use super::super::super::qlib::linux_def::*; use super::super::super::qlib::ShareSpace; use super::super::super::qlib::addr::AccessType; use super::super::super::qlib::addr; use super::super::super::qlib::config::*; use super::super::super::qlib::perf_tunning::*; use super::super::super::qlib::task_mgr::*; use super::super::super::qlib::qmsg::*; use super::super::super::syncmgr; use super::super::super::runc::runtime::loader::*; use super::super::super::qcall; use super::super::super::kvm_vcpu::*; use super::super::super::elf_loader::*; use super::super::super::vmspace::*; use super::super::super::{FD_NOTIFIER, VMS, PMA_KEEPER}; use super::super::super::ucall::ucall_server::*; lazy_static! { static ref EXIT_STATUS : AtomicI32 = AtomicI32::new(-1); } const HEAP_OFFSET: u64 = 1 * MemoryDef::ONE_GB; #[inline] pub fn IsRunning() -> bool { return EXIT_STATUS.load(Ordering::Relaxed) == -1 } pub fn SetExitStatus(status: i32) { EXIT_STATUS.store(status, Ordering::Release); } pub fn GetExitStatus() -> i32 { return EXIT_STATUS.load(Ordering::Acquire) } pub struct BootStrapMem { pub startAddr: u64, pub vcpuCount: usize, } pub const KERNEL_HEAP_ORD : usize = 32; // 4GB pub const PAGE_POOL_ORD: usize = KERNEL_HEAP_ORD - 8; impl BootStrapMem { pub const PAGE_POOL_SIZE : usize = 1 << PAGE_POOL_ORD; pub fn New(startAddr: u64, vcpuCount: usize) -> Self { return Self { startAddr: startAddr, vcpuCount: vcpuCount, } } pub fn Size(&self) -> usize { let size = self.vcpuCount * VcpuBootstrapMem::AlignedSize() + Self::PAGE_POOL_SIZE; return size; } pub fn VcpuBootstrapMem(&self, idx: usize) -> &'static VcpuBootstrapMem { let addr = self.startAddr + (idx * VcpuBootstrapMem::AlignedSize()) as u64; return VcpuBootstrapMem::FromAddr(addr); } pub fn SimplePageAllocator(&self) -> SimplePageAllocator { let addr = self.startAddr + (self.vcpuCount * VcpuBootstrapMem::AlignedSize()) as u64; return SimplePageAllocator::New(addr, Self::PAGE_POOL_SIZE) } } pub struct VirtualMachine { pub kvm: Kvm, pub vmfd: VmFd, pub vcpus: Vec<Arc<Mutex<KVMVcpu>>>, pub elf: KernelELF, } impl VirtualMachine { pub fn SetMemRegion(slotId: u32, vm_fd: &VmFd, phyAddr: u64, hostAddr: u64, pageMmapsize: u64) -> Result<()> { info!("SetMemRegion phyAddr = {:x}, hostAddr={:x}; pageMmapsize = {:x} MB", phyAddr, hostAddr, (pageMmapsize >> 20)); // guest_phys_addr must be <512G let mem_region = kvm_userspace_memory_region { slot: slotId, guest_phys_addr: phyAddr, memory_size: pageMmapsize, userspace_addr: hostAddr, flags: 0, //kvm_bindings::KVM_MEM_LOG_DIRTY_PAGES, }; unsafe { vm_fd.set_user_memory_region(mem_region).map_err(|e| Error::IOError(format!("io::error is {:?}", e)))?; } return Ok(()) } pub fn Umask() -> u32 { let umask = unsafe{ libc::umask(0) }; return umask } #[cfg(debug_assertions)] pub const KERNEL_IMAGE : &'static str = "/usr/local/bin/qkernel_d.bin"; #[cfg(not(debug_assertions))] pub const KERNEL_IMAGE : &'static str = "/usr/local/bin/qkernel.bin"; pub fn Init(args: Args /*args: &Args, kvmfd: i32*/) -> Result<Self> { PerfGoto(PerfType::Other); /*{ use super::super::super::qlib::cpuid::*; let featureSet = HostFeatureSet(); error!("Host::hasXSAVEOPT is {}", featureSet.UseXsaveopt()); error!("Host::hasXSAVE is {}", featureSet.UseXsave()); error!("Host::hasFSGSBASE is {}", featureSet.HasFeature(Feature(X86Feature::X86FeatureFSGSBase as i32))); error!("Host::X86FeatureXSAVEOPT is {}", featureSet.HasFeature(Feature(X86Feature::X86FeatureXSAVEOPT as i32))); error!("Host::X86FeatureXSAVE is {}", featureSet.HasFeature(Feature(X86Feature::X86FeatureXSAVE as i32))); error!("Host::X86FeatureOSXSAVE is {}", featureSet.HasFeature(Feature(X86Feature::X86FeatureOSXSAVE as i32))); }*/ let mut config = Config::default(); config.Load(); let kvmfd = args.KvmFd; let cpuCount = VMSpace::VCPUCount() - 1; let kernelMemRegionSize = config.KernelMemSize; let controlSock = args.ControlSock; let umask = Self::Umask(); info!("reset umask from {:o} to {}, kernelMemRegionSize is {:x}", umask, 0, kernelMemRegionSize); let eventfd = FD_NOTIFIER.Eventfd(); let kvm = unsafe { Kvm::from_raw_fd(kvmfd) }; let kvm_cpuid = kvm.get_supported_cpuid(kvm_bindings::KVM_MAX_CPUID_ENTRIES).unwrap(); let vm_fd = kvm.create_vm().map_err(|e| Error::IOError(format!("io::error is {:?}", e)))?; let mut cap: kvm_enable_cap = Default::default(); cap.cap = KVM_CAP_X86_DISABLE_EXITS; cap.args[0] = (KVM_X86_DISABLE_EXITS_HLT | KVM_X86_DISABLE_EXITS_MWAIT) as u64; vm_fd.enable_cap(&cap).unwrap(); let mut elf = KernelELF::New()?; Self::SetMemRegion(1, &vm_fd, MemoryDef::PHY_LOWER_ADDR, MemoryDef::PHY_LOWER_ADDR, kernelMemRegionSize * MemoryDef::ONE_GB)?; PMA_KEEPER.Init(MemoryDef::PHY_LOWER_ADDR + HEAP_OFFSET, kernelMemRegionSize * MemoryDef::ONE_GB - HEAP_OFFSET); info!("set map region start={:x}, end={:x}", MemoryDef::PHY_LOWER_ADDR, MemoryDef::PHY_LOWER_ADDR + kernelMemRegionSize * MemoryDef::ONE_GB); let pageAllocatorBaseAddr; let pageAllocatorOrd; let autoStart; let bootstrapMem; { let memOrd = KERNEL_HEAP_ORD; // 8GB let kernelMemSize = 1 << memOrd; //pageMmap = KVMMachine::initKernelMem(&vm_fd, MemoryDef::PHY_LOWER_ADDR + 64 * MemoryDef::ONE_MB, kernelMemSize)?; //pageAllocatorBaseAddr = pageMmap.as_ptr() as u64; info!("kernelMemSize is {:x}", kernelMemSize); let vms = &mut VMS.lock(); //pageAllocatorBaseAddr = vms.pmaMgr.MapAnon(kernelMemSize, AccessType::ReadWrite().Val() as i32, true, false)?; pageAllocatorBaseAddr = PMA_KEEPER.MapAnon(kernelMemSize, AccessType::ReadWrite().Val() as i32)?; info!("*******************alloc address is {:x}, expect{:x}", pageAllocatorBaseAddr, MemoryDef::PHY_LOWER_ADDR + MemoryDef::ONE_GB); PMA_KEEPER.InitHugePages(); //pageAlloc = PageAllocator::Init(pageMmap.as_ptr() as u64, memOrd - 12 /*1GB*/); pageAllocatorOrd = memOrd - 12 /*1GB*/; bootstrapMem = BootStrapMem::New(pageAllocatorBaseAddr, cpuCount); vms.allocator = Some(bootstrapMem.SimplePageAllocator()); vms.hostAddrTop = MemoryDef::PHY_LOWER_ADDR + 64 * MemoryDef::ONE_MB + 2 * MemoryDef::ONE_GB; vms.pageTables = PageTables::New(vms.allocator.as_ref().unwrap())?; info!("the pageAllocatorBaseAddr is {:x}, the end of pageAllocator is {:x}", pageAllocatorBaseAddr, pageAllocatorBaseAddr + kernelMemSize); vms.KernelMapHugeTable(addr::Addr(MemoryDef::PHY_LOWER_ADDR), addr::Addr(MemoryDef::PHY_LOWER_ADDR + kernelMemRegionSize * MemoryDef::ONE_GB), addr::Addr(MemoryDef::PHY_LOWER_ADDR), addr::PageOpts::Zero().SetPresent().SetWrite().SetGlobal().Val())?; autoStart = args.AutoStart; vms.pivot = args.Pivot; vms.args = Some(args); } info!("before loadKernel"); let entry = elf.LoadKernel(Self::KERNEL_IMAGE)?; //let vdsoMap = VDSOMemMap::Init(&"/home/brad/rust/quark/vdso/vdso.so".to_string()).unwrap(); elf.LoadVDSO(&"/usr/local/bin/vdso.so".to_string())?; VMS.lock().vdsoAddr = elf.vdsoStart; let p = entry as *const u8; info!("entry is 0x{:x}, data at entry is {:x}", entry, unsafe { *p } ); //let usocket = USocket::InitServer(&ControlSocketAddr(&containerId))?; //let usocket = USocket::CreateServer(&ControlSocketAddr(&containerId), usockfd)?; InitUCallController(controlSock)?; { super::super::super::URING_MGR.lock(); } let mut vcpus = Vec::with_capacity(cpuCount); for i in 0..cpuCount/*args.NumCPU*/ { let vcpu = Arc::new(Mutex::new(KVMVcpu::Init(i as usize, cpuCount, &vm_fd, &bootstrapMem, entry, pageAllocatorBaseAddr, pageAllocatorOrd as u64, eventfd, autoStart)?)); // enable cpuid in host vcpu.lock().vcpu.set_cpuid2(&kvm_cpuid).unwrap(); vcpus.push(vcpu); } let vm = Self { kvm: kvm, vmfd: vm_fd, vcpus: vcpus, elf: elf, }; PerfGofrom(PerfType::Other); Ok(vm) } pub fn run(&mut self) -> Result<i32> { let cpu = self.vcpus[0].clone(); let mut threads = Vec::new(); threads.push(thread::spawn(move || { cpu.lock().run().expect("vcpu run fail"); info!("cpu#{} finish", 0); })); syncmgr::SyncMgr::WaitShareSpaceReady(); info!("shareSpace ready..."); for i in 1..self.vcpus.len() { let cpu = self.vcpus[i].clone(); cpu.lock().shareSpace = VMS.lock().GetShareSpace(); threads.push(thread::spawn(move || { info!("cpu#{} start", i); cpu.lock().run().expect("vcpu run fail"); info!("cpu#{} finish", i); })); } threads.push(thread::spawn(move || { UcallSrvProcess().unwrap(); info!("UcallSrvProcess finish..."); })); threads.push(thread::spawn(move || { Self::Process(); info!("IOThread finish..."); })); for t in threads { t.join().expect("the working threads has panicked"); } Ok(GetExitStatus()) } pub fn WakeAll(shareSpace: &ShareSpace) { shareSpace.scheduler.WakeAll(); } pub fn Schedule(shareSpace: &ShareSpace, taskId: TaskIdQ) { shareSpace.scheduler.ScheduleQ(taskId.TaskId(), taskId.Queue()); } pub fn PrintQ(shareSpace: &ShareSpace, vcpuId: u64) -> String { return shareSpace.scheduler.PrintQ(vcpuId) } pub const EVENT_COUNT: usize = 128; pub fn Process() { let shareSpace = VMS.lock().GetShareSpace(); 'main: loop { //PerfGoto(PerfType::QCall); while shareSpace.ReadyOutputMsgCnt() > 0 { unsafe { let msg = shareSpace.AQHostOutputPop(); match msg { None => { llvm_asm!("pause" :::: "volatile"); //error!("get none output msg ..."); }, Some(HostOutputMsg::QCall(addr)) => { let eventAddr = addr as *mut Event; // as &mut qlib::Event; let event = &mut (*eventAddr); let currTaskId = event.taskId; //error!("qcall event is {:x?}", &event); match qcall::qCall(addr, event) { qcall::QcallRet::Normal => { if currTaskId.Addr() != 0 { Self::Schedule(shareSpace, currTaskId); } } qcall::QcallRet::Block => { //info!("start blocked wait ..........."); } } } Some(msg) => { //error!("qcall msg is {:x?}", &msg); qcall::AQHostCall(msg, shareSpace); } } } } if !IsRunning() { VMS.lock().CloseVMSpace(); return; } //PerfGofrom(PerfType::QCall); FD_NOTIFIER.WaitAndNotify(shareSpace, 0).unwrap(); for _ in 0..10 { for _ in 0..20 { if shareSpace.ReadyOutputMsgCnt() > 0 { continue 'main } unsafe { llvm_asm!("pause" :::: "volatile"); } unsafe { llvm_asm!("pause" :::: "volatile"); } /*unsafe { llvm_asm!("pause" :::: "volatile"); } unsafe { llvm_asm!("pause" :::: "volatile"); } unsafe { llvm_asm!("pause" :::: "volatile"); }*/ } } loop { //PerfGoto(PerfType::IdleWait); shareSpace.WaitInHost(); if shareSpace.ReadyOutputMsgCnt() > 0 { shareSpace.WakeInHost(); break; } //error!("io thread sleep... shareSpace.ReadyOutputMsgCnt() = {}", shareSpace.ReadyOutputMsgCnt()); let _cnt = FD_NOTIFIER.WaitAndNotify(shareSpace, -1).unwrap(); //error!("io thread wake..."); if !IsRunning() { VMS.lock().CloseVMSpace(); return; } shareSpace.WakeInHost(); //PerfGofrom(PerfType::IdleWait); if shareSpace.ReadyOutputMsgCnt() > 0 { break; } } } } }
pub mod entity; pub mod orm; pub mod repository;
#![feature(llvm_asm)] extern "C" fn foo() { } fn main() { let x: usize; unsafe { llvm_asm!("movq $1, $0" : "=r"(x) : "r"(foo)); } assert!(x != 0); }
use tokio::sync::{Mutex, MutexGuard}; use crate::actor::Actor; use crate::data::ContextData; use std::{collections::HashMap, sync::Arc}; #[derive(Clone)] pub struct AppContext(Arc<Mutex<Context>>); impl AppContext { pub fn init() -> AppContext { AppContext(Arc::new(Mutex::new(Context::new()))) } pub async fn trigger_action(&self, id: u32) -> () { let mut lock = self.lock().await; if let Some(a) = lock.actors.get_mut(&id) { a.act(self.clone()); } } pub async fn lock(&self) -> MutexGuard<'_, Context> { self.0.lock().await } } pub struct Context { actors: HashMap<u32, Actor>, shared_data: ContextData } impl Context { pub fn new() -> Context { Context { actors: HashMap::new(), shared_data: ContextData::new() } } pub fn add_actor(&mut self) { let count = self.actors.len() as u32; let actor = Actor::new(count + 1); self.actors.insert(actor.get_id(), actor); } pub fn get_actor(&self, id: u32) -> Option<&Actor> { self.actors.get(&id) } pub fn get_actors(&self) -> Vec<&Actor> { self.actors.values().clone().collect() } pub fn get_data(&self) -> &ContextData { &self.shared_data } pub fn get_data_mut(&mut self) -> &mut ContextData { &mut self.shared_data } }
pub mod large; pub mod small; use num_bigint::BigInt; use liblumen_alloc::erts::exception::InternalResult; use liblumen_alloc::erts::term::prelude::*; use liblumen_alloc::Process; use super::{sign, try_split_at}; fn decode<'a>(process: &Process, bytes: &'a [u8], len: usize) -> InternalResult<(Term, &'a [u8])> { let (sign, after_sign_bytes) = sign::decode(bytes)?; try_split_at(after_sign_bytes, len).and_then(|(digits_bytes, after_digits_bytes)| { let big_int = BigInt::from_bytes_le(sign, digits_bytes); let integer = process.integer(big_int); Ok((integer, after_digits_bytes)) }) }
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt::Debug; use std::io::Cursor; use std::ops::Deref; use std::ops::RangeBounds; use std::sync::Arc; use async_trait::async_trait; use common_meta_raft_store::config::RaftConfig; use common_meta_raft_store::state_machine::StoredSnapshot; use common_meta_sled_store::openraft::ErrorSubject; use common_meta_sled_store::openraft::ErrorVerb; use common_meta_sled_store::openraft::LogState; use common_meta_sled_store::openraft::RaftLogReader; use common_meta_sled_store::openraft::RaftSnapshotBuilder; use common_meta_sled_store::openraft::RaftStorage; use common_meta_types::AppliedState; use common_meta_types::Entry; use common_meta_types::LogId; use common_meta_types::MetaStartupError; use common_meta_types::Snapshot; use common_meta_types::SnapshotMeta; use common_meta_types::StorageError; use common_meta_types::StoredMembership; use common_meta_types::TypeConfig; use common_meta_types::Vote; use tracing::debug; use tracing::error; use tracing::info; use crate::metrics::raft_metrics; use crate::metrics::server_metrics; use crate::store::StoreInner; use crate::store::ToStorageError; /// A bare store that implements `RaftStorage` trait and provides full functions but without defensive check. /// /// It is designed to be cloneable in order to be shared by MetaNode and Raft. #[derive(Clone)] pub struct RaftStoreBare { pub(crate) inner: Arc<StoreInner>, } impl RaftStoreBare { pub fn new(sto: StoreInner) -> Self { Self { inner: Arc::new(sto), } } #[tracing::instrument(level = "debug", skip_all, fields(config_id=%config.config_id))] pub async fn open_create( config: &RaftConfig, open: Option<()>, create: Option<()>, ) -> Result<Self, MetaStartupError> { let sto = StoreInner::open_create(config, open, create).await?; Ok(Self::new(sto)) } } impl Deref for RaftStoreBare { type Target = StoreInner; fn deref(&self) -> &Self::Target { &self.inner } } #[async_trait] impl RaftLogReader<TypeConfig> for RaftStoreBare { async fn get_log_state(&mut self) -> Result<LogState<TypeConfig>, StorageError> { let last_purged_log_id = match self .log .get_last_purged() .map_to_sto_err(ErrorSubject::Logs, ErrorVerb::Read) { Err(err) => { raft_metrics::storage::incr_raft_storage_fail("get_log_state", false); return Err(err); } Ok(r) => r, }; let last = match self .log .logs() .last() .map_to_sto_err(ErrorSubject::Logs, ErrorVerb::Read) { Err(err) => { raft_metrics::storage::incr_raft_storage_fail("get_log_state", false); return Err(err); } Ok(r) => r, }; let last_log_id = match last { None => last_purged_log_id, Some(x) => Some(x.1.log_id), }; debug!( "get_log_state: ({:?},{:?}]", last_purged_log_id, last_log_id ); Ok(LogState { last_purged_log_id, last_log_id, }) } #[tracing::instrument(level = "debug", skip(self), fields(id=self.id))] async fn try_get_log_entries<RB: RangeBounds<u64> + Clone + Debug + Send + Sync>( &mut self, range: RB, ) -> Result<Vec<Entry>, StorageError> { debug!("try_get_log_entries: range: {:?}", range); match self .log .range_values(range) .map_to_sto_err(ErrorSubject::Logs, ErrorVerb::Read) { Ok(entries) => return Ok(entries), Err(err) => { raft_metrics::storage::incr_raft_storage_fail("try_get_log_entries", false); Err(err) } } } } #[async_trait] impl RaftSnapshotBuilder<TypeConfig, Cursor<Vec<u8>>> for RaftStoreBare { #[tracing::instrument(level = "debug", skip(self), fields(id=self.id))] async fn build_snapshot(&mut self) -> Result<Snapshot, StorageError> { self.do_build_snapshot().await } } #[async_trait] impl RaftStorage<TypeConfig> for RaftStoreBare { type SnapshotData = Cursor<Vec<u8>>; type LogReader = RaftStoreBare; type SnapshotBuilder = RaftStoreBare; async fn get_log_reader(&mut self) -> Self::LogReader { self.clone() } async fn get_snapshot_builder(&mut self) -> Self::SnapshotBuilder { self.clone() } #[tracing::instrument(level = "debug", skip(self, hs), fields(id=self.id))] async fn save_vote(&mut self, hs: &Vote) -> Result<(), StorageError> { info!("save_vote: {:?}", hs); match self .raft_state .save_vote(hs) .await .map_to_sto_err(ErrorSubject::Vote, ErrorVerb::Write) { Err(err) => { return { raft_metrics::storage::incr_raft_storage_fail("save_vote", true); Err(err) }; } Ok(_) => return Ok(()), } } #[tracing::instrument(level = "debug", skip(self), fields(id=self.id))] async fn delete_conflict_logs_since(&mut self, log_id: LogId) -> Result<(), StorageError> { info!("delete_conflict_logs_since: {}", log_id); match self .log .range_remove(log_id.index..) .await .map_to_sto_err(ErrorSubject::Log(log_id), ErrorVerb::Delete) { Ok(_) => return Ok(()), Err(err) => { raft_metrics::storage::incr_raft_storage_fail("delete_conflict_logs_since", true); Err(err) } } } #[tracing::instrument(level = "debug", skip(self), fields(id=self.id))] async fn purge_logs_upto(&mut self, log_id: LogId) -> Result<(), StorageError> { info!("purge_logs_upto: {}", log_id); if let Err(err) = self .log .set_last_purged(log_id) .await .map_to_sto_err(ErrorSubject::Logs, ErrorVerb::Write) { raft_metrics::storage::incr_raft_storage_fail("purge_logs_upto", true); return Err(err); }; if let Err(err) = self .log .range_remove(..=log_id.index) .await .map_to_sto_err(ErrorSubject::Log(log_id), ErrorVerb::Delete) { raft_metrics::storage::incr_raft_storage_fail("purge_logs_upto", true); return Err(err); } Ok(()) } #[tracing::instrument(level = "debug", skip(self, entries), fields(id=self.id))] async fn append_to_log(&mut self, entries: &[&Entry]) -> Result<(), StorageError> { for ent in entries { info!("append_to_log: {}", ent.log_id); } let entries = entries.iter().map(|x| (*x).clone()).collect::<Vec<_>>(); match self .log .append(&entries) .await .map_to_sto_err(ErrorSubject::Logs, ErrorVerb::Write) { Err(err) => { raft_metrics::storage::incr_raft_storage_fail("append_to_log", true); Err(err) } Ok(_) => return Ok(()), } } #[tracing::instrument(level = "debug", skip(self, entries), fields(id=self.id))] async fn apply_to_state_machine( &mut self, entries: &[&Entry], ) -> Result<Vec<AppliedState>, StorageError> { for ent in entries { info!("apply_to_state_machine: {}", ent.log_id); } let mut res = Vec::with_capacity(entries.len()); let sm = self.state_machine.write().await; for entry in entries { let r = match sm .apply(entry) .await .map_to_sto_err(ErrorSubject::Apply(entry.log_id), ErrorVerb::Write) { Err(err) => { raft_metrics::storage::incr_raft_storage_fail("apply_to_state_machine", true); return Err(err); } Ok(r) => r, }; res.push(r); } Ok(res) } #[tracing::instrument(level = "debug", skip(self), fields(id=self.id))] async fn begin_receiving_snapshot(&mut self) -> Result<Box<Self::SnapshotData>, StorageError> { server_metrics::incr_applying_snapshot(1); Ok(Box::new(Cursor::new(Vec::new()))) } #[tracing::instrument(level = "debug", skip(self, snapshot), fields(id=self.id))] async fn install_snapshot( &mut self, meta: &SnapshotMeta, snapshot: Box<Self::SnapshotData>, ) -> Result<(), StorageError> { // TODO(xp): disallow installing a snapshot with smaller last_applied. info!( { snapshot_size = snapshot.get_ref().len() }, "decoding snapshot for installation" ); server_metrics::incr_applying_snapshot(-1); let new_snapshot = StoredSnapshot { meta: meta.clone(), data: snapshot.into_inner(), }; info!("snapshot meta: {:?}", meta); // Replace state machine with the new one let res = self.do_install_snapshot(&new_snapshot.data).await; match res { Ok(_) => {} Err(e) => { raft_metrics::storage::incr_raft_storage_fail("install_snapshot", true); error!("error: {:?} when install_snapshot", e); } }; // Update current snapshot. { let mut current_snapshot = self.current_snapshot.write().await; *current_snapshot = Some(new_snapshot); } Ok(()) } #[tracing::instrument(level = "debug", skip(self), fields(id=self.id))] async fn get_current_snapshot(&mut self) -> Result<Option<Snapshot>, StorageError> { info!("get snapshot start"); let snap = match &*self.current_snapshot.read().await { Some(snapshot) => { let data = snapshot.data.clone(); Ok(Some(Snapshot { meta: snapshot.meta.clone(), snapshot: Box::new(Cursor::new(data)), })) } None => Ok(None), }; info!("get snapshot complete"); snap } #[tracing::instrument(level = "debug", skip(self))] async fn read_vote(&mut self) -> Result<Option<Vote>, StorageError> { match self .raft_state .read_vote() .map_to_sto_err(ErrorSubject::Vote, ErrorVerb::Read) { Err(err) => { raft_metrics::storage::incr_raft_storage_fail("read_vote", false); return Err(err); } Ok(vote) => return Ok(vote), } } async fn last_applied_state( &mut self, ) -> Result<(Option<LogId>, StoredMembership), StorageError> { let sm = self.state_machine.read().await; let last_applied = match sm .get_last_applied() .map_to_sto_err(ErrorSubject::StateMachine, ErrorVerb::Read) { Err(err) => { raft_metrics::storage::incr_raft_storage_fail("last_applied_state", false); return Err(err); } Ok(r) => r, }; let last_membership = match sm .get_membership() .map_to_sto_err(ErrorSubject::StateMachine, ErrorVerb::Read) { Err(err) => { raft_metrics::storage::incr_raft_storage_fail("last_applied_state", false); return Err(err); } Ok(r) => r, }; debug!( "last_applied_state: applied: {:?}, membership: {:?}", last_applied, last_membership ); let last_membership = last_membership.unwrap_or_default(); Ok((last_applied, last_membership)) } }
use std::io::{self, Cursor, Read, Seek, SeekFrom}; use std::num::ParseIntError; use std::result::Result as StdResult; use {RealTime, Run, Segment, Time, TimeSpan}; use base64::{self, STANDARD}; use byteorder::{ReadBytesExt, BE}; use imagelib::{png, ColorType, ImageBuffer, Rgba}; use super::xml_util::{self, text}; use sxd_document::dom::Element; use sxd_document::parser::{parse as parse_xml, Error as XmlError}; quick_error! { #[derive(Debug)] pub enum Error { Xml(err: (usize, Vec<XmlError>)) { from() } Io(err: io::Error) { from() } Int(err: ParseIntError) { from() } LengthOutOfBounds ElementNotFound AttributeNotFound } } pub type Result<T> = StdResult<T, Error>; fn child<'d>(element: &Element<'d>, name: &str) -> Result<Element<'d>> { xml_util::child(element, name).ok_or(Error::ElementNotFound) } fn attribute<'d>(element: &Element<'d>, attribute: &str) -> Result<&'d str> { xml_util::attribute(element, attribute).ok_or(Error::AttributeNotFound) } fn time_span(element: &Element, buf: &mut String) -> Result<TimeSpan> { let text = text(element, buf); let milliseconds = text.parse::<i64>()?; Ok(TimeSpan::from_milliseconds(milliseconds as f64)) } fn time(element: &Element, buf: &mut String) -> Result<Time> { Ok(RealTime(Some(time_span(element, buf)?)).into()) } fn image<'b>( node: &Element, buf: &mut Vec<u8>, buf2: &'b mut Vec<u8>, str_buf: &mut String, ) -> Result<&'b [u8]> { let node = child(node, "icon")?; let node = child(&node, "ImageIcon")?; buf.clear(); base64::decode_config_buf(text(&node, str_buf), STANDARD, buf) .map_err(|_| Error::ElementNotFound)?; let (width, height); { let mut cursor = Cursor::new(&buf); cursor.seek(SeekFrom::Current(0xD1))?; height = cursor.read_u32::<BE>()?; width = cursor.read_u32::<BE>()?; } let len = (width as usize) .checked_mul(height as usize) .and_then(|b| b.checked_mul(4)) .ok_or(Error::LengthOutOfBounds)?; if buf.len() < 0xFE + len { return Err(Error::ElementNotFound); } let buf = &buf[0xFE..][..len]; let image = ImageBuffer::<Rgba<_>, _>::from_raw(width, height, buf).ok_or(Error::ElementNotFound)?; buf2.clear(); png::PNGEncoder::new(&mut *buf2) .encode(image.as_ref(), width, height, ColorType::RGBA(8)) .map_err(|_| Error::ElementNotFound)?; Ok(buf2) } pub fn parse<R: Read>(mut source: R) -> Result<Run> { let buf = &mut String::new(); let mut byte_buf = Vec::new(); let mut byte_buf2 = Vec::new(); source.read_to_string(buf)?; let package = parse_xml(buf)?; let node = package .as_document() .root() .children() .into_iter() .filter_map(|c| c.element()) .next() .unwrap(); let mut run = Run::new(); let node = child(&node, "Run")?; let node = child(&node, "default")?; run.set_game_name(text(&child(&node, "name")?, buf)); run.set_category_name(text(&child(&node, "subTitle")?, buf)); run.set_offset( TimeSpan::zero() - time_span(&child(&node, "delayedStart")?, buf)?, ); run.set_attempt_count(text(&child(&node, "numberOfAttempts")?, buf).parse()?); let segments = child(&node, "segments")?; let mut total_time = TimeSpan::zero(); for node in segments.children().into_iter().filter_map(|c| c.element()) { let node = child(&node, "Segment")?; let node = child(&node, "default")?; let mut segment = Segment::new(text(&child(&node, "name")?, buf)); if let Ok(node) = child(&node, "bestTime") { if let Ok(node) = child(&node, "milliseconds") { segment.set_best_segment_time(time(&node, buf)?); } } if let Ok(node) = child(&node, "runTime") { if let Ok(node) = child(&node, "milliseconds") { total_time += time_span(&node, buf)?; } else if let Ok("../bestTime") = attribute(&node, "reference") { total_time += segment .best_segment_time() .real_time .ok_or(Error::ElementNotFound)?; } segment.set_personal_best_split_time(RealTime(Some(total_time)).into()); } if let Ok(image) = image(&node, &mut byte_buf, &mut byte_buf2, buf) { segment.set_icon(image); } run.push_segment(segment); } Ok(run) }
use crate::geometry::MeasuredSize; #[derive(Copy, Clone, Debug)] pub enum MeasureConstraint { AtMost(u32), Exactly(u32), Unspecified, } impl MeasureConstraint { pub fn shrink(self, by: u32) -> MeasureConstraint { match self { MeasureConstraint::AtMost(size) => MeasureConstraint::AtMost(size.saturating_sub(by)), MeasureConstraint::Exactly(size) => MeasureConstraint::Exactly(size.saturating_sub(by)), MeasureConstraint::Unspecified => MeasureConstraint::Unspecified, } } pub fn apply_to_measured(self, measured: u32) -> u32 { match self { MeasureConstraint::AtMost(constraint) => constraint.min(measured), MeasureConstraint::Exactly(constraint) => constraint, MeasureConstraint::Unspecified => measured, } } pub fn to_at_most(self) -> MeasureConstraint { match self { MeasureConstraint::AtMost(size) => MeasureConstraint::AtMost(size), MeasureConstraint::Exactly(size) => MeasureConstraint::AtMost(size), MeasureConstraint::Unspecified => MeasureConstraint::AtMost(u32::MAX), } } pub fn largest(self) -> Option<u32> { match self { MeasureConstraint::AtMost(size) => Some(size), MeasureConstraint::Exactly(size) => Some(size), MeasureConstraint::Unspecified => None, } } /// Returns `true` if the measure_constraint is [`MeasureConstraint::Exactly`]. pub fn is_exact(&self) -> bool { matches!(self, Self::Exactly(..)) } } #[derive(Copy, Clone, Debug)] pub struct MeasureSpec { pub width: MeasureConstraint, pub height: MeasureConstraint, } impl MeasureSpec { pub fn from_measured_at_most(MeasuredSize { width, height }: MeasuredSize) -> Self { Self { width: MeasureConstraint::AtMost(width), height: MeasureConstraint::AtMost(height), } } pub fn from_measured_exactly(MeasuredSize { width, height }: MeasuredSize) -> Self { Self { width: MeasureConstraint::Exactly(width), height: MeasureConstraint::Exactly(height), } } pub fn is_exact(&self) -> bool { self.width.is_exact() && self.height.is_exact() } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qmutex.h // dst-file: /src/core/qmutex.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use std::ops::Deref; // use super::qmutex::QBasicMutex; // 773 // use super::qmutex::QMutex; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QMutexLocker_Class_Size() -> c_int; // proto: void QMutexLocker::QMutexLocker(QBasicMutex * m); fn C_ZN12QMutexLockerC2EP11QBasicMutex(arg0: *mut c_void) -> u64; // proto: QMutex * QMutexLocker::mutex(); fn C_ZNK12QMutexLocker5mutexEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QMutexLocker::relock(); fn C_ZN12QMutexLocker6relockEv(qthis: u64 /* *mut c_void*/); // proto: void QMutexLocker::unlock(); fn C_ZN12QMutexLocker6unlockEv(qthis: u64 /* *mut c_void*/); // proto: void QMutexLocker::~QMutexLocker(); fn C_ZN12QMutexLockerD2Ev(qthis: u64 /* *mut c_void*/); fn QBasicMutex_Class_Size() -> c_int; // proto: void QBasicMutex::lock(); fn C_ZN11QBasicMutex4lockEv(qthis: u64 /* *mut c_void*/); // proto: bool QBasicMutex::tryLock(); fn C_ZN11QBasicMutex7tryLockEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: bool QBasicMutex::isRecursive(); fn C_ZN11QBasicMutex11isRecursiveEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QBasicMutex::unlock(); fn C_ZN11QBasicMutex6unlockEv(qthis: u64 /* *mut c_void*/); fn QMutex_Class_Size() -> c_int; // proto: void QMutex::~QMutex(); fn C_ZN6QMutexD2Ev(qthis: u64 /* *mut c_void*/); // proto: bool QMutex::tryLock(int timeout); fn C_ZN6QMutex7tryLockEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_char; // proto: void QMutex::lock(); fn C_ZN6QMutex4lockEv(qthis: u64 /* *mut c_void*/); // proto: void QMutex::unlock(); fn C_ZN6QMutex6unlockEv(qthis: u64 /* *mut c_void*/); } // <= ext block end // body block begin => // class sizeof(QMutexLocker)=4 #[derive(Default)] pub struct QMutexLocker { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } // class sizeof(QBasicMutex)=1 #[derive(Default)] pub struct QBasicMutex { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } // class sizeof(QMutex)=1 #[derive(Default)] pub struct QMutex { qbase: QBasicMutex, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QMutexLocker { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMutexLocker { return QMutexLocker{qclsinst: qthis, ..Default::default()}; } } // proto: void QMutexLocker::QMutexLocker(QBasicMutex * m); impl /*struct*/ QMutexLocker { pub fn new<T: QMutexLocker_new>(value: T) -> QMutexLocker { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QMutexLocker_new { fn new(self) -> QMutexLocker; } // proto: void QMutexLocker::QMutexLocker(QBasicMutex * m); impl<'a> /*trait*/ QMutexLocker_new for (&'a QBasicMutex) { fn new(self) -> QMutexLocker { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QMutexLockerC2EP11QBasicMutex()}; let ctysz: c_int = unsafe{QMutexLocker_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN12QMutexLockerC2EP11QBasicMutex(arg0)}; let rsthis = QMutexLocker{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QMutex * QMutexLocker::mutex(); impl /*struct*/ QMutexLocker { pub fn mutex<RetType, T: QMutexLocker_mutex<RetType>>(& self, overload_args: T) -> RetType { return overload_args.mutex(self); // return 1; } } pub trait QMutexLocker_mutex<RetType> { fn mutex(self , rsthis: & QMutexLocker) -> RetType; } // proto: QMutex * QMutexLocker::mutex(); impl<'a> /*trait*/ QMutexLocker_mutex<QMutex> for () { fn mutex(self , rsthis: & QMutexLocker) -> QMutex { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK12QMutexLocker5mutexEv()}; let mut ret = unsafe {C_ZNK12QMutexLocker5mutexEv(rsthis.qclsinst)}; let mut ret1 = QMutex::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QMutexLocker::relock(); impl /*struct*/ QMutexLocker { pub fn relock<RetType, T: QMutexLocker_relock<RetType>>(& self, overload_args: T) -> RetType { return overload_args.relock(self); // return 1; } } pub trait QMutexLocker_relock<RetType> { fn relock(self , rsthis: & QMutexLocker) -> RetType; } // proto: void QMutexLocker::relock(); impl<'a> /*trait*/ QMutexLocker_relock<()> for () { fn relock(self , rsthis: & QMutexLocker) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QMutexLocker6relockEv()}; unsafe {C_ZN12QMutexLocker6relockEv(rsthis.qclsinst)}; // return 1; } } // proto: void QMutexLocker::unlock(); impl /*struct*/ QMutexLocker { pub fn unlock<RetType, T: QMutexLocker_unlock<RetType>>(& self, overload_args: T) -> RetType { return overload_args.unlock(self); // return 1; } } pub trait QMutexLocker_unlock<RetType> { fn unlock(self , rsthis: & QMutexLocker) -> RetType; } // proto: void QMutexLocker::unlock(); impl<'a> /*trait*/ QMutexLocker_unlock<()> for () { fn unlock(self , rsthis: & QMutexLocker) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QMutexLocker6unlockEv()}; unsafe {C_ZN12QMutexLocker6unlockEv(rsthis.qclsinst)}; // return 1; } } // proto: void QMutexLocker::~QMutexLocker(); impl /*struct*/ QMutexLocker { pub fn free<RetType, T: QMutexLocker_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QMutexLocker_free<RetType> { fn free(self , rsthis: & QMutexLocker) -> RetType; } // proto: void QMutexLocker::~QMutexLocker(); impl<'a> /*trait*/ QMutexLocker_free<()> for () { fn free(self , rsthis: & QMutexLocker) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN12QMutexLockerD2Ev()}; unsafe {C_ZN12QMutexLockerD2Ev(rsthis.qclsinst)}; // return 1; } } impl /*struct*/ QBasicMutex { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QBasicMutex { return QBasicMutex{qclsinst: qthis, ..Default::default()}; } } // proto: void QBasicMutex::lock(); impl /*struct*/ QBasicMutex { pub fn lock<RetType, T: QBasicMutex_lock<RetType>>(& self, overload_args: T) -> RetType { return overload_args.lock(self); // return 1; } } pub trait QBasicMutex_lock<RetType> { fn lock(self , rsthis: & QBasicMutex) -> RetType; } // proto: void QBasicMutex::lock(); impl<'a> /*trait*/ QBasicMutex_lock<()> for () { fn lock(self , rsthis: & QBasicMutex) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QBasicMutex4lockEv()}; unsafe {C_ZN11QBasicMutex4lockEv(rsthis.qclsinst)}; // return 1; } } // proto: bool QBasicMutex::tryLock(); impl /*struct*/ QBasicMutex { pub fn tryLock<RetType, T: QBasicMutex_tryLock<RetType>>(& self, overload_args: T) -> RetType { return overload_args.tryLock(self); // return 1; } } pub trait QBasicMutex_tryLock<RetType> { fn tryLock(self , rsthis: & QBasicMutex) -> RetType; } // proto: bool QBasicMutex::tryLock(); impl<'a> /*trait*/ QBasicMutex_tryLock<i8> for () { fn tryLock(self , rsthis: & QBasicMutex) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QBasicMutex7tryLockEv()}; let mut ret = unsafe {C_ZN11QBasicMutex7tryLockEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: bool QBasicMutex::isRecursive(); impl /*struct*/ QBasicMutex { pub fn isRecursive<RetType, T: QBasicMutex_isRecursive<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isRecursive(self); // return 1; } } pub trait QBasicMutex_isRecursive<RetType> { fn isRecursive(self , rsthis: & QBasicMutex) -> RetType; } // proto: bool QBasicMutex::isRecursive(); impl<'a> /*trait*/ QBasicMutex_isRecursive<i8> for () { fn isRecursive(self , rsthis: & QBasicMutex) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QBasicMutex11isRecursiveEv()}; let mut ret = unsafe {C_ZN11QBasicMutex11isRecursiveEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: void QBasicMutex::unlock(); impl /*struct*/ QBasicMutex { pub fn unlock<RetType, T: QBasicMutex_unlock<RetType>>(& self, overload_args: T) -> RetType { return overload_args.unlock(self); // return 1; } } pub trait QBasicMutex_unlock<RetType> { fn unlock(self , rsthis: & QBasicMutex) -> RetType; } // proto: void QBasicMutex::unlock(); impl<'a> /*trait*/ QBasicMutex_unlock<()> for () { fn unlock(self , rsthis: & QBasicMutex) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QBasicMutex6unlockEv()}; unsafe {C_ZN11QBasicMutex6unlockEv(rsthis.qclsinst)}; // return 1; } } impl /*struct*/ QMutex { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMutex { return QMutex{qbase: QBasicMutex::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QMutex { type Target = QBasicMutex; fn deref(&self) -> &QBasicMutex { return & self.qbase; } } impl AsRef<QBasicMutex> for QMutex { fn as_ref(& self) -> & QBasicMutex { return & self.qbase; } } // proto: void QMutex::~QMutex(); impl /*struct*/ QMutex { pub fn free<RetType, T: QMutex_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QMutex_free<RetType> { fn free(self , rsthis: & QMutex) -> RetType; } // proto: void QMutex::~QMutex(); impl<'a> /*trait*/ QMutex_free<()> for () { fn free(self , rsthis: & QMutex) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN6QMutexD2Ev()}; unsafe {C_ZN6QMutexD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: bool QMutex::tryLock(int timeout); impl /*struct*/ QMutex { pub fn tryLock<RetType, T: QMutex_tryLock<RetType>>(& self, overload_args: T) -> RetType { return overload_args.tryLock(self); // return 1; } } pub trait QMutex_tryLock<RetType> { fn tryLock(self , rsthis: & QMutex) -> RetType; } // proto: bool QMutex::tryLock(int timeout); impl<'a> /*trait*/ QMutex_tryLock<i8> for (Option<i32>) { fn tryLock(self , rsthis: & QMutex) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN6QMutex7tryLockEi()}; let arg0 = (if self.is_none() {0} else {self.unwrap()}) as c_int; let mut ret = unsafe {C_ZN6QMutex7tryLockEi(rsthis.qclsinst, arg0)}; return ret as i8; // 1 // return 1; } } // proto: void QMutex::lock(); impl /*struct*/ QMutex { pub fn lock<RetType, T: QMutex_lock<RetType>>(& self, overload_args: T) -> RetType { return overload_args.lock(self); // return 1; } } pub trait QMutex_lock<RetType> { fn lock(self , rsthis: & QMutex) -> RetType; } // proto: void QMutex::lock(); impl<'a> /*trait*/ QMutex_lock<()> for () { fn lock(self , rsthis: & QMutex) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN6QMutex4lockEv()}; unsafe {C_ZN6QMutex4lockEv(rsthis.qclsinst)}; // return 1; } } // proto: void QMutex::unlock(); impl /*struct*/ QMutex { pub fn unlock<RetType, T: QMutex_unlock<RetType>>(& self, overload_args: T) -> RetType { return overload_args.unlock(self); // return 1; } } pub trait QMutex_unlock<RetType> { fn unlock(self , rsthis: & QMutex) -> RetType; } // proto: void QMutex::unlock(); impl<'a> /*trait*/ QMutex_unlock<()> for () { fn unlock(self , rsthis: & QMutex) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN6QMutex6unlockEv()}; unsafe {C_ZN6QMutex6unlockEv(rsthis.qclsinst)}; // return 1; } } // <= body block end
//! Self-contained dependency graph for a set of packages. use std::collections::{BTreeMap, HashSet}; use std::error::Error; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::sync::Arc; use deck_core::{Manifest, ManifestId, OutputId}; type Result<T> = std::result::Result<T, ClosureError>; /// Self-contained dependency graph for a set of packages. #[derive(Clone, Debug)] pub struct Closure { target: ManifestId, packages: Arc<BTreeMap<ManifestId, Manifest>>, } impl Closure { /// Creates a new `Closure` for the given target `ManifestId` with the specified `packages`. pub fn new(target: ManifestId, packages: HashSet<Manifest>) -> Result<Self> { let with_ids: BTreeMap<ManifestId, Manifest> = packages .into_iter() .map(|manifest| (manifest.compute_id(), manifest)) .collect(); validate_closure(target.clone(), &with_ids)?; Ok(Closure { target, packages: Arc::new(with_ids), }) } /// Returns the target `ManifestId` represented by this closure. #[inline] pub fn target(&self) -> &ManifestId { &self.target } /// Returns the target `Manifest` represented by this closure. #[inline] pub fn target_manifest(&self) -> &Manifest { &self.packages[&self.target] } /// Returns a set of sub-closures for each dependency of the target. #[inline] pub fn dependent_closures(&self) -> impl Iterator<Item = Closure> + '_ { let packages = self.packages.clone(); self.target_manifest() .dependencies() .cloned() .map(move |dep| Closure { target: dep, packages: packages.clone(), }) } } /// Checks the given set of packages against the target `ManifestId` and checks whether the /// essential properties hold, namely: /// /// 1. For this closure and all dependent closures, `target` must be contained within `packages`. /// 2. For all dependencies in this closure, there must be no direct cycles (however, note that /// filesystem-level self-references within an output are allowed). /// 3. For all outputs specified in `target`, each set of references must correspond to exactly one /// declared dependency. Undeclared references and references to build/dev dependencies are /// disallowed. fn validate_closure(target: ManifestId, packages: &BTreeMap<ManifestId, Manifest>) -> Result<()> { let manifest = packages .get(&target) .ok_or_else(|| ClosureError::MissingTarget(target.clone()))?; for dep in manifest.dependencies() { if *dep == target { return Err(ClosureError::CycleDetected(target)); } if packages.contains_key(&dep) { return validate_closure(dep.clone(), packages); } else { return Err(ClosureError::MissingDependency { package: target, dependency: dep.clone(), }); } } for out in manifest.outputs() { if !manifest.dependencies().any(|dep| dep.is_same_package(&out)) { return Err(ClosureError::InvalidInput { package: target, input: out.clone(), }); } } Ok(()) } /// Types of errors that can occur while constructing and validating closures. #[derive(Clone, Debug, Eq, PartialEq)] pub enum ClosureError { /// A package contained a dependency on itself. CycleDetected(ManifestId), /// A package references an output that is not declared in the package dependencies. InvalidInput { /// Package which contained the invalid reference. package: ManifestId, /// The invalid reference in question. input: OutputId, }, /// Closure for `package` lacks the manifest information for a required dependency. MissingDependency { /// Package's closure being evaluated. package: ManifestId, /// The missing dependency in question. dependency: ManifestId, }, /// Closure lacks the manifest information for its own target. MissingTarget(ManifestId), } impl Display for ClosureError { fn fmt(&self, fmt: &mut Formatter) -> FmtResult { use self::ClosureError::*; match *self { CycleDetected(ref pkg) => { write!(fmt, "manifest {} contains a dependency on itself", pkg) } InvalidInput { ref package, ref input, } => write!( fmt, "manifest {} references output {}, but its parent package is not in `dependencies`", package, input ), MissingDependency { ref package, ref dependency, } => write!( fmt, "closure for {} is missing manifest information for dependency {}", package, dependency ), MissingTarget(ref pkg) => write!( fmt, "closure for {} is missing manifest information of its target", pkg ), } } } impl Error for ClosureError { fn source(&self) -> Option<&(dyn Error + 'static)> { None } }
extern crate cfnetwork; use cfnetwork::*; fn main() { unsafe { println!("{:?}", CFHostGetTypeID()); println!("{:?}", CFHTTPAuthenticationGetTypeID()); println!("{:?}", CFHTTPMessageGetTypeID()); println!("{:?}", CFNetServiceGetTypeID()); println!("{:?}", CFNetServiceMonitorGetTypeID()); println!("{:?}", CFNetServiceBrowserGetTypeID()); } }
#[doc = r"Value read from the register"] pub struct R { bits: u8, } #[doc = r"Value to write to the register"] pub struct W { bits: u8, } impl super::DEVCTL { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u8 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct USB_DEVCTL_SESSIONR { bits: bool, } impl USB_DEVCTL_SESSIONR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DEVCTL_SESSIONW<'a> { w: &'a mut W, } impl<'a> _USB_DEVCTL_SESSIONW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u8) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct USB_DEVCTL_HOSTREQR { bits: bool, } impl USB_DEVCTL_HOSTREQR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DEVCTL_HOSTREQW<'a> { w: &'a mut W, } impl<'a> _USB_DEVCTL_HOSTREQW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u8) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct USB_DEVCTL_HOSTR { bits: bool, } impl USB_DEVCTL_HOSTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DEVCTL_HOSTW<'a> { w: &'a mut W, } impl<'a> _USB_DEVCTL_HOSTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u8) & 1) << 2; self.w } } #[doc = "Possible values of the field `USB_DEVCTL_VBUS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USB_DEVCTL_VBUSR { #[doc = "Below SessionEnd"] USB_DEVCTL_VBUS_NONE, #[doc = "Above SessionEnd, below AValid"] USB_DEVCTL_VBUS_SEND, #[doc = "Above AValid, below VBUSValid"] USB_DEVCTL_VBUS_AVALID, #[doc = "Above VBUSValid"] USB_DEVCTL_VBUS_VALID, } impl USB_DEVCTL_VBUSR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_NONE => 0, USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_SEND => 1, USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_AVALID => 2, USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_VALID => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> USB_DEVCTL_VBUSR { match value { 0 => USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_NONE, 1 => USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_SEND, 2 => USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_AVALID, 3 => USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_VALID, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `USB_DEVCTL_VBUS_NONE`"] #[inline(always)] pub fn is_usb_devctl_vbus_none(&self) -> bool { *self == USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_NONE } #[doc = "Checks if the value of the field is `USB_DEVCTL_VBUS_SEND`"] #[inline(always)] pub fn is_usb_devctl_vbus_send(&self) -> bool { *self == USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_SEND } #[doc = "Checks if the value of the field is `USB_DEVCTL_VBUS_AVALID`"] #[inline(always)] pub fn is_usb_devctl_vbus_avalid(&self) -> bool { *self == USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_AVALID } #[doc = "Checks if the value of the field is `USB_DEVCTL_VBUS_VALID`"] #[inline(always)] pub fn is_usb_devctl_vbus_valid(&self) -> bool { *self == USB_DEVCTL_VBUSR::USB_DEVCTL_VBUS_VALID } } #[doc = "Values that can be written to the field `USB_DEVCTL_VBUS`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USB_DEVCTL_VBUSW { #[doc = "Below SessionEnd"] USB_DEVCTL_VBUS_NONE, #[doc = "Above SessionEnd, below AValid"] USB_DEVCTL_VBUS_SEND, #[doc = "Above AValid, below VBUSValid"] USB_DEVCTL_VBUS_AVALID, #[doc = "Above VBUSValid"] USB_DEVCTL_VBUS_VALID, } impl USB_DEVCTL_VBUSW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { USB_DEVCTL_VBUSW::USB_DEVCTL_VBUS_NONE => 0, USB_DEVCTL_VBUSW::USB_DEVCTL_VBUS_SEND => 1, USB_DEVCTL_VBUSW::USB_DEVCTL_VBUS_AVALID => 2, USB_DEVCTL_VBUSW::USB_DEVCTL_VBUS_VALID => 3, } } } #[doc = r"Proxy"] pub struct _USB_DEVCTL_VBUSW<'a> { w: &'a mut W, } impl<'a> _USB_DEVCTL_VBUSW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USB_DEVCTL_VBUSW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Below SessionEnd"] #[inline(always)] pub fn usb_devctl_vbus_none(self) -> &'a mut W { self.variant(USB_DEVCTL_VBUSW::USB_DEVCTL_VBUS_NONE) } #[doc = "Above SessionEnd, below AValid"] #[inline(always)] pub fn usb_devctl_vbus_send(self) -> &'a mut W { self.variant(USB_DEVCTL_VBUSW::USB_DEVCTL_VBUS_SEND) } #[doc = "Above AValid, below VBUSValid"] #[inline(always)] pub fn usb_devctl_vbus_avalid(self) -> &'a mut W { self.variant(USB_DEVCTL_VBUSW::USB_DEVCTL_VBUS_AVALID) } #[doc = "Above VBUSValid"] #[inline(always)] pub fn usb_devctl_vbus_valid(self) -> &'a mut W { self.variant(USB_DEVCTL_VBUSW::USB_DEVCTL_VBUS_VALID) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 3); self.w.bits |= ((value as u8) & 3) << 3; self.w } } #[doc = r"Value of the field"] pub struct USB_DEVCTL_LSDEVR { bits: bool, } impl USB_DEVCTL_LSDEVR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DEVCTL_LSDEVW<'a> { w: &'a mut W, } impl<'a> _USB_DEVCTL_LSDEVW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u8) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct USB_DEVCTL_FSDEVR { bits: bool, } impl USB_DEVCTL_FSDEVR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DEVCTL_FSDEVW<'a> { w: &'a mut W, } impl<'a> _USB_DEVCTL_FSDEVW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u8) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct USB_DEVCTL_DEVR { bits: bool, } impl USB_DEVCTL_DEVR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_DEVCTL_DEVW<'a> { w: &'a mut W, } impl<'a> _USB_DEVCTL_DEVW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u8) & 1) << 7; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } #[doc = "Bit 0 - Session Start/End (OTG only)"] #[inline(always)] pub fn usb_devctl_session(&self) -> USB_DEVCTL_SESSIONR { let bits = ((self.bits >> 0) & 1) != 0; USB_DEVCTL_SESSIONR { bits } } #[doc = "Bit 1 - Host Request (OTG only)"] #[inline(always)] pub fn usb_devctl_hostreq(&self) -> USB_DEVCTL_HOSTREQR { let bits = ((self.bits >> 1) & 1) != 0; USB_DEVCTL_HOSTREQR { bits } } #[doc = "Bit 2 - Host Mode"] #[inline(always)] pub fn usb_devctl_host(&self) -> USB_DEVCTL_HOSTR { let bits = ((self.bits >> 2) & 1) != 0; USB_DEVCTL_HOSTR { bits } } #[doc = "Bits 3:4 - VBUS Level (OTG only)"] #[inline(always)] pub fn usb_devctl_vbus(&self) -> USB_DEVCTL_VBUSR { USB_DEVCTL_VBUSR::_from(((self.bits >> 3) & 3) as u8) } #[doc = "Bit 5 - Low-Speed Device Detected"] #[inline(always)] pub fn usb_devctl_lsdev(&self) -> USB_DEVCTL_LSDEVR { let bits = ((self.bits >> 5) & 1) != 0; USB_DEVCTL_LSDEVR { bits } } #[doc = "Bit 6 - Full-Speed Device Detected"] #[inline(always)] pub fn usb_devctl_fsdev(&self) -> USB_DEVCTL_FSDEVR { let bits = ((self.bits >> 6) & 1) != 0; USB_DEVCTL_FSDEVR { bits } } #[doc = "Bit 7 - Device Mode (OTG only)"] #[inline(always)] pub fn usb_devctl_dev(&self) -> USB_DEVCTL_DEVR { let bits = ((self.bits >> 7) & 1) != 0; USB_DEVCTL_DEVR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u8) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Session Start/End (OTG only)"] #[inline(always)] pub fn usb_devctl_session(&mut self) -> _USB_DEVCTL_SESSIONW { _USB_DEVCTL_SESSIONW { w: self } } #[doc = "Bit 1 - Host Request (OTG only)"] #[inline(always)] pub fn usb_devctl_hostreq(&mut self) -> _USB_DEVCTL_HOSTREQW { _USB_DEVCTL_HOSTREQW { w: self } } #[doc = "Bit 2 - Host Mode"] #[inline(always)] pub fn usb_devctl_host(&mut self) -> _USB_DEVCTL_HOSTW { _USB_DEVCTL_HOSTW { w: self } } #[doc = "Bits 3:4 - VBUS Level (OTG only)"] #[inline(always)] pub fn usb_devctl_vbus(&mut self) -> _USB_DEVCTL_VBUSW { _USB_DEVCTL_VBUSW { w: self } } #[doc = "Bit 5 - Low-Speed Device Detected"] #[inline(always)] pub fn usb_devctl_lsdev(&mut self) -> _USB_DEVCTL_LSDEVW { _USB_DEVCTL_LSDEVW { w: self } } #[doc = "Bit 6 - Full-Speed Device Detected"] #[inline(always)] pub fn usb_devctl_fsdev(&mut self) -> _USB_DEVCTL_FSDEVW { _USB_DEVCTL_FSDEVW { w: self } } #[doc = "Bit 7 - Device Mode (OTG only)"] #[inline(always)] pub fn usb_devctl_dev(&mut self) -> _USB_DEVCTL_DEVW { _USB_DEVCTL_DEVW { w: self } } }
#[cfg(target_os = "linux")] use honggfuzz::fuzz; #[cfg(target_os = "linux")] fn main() { loop { fuzz!(|data: &[u8]| { if data.len() != 3 { return; } if data[0] != b'h' { return; } if data[1] != b'e' { return; } if data[2] != b'y' { return; } panic!("BOOM") }); } }
extern crate gotham; extern crate handlebars_gotham as hbs; extern crate hyper; extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; #[macro_use] extern crate maplit; extern crate mime; use gotham::state::State; use gotham::http::response::create_response; use gotham::handler::{NewHandlerService, NewHandler}; use gotham::middleware::pipeline::new_pipeline; use gotham::router::Router; use gotham::router::route::{Extractors, Route, RouteImpl, Delegation}; use gotham::router::route::dispatch::{new_pipeline_set, finalize_pipeline_set, PipelineSet, PipelineHandleChain, DispatcherImpl}; use gotham::router::route::matcher::MethodOnlyRouteMatcher; use gotham::router::request::path::NoopPathExtractor; use gotham::router::request::query_string::NoopQueryStringExtractor; use gotham::router::response::finalizer::ResponseFinalizerBuilder; use gotham::router::tree::TreeBuilder; use gotham::router::tree::node::{NodeBuilder, SegmentType}; use hbs::{Template, HandlebarsEngine, DirectorySource, MemorySource}; use hbs::handlebars::{Handlebars, RenderContext, RenderError, Helper, to_json}; use hyper::server::Http; use hyper::{Method, Request, Response, StatusCode}; use serde_json::value::{Value, Map}; #[derive(Serialize, Debug)] pub struct Team { name: String, pts: u16, } pub fn make_data() -> Map<String, Value> { let mut data = Map::new(); data.insert("year".to_string(), to_json(&"2017".to_owned())); let teams = vec![ Team { name: "Jiangsu Sainty".to_string(), pts: 43u16, }, Team { name: "Beijing Guoan".to_string(), pts: 27u16, }, Team { name: "Guangzhou Evergrand".to_string(), pts: 22u16, }, Team { name: "Shandong Luneng".to_string(), pts: 12u16, }, ]; data.insert("teams".to_string(), to_json(&teams)); data.insert("engine".to_string(), to_json(&"serde_json".to_owned())); data } /// the handlers fn index(mut state: State, _req: Request) -> (State, Response) { state.put(Template::new("some/path/hello", make_data())); let res = create_response(&state, StatusCode::Ok, None); (state, res) } fn memory(mut state: State, _req: Request) -> (State, Response) { state.put(Template::new("memory", make_data())); let res = create_response(&state, StatusCode::Ok, None); (state, res) } fn temp(mut state: State, _req: Request) -> (State, Response) { state.put(Template::with( include_str!("templates/some/path/hello.hbs"), make_data(), )); let res = create_response(&state, StatusCode::Ok, None); (state, res) } fn plain(state: State, _req: Request) -> (State, Response) { let res = create_response( &state, StatusCode::Ok, Some(("It works".as_bytes().to_owned(), mime::TEXT_PLAIN)), ); (state, res) } fn main() { let mem_templates = btreemap! { "memory".to_owned() => include_str!("templates/some/path/hello.hbs").to_owned() }; let hbse = HandlebarsEngine::new(vec![ Box::new( DirectorySource::new("./examples/templates/", ".hbs") ), Box::new(MemorySource(mem_templates)), ]); // load templates from all registered sources if let Err(r) = hbse.reload() { panic!("{}", r); } hbse.handlebars_mut().register_helper( "some_helper", Box::new(|_: &Helper, _: &Handlebars, _: &mut RenderContext| -> Result<(), RenderError> { Ok(()) }), ); // -________________________- start let mut tree_builder = TreeBuilder::new(); let ps_builder = new_pipeline_set(); let (ps_builder, global) = ps_builder.add(new_pipeline().add(hbse).build()); let ps = finalize_pipeline_set(ps_builder); tree_builder.add_route(static_route( vec![Method::Get], || Ok(index), (global, ()), ps.clone(), )); let mut memory_handler = NodeBuilder::new("memory", SegmentType::Static); memory_handler.add_route(static_route( vec![Method::Get], || Ok(memory), (global, ()), ps.clone(), )); tree_builder.add_child(memory_handler); let mut temp_handler = NodeBuilder::new("temp", SegmentType::Static); temp_handler.add_route(static_route( vec![Method::Get], || Ok(temp), (global, ()), ps.clone(), )); tree_builder.add_child(temp_handler); let mut plain_handler = NodeBuilder::new("plain", SegmentType::Static); plain_handler.add_route(static_route( vec![Method::Get], || Ok(plain), (global, ()), ps.clone(), )); tree_builder.add_child(plain_handler); let tree = tree_builder.finalize(); let response_finalizer_builder = ResponseFinalizerBuilder::new(); let response_finalizer = response_finalizer_builder.finalize(); let router = Router::new(tree, response_finalizer); // -____________________________- end let addr = "127.0.0.1:7878".parse().unwrap(); let server = Http::new() .bind(&addr, NewHandlerService::new(router)) .unwrap(); println!("Listening on http://{}", server.local_addr().unwrap()); server.run().unwrap(); } // router copied from gotham example fn static_route<NH, P, C>( methods: Vec<Method>, new_handler: NH, active_pipelines: C, ps: PipelineSet<P>, ) -> Box<Route + Send + Sync> where NH: NewHandler + 'static, C: PipelineHandleChain<P> + Send + Sync + 'static, P: Send + Sync + 'static, { // Requests must have used the specified method(s) in order for this Route to match. // // You could define your on RouteMatcher of course.. perhaps you'd like to only match on // requests that are made using the GET method and send a User-Agent header for a particular // version of browser you'd like to make fun of.... let matcher = MethodOnlyRouteMatcher::new(methods); // For Requests that match this Route we'll dispatch them to new_handler via the pipelines // defined in active_pipelines. // // n.b. We also specify the set of all known pipelines in the application so the dispatcher can // resolve the pipeline references provided in active_pipelines. For this application that is // only the global pipeline. let dispatcher = DispatcherImpl::new(new_handler, active_pipelines, ps); let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> = Extractors::new(); let route = RouteImpl::new( matcher, Box::new(dispatcher), extractors, Delegation::Internal, ); Box::new(route) } //
use super::input::Input; use crate::{runner::RunResult, values::InputGeneration}; use candy_vm::heap::{Heap, SymbolTable}; use itertools::Itertools; use rand::{rngs::ThreadRng, seq::SliceRandom, Rng}; use rustc_hash::FxHashMap; use std::{cell::RefCell, rc::Rc}; pub type Score = f64; pub struct InputPool { heap: Rc<RefCell<Heap>>, num_args: usize, symbol_table: SymbolTable, results_and_scores: FxHashMap<Input, (RunResult, Score)>, } impl InputPool { pub fn new(num_args: usize, symbol_table: SymbolTable) -> Self { Self { heap: Rc::default(), num_args, symbol_table, results_and_scores: FxHashMap::default(), } } pub fn generate_new_input(&self) -> Input { loop { let input = self.generate_input(); if !self.results_and_scores.contains_key(&input) { return input; } } } pub fn generate_input(&self) -> Input { let mut rng = ThreadRng::default(); if rng.gen_bool(0.1) || self.results_and_scores.len() < 20 { return Input::generate(self.heap.clone(), self.num_args, &self.symbol_table); } let inputs_and_scores = self.results_and_scores.iter().collect_vec(); let (input, _) = inputs_and_scores .choose_weighted(&mut rng, |(_, (_, score))| *score) .unwrap(); let mut input = (**input).clone(); input.mutate(&mut rng, &self.symbol_table); input } pub fn add(&mut self, input: Input, result: RunResult, score: Score) { self.results_and_scores.insert(input, (result, score)); } pub fn interesting_inputs(&self) -> Vec<Input> { self.results_and_scores .iter() .sorted_by( |(_, (result_a, mut score_a)), (_, (result_b, mut score_b))| { if matches!(result_a, RunResult::Done { .. }) { score_a += 50.; } if matches!(result_b, RunResult::Done { .. }) { score_b += 50.; } score_a.partial_cmp(&score_b).unwrap() }, ) .rev() .take(3) .map(|(input, _)| input.clone()) .collect_vec() } pub fn result_of(&self, input: &Input) -> &RunResult { &self.results_and_scores.get(input).unwrap().0 } }
#[macro_use] extern crate lazy_static; extern crate itertools; extern crate regex; use itertools::Itertools; use regex::Regex; #[derive(Clone)] struct Claim { id: i32, offset_left: i32, offset_top: i32, width: i32, height: i32, } impl Claim { fn parse(raw_claim: &str) -> Claim { lazy_static! { static ref CLAIM_REGEX: Regex = Regex::new(r"^#(\d+) @ (\d+),(\d+): (\d+)x(\d+)$").unwrap(); } let captures = CLAIM_REGEX.captures(raw_claim).unwrap(); Claim { id: captures.get(1).unwrap().as_str().parse::<i32>().unwrap(), offset_left: captures.get(2).unwrap().as_str().parse::<i32>().unwrap(), offset_top: captures.get(3).unwrap().as_str().parse::<i32>().unwrap(), width: captures.get(4).unwrap().as_str().parse::<i32>().unwrap(), height: captures.get(5).unwrap().as_str().parse::<i32>().unwrap(), } } fn coordinates(self) -> Vec<(i32, i32)> { let mut coords = Vec::new(); for x in 0..self.width { for y in 0..self.height { coords.push((x + self.offset_left, y + self.offset_top)); } } coords } } fn overlapping_inches(input: String) -> i32 { let mut claims: Vec<Claim> = Vec::new(); for raw_claim in input.split("\n") { claims.push(Claim::parse(raw_claim)); } let coords = claims.into_iter().flat_map(|x| x.coordinates()).sorted(); let mut prev = (-1, -1); let mut checked = false; let mut overlaps = 0; for c in coords { if prev == c && !checked { overlaps += 1; checked = true; } else if prev != c { checked = false; } prev = c; } overlaps } fn main() { let input = include_str!("input.txt").into(); println!("{}", overlapping_inches(input)); } #[test] fn test_03() { let input = vec!["#1 @ 1,3: 4x4", "#2 @ 3,1: 4x4", "#3 @ 5,5: 2x2"]; let result = overlapping_inches(input.join("\n")); assert_eq!(result, 4); }
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let s: u32 = rd.get(); let t: u32 = rd.get(); let mut ans = 0_u32; for a in 0..=s { for b in 0..=s { for c in 0..=s { if a + b + c <= s && a * b * c <= t { ans += 1; } } } } println!("{}", ans); }
use std::collections::{HashMap, HashSet}; use crate::{ parser::types::{Field, Selection, SelectionSet}, validation::visitor::{Visitor, VisitorContext}, Positioned, }; #[derive(Default)] pub struct OverlappingFieldsCanBeMerged; impl<'a> Visitor<'a> for OverlappingFieldsCanBeMerged { fn enter_selection_set( &mut self, ctx: &mut VisitorContext<'a>, selection_set: &'a Positioned<SelectionSet>, ) { let mut find_conflicts = FindConflicts { outputs: Default::default(), visited: Default::default(), ctx, }; find_conflicts.find(None, selection_set); } } struct FindConflicts<'a, 'ctx> { outputs: HashMap<(Option<&'a str>, &'a str), &'a Positioned<Field>>, visited: HashSet<&'a str>, ctx: &'a mut VisitorContext<'ctx>, } impl<'a, 'ctx> FindConflicts<'a, 'ctx> { pub fn find(&mut self, on_type: Option<&'a str>, selection_set: &'a Positioned<SelectionSet>) { for selection in &selection_set.node.items { match &selection.node { Selection::Field(field) => { let output_name = field .node .alias .as_ref() .map(|name| &name.node) .unwrap_or_else(|| &field.node.name.node); self.add_output(on_type, &output_name, field); } Selection::InlineFragment(inline_fragment) => { let on_type = inline_fragment .node .type_condition .as_ref() .map(|cond| cond.node.on.node.as_str()); self.find(on_type, &inline_fragment.node.selection_set); } Selection::FragmentSpread(fragment_spread) => { if let Some(fragment) = self.ctx.fragment(&fragment_spread.node.fragment_name.node) { let on_type = Some(fragment.node.type_condition.node.on.node.as_str()); if !self .visited .insert(fragment_spread.node.fragment_name.node.as_str()) { // To avoid recursing itself, this error is detected by the // `NoFragmentCycles` validator. continue; } self.find(on_type, &fragment.node.selection_set); } } } } } fn add_output( &mut self, on_type: Option<&'a str>, name: &'a str, field: &'a Positioned<Field>, ) { if let Some(prev_field) = self.outputs.get(&(on_type, name)) { if prev_field.node.name.node != field.node.name.node { self.ctx.report_error( vec![prev_field.pos, field.pos], format!("Fields \"{}\" conflict because \"{}\" and \"{}\" are different fields. Use different aliases on the fields to fetch both if this was intentional.", name, prev_field.node.name.node, field.node.name.node)); } // check arguments if prev_field.node.arguments.len() != field.node.arguments.len() { self.ctx.report_error( vec![prev_field.pos, field.pos], format!("Fields \"{}\" conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional.", name)); } for (name, value) in &prev_field.node.arguments { match field.node.get_argument(&name.node) { Some(other_value) if value == other_value => {} _=> self.ctx.report_error( vec![prev_field.pos, field.pos], format!("Fields \"{}\" conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional.", name)), } } } else { self.outputs.insert((on_type, name), field); } } } #[cfg(test)] mod tests { use super::*; pub fn factory() -> OverlappingFieldsCanBeMerged { OverlappingFieldsCanBeMerged } #[test] fn same_field_on_different_type() { expect_passes_rule!( factory, r#" { pet { ... on Dog { doesKnowCommand(dogCommand: SIT) } ... on Cat { doesKnowCommand(catCommand: JUMP) } } } "#, ); } #[test] fn same_field_on_same_type() { expect_fails_rule!( factory, r#" { pet { ... on Dog { doesKnowCommand(dogCommand: SIT) } ... on Dog { doesKnowCommand(dogCommand: Heel) } } } "#, ); } #[test] fn same_alias_on_different_type() { expect_passes_rule!( factory, r#" { pet { ... on Dog { volume: barkVolume } ... on Cat { volume: meowVolume } } } "#, ); } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - OTG_FS host configuration register (OTG_FS_HCFG)"] pub otg_fs_hcfg: OTG_FS_HCFG, #[doc = "0x04 - OTG_FS Host frame interval register"] pub otg_fs_hfir: OTG_FS_HFIR, #[doc = "0x08 - OTG_FS host frame number/frame time remaining register (OTG_FS_HFNUM)"] pub otg_fs_hfnum: OTG_FS_HFNUM, _reserved3: [u8; 4usize], #[doc = "0x10 - OTG_FS_Host periodic transmit FIFO/queue status register (OTG_FS_HPTXSTS)"] pub otg_fs_hptxsts: OTG_FS_HPTXSTS, #[doc = "0x14 - OTG_FS Host all channels interrupt register"] pub otg_fs_haint: OTG_FS_HAINT, #[doc = "0x18 - OTG_FS host all channels interrupt mask register"] pub otg_fs_haintmsk: OTG_FS_HAINTMSK, _reserved6: [u8; 36usize], #[doc = "0x40 - OTG_FS host port control and status register (OTG_FS_HPRT)"] pub otg_fs_hprt: OTG_FS_HPRT, _reserved7: [u8; 188usize], #[doc = "0x100 - OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)"] pub otg_fs_hcchar0: OTG_FS_HCCHAR0, _reserved8: [u8; 4usize], #[doc = "0x108 - OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)"] pub otg_fs_hcint0: OTG_FS_HCINT0, #[doc = "0x10c - OTG_FS host channel-0 mask register (OTG_FS_HCINTMSK0)"] pub otg_fs_hcintmsk0: OTG_FS_HCINTMSK0, #[doc = "0x110 - OTG_FS host channel-0 transfer size register"] pub otg_fs_hctsiz0: OTG_FS_HCTSIZ0, _reserved11: [u8; 12usize], #[doc = "0x120 - OTG_FS host channel-1 characteristics register (OTG_FS_HCCHAR1)"] pub otg_fs_hcchar1: OTG_FS_HCCHAR1, _reserved12: [u8; 4usize], #[doc = "0x128 - OTG_FS host channel-1 interrupt register (OTG_FS_HCINT1)"] pub otg_fs_hcint1: OTG_FS_HCINT1, #[doc = "0x12c - OTG_FS host channel-1 mask register (OTG_FS_HCINTMSK1)"] pub otg_fs_hcintmsk1: OTG_FS_HCINTMSK1, #[doc = "0x130 - OTG_FS host channel-1 transfer size register"] pub otg_fs_hctsiz1: OTG_FS_HCTSIZ1, _reserved15: [u8; 12usize], #[doc = "0x140 - OTG_FS host channel-2 characteristics register (OTG_FS_HCCHAR2)"] pub otg_fs_hcchar2: OTG_FS_HCCHAR2, _reserved16: [u8; 4usize], #[doc = "0x148 - OTG_FS host channel-2 interrupt register (OTG_FS_HCINT2)"] pub otg_fs_hcint2: OTG_FS_HCINT2, #[doc = "0x14c - OTG_FS host channel-2 mask register (OTG_FS_HCINTMSK2)"] pub otg_fs_hcintmsk2: OTG_FS_HCINTMSK2, #[doc = "0x150 - OTG_FS host channel-2 transfer size register"] pub otg_fs_hctsiz2: OTG_FS_HCTSIZ2, _reserved19: [u8; 12usize], #[doc = "0x160 - OTG_FS host channel-3 characteristics register (OTG_FS_HCCHAR3)"] pub otg_fs_hcchar3: OTG_FS_HCCHAR3, _reserved20: [u8; 4usize], #[doc = "0x168 - OTG_FS host channel-3 interrupt register (OTG_FS_HCINT3)"] pub otg_fs_hcint3: OTG_FS_HCINT3, #[doc = "0x16c - OTG_FS host channel-3 mask register (OTG_FS_HCINTMSK3)"] pub otg_fs_hcintmsk3: OTG_FS_HCINTMSK3, #[doc = "0x170 - OTG_FS host channel-3 transfer size register"] pub otg_fs_hctsiz3: OTG_FS_HCTSIZ3, _reserved23: [u8; 12usize], #[doc = "0x180 - OTG_FS host channel-4 characteristics register (OTG_FS_HCCHAR4)"] pub otg_fs_hcchar4: OTG_FS_HCCHAR4, _reserved24: [u8; 4usize], #[doc = "0x188 - OTG_FS host channel-4 interrupt register (OTG_FS_HCINT4)"] pub otg_fs_hcint4: OTG_FS_HCINT4, #[doc = "0x18c - OTG_FS host channel-4 mask register (OTG_FS_HCINTMSK4)"] pub otg_fs_hcintmsk4: OTG_FS_HCINTMSK4, #[doc = "0x190 - OTG_FS host channel-x transfer size register"] pub otg_fs_hctsiz4: OTG_FS_HCTSIZ4, _reserved27: [u8; 12usize], #[doc = "0x1a0 - OTG_FS host channel-5 characteristics register (OTG_FS_HCCHAR5)"] pub otg_fs_hcchar5: OTG_FS_HCCHAR5, _reserved28: [u8; 4usize], #[doc = "0x1a8 - OTG_FS host channel-5 interrupt register (OTG_FS_HCINT5)"] pub otg_fs_hcint5: OTG_FS_HCINT5, #[doc = "0x1ac - OTG_FS host channel-5 mask register (OTG_FS_HCINTMSK5)"] pub otg_fs_hcintmsk5: OTG_FS_HCINTMSK5, #[doc = "0x1b0 - OTG_FS host channel-5 transfer size register"] pub otg_fs_hctsiz5: OTG_FS_HCTSIZ5, _reserved31: [u8; 12usize], #[doc = "0x1c0 - OTG_FS host channel-6 characteristics register (OTG_FS_HCCHAR6)"] pub otg_fs_hcchar6: OTG_FS_HCCHAR6, _reserved32: [u8; 4usize], #[doc = "0x1c8 - OTG_FS host channel-6 interrupt register (OTG_FS_HCINT6)"] pub otg_fs_hcint6: OTG_FS_HCINT6, #[doc = "0x1cc - OTG_FS host channel-6 mask register (OTG_FS_HCINTMSK6)"] pub otg_fs_hcintmsk6: OTG_FS_HCINTMSK6, #[doc = "0x1d0 - OTG_FS host channel-6 transfer size register"] pub otg_fs_hctsiz6: OTG_FS_HCTSIZ6, _reserved35: [u8; 12usize], #[doc = "0x1e0 - OTG_FS host channel-7 characteristics register (OTG_FS_HCCHAR7)"] pub otg_fs_hcchar7: OTG_FS_HCCHAR7, _reserved36: [u8; 4usize], #[doc = "0x1e8 - OTG_FS host channel-7 interrupt register (OTG_FS_HCINT7)"] pub otg_fs_hcint7: OTG_FS_HCINT7, #[doc = "0x1ec - OTG_FS host channel-7 mask register (OTG_FS_HCINTMSK7)"] pub otg_fs_hcintmsk7: OTG_FS_HCINTMSK7, #[doc = "0x1f0 - OTG_FS host channel-7 transfer size register"] pub otg_fs_hctsiz7: OTG_FS_HCTSIZ7, #[doc = "0x1f4 - OTG_FS host channel-8 characteristics register"] pub otg_fs_hcchar8: OTG_FS_HCCHAR8, #[doc = "0x1f8 - OTG_FS host channel-8 interrupt register"] pub otg_fs_hcint8: OTG_FS_HCINT8, #[doc = "0x1fc - OTG_FS host channel-8 mask register"] pub otg_fs_hcintmsk8: OTG_FS_HCINTMSK8, #[doc = "0x200 - OTG_FS host channel-8 transfer size register"] pub otg_fs_hctsiz8: OTG_FS_HCTSIZ8, #[doc = "0x204 - OTG_FS host channel-9 characteristics register"] pub otg_fs_hcchar9: OTG_FS_HCCHAR9, #[doc = "0x208 - OTG_FS host channel-9 interrupt register"] pub otg_fs_hcint9: OTG_FS_HCINT9, #[doc = "0x20c - OTG_FS host channel-9 mask register"] pub otg_fs_hcintmsk9: OTG_FS_HCINTMSK9, #[doc = "0x210 - OTG_FS host channel-9 transfer size register"] pub otg_fs_hctsiz9: OTG_FS_HCTSIZ9, #[doc = "0x214 - OTG_FS host channel-10 characteristics register"] pub otg_fs_hcchar10: OTG_FS_HCCHAR10, #[doc = "0x218 - OTG_FS host channel-10 interrupt register"] pub otg_fs_hcint10: OTG_FS_HCINT10, #[doc = "0x21c - OTG_FS host channel-10 mask register"] pub otg_fs_hcintmsk10: OTG_FS_HCINTMSK10, #[doc = "0x220 - OTG_FS host channel-10 transfer size register"] pub otg_fs_hctsiz10: OTG_FS_HCTSIZ10, #[doc = "0x224 - OTG_FS host channel-11 characteristics register"] pub otg_fs_hcchar11: OTG_FS_HCCHAR11, #[doc = "0x228 - OTG_FS host channel-11 interrupt register"] pub otg_fs_hcint11: OTG_FS_HCINT11, #[doc = "0x22c - OTG_FS host channel-11 mask register"] pub otg_fs_hcintmsk11: OTG_FS_HCINTMSK11, #[doc = "0x230 - OTG_FS host channel-11 transfer size register"] pub otg_fs_hctsiz11: OTG_FS_HCTSIZ11, } #[doc = "OTG_FS host configuration register (OTG_FS_HCFG)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcfg](otg_fs_hcfg) module"] pub type OTG_FS_HCFG = crate::Reg<u32, _OTG_FS_HCFG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCFG; #[doc = "`read()` method returns [otg_fs_hcfg::R](otg_fs_hcfg::R) reader structure"] impl crate::Readable for OTG_FS_HCFG {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcfg::W](otg_fs_hcfg::W) writer structure"] impl crate::Writable for OTG_FS_HCFG {} #[doc = "OTG_FS host configuration register (OTG_FS_HCFG)"] pub mod otg_fs_hcfg; #[doc = "OTG_FS Host frame interval register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hfir](otg_fs_hfir) module"] pub type OTG_FS_HFIR = crate::Reg<u32, _OTG_FS_HFIR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HFIR; #[doc = "`read()` method returns [otg_fs_hfir::R](otg_fs_hfir::R) reader structure"] impl crate::Readable for OTG_FS_HFIR {} #[doc = "`write(|w| ..)` method takes [otg_fs_hfir::W](otg_fs_hfir::W) writer structure"] impl crate::Writable for OTG_FS_HFIR {} #[doc = "OTG_FS Host frame interval register"] pub mod otg_fs_hfir; #[doc = "OTG_FS host frame number/frame time remaining register (OTG_FS_HFNUM)\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hfnum](otg_fs_hfnum) module"] pub type OTG_FS_HFNUM = crate::Reg<u32, _OTG_FS_HFNUM>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HFNUM; #[doc = "`read()` method returns [otg_fs_hfnum::R](otg_fs_hfnum::R) reader structure"] impl crate::Readable for OTG_FS_HFNUM {} #[doc = "OTG_FS host frame number/frame time remaining register (OTG_FS_HFNUM)"] pub mod otg_fs_hfnum; #[doc = "OTG_FS_Host periodic transmit FIFO/queue status register (OTG_FS_HPTXSTS)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hptxsts](otg_fs_hptxsts) module"] pub type OTG_FS_HPTXSTS = crate::Reg<u32, _OTG_FS_HPTXSTS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HPTXSTS; #[doc = "`read()` method returns [otg_fs_hptxsts::R](otg_fs_hptxsts::R) reader structure"] impl crate::Readable for OTG_FS_HPTXSTS {} #[doc = "`write(|w| ..)` method takes [otg_fs_hptxsts::W](otg_fs_hptxsts::W) writer structure"] impl crate::Writable for OTG_FS_HPTXSTS {} #[doc = "OTG_FS_Host periodic transmit FIFO/queue status register (OTG_FS_HPTXSTS)"] pub mod otg_fs_hptxsts; #[doc = "OTG_FS Host all channels interrupt register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_haint](otg_fs_haint) module"] pub type OTG_FS_HAINT = crate::Reg<u32, _OTG_FS_HAINT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HAINT; #[doc = "`read()` method returns [otg_fs_haint::R](otg_fs_haint::R) reader structure"] impl crate::Readable for OTG_FS_HAINT {} #[doc = "OTG_FS Host all channels interrupt register"] pub mod otg_fs_haint; #[doc = "OTG_FS host all channels interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_haintmsk](otg_fs_haintmsk) module"] pub type OTG_FS_HAINTMSK = crate::Reg<u32, _OTG_FS_HAINTMSK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HAINTMSK; #[doc = "`read()` method returns [otg_fs_haintmsk::R](otg_fs_haintmsk::R) reader structure"] impl crate::Readable for OTG_FS_HAINTMSK {} #[doc = "`write(|w| ..)` method takes [otg_fs_haintmsk::W](otg_fs_haintmsk::W) writer structure"] impl crate::Writable for OTG_FS_HAINTMSK {} #[doc = "OTG_FS host all channels interrupt mask register"] pub mod otg_fs_haintmsk; #[doc = "OTG_FS host port control and status register (OTG_FS_HPRT)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hprt](otg_fs_hprt) module"] pub type OTG_FS_HPRT = crate::Reg<u32, _OTG_FS_HPRT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HPRT; #[doc = "`read()` method returns [otg_fs_hprt::R](otg_fs_hprt::R) reader structure"] impl crate::Readable for OTG_FS_HPRT {} #[doc = "`write(|w| ..)` method takes [otg_fs_hprt::W](otg_fs_hprt::W) writer structure"] impl crate::Writable for OTG_FS_HPRT {} #[doc = "OTG_FS host port control and status register (OTG_FS_HPRT)"] pub mod otg_fs_hprt; #[doc = "OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar0](otg_fs_hcchar0) module"] pub type OTG_FS_HCCHAR0 = crate::Reg<u32, _OTG_FS_HCCHAR0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR0; #[doc = "`read()` method returns [otg_fs_hcchar0::R](otg_fs_hcchar0::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR0 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar0::W](otg_fs_hcchar0::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR0 {} #[doc = "OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)"] pub mod otg_fs_hcchar0; #[doc = "OTG_FS host channel-1 characteristics register (OTG_FS_HCCHAR1)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar1](otg_fs_hcchar1) module"] pub type OTG_FS_HCCHAR1 = crate::Reg<u32, _OTG_FS_HCCHAR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR1; #[doc = "`read()` method returns [otg_fs_hcchar1::R](otg_fs_hcchar1::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR1 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar1::W](otg_fs_hcchar1::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR1 {} #[doc = "OTG_FS host channel-1 characteristics register (OTG_FS_HCCHAR1)"] pub mod otg_fs_hcchar1; #[doc = "OTG_FS host channel-2 characteristics register (OTG_FS_HCCHAR2)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar2](otg_fs_hcchar2) module"] pub type OTG_FS_HCCHAR2 = crate::Reg<u32, _OTG_FS_HCCHAR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR2; #[doc = "`read()` method returns [otg_fs_hcchar2::R](otg_fs_hcchar2::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR2 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar2::W](otg_fs_hcchar2::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR2 {} #[doc = "OTG_FS host channel-2 characteristics register (OTG_FS_HCCHAR2)"] pub mod otg_fs_hcchar2; #[doc = "OTG_FS host channel-3 characteristics register (OTG_FS_HCCHAR3)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar3](otg_fs_hcchar3) module"] pub type OTG_FS_HCCHAR3 = crate::Reg<u32, _OTG_FS_HCCHAR3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR3; #[doc = "`read()` method returns [otg_fs_hcchar3::R](otg_fs_hcchar3::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR3 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar3::W](otg_fs_hcchar3::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR3 {} #[doc = "OTG_FS host channel-3 characteristics register (OTG_FS_HCCHAR3)"] pub mod otg_fs_hcchar3; #[doc = "OTG_FS host channel-4 characteristics register (OTG_FS_HCCHAR4)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar4](otg_fs_hcchar4) module"] pub type OTG_FS_HCCHAR4 = crate::Reg<u32, _OTG_FS_HCCHAR4>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR4; #[doc = "`read()` method returns [otg_fs_hcchar4::R](otg_fs_hcchar4::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR4 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar4::W](otg_fs_hcchar4::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR4 {} #[doc = "OTG_FS host channel-4 characteristics register (OTG_FS_HCCHAR4)"] pub mod otg_fs_hcchar4; #[doc = "OTG_FS host channel-5 characteristics register (OTG_FS_HCCHAR5)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar5](otg_fs_hcchar5) module"] pub type OTG_FS_HCCHAR5 = crate::Reg<u32, _OTG_FS_HCCHAR5>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR5; #[doc = "`read()` method returns [otg_fs_hcchar5::R](otg_fs_hcchar5::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR5 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar5::W](otg_fs_hcchar5::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR5 {} #[doc = "OTG_FS host channel-5 characteristics register (OTG_FS_HCCHAR5)"] pub mod otg_fs_hcchar5; #[doc = "OTG_FS host channel-6 characteristics register (OTG_FS_HCCHAR6)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar6](otg_fs_hcchar6) module"] pub type OTG_FS_HCCHAR6 = crate::Reg<u32, _OTG_FS_HCCHAR6>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR6; #[doc = "`read()` method returns [otg_fs_hcchar6::R](otg_fs_hcchar6::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR6 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar6::W](otg_fs_hcchar6::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR6 {} #[doc = "OTG_FS host channel-6 characteristics register (OTG_FS_HCCHAR6)"] pub mod otg_fs_hcchar6; #[doc = "OTG_FS host channel-7 characteristics register (OTG_FS_HCCHAR7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar7](otg_fs_hcchar7) module"] pub type OTG_FS_HCCHAR7 = crate::Reg<u32, _OTG_FS_HCCHAR7>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR7; #[doc = "`read()` method returns [otg_fs_hcchar7::R](otg_fs_hcchar7::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR7 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar7::W](otg_fs_hcchar7::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR7 {} #[doc = "OTG_FS host channel-7 characteristics register (OTG_FS_HCCHAR7)"] pub mod otg_fs_hcchar7; #[doc = "OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint0](otg_fs_hcint0) module"] pub type OTG_FS_HCINT0 = crate::Reg<u32, _OTG_FS_HCINT0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT0; #[doc = "`read()` method returns [otg_fs_hcint0::R](otg_fs_hcint0::R) reader structure"] impl crate::Readable for OTG_FS_HCINT0 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint0::W](otg_fs_hcint0::W) writer structure"] impl crate::Writable for OTG_FS_HCINT0 {} #[doc = "OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)"] pub mod otg_fs_hcint0; #[doc = "OTG_FS host channel-1 interrupt register (OTG_FS_HCINT1)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint1](otg_fs_hcint1) module"] pub type OTG_FS_HCINT1 = crate::Reg<u32, _OTG_FS_HCINT1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT1; #[doc = "`read()` method returns [otg_fs_hcint1::R](otg_fs_hcint1::R) reader structure"] impl crate::Readable for OTG_FS_HCINT1 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint1::W](otg_fs_hcint1::W) writer structure"] impl crate::Writable for OTG_FS_HCINT1 {} #[doc = "OTG_FS host channel-1 interrupt register (OTG_FS_HCINT1)"] pub mod otg_fs_hcint1; #[doc = "OTG_FS host channel-2 interrupt register (OTG_FS_HCINT2)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint2](otg_fs_hcint2) module"] pub type OTG_FS_HCINT2 = crate::Reg<u32, _OTG_FS_HCINT2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT2; #[doc = "`read()` method returns [otg_fs_hcint2::R](otg_fs_hcint2::R) reader structure"] impl crate::Readable for OTG_FS_HCINT2 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint2::W](otg_fs_hcint2::W) writer structure"] impl crate::Writable for OTG_FS_HCINT2 {} #[doc = "OTG_FS host channel-2 interrupt register (OTG_FS_HCINT2)"] pub mod otg_fs_hcint2; #[doc = "OTG_FS host channel-3 interrupt register (OTG_FS_HCINT3)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint3](otg_fs_hcint3) module"] pub type OTG_FS_HCINT3 = crate::Reg<u32, _OTG_FS_HCINT3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT3; #[doc = "`read()` method returns [otg_fs_hcint3::R](otg_fs_hcint3::R) reader structure"] impl crate::Readable for OTG_FS_HCINT3 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint3::W](otg_fs_hcint3::W) writer structure"] impl crate::Writable for OTG_FS_HCINT3 {} #[doc = "OTG_FS host channel-3 interrupt register (OTG_FS_HCINT3)"] pub mod otg_fs_hcint3; #[doc = "OTG_FS host channel-4 interrupt register (OTG_FS_HCINT4)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint4](otg_fs_hcint4) module"] pub type OTG_FS_HCINT4 = crate::Reg<u32, _OTG_FS_HCINT4>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT4; #[doc = "`read()` method returns [otg_fs_hcint4::R](otg_fs_hcint4::R) reader structure"] impl crate::Readable for OTG_FS_HCINT4 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint4::W](otg_fs_hcint4::W) writer structure"] impl crate::Writable for OTG_FS_HCINT4 {} #[doc = "OTG_FS host channel-4 interrupt register (OTG_FS_HCINT4)"] pub mod otg_fs_hcint4; #[doc = "OTG_FS host channel-5 interrupt register (OTG_FS_HCINT5)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint5](otg_fs_hcint5) module"] pub type OTG_FS_HCINT5 = crate::Reg<u32, _OTG_FS_HCINT5>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT5; #[doc = "`read()` method returns [otg_fs_hcint5::R](otg_fs_hcint5::R) reader structure"] impl crate::Readable for OTG_FS_HCINT5 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint5::W](otg_fs_hcint5::W) writer structure"] impl crate::Writable for OTG_FS_HCINT5 {} #[doc = "OTG_FS host channel-5 interrupt register (OTG_FS_HCINT5)"] pub mod otg_fs_hcint5; #[doc = "OTG_FS host channel-6 interrupt register (OTG_FS_HCINT6)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint6](otg_fs_hcint6) module"] pub type OTG_FS_HCINT6 = crate::Reg<u32, _OTG_FS_HCINT6>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT6; #[doc = "`read()` method returns [otg_fs_hcint6::R](otg_fs_hcint6::R) reader structure"] impl crate::Readable for OTG_FS_HCINT6 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint6::W](otg_fs_hcint6::W) writer structure"] impl crate::Writable for OTG_FS_HCINT6 {} #[doc = "OTG_FS host channel-6 interrupt register (OTG_FS_HCINT6)"] pub mod otg_fs_hcint6; #[doc = "OTG_FS host channel-7 interrupt register (OTG_FS_HCINT7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint7](otg_fs_hcint7) module"] pub type OTG_FS_HCINT7 = crate::Reg<u32, _OTG_FS_HCINT7>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT7; #[doc = "`read()` method returns [otg_fs_hcint7::R](otg_fs_hcint7::R) reader structure"] impl crate::Readable for OTG_FS_HCINT7 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint7::W](otg_fs_hcint7::W) writer structure"] impl crate::Writable for OTG_FS_HCINT7 {} #[doc = "OTG_FS host channel-7 interrupt register (OTG_FS_HCINT7)"] pub mod otg_fs_hcint7; #[doc = "OTG_FS host channel-0 mask register (OTG_FS_HCINTMSK0)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk0](otg_fs_hcintmsk0) module"] pub type OTG_FS_HCINTMSK0 = crate::Reg<u32, _OTG_FS_HCINTMSK0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK0; #[doc = "`read()` method returns [otg_fs_hcintmsk0::R](otg_fs_hcintmsk0::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK0 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk0::W](otg_fs_hcintmsk0::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK0 {} #[doc = "OTG_FS host channel-0 mask register (OTG_FS_HCINTMSK0)"] pub mod otg_fs_hcintmsk0; #[doc = "OTG_FS host channel-1 mask register (OTG_FS_HCINTMSK1)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk1](otg_fs_hcintmsk1) module"] pub type OTG_FS_HCINTMSK1 = crate::Reg<u32, _OTG_FS_HCINTMSK1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK1; #[doc = "`read()` method returns [otg_fs_hcintmsk1::R](otg_fs_hcintmsk1::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK1 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk1::W](otg_fs_hcintmsk1::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK1 {} #[doc = "OTG_FS host channel-1 mask register (OTG_FS_HCINTMSK1)"] pub mod otg_fs_hcintmsk1; #[doc = "OTG_FS host channel-2 mask register (OTG_FS_HCINTMSK2)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk2](otg_fs_hcintmsk2) module"] pub type OTG_FS_HCINTMSK2 = crate::Reg<u32, _OTG_FS_HCINTMSK2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK2; #[doc = "`read()` method returns [otg_fs_hcintmsk2::R](otg_fs_hcintmsk2::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK2 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk2::W](otg_fs_hcintmsk2::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK2 {} #[doc = "OTG_FS host channel-2 mask register (OTG_FS_HCINTMSK2)"] pub mod otg_fs_hcintmsk2; #[doc = "OTG_FS host channel-3 mask register (OTG_FS_HCINTMSK3)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk3](otg_fs_hcintmsk3) module"] pub type OTG_FS_HCINTMSK3 = crate::Reg<u32, _OTG_FS_HCINTMSK3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK3; #[doc = "`read()` method returns [otg_fs_hcintmsk3::R](otg_fs_hcintmsk3::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK3 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk3::W](otg_fs_hcintmsk3::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK3 {} #[doc = "OTG_FS host channel-3 mask register (OTG_FS_HCINTMSK3)"] pub mod otg_fs_hcintmsk3; #[doc = "OTG_FS host channel-4 mask register (OTG_FS_HCINTMSK4)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk4](otg_fs_hcintmsk4) module"] pub type OTG_FS_HCINTMSK4 = crate::Reg<u32, _OTG_FS_HCINTMSK4>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK4; #[doc = "`read()` method returns [otg_fs_hcintmsk4::R](otg_fs_hcintmsk4::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK4 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk4::W](otg_fs_hcintmsk4::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK4 {} #[doc = "OTG_FS host channel-4 mask register (OTG_FS_HCINTMSK4)"] pub mod otg_fs_hcintmsk4; #[doc = "OTG_FS host channel-5 mask register (OTG_FS_HCINTMSK5)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk5](otg_fs_hcintmsk5) module"] pub type OTG_FS_HCINTMSK5 = crate::Reg<u32, _OTG_FS_HCINTMSK5>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK5; #[doc = "`read()` method returns [otg_fs_hcintmsk5::R](otg_fs_hcintmsk5::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK5 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk5::W](otg_fs_hcintmsk5::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK5 {} #[doc = "OTG_FS host channel-5 mask register (OTG_FS_HCINTMSK5)"] pub mod otg_fs_hcintmsk5; #[doc = "OTG_FS host channel-6 mask register (OTG_FS_HCINTMSK6)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk6](otg_fs_hcintmsk6) module"] pub type OTG_FS_HCINTMSK6 = crate::Reg<u32, _OTG_FS_HCINTMSK6>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK6; #[doc = "`read()` method returns [otg_fs_hcintmsk6::R](otg_fs_hcintmsk6::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK6 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk6::W](otg_fs_hcintmsk6::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK6 {} #[doc = "OTG_FS host channel-6 mask register (OTG_FS_HCINTMSK6)"] pub mod otg_fs_hcintmsk6; #[doc = "OTG_FS host channel-7 mask register (OTG_FS_HCINTMSK7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk7](otg_fs_hcintmsk7) module"] pub type OTG_FS_HCINTMSK7 = crate::Reg<u32, _OTG_FS_HCINTMSK7>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK7; #[doc = "`read()` method returns [otg_fs_hcintmsk7::R](otg_fs_hcintmsk7::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK7 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk7::W](otg_fs_hcintmsk7::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK7 {} #[doc = "OTG_FS host channel-7 mask register (OTG_FS_HCINTMSK7)"] pub mod otg_fs_hcintmsk7; #[doc = "OTG_FS host channel-0 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz0](otg_fs_hctsiz0) module"] pub type OTG_FS_HCTSIZ0 = crate::Reg<u32, _OTG_FS_HCTSIZ0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ0; #[doc = "`read()` method returns [otg_fs_hctsiz0::R](otg_fs_hctsiz0::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ0 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz0::W](otg_fs_hctsiz0::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ0 {} #[doc = "OTG_FS host channel-0 transfer size register"] pub mod otg_fs_hctsiz0; #[doc = "OTG_FS host channel-1 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz1](otg_fs_hctsiz1) module"] pub type OTG_FS_HCTSIZ1 = crate::Reg<u32, _OTG_FS_HCTSIZ1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ1; #[doc = "`read()` method returns [otg_fs_hctsiz1::R](otg_fs_hctsiz1::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ1 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz1::W](otg_fs_hctsiz1::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ1 {} #[doc = "OTG_FS host channel-1 transfer size register"] pub mod otg_fs_hctsiz1; #[doc = "OTG_FS host channel-2 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz2](otg_fs_hctsiz2) module"] pub type OTG_FS_HCTSIZ2 = crate::Reg<u32, _OTG_FS_HCTSIZ2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ2; #[doc = "`read()` method returns [otg_fs_hctsiz2::R](otg_fs_hctsiz2::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ2 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz2::W](otg_fs_hctsiz2::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ2 {} #[doc = "OTG_FS host channel-2 transfer size register"] pub mod otg_fs_hctsiz2; #[doc = "OTG_FS host channel-3 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz3](otg_fs_hctsiz3) module"] pub type OTG_FS_HCTSIZ3 = crate::Reg<u32, _OTG_FS_HCTSIZ3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ3; #[doc = "`read()` method returns [otg_fs_hctsiz3::R](otg_fs_hctsiz3::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ3 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz3::W](otg_fs_hctsiz3::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ3 {} #[doc = "OTG_FS host channel-3 transfer size register"] pub mod otg_fs_hctsiz3; #[doc = "OTG_FS host channel-x transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz4](otg_fs_hctsiz4) module"] pub type OTG_FS_HCTSIZ4 = crate::Reg<u32, _OTG_FS_HCTSIZ4>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ4; #[doc = "`read()` method returns [otg_fs_hctsiz4::R](otg_fs_hctsiz4::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ4 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz4::W](otg_fs_hctsiz4::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ4 {} #[doc = "OTG_FS host channel-x transfer size register"] pub mod otg_fs_hctsiz4; #[doc = "OTG_FS host channel-5 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz5](otg_fs_hctsiz5) module"] pub type OTG_FS_HCTSIZ5 = crate::Reg<u32, _OTG_FS_HCTSIZ5>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ5; #[doc = "`read()` method returns [otg_fs_hctsiz5::R](otg_fs_hctsiz5::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ5 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz5::W](otg_fs_hctsiz5::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ5 {} #[doc = "OTG_FS host channel-5 transfer size register"] pub mod otg_fs_hctsiz5; #[doc = "OTG_FS host channel-6 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz6](otg_fs_hctsiz6) module"] pub type OTG_FS_HCTSIZ6 = crate::Reg<u32, _OTG_FS_HCTSIZ6>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ6; #[doc = "`read()` method returns [otg_fs_hctsiz6::R](otg_fs_hctsiz6::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ6 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz6::W](otg_fs_hctsiz6::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ6 {} #[doc = "OTG_FS host channel-6 transfer size register"] pub mod otg_fs_hctsiz6; #[doc = "OTG_FS host channel-7 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz7](otg_fs_hctsiz7) module"] pub type OTG_FS_HCTSIZ7 = crate::Reg<u32, _OTG_FS_HCTSIZ7>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ7; #[doc = "`read()` method returns [otg_fs_hctsiz7::R](otg_fs_hctsiz7::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ7 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz7::W](otg_fs_hctsiz7::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ7 {} #[doc = "OTG_FS host channel-7 transfer size register"] pub mod otg_fs_hctsiz7; #[doc = "OTG_FS host channel-8 characteristics register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar8](otg_fs_hcchar8) module"] pub type OTG_FS_HCCHAR8 = crate::Reg<u32, _OTG_FS_HCCHAR8>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR8; #[doc = "`read()` method returns [otg_fs_hcchar8::R](otg_fs_hcchar8::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR8 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar8::W](otg_fs_hcchar8::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR8 {} #[doc = "OTG_FS host channel-8 characteristics register"] pub mod otg_fs_hcchar8; #[doc = "OTG_FS host channel-8 interrupt register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint8](otg_fs_hcint8) module"] pub type OTG_FS_HCINT8 = crate::Reg<u32, _OTG_FS_HCINT8>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT8; #[doc = "`read()` method returns [otg_fs_hcint8::R](otg_fs_hcint8::R) reader structure"] impl crate::Readable for OTG_FS_HCINT8 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint8::W](otg_fs_hcint8::W) writer structure"] impl crate::Writable for OTG_FS_HCINT8 {} #[doc = "OTG_FS host channel-8 interrupt register"] pub mod otg_fs_hcint8; #[doc = "OTG_FS host channel-8 mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk8](otg_fs_hcintmsk8) module"] pub type OTG_FS_HCINTMSK8 = crate::Reg<u32, _OTG_FS_HCINTMSK8>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK8; #[doc = "`read()` method returns [otg_fs_hcintmsk8::R](otg_fs_hcintmsk8::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK8 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk8::W](otg_fs_hcintmsk8::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK8 {} #[doc = "OTG_FS host channel-8 mask register"] pub mod otg_fs_hcintmsk8; #[doc = "OTG_FS host channel-8 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz8](otg_fs_hctsiz8) module"] pub type OTG_FS_HCTSIZ8 = crate::Reg<u32, _OTG_FS_HCTSIZ8>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ8; #[doc = "`read()` method returns [otg_fs_hctsiz8::R](otg_fs_hctsiz8::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ8 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz8::W](otg_fs_hctsiz8::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ8 {} #[doc = "OTG_FS host channel-8 transfer size register"] pub mod otg_fs_hctsiz8; #[doc = "OTG_FS host channel-9 characteristics register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar9](otg_fs_hcchar9) module"] pub type OTG_FS_HCCHAR9 = crate::Reg<u32, _OTG_FS_HCCHAR9>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR9; #[doc = "`read()` method returns [otg_fs_hcchar9::R](otg_fs_hcchar9::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR9 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar9::W](otg_fs_hcchar9::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR9 {} #[doc = "OTG_FS host channel-9 characteristics register"] pub mod otg_fs_hcchar9; #[doc = "OTG_FS host channel-9 interrupt register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint9](otg_fs_hcint9) module"] pub type OTG_FS_HCINT9 = crate::Reg<u32, _OTG_FS_HCINT9>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT9; #[doc = "`read()` method returns [otg_fs_hcint9::R](otg_fs_hcint9::R) reader structure"] impl crate::Readable for OTG_FS_HCINT9 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint9::W](otg_fs_hcint9::W) writer structure"] impl crate::Writable for OTG_FS_HCINT9 {} #[doc = "OTG_FS host channel-9 interrupt register"] pub mod otg_fs_hcint9; #[doc = "OTG_FS host channel-9 mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk9](otg_fs_hcintmsk9) module"] pub type OTG_FS_HCINTMSK9 = crate::Reg<u32, _OTG_FS_HCINTMSK9>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK9; #[doc = "`read()` method returns [otg_fs_hcintmsk9::R](otg_fs_hcintmsk9::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK9 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk9::W](otg_fs_hcintmsk9::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK9 {} #[doc = "OTG_FS host channel-9 mask register"] pub mod otg_fs_hcintmsk9; #[doc = "OTG_FS host channel-9 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz9](otg_fs_hctsiz9) module"] pub type OTG_FS_HCTSIZ9 = crate::Reg<u32, _OTG_FS_HCTSIZ9>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ9; #[doc = "`read()` method returns [otg_fs_hctsiz9::R](otg_fs_hctsiz9::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ9 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz9::W](otg_fs_hctsiz9::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ9 {} #[doc = "OTG_FS host channel-9 transfer size register"] pub mod otg_fs_hctsiz9; #[doc = "OTG_FS host channel-10 characteristics register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar10](otg_fs_hcchar10) module"] pub type OTG_FS_HCCHAR10 = crate::Reg<u32, _OTG_FS_HCCHAR10>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR10; #[doc = "`read()` method returns [otg_fs_hcchar10::R](otg_fs_hcchar10::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR10 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar10::W](otg_fs_hcchar10::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR10 {} #[doc = "OTG_FS host channel-10 characteristics register"] pub mod otg_fs_hcchar10; #[doc = "OTG_FS host channel-10 interrupt register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint10](otg_fs_hcint10) module"] pub type OTG_FS_HCINT10 = crate::Reg<u32, _OTG_FS_HCINT10>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT10; #[doc = "`read()` method returns [otg_fs_hcint10::R](otg_fs_hcint10::R) reader structure"] impl crate::Readable for OTG_FS_HCINT10 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint10::W](otg_fs_hcint10::W) writer structure"] impl crate::Writable for OTG_FS_HCINT10 {} #[doc = "OTG_FS host channel-10 interrupt register"] pub mod otg_fs_hcint10; #[doc = "OTG_FS host channel-10 mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk10](otg_fs_hcintmsk10) module"] pub type OTG_FS_HCINTMSK10 = crate::Reg<u32, _OTG_FS_HCINTMSK10>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK10; #[doc = "`read()` method returns [otg_fs_hcintmsk10::R](otg_fs_hcintmsk10::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK10 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk10::W](otg_fs_hcintmsk10::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK10 {} #[doc = "OTG_FS host channel-10 mask register"] pub mod otg_fs_hcintmsk10; #[doc = "OTG_FS host channel-10 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz10](otg_fs_hctsiz10) module"] pub type OTG_FS_HCTSIZ10 = crate::Reg<u32, _OTG_FS_HCTSIZ10>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ10; #[doc = "`read()` method returns [otg_fs_hctsiz10::R](otg_fs_hctsiz10::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ10 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz10::W](otg_fs_hctsiz10::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ10 {} #[doc = "OTG_FS host channel-10 transfer size register"] pub mod otg_fs_hctsiz10; #[doc = "OTG_FS host channel-11 characteristics register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcchar11](otg_fs_hcchar11) module"] pub type OTG_FS_HCCHAR11 = crate::Reg<u32, _OTG_FS_HCCHAR11>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCCHAR11; #[doc = "`read()` method returns [otg_fs_hcchar11::R](otg_fs_hcchar11::R) reader structure"] impl crate::Readable for OTG_FS_HCCHAR11 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcchar11::W](otg_fs_hcchar11::W) writer structure"] impl crate::Writable for OTG_FS_HCCHAR11 {} #[doc = "OTG_FS host channel-11 characteristics register"] pub mod otg_fs_hcchar11; #[doc = "OTG_FS host channel-11 interrupt register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcint11](otg_fs_hcint11) module"] pub type OTG_FS_HCINT11 = crate::Reg<u32, _OTG_FS_HCINT11>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINT11; #[doc = "`read()` method returns [otg_fs_hcint11::R](otg_fs_hcint11::R) reader structure"] impl crate::Readable for OTG_FS_HCINT11 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcint11::W](otg_fs_hcint11::W) writer structure"] impl crate::Writable for OTG_FS_HCINT11 {} #[doc = "OTG_FS host channel-11 interrupt register"] pub mod otg_fs_hcint11; #[doc = "OTG_FS host channel-11 mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hcintmsk11](otg_fs_hcintmsk11) module"] pub type OTG_FS_HCINTMSK11 = crate::Reg<u32, _OTG_FS_HCINTMSK11>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCINTMSK11; #[doc = "`read()` method returns [otg_fs_hcintmsk11::R](otg_fs_hcintmsk11::R) reader structure"] impl crate::Readable for OTG_FS_HCINTMSK11 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hcintmsk11::W](otg_fs_hcintmsk11::W) writer structure"] impl crate::Writable for OTG_FS_HCINTMSK11 {} #[doc = "OTG_FS host channel-11 mask register"] pub mod otg_fs_hcintmsk11; #[doc = "OTG_FS host channel-11 transfer size register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [otg_fs_hctsiz11](otg_fs_hctsiz11) module"] pub type OTG_FS_HCTSIZ11 = crate::Reg<u32, _OTG_FS_HCTSIZ11>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OTG_FS_HCTSIZ11; #[doc = "`read()` method returns [otg_fs_hctsiz11::R](otg_fs_hctsiz11::R) reader structure"] impl crate::Readable for OTG_FS_HCTSIZ11 {} #[doc = "`write(|w| ..)` method takes [otg_fs_hctsiz11::W](otg_fs_hctsiz11::W) writer structure"] impl crate::Writable for OTG_FS_HCTSIZ11 {} #[doc = "OTG_FS host channel-11 transfer size register"] pub mod otg_fs_hctsiz11;
use std::collections::BTreeMap; #[derive(Debug)] pub(crate) struct RunnerSpec { cases: Vec<CaseSpec>, include: Option<Vec<String>>, default_bin: Option<crate::schema::Bin>, timeout: Option<std::time::Duration>, env: crate::schema::Env, } impl RunnerSpec { pub(crate) fn new() -> Self { Self { cases: Default::default(), include: None, default_bin: None, timeout: Default::default(), env: Default::default(), } } pub(crate) fn case( &mut self, glob: &std::path::Path, #[cfg_attr(miri, allow(unused_variables))] expected: Option<crate::schema::CommandStatus>, ) { self.cases.push(CaseSpec { glob: glob.into(), #[cfg(not(miri))] expected, #[cfg(miri)] expected: Some(crate::schema::CommandStatus::Skipped), }); } pub(crate) fn include(&mut self, include: Option<Vec<String>>) { self.include = include; } pub(crate) fn default_bin(&mut self, bin: Option<crate::schema::Bin>) { self.default_bin = bin; } pub(crate) fn timeout(&mut self, time: Option<std::time::Duration>) { self.timeout = time; } pub(crate) fn env(&mut self, key: impl Into<String>, value: impl Into<String>) { self.env.add.insert(key.into(), value.into()); } pub(crate) fn prepare(&mut self) -> crate::Runner { let mut runner = crate::Runner::new(); // Both sort and let the last writer win to allow overriding specific cases within a glob let mut cases: BTreeMap<std::path::PathBuf, crate::Case> = BTreeMap::new(); for spec in &self.cases { if let Some(glob) = get_glob(&spec.glob) { match ::glob::glob(glob) { Ok(paths) => { for path in paths { match path { Ok(path) => { cases.insert( path.clone(), crate::Case { path, expected: spec.expected, default_bin: self.default_bin.clone(), timeout: self.timeout, env: self.env.clone(), error: None, }, ); } Err(err) => { let path = err.path().to_owned(); let err = crate::Error::new(err.into_error().to_string()); cases.insert(path.clone(), crate::Case::with_error(path, err)); } } } } Err(err) => { let err = crate::Error::new(err.to_string()); cases.insert( spec.glob.clone(), crate::Case::with_error(spec.glob.clone(), err), ); } } } else { let path = spec.glob.as_path(); cases.insert( path.into(), crate::Case { path: path.into(), expected: spec.expected, default_bin: self.default_bin.clone(), timeout: self.timeout, env: self.env.clone(), error: None, }, ); } } for case in cases.into_values() { if self.is_included(&case) { runner.case(case); } } runner } fn is_included(&self, case: &crate::Case) -> bool { if let Some(include) = self.include.as_deref() { include .iter() .any(|i| case.path.to_string_lossy().contains(i)) } else { true } } } impl Default for RunnerSpec { fn default() -> Self { Self::new() } } #[derive(Debug)] struct CaseSpec { glob: std::path::PathBuf, expected: Option<crate::schema::CommandStatus>, } fn get_glob(path: &std::path::Path) -> Option<&str> { if let Some(utf8) = path.to_str() { if utf8.contains('*') { return Some(utf8); } } None }
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[crate_id = "github.com/mozilla-servo/rust-core-text#core_text:0.1"]; extern mod std; extern mod core_foundation; extern mod core_graphics; pub mod font; pub mod font_collection; pub mod font_descriptor; pub mod font_manager;
#![feature(drain_filter)] extern crate futures; extern crate tokio_core; extern crate tokio_io; extern crate bincode; extern crate rustc_serialize; mod udp; use tokio_core::reactor::Core; use futures::*; use futures::sync::mpsc; use std::thread; use std::net::SocketAddr; fn main() { let target_addr_str = "127.0.0.1"; let target_addr_1: SocketAddr = format!("{}:{}", target_addr_str, 10001).parse().unwrap(); let target_addr_2: SocketAddr = format!("{}:{}", target_addr_str, 10002).parse().unwrap(); let target_addr_3: SocketAddr = format!("{}:{}", target_addr_str, 10003).parse().unwrap(); let (multi_path_udp_1st_tx, multi_path_udp_1st_rx) = mpsc::channel::<Vec<u8>>(5000); let (multi_path_udp_2nd_tx, multi_path_udp_2nd_rx) = mpsc::channel::<Vec<u8>>(5000); let (multi_path_udp_3rd_tx, multi_path_udp_3rd_rx) = mpsc::channel::<Vec<u8>>(5000); let th_send_1 = udp::sender(multi_path_udp_1st_rx.map(move |x| (target_addr_1, x))); let th_send_2 = udp::sender(multi_path_udp_2nd_rx.map(move |x| (target_addr_2, x))); let th_send_3 = udp::sender(multi_path_udp_3rd_rx.map(move |x| (target_addr_3, x))); let (recv_udp_tx, recv_udp_rx) = mpsc::channel::<Vec<u8>>(5000); let recv_addr: SocketAddr = format!("0.0.0.0:{}", 10000).parse().unwrap(); let th_recv = udp::receiver(recv_addr, recv_udp_tx); let th_broadcast = thread::spawn(|| { let mut core = Core::new().unwrap(); let r = recv_udp_rx.fold((multi_path_udp_1st_tx, multi_path_udp_2nd_tx, multi_path_udp_3rd_tx), broadcast); let _ = core.run(r); }); let _ = th_recv.join(); let _ = th_send_1.join(); let _ = th_send_2.join(); let _ = th_send_3.join(); let _ = th_broadcast; } type SenderTuple = (mpsc::Sender<Vec<u8>>, mpsc::Sender<Vec<u8>>, mpsc::Sender<Vec<u8>>); fn broadcast(sum: SenderTuple, acc: Vec<u8>) -> Result<SenderTuple, ()> { let s1 = sum.0.send(acc.clone()).wait().unwrap(); let s2 = sum.1.send(acc.clone()).wait().unwrap(); let s3 = sum.2.send(acc).wait().unwrap(); Ok((s1, s2, s3)) }
extern crate regex; use regex::Regex; use std::collections::HashMap; use std::env; use std::fs::File; use std::io::BufRead; use std::io::BufReader; fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let file = File::open(filename).expect("Could not read file"); let mut lines = BufReader::new(file) .lines() .map(|line| line.expect("Line could not be read")) .filter(|line| line.len() > 0) .collect::<Vec<String>>(); lines.sort(); part_one_and_two(&lines); } fn part_one_and_two(lines: &Vec<String>) { let mut sleeping = HashMap::new(); let date_time = Regex::new(r"\-\d{2}\-\d{2} \d{2}:(\d{2})").unwrap(); let begin = Regex::new(r"Guard #(\d*)").unwrap(); let sleep = Regex::new(r"falls asleep").unwrap(); let wake = Regex::new(r"wakes up").unwrap(); let cap_number = |ref cap: &regex::Captures, i| cap.get(i).unwrap().as_str().parse::<usize>().unwrap(); let mut guard = None; let mut sleep_time = None; for line in lines { let date_time_caps = date_time .captures(line) .expect("Line should contain a date"); let minute = cap_number(&date_time_caps, 1); if begin.is_match(line) { guard = Some(cap_number(&(begin.captures(line).unwrap()), 1)); } if sleep.is_match(line) { sleep_time = Some(minute); } if wake.is_match(line) { let array = sleeping.entry(guard.unwrap()).or_insert(vec![0; 60]); for i in sleep_time.unwrap()..minute { array[i] += 1; } } } println!( "{}", sleeping .iter() // Get guard who spent largest total time asleep .max_by_key(|(_, v)| v.iter().sum::<usize>()) // Get the time they were most often asleep .map(|(k, v)| ( k, v.iter().position(|r| r == v.iter().max().unwrap()).unwrap(), )).map(|(k, v)| k * v) .unwrap() ); println!( "{}", sleeping .iter() // Get guard who slept most on the same minute across days .max_by_key(|(_, v)| v.iter().max()) // Get that minute .map(|(k, v)| ( k, v.iter().position(|r| r == v.iter().max().unwrap()).unwrap() )).map(|(k, v)| k * v) .unwrap() ); }
#[doc(hidden)] pub use crate::{ adapter::Adapter, client::StdoutWriter, events::{self, Event, EventBody}, line_reader::{FileLineReader, LineReader}, requests::{self, Command, Request}, responses::{self, Response, ResponseBody}, reverse_requests::{ReverseCommand, ReverseRequest}, server::Server, types, };
mod vector; pub use vector::Vector; /// Functions to generate waves from some continuously rising value pub mod gen { /// Generate a saw wave with given phase, length and amplitude value at state. /// If abs is true, output ranges from 0 to amplitude. /// If abs is false, output ranges from -amplitude/2 to amplitude/2 pub fn saw(state: f32, phase: f32, length: f32, amplitude: f32, abs: bool) -> f32 { let mut state = state; state += phase; state %= length; state /= length; state = f32::abs(state - 0.5) * 2.; if abs { state *= amplitude; } else { state -= 0.5; state *= amplitude / 2. } state } } pub mod ants { use core::f64; use core::ops::Add; use std::f64::consts::PI; //use std::sync::{Arc, Mutex}; use rayon::prelude::*; use super::vector::{Vector, angle_diff}; use parking_lot::RwLock; static MOVE: f64 = 0.0333; #[derive(Clone, Copy)] pub struct Ant { pub pos: Vector, pub dir: Vector } impl Default for Ant { fn default() -> Self { Ant { pos: Vector {x: rand::random(), y: rand::random()}, dir: Vector::from_angle((rand::random::<f64>() - 0.4) * 2. * PI) } } } impl Ant { pub fn new() -> Ant{ Ant::default() } pub fn evolve(&mut self, pheromones: &[Pheromone]) { let self_angle = self.dir.angle(); if self_angle > PI { self.dir = self.dir.rotated(-2. * PI) } else if self_angle < PI { self.dir = self.dir.rotated(2. * PI) } let (mean_angle, mut total_weight)= { // weighted mean let mut mean = Vector::new(); let mut total_weight = 0.; for p in pheromones.iter() { if p.pos == self.pos { continue; } let to_p = p.pos - self.pos; let mut angle_diff = angle_diff(self_angle, to_p.angle()).abs(); if angle_diff == 0. { angle_diff = 1. } let weight = p.pow * ((1. / angle_diff) * 2.); total_weight += weight * to_p.length(); mean = mean + to_p.mul_by_float(weight); } (mean.angle(), total_weight) }; if total_weight == 0. { total_weight = 1. } if mean_angle != 0. { self.dir = self.dir.rotated(angle_diff(self_angle, mean_angle) / 40.); } let noise: f64 = (rand::random::<f64>() - 0.5)/4.; self.dir = self.dir.rotated(noise); self.pos = self.pos + self.dir.mul_by_float(MOVE/(total_weight.sqrt()/10.)); if self.pos.x > 1. || self.pos.x < 0. || self.pos.y > 1. || self.pos.y < 0. { self.dir = self.dir.rotated(PI); self.pos = self.pos + self.dir.mul_by_float(MOVE/(total_weight.sqrt()/10.)); } } } #[derive(Clone, Copy, Default)] pub struct Pheromone { pub pos: crate::Vector, pub pow: f64 } impl Add for Pheromone { type Output = Self; fn add(self, other: Self) -> Self { Self { pos: self.pos + other.pos, pow: self.pow + other.pow } } } impl Pheromone { pub fn new() -> Pheromone{ Pheromone::default() } pub fn evolve(&mut self) { self.pow -= 0.1 } } #[derive(Clone, Default)] pub struct World { pub ants: Vec<Ant>, pub pheromones: Vec<Pheromone> } impl World { pub fn new(num_ants: usize) -> World { World { ants: { let mut vec = Vec::with_capacity(num_ants); for _ in 0..num_ants { vec.push(Ant::default()); } vec }, pheromones: Vec::new() } } pub fn evolve(&mut self) { for p in &mut self.pheromones { p.evolve() } self.pheromones.retain(|x| x.pow > 0.); for a in &mut self.ants { self.pheromones.push(Pheromone {pos: a.pos, pow: 1.}); a.evolve(&self.pheromones) } } pub fn evolve_threaded(&mut self, threads: usize) { let mut ants_per_thread = self.ants.len() / threads; let mut pheromones_per_thread = self.pheromones.len() / threads; if pheromones_per_thread == 0 { pheromones_per_thread = 1 } if ants_per_thread == 0 { ants_per_thread = 1 } self.pheromones.as_mut_slice().par_chunks_mut(pheromones_per_thread).for_each(|pheromones| { for p in pheromones { p.evolve(); } }); self.pheromones.retain(|x| x.pow > 0.); let pheromones = RwLock::new(&mut self.pheromones); self.ants.as_mut_slice().par_chunks_mut(ants_per_thread).for_each(|ants| { for a in ants { pheromones.write().push(Pheromone {pos: a.pos, pow: 1.}); let pheromones = pheromones.read(); a.evolve(&pheromones); } }); } } }
#[doc = "Reader of register ICR"] pub type R = crate::R<u32, super::ICR>; #[doc = "Writer for register ICR"] pub type W = crate::W<u32, super::ICR>; #[doc = "Register ICR `reset()`'s with value 0"] impl crate::ResetValue for super::ICR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `IC4`"] pub type IC4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `IC4`"] pub struct IC4_W<'a> { w: &'a mut W, } impl<'a> IC4_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `IC3`"] pub type IC3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `IC3`"] pub struct IC3_W<'a> { w: &'a mut W, } impl<'a> IC3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `IC2`"] pub type IC2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `IC2`"] pub struct IC2_W<'a> { w: &'a mut W, } impl<'a> IC2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `IC1`"] pub type IC1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `IC1`"] pub struct IC1_W<'a> { w: &'a mut W, } impl<'a> IC1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `TIM`"] pub type TIM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TIM`"] pub struct TIM_W<'a> { w: &'a mut W, } impl<'a> TIM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16); self.w } } #[doc = "Reader of field `IC4IOS`"] pub type IC4IOS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IC4IOS`"] pub struct IC4IOS_W<'a> { w: &'a mut W, } impl<'a> IC4IOS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "Reader of field `IC3IOS`"] pub type IC3IOS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IC3IOS`"] pub struct IC3IOS_W<'a> { w: &'a mut W, } impl<'a> IC3IOS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `IC2IOS`"] pub type IC2IOS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IC2IOS`"] pub struct IC2IOS_W<'a> { w: &'a mut W, } impl<'a> IC2IOS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `IC1IOS`"] pub type IC1IOS_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IC1IOS`"] pub struct IC1IOS_W<'a> { w: &'a mut W, } impl<'a> IC1IOS_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } impl R { #[doc = "Bit 21 - IC4"] #[inline(always)] pub fn ic4(&self) -> IC4_R { IC4_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 20 - IC3"] #[inline(always)] pub fn ic3(&self) -> IC3_R { IC3_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 19 - IC2"] #[inline(always)] pub fn ic2(&self) -> IC2_R { IC2_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - IC1"] #[inline(always)] pub fn ic1(&self) -> IC1_R { IC1_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bits 16:17 - Timer select bits"] #[inline(always)] pub fn tim(&self) -> TIM_R { TIM_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bits 12:15 - Input capture 4 select bits"] #[inline(always)] pub fn ic4ios(&self) -> IC4IOS_R { IC4IOS_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 8:11 - Input capture 3 select bits"] #[inline(always)] pub fn ic3ios(&self) -> IC3IOS_R { IC3IOS_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 4:7 - Input capture 2 select bits"] #[inline(always)] pub fn ic2ios(&self) -> IC2IOS_R { IC2IOS_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 0:3 - Input capture 1 select bits"] #[inline(always)] pub fn ic1ios(&self) -> IC1IOS_R { IC1IOS_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bit 21 - IC4"] #[inline(always)] pub fn ic4(&mut self) -> IC4_W { IC4_W { w: self } } #[doc = "Bit 20 - IC3"] #[inline(always)] pub fn ic3(&mut self) -> IC3_W { IC3_W { w: self } } #[doc = "Bit 19 - IC2"] #[inline(always)] pub fn ic2(&mut self) -> IC2_W { IC2_W { w: self } } #[doc = "Bit 18 - IC1"] #[inline(always)] pub fn ic1(&mut self) -> IC1_W { IC1_W { w: self } } #[doc = "Bits 16:17 - Timer select bits"] #[inline(always)] pub fn tim(&mut self) -> TIM_W { TIM_W { w: self } } #[doc = "Bits 12:15 - Input capture 4 select bits"] #[inline(always)] pub fn ic4ios(&mut self) -> IC4IOS_W { IC4IOS_W { w: self } } #[doc = "Bits 8:11 - Input capture 3 select bits"] #[inline(always)] pub fn ic3ios(&mut self) -> IC3IOS_W { IC3IOS_W { w: self } } #[doc = "Bits 4:7 - Input capture 2 select bits"] #[inline(always)] pub fn ic2ios(&mut self) -> IC2IOS_W { IC2IOS_W { w: self } } #[doc = "Bits 0:3 - Input capture 1 select bits"] #[inline(always)] pub fn ic1ios(&mut self) -> IC1IOS_W { IC1IOS_W { w: self } } }
/* origin: FreeBSD /usr/src/lib/msun/src/s_log1p.c */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ /* double log1p(double x) * Return the natural logarithm of 1+x. * * Method : * 1. Argument Reduction: find k and f such that * 1+x = 2^k * (1+f), * where sqrt(2)/2 < 1+f < sqrt(2) . * * Note. If k=0, then f=x is exact. However, if k!=0, then f * may not be representable exactly. In that case, a correction * term is need. Let u=1+x rounded. Let c = (1+x)-u, then * log(1+x) - log(u) ~ c/u. Thus, we proceed to compute log(u), * and add back the correction term c/u. * (Note: when x > 2**53, one can simply return log(x)) * * 2. Approximation of log(1+f): See log.c * * 3. Finally, log1p(x) = k*ln2 + log(1+f) + c/u. See log.c * * Special cases: * log1p(x) is NaN with signal if x < -1 (including -INF) ; * log1p(+INF) is +INF; log1p(-1) is -INF with signal; * log1p(NaN) is that NaN with no signal. * * Accuracy: * according to an error analysis, the error is always less than * 1 ulp (unit in the last place). * * Constants: * The hexadecimal values are the intended ones for the following * constants. The decimal values may be used, provided that the * compiler will convert from decimal to binary accurately enough * to produce the hexadecimal values shown. * * Note: Assuming log() return accurate answer, the following * algorithm can be used to compute log1p(x) to within a few ULP: * * u = 1+x; * if(u==1.0) return x ; else * return log(u)*(x/(u-1.0)); * * See HP-15C Advanced Functions Handbook, p.193. */ use core::f64; const LN2_HI: f64 = 6.93147180369123816490e-01; /* 3fe62e42 fee00000 */ const LN2_LO: f64 = 1.90821492927058770002e-10; /* 3dea39ef 35793c76 */ const LG1: f64 = 6.666666666666735130e-01; /* 3FE55555 55555593 */ const LG2: f64 = 3.999999999940941908e-01; /* 3FD99999 9997FA04 */ const LG3: f64 = 2.857142874366239149e-01; /* 3FD24924 94229359 */ const LG4: f64 = 2.222219843214978396e-01; /* 3FCC71C5 1D8E78AF */ const LG5: f64 = 1.818357216161805012e-01; /* 3FC74664 96CB03DE */ const LG6: f64 = 1.531383769920937332e-01; /* 3FC39A09 D078C69F */ const LG7: f64 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn log1p(x: f64) -> f64 { let mut ui: u64 = x.to_bits(); let hfsq: f64; let mut f: f64 = 0.; let mut c: f64 = 0.; let s: f64; let z: f64; let r: f64; let w: f64; let t1: f64; let t2: f64; let dk: f64; let hx: u32; let mut hu: u32; let mut k: i32; hx = (ui >> 32) as u32; k = 1; if hx < 0x3fda827a || (hx >> 31) > 0 { /* 1+x < sqrt(2)+ */ if hx >= 0xbff00000 { /* x <= -1.0 */ if x == -1. { return x / 0.0; /* log1p(-1) = -inf */ } return (x - x) / 0.0; /* log1p(x<-1) = NaN */ } if hx << 1 < 0x3ca00000 << 1 { /* |x| < 2**-53 */ /* underflow if subnormal */ if (hx & 0x7ff00000) == 0 { force_eval!(x as f32); } return x; } if hx <= 0xbfd2bec4 { /* sqrt(2)/2- <= 1+x < sqrt(2)+ */ k = 0; c = 0.; f = x; } } else if hx >= 0x7ff00000 { return x; } if k > 0 { ui = (1. + x).to_bits(); hu = (ui >> 32) as u32; hu += 0x3ff00000 - 0x3fe6a09e; k = (hu >> 20) as i32 - 0x3ff; /* correction term ~ log(1+x)-log(u), avoid underflow in c/u */ if k < 54 { c = if k >= 2 { 1. - (f64::from_bits(ui) - x) } else { x - (f64::from_bits(ui) - 1.) }; c /= f64::from_bits(ui); } else { c = 0.; } /* reduce u into [sqrt(2)/2, sqrt(2)] */ hu = (hu & 0x000fffff) + 0x3fe6a09e; ui = (hu as u64) << 32 | (ui & 0xffffffff); f = f64::from_bits(ui) - 1.; } hfsq = 0.5 * f * f; s = f / (2.0 + f); z = s * s; w = z * z; t1 = w * (LG2 + w * (LG4 + w * LG6)); t2 = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7))); r = t2 + t1; dk = k as f64; s * (hfsq + r) + (dk * LN2_LO + c) - hfsq + f + dk * LN2_HI }
use fonttools_cli::{open_font, read_args, save_font}; fn main() { let matches = read_args( "ttf-fix-checksum", "Ensures TTF files have correct checksum", ); let infont = open_font(&matches); save_font(infont, &matches); }
use crate::error; use crate::plan::ir::Field; use arrow::datatypes::DataType; use datafusion::common::{DFSchemaRef, Result}; use datafusion::logical_expr::{Expr, LogicalPlan, LogicalPlanBuilder}; use datafusion_util::AsExpr; use generated_types::influxdata::iox::querier::v1::influx_ql_metadata::TagKeyColumn; use influxdb_influxql_parser::expression::{Call, Expr as IQLExpr, VarRef, VarRefDataType}; use influxdb_influxql_parser::identifier::Identifier; use influxdb_influxql_parser::literal::Literal; use itertools::Itertools; use schema::{InfluxColumnType, INFLUXQL_MEASUREMENT_COLUMN_NAME}; use std::collections::{HashMap, HashSet}; use std::fmt::{Display, Formatter}; pub(super) fn make_tag_key_column_meta( fields: &[Field], tag_set: &[&str], is_projected: &[bool], ) -> Vec<TagKeyColumn> { /// There is always a [INFLUXQL_MEASUREMENT_COLUMN_NAME] and `time` column projected in the LogicalPlan, /// therefore the start index is 2 for determining the offsets of the /// tag key columns in the column projection list. const START_INDEX: usize = 1; // Create a map of tag key columns to their respective index in the projection let index_map = fields .iter() .enumerate() .filter_map(|(index, f)| match &f.data_type { Some(InfluxColumnType::Tag) | None => Some((f.name.as_str(), index + START_INDEX)), _ => None, }) .collect::<HashMap<_, _>>(); // tag_set was previously sorted, so tag_key_columns will be in the correct order tag_set .iter() .zip(is_projected) .map(|(tag_key, is_projected)| TagKeyColumn { tag_key: (*tag_key).to_owned(), column_index: *index_map.get(*tag_key).unwrap() as _, is_projected: *is_projected, }) .collect() } /// Create a plan that sorts the input plan. /// /// The ordering of the results is as follows: /// /// iox::measurement, [group by tag 0, .., group by tag n], time, [projection tag 0, .., projection tag n] /// /// ## NOTE /// /// Sort expressions referring to tag keys are always specified in lexicographically ascending order. pub(super) fn plan_with_sort( plan: LogicalPlan, mut sort_exprs: Vec<Expr>, sort_by_measurement: bool, group_by_tag_set: &[&str], projection_tag_set: &[&str], ) -> Result<LogicalPlan> { let mut series_sort = if sort_by_measurement { vec![Expr::sort( INFLUXQL_MEASUREMENT_COLUMN_NAME.as_expr(), true, false, )] } else { vec![] }; /// Map the fields to DataFusion [`Expr::Sort`] expressions, excluding those columns that /// are [`DataType::Null`]'s, as sorting these column types is not supported and unnecessary. fn map_to_expr<'a>( schema: &'a DFSchemaRef, fields: &'a [&str], ) -> impl Iterator<Item = Expr> + 'a { fields_to_exprs_no_nulls(schema, fields).map(|f| Expr::sort(f, true, false)) } let schema = plan.schema(); if !group_by_tag_set.is_empty() { series_sort.extend(map_to_expr(schema, group_by_tag_set)); }; series_sort.append(&mut sort_exprs); series_sort.extend(map_to_expr(schema, projection_tag_set)); LogicalPlanBuilder::from(plan).sort(series_sort)?.build() } /// Map the fields to DataFusion [`Expr::Column`] expressions, excluding those columns that /// are [`DataType::Null`]'s. pub(super) fn fields_to_exprs_no_nulls<'a>( schema: &'a DFSchemaRef, fields: &'a [&str], ) -> impl Iterator<Item = Expr> + 'a { fields .iter() .filter(|f| { if let Ok(df) = schema.field_with_unqualified_name(f) { *df.data_type() != DataType::Null } else { false } }) .map(|f| f.as_expr()) } /// Contains an expanded `SELECT` projection pub(super) struct ProjectionInfo<'a> { /// A copy of the `SELECT` fields that includes tags from the `GROUP BY` that were not /// specified in the original `SELECT` projection. pub(super) fields: Vec<Field>, /// A list of tag column names specified in the `GROUP BY` clause. pub(super) group_by_tag_set: Vec<&'a str>, /// A list of tag column names specified exclusively in the `SELECT` projection. pub(super) projection_tag_set: Vec<&'a str>, /// A list of booleans indicating whether matching elements in the /// `group_by_tag_set` are also projected in the query. pub(super) is_projected: Vec<bool>, } impl<'a> ProjectionInfo<'a> { /// Computes a `ProjectionInfo` from the specified `fields` and `group_by_tags`. pub(super) fn new(fields: &'a [Field], group_by_tags: &'a [&'a str]) -> Self { // Skip the `time` column let fields_no_time = &fields[1..]; // always start with the time column let mut fields = vec![fields.first().cloned().unwrap()]; let (group_by_tag_set, projection_tag_set, is_projected) = if group_by_tags.is_empty() { let tag_columns = find_tag_and_unknown_columns(fields_no_time) .sorted() .collect::<Vec<_>>(); (vec![], tag_columns, vec![]) } else { let mut tag_columns = find_tag_and_unknown_columns(fields_no_time).collect::<HashSet<_>>(); // Find the list of tag keys specified in the `GROUP BY` clause, and // whether any of the tag keys are also projected in the SELECT list. let (tag_set, is_projected): (Vec<_>, Vec<_>) = group_by_tags .iter() .map(|s| (*s, tag_columns.contains(s))) .unzip(); // Tags specified in the `GROUP BY` clause that are not already added to the // projection must be projected, so they can be used in the group key. // // At the end of the loop, the `tag_columns` set will contain the tag columns that // exist in the projection and not in the `GROUP BY`. fields.extend( tag_set .iter() .filter_map(|col| match tag_columns.remove(*col) { true => None, false => Some(Field { expr: IQLExpr::VarRef(VarRef { name: (*col).into(), data_type: Some(VarRefDataType::Tag), }), name: col.to_string(), data_type: Some(InfluxColumnType::Tag), }), }), ); ( tag_set, tag_columns.into_iter().sorted().collect::<Vec<_>>(), is_projected, ) }; fields.extend(fields_no_time.iter().cloned()); Self { fields, group_by_tag_set, projection_tag_set, is_projected, } } } /// Find all the columns where the resolved data type /// is a tag or is [`None`], which is unknown. fn find_tag_and_unknown_columns(fields: &[Field]) -> impl Iterator<Item = &str> { fields.iter().filter_map(|f| match f.data_type { Some(InfluxColumnType::Tag) | None => Some(f.name.as_str()), _ => None, }) } /// The selector function that has been specified for use with a selector /// projection type. #[derive(Debug)] pub(super) enum Selector<'a> { Bottom { field_key: &'a Identifier, tag_keys: Vec<&'a Identifier>, n: i64, }, First { field_key: &'a Identifier, }, Last { field_key: &'a Identifier, }, Max { field_key: &'a Identifier, }, Min { field_key: &'a Identifier, }, Percentile { field_key: &'a Identifier, n: f64, }, Sample { field_key: &'a Identifier, n: i64, }, Top { field_key: &'a Identifier, tag_keys: Vec<&'a Identifier>, n: i64, }, } impl<'a> Selector<'a> { /// Find the selector function, with its location, in the specified field list. pub(super) fn find_enumerated(fields: &'a [Field]) -> Result<(usize, Self)> { fields .iter() .enumerate() .find_map(|(idx, f)| match &f.expr { IQLExpr::Call(c) => Some((idx, c)), _ => None, }) .map(|(idx, c)| { Ok(( idx, match c.name.as_str() { "bottom" => Self::bottom(c), "first" => Self::first(c), "last" => Self::last(c), "max" => Self::max(c), "min" => Self::min(c), "percentile" => Self::percentile(c), "sample" => Self::sample(c), "top" => Self::top(c), name => error::internal(format!("unexpected selector function: {name}")), }?, )) }) .ok_or_else(|| error::map::internal("expected Call expression"))? } fn bottom(call: &'a Call) -> Result<Self> { let [field_key, tag_keys @ .., narg] = call.args.as_slice() else { return error::internal(format!( "invalid number of arguments for bottom: expected 2 or more, got {}", call.args.len() )); }; let tag_keys: Result<Vec<_>> = tag_keys.iter().map(Self::identifier).collect(); Ok(Self::Bottom { field_key: Self::identifier(field_key)?, tag_keys: tag_keys?, n: Self::literal_int(narg)?, }) } fn first(call: &'a Call) -> Result<Self> { if call.args.len() != 1 { return error::internal(format!( "invalid number of arguments for first: expected 1, got {}", call.args.len() )); } Ok(Self::First { field_key: Self::identifier(call.args.get(0).unwrap())?, }) } fn last(call: &'a Call) -> Result<Self> { if call.args.len() != 1 { return error::internal(format!( "invalid number of arguments for last: expected 1, got {}", call.args.len() )); } Ok(Self::Last { field_key: Self::identifier(call.args.get(0).unwrap())?, }) } fn max(call: &'a Call) -> Result<Self> { if call.args.len() != 1 { return error::internal(format!( "invalid number of arguments for max: expected 1, got {}", call.args.len() )); } Ok(Self::Max { field_key: Self::identifier(call.args.get(0).unwrap())?, }) } fn min(call: &'a Call) -> Result<Self> { if call.args.len() != 1 { return error::internal(format!( "invalid number of arguments for min: expected 1, got {}", call.args.len() )); } Ok(Self::Min { field_key: Self::identifier(call.args.get(0).unwrap())?, }) } fn percentile(call: &'a Call) -> Result<Self> { if call.args.len() != 2 { return error::internal(format!( "invalid number of arguments for min: expected 1, got {}", call.args.len() )); } Ok(Self::Percentile { field_key: Self::identifier(call.args.get(0).unwrap())?, n: Self::literal_num(call.args.get(1).unwrap())?, }) } fn sample(call: &'a Call) -> Result<Self> { if call.args.len() != 2 { return error::internal(format!( "invalid number of arguments for min: expected 1, got {}", call.args.len() )); } Ok(Self::Sample { field_key: Self::identifier(call.args.get(0).unwrap())?, n: Self::literal_int(call.args.get(1).unwrap())?, }) } fn top(call: &'a Call) -> Result<Self> { let [field_key, tag_keys @ .., narg] = call.args.as_slice() else { return error::internal(format!( "invalid number of arguments for top: expected 2 or more, got {}", call.args.len() )); }; let tag_keys: Result<Vec<_>> = tag_keys.iter().map(Self::identifier).collect(); Ok(Self::Top { field_key: Self::identifier(field_key)?, tag_keys: tag_keys?, n: Self::literal_int(narg)?, }) } fn identifier(expr: &'a IQLExpr) -> Result<&'a Identifier> { match expr { IQLExpr::VarRef(v) => Ok(&v.name), e => error::internal(format!("invalid column identifier: {}", e)), } } fn literal_int(expr: &'a IQLExpr) -> Result<i64> { match expr { IQLExpr::Literal(Literal::Integer(n)) => Ok(*n), e => error::internal(format!("invalid integer literal: {}", e)), } } fn literal_num(expr: &'a IQLExpr) -> Result<f64> { match expr { IQLExpr::Literal(Literal::Integer(n)) => Ok(*n as f64), IQLExpr::Literal(Literal::Float(n)) => Ok(*n), e => error::internal(format!("invalid integer literal: {}", e)), } } } impl<'a> Display for Selector<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { match self { Self::Bottom { field_key, tag_keys, n, } => { write!(f, "bottom({field_key}")?; for tag_key in tag_keys { write!(f, ", {tag_key}")?; } write!(f, ", {n})") } Self::First { field_key } => write!(f, "first({field_key})"), Self::Last { field_key } => write!(f, "last({field_key})"), Self::Max { field_key } => write!(f, "max({field_key})"), Self::Min { field_key } => write!(f, "min({field_key})"), Self::Percentile { field_key, n } => write!(f, "percentile({field_key}, {n})"), Self::Sample { field_key, n } => write!(f, "sample({field_key}, {n})"), Self::Top { field_key, tag_keys, n, } => { write!(f, "top({field_key}")?; for tag_key in tag_keys { write!(f, ", {tag_key}")?; } write!(f, ", {n})") } } } } #[derive(Clone, Copy, Debug)] pub(super) enum SelectorWindowOrderBy<'a> { FieldAsc(&'a Identifier), FieldDesc(&'a Identifier), }
pub fn lambda(handler: fn(&str) -> std::result::Result<String, String>) { // Initialise one-time resources here // If initialisation error, POST to /runtime/init/error // Get new invocation events and pass to handler let aws_lambda_runtime_api = std::env::var("AWS_LAMBDA_RUNTIME_API").unwrap(); loop { let invocation = ureq::get(&format!( "http://{}/2018-06-01/runtime/invocation/next", aws_lambda_runtime_api )) .call(); let request_id = invocation .header("Lambda-Runtime-Aws-Request-Id") .unwrap() .to_string(); let response = handler(invocation.into_string().unwrap().as_str()); match response { Ok(res) => { let _resp = ureq::post(&format!( "http://{}/2018-06-01/runtime/invocation/{}/response", aws_lambda_runtime_api, request_id )) .send_string(&res); } Err(err) => { // Handle error // If invocation error, POST to /runtime/invocation/AwsRequestId/error let _resp = ureq::post(&format!( "http://{}/2018-06-01/runtime/invocation/{}/error", aws_lambda_runtime_api, request_id )) .send_string(&err.to_string()); } } } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type HostMessageReceivedCallback = *mut ::core::ffi::c_void; pub type IsolatedWindowsEnvironment = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct IsolatedWindowsEnvironmentActivator(pub i32); impl IsolatedWindowsEnvironmentActivator { pub const System: Self = Self(0i32); pub const User: Self = Self(1i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentActivator {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentActivator { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct IsolatedWindowsEnvironmentAllowedClipboardFormats(pub u32); impl IsolatedWindowsEnvironmentAllowedClipboardFormats { pub const None: Self = Self(0u32); pub const Text: Self = Self(1u32); pub const Image: Self = Self(2u32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentAllowedClipboardFormats {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentAllowedClipboardFormats { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct IsolatedWindowsEnvironmentAvailablePrinters(pub u32); impl IsolatedWindowsEnvironmentAvailablePrinters { pub const None: Self = Self(0u32); pub const Local: Self = Self(1u32); pub const Network: Self = Self(2u32); pub const SystemPrintToPdf: Self = Self(4u32); pub const SystemPrintToXps: Self = Self(8u32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentAvailablePrinters {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentAvailablePrinters { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct IsolatedWindowsEnvironmentClipboardCopyPasteDirections(pub u32); impl IsolatedWindowsEnvironmentClipboardCopyPasteDirections { pub const None: Self = Self(0u32); pub const HostToIsolatedWindowsEnvironment: Self = Self(1u32); pub const IsolatedWindowsEnvironmentToHost: Self = Self(2u32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentClipboardCopyPasteDirections {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentClipboardCopyPasteDirections { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct IsolatedWindowsEnvironmentCreateProgress { pub State: IsolatedWindowsEnvironmentProgressState, pub PercentComplete: u32, } impl ::core::marker::Copy for IsolatedWindowsEnvironmentCreateProgress {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentCreateProgress { fn clone(&self) -> Self { *self } } pub type IsolatedWindowsEnvironmentCreateResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct IsolatedWindowsEnvironmentCreateStatus(pub i32); impl IsolatedWindowsEnvironmentCreateStatus { pub const Success: Self = Self(0i32); pub const FailureByPolicy: Self = Self(1i32); pub const UnknownFailure: Self = Self(2i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentCreateStatus {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentCreateStatus { fn clone(&self) -> Self { *self } } pub type IsolatedWindowsEnvironmentFile = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct IsolatedWindowsEnvironmentHostError(pub i32); impl IsolatedWindowsEnvironmentHostError { pub const AdminPolicyIsDisabledOrNotPresent: Self = Self(0i32); pub const FeatureNotInstalled: Self = Self(1i32); pub const HardwareRequirementsNotMet: Self = Self(2i32); pub const RebootRequired: Self = Self(3i32); pub const UnknownError: Self = Self(4i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentHostError {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentHostError { fn clone(&self) -> Self { *self } } pub type IsolatedWindowsEnvironmentLaunchFileResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct IsolatedWindowsEnvironmentLaunchFileStatus(pub i32); impl IsolatedWindowsEnvironmentLaunchFileStatus { pub const Success: Self = Self(0i32); pub const UnknownFailure: Self = Self(1i32); pub const EnvironmentUnavailable: Self = Self(2i32); pub const FileNotFound: Self = Self(3i32); pub const TimedOut: Self = Self(4i32); pub const AlreadySharedWithConflictingOptions: Self = Self(5i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentLaunchFileStatus {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentLaunchFileStatus { fn clone(&self) -> Self { *self } } pub type IsolatedWindowsEnvironmentOptions = *mut ::core::ffi::c_void; pub type IsolatedWindowsEnvironmentOwnerRegistrationData = *mut ::core::ffi::c_void; pub type IsolatedWindowsEnvironmentOwnerRegistrationResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct IsolatedWindowsEnvironmentOwnerRegistrationStatus(pub i32); impl IsolatedWindowsEnvironmentOwnerRegistrationStatus { pub const Success: Self = Self(0i32); pub const InvalidArgument: Self = Self(1i32); pub const AccessDenied: Self = Self(2i32); pub const InsufficientMemory: Self = Self(3i32); pub const UnknownFailure: Self = Self(4i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentOwnerRegistrationStatus {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentOwnerRegistrationStatus { fn clone(&self) -> Self { *self } } pub type IsolatedWindowsEnvironmentPostMessageResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct IsolatedWindowsEnvironmentPostMessageStatus(pub i32); impl IsolatedWindowsEnvironmentPostMessageStatus { pub const Success: Self = Self(0i32); pub const UnknownFailure: Self = Self(1i32); pub const EnvironmentUnavailable: Self = Self(2i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentPostMessageStatus {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentPostMessageStatus { fn clone(&self) -> Self { *self } } pub type IsolatedWindowsEnvironmentProcess = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct IsolatedWindowsEnvironmentProcessState(pub i32); impl IsolatedWindowsEnvironmentProcessState { pub const Running: Self = Self(1i32); pub const Aborted: Self = Self(2i32); pub const Completed: Self = Self(3i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentProcessState {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentProcessState { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct IsolatedWindowsEnvironmentProgressState(pub i32); impl IsolatedWindowsEnvironmentProgressState { pub const Queued: Self = Self(0i32); pub const Processing: Self = Self(1i32); pub const Completed: Self = Self(2i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentProgressState {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentProgressState { fn clone(&self) -> Self { *self } } pub type IsolatedWindowsEnvironmentShareFileRequestOptions = *mut ::core::ffi::c_void; pub type IsolatedWindowsEnvironmentShareFileResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct IsolatedWindowsEnvironmentShareFileStatus(pub i32); impl IsolatedWindowsEnvironmentShareFileStatus { pub const Success: Self = Self(0i32); pub const UnknownFailure: Self = Self(1i32); pub const EnvironmentUnavailable: Self = Self(2i32); pub const AlreadySharedWithConflictingOptions: Self = Self(3i32); pub const FileNotFound: Self = Self(4i32); pub const AccessDenied: Self = Self(5i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentShareFileStatus {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentShareFileStatus { fn clone(&self) -> Self { *self } } pub type IsolatedWindowsEnvironmentShareFolderRequestOptions = *mut ::core::ffi::c_void; pub type IsolatedWindowsEnvironmentShareFolderResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct IsolatedWindowsEnvironmentShareFolderStatus(pub i32); impl IsolatedWindowsEnvironmentShareFolderStatus { pub const Success: Self = Self(0i32); pub const UnknownFailure: Self = Self(1i32); pub const EnvironmentUnavailable: Self = Self(2i32); pub const FolderNotFound: Self = Self(3i32); pub const AccessDenied: Self = Self(4i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentShareFolderStatus {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentShareFolderStatus { fn clone(&self) -> Self { *self } } pub type IsolatedWindowsEnvironmentStartProcessResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct IsolatedWindowsEnvironmentStartProcessStatus(pub i32); impl IsolatedWindowsEnvironmentStartProcessStatus { pub const Success: Self = Self(0i32); pub const UnknownFailure: Self = Self(1i32); pub const EnvironmentUnavailable: Self = Self(2i32); pub const FileNotFound: Self = Self(3i32); pub const AppNotRegistered: Self = Self(4i32); } impl ::core::marker::Copy for IsolatedWindowsEnvironmentStartProcessStatus {} impl ::core::clone::Clone for IsolatedWindowsEnvironmentStartProcessStatus { fn clone(&self) -> Self { *self } } pub type IsolatedWindowsEnvironmentTelemetryParameters = *mut ::core::ffi::c_void; pub type IsolatedWindowsEnvironmentUserInfo = *mut ::core::ffi::c_void; pub type MessageReceivedCallback = *mut ::core::ffi::c_void;
use actix::prelude::*; use crate::WorkerState; use crate::messages::StatusUpdate; pub struct Executor { worker_state: Addr<WorkerState> } impl Executor { pub fn new(worker_state: Addr<WorkerState>) -> Executor { Executor { worker_state } } } impl Actor for Executor { type Context = Context<Self>; fn started(&mut self, _ctx: &mut Self::Context) { println!("[Executor] Started"); } } impl StreamHandler<StatusUpdate, ()> for Executor { fn handle(&mut self, msg: StatusUpdate, _: &mut Context<Executor>) { match msg { StatusUpdate::NoUpdate => {}, _ => { self.worker_state.do_send(msg); } } } fn error(&mut self, _: (), _: &mut Context<Executor>) -> Running { println!("[Executor] got error from stream"); Running::Continue } fn finished(&mut self, _: &mut Context<Executor>) { println!("[Executor] finished with stream"); } }
//! Macros for defining plugin functions. /// Define file importer #[macro_export] macro_rules! plugkit_api_file_import { ( $x:ident ) => { #[no_mangle] pub extern "C" fn plugkit_v1_file_importer_is_supported(c: *mut Context, p: *const libc::c_char) -> bool { use std::ffi::CStr; use std::str; use std::path::Path; let path = unsafe { let slice = CStr::from_ptr(p); Path::new(str::from_utf8_unchecked(slice.to_bytes())) }; let ctx = unsafe { &mut *c }; $x::is_supported(ctx, path) } #[no_mangle] pub extern "C" fn plugkit_v1_file_importer_start(c: *mut Context, p: *const libc::c_char, d: *mut RawFrame, s: libc::size_t, callback: extern "C" fn (*mut Context, libc::size_t, f64)) -> plugkit::file::Status { use std::ffi::CStr; use std::{str,slice}; use std::path::Path; use plugkit::file::Status; let path = unsafe { let slice = CStr::from_ptr(p); Path::new(str::from_utf8_unchecked(slice.to_bytes())) }; let dst = unsafe { slice::from_raw_parts_mut(d, s as usize) }; let ctx = unsafe { &mut *c }; let result = $x::start(ctx, path, dst, &|ctx, len, prog| { callback(ctx as *mut Context, len, prog); }); callback(c, 0, 1.0); if result.is_err() { Status::Error } else { Status::Done } } }; } /// Define file exporter #[macro_export] macro_rules! plugkit_api_file_export { ( $x:ident ) => { #[no_mangle] pub extern "C" fn plugkit_v1_file_exporter_is_supported(c: *mut Context, p: *const libc::c_char) -> bool { use std::ffi::CStr; use std::str; use std::path::Path; let path = unsafe { let slice = CStr::from_ptr(p); Path::new(str::from_utf8_unchecked(slice.to_bytes())) }; let ctx = unsafe { &mut *c }; $x::is_supported(ctx, path) } #[no_mangle] pub extern "C" fn plugkit_v1_file_exporter_start(c: *mut Context, p: *const libc::c_char, callback: extern "C" fn (*mut Context, *mut libc::size_t) -> *const RawFrame) -> plugkit::file::Status { use std::ffi::CStr; use std::{str,slice}; use std::path::Path; use plugkit::file::Status; let path = unsafe { let slice = CStr::from_ptr(p); Path::new(str::from_utf8_unchecked(slice.to_bytes())) }; let ctx = unsafe { &mut *c }; let result = $x::start(ctx, path, &|ctx| { let mut len : libc::size_t = 0; unsafe { let ptr = &*callback(ctx as *mut Context, &mut len as *mut libc::size_t); slice::from_raw_parts(ptr, len as usize) } }); if result.is_err() { Status::Error } else { Status::Done } } }; } /// Define layer hints #[macro_export] macro_rules! plugkit_api_layer_hints { ( $( $x:expr ), * ) => { #[no_mangle] pub extern "C" fn plugkit_v1_layer_hints(index: u32) -> u32 { let mut temp_vec = Vec::new(); $( temp_vec.push($x); )* temp_vec.push(0); temp_vec[index as usize] } }; } /// Define worker #[macro_export] macro_rules! plugkit_api_worker { ( $x: ty, $y:expr ) => { #[no_mangle] pub extern "C" fn plugkit_v1_create_worker(_ctx: *const (), _diss: *const ()) -> *mut() { Box::into_raw(Box::new($y)) as *mut() } #[no_mangle] pub extern "C" fn plugkit_v1_destroy_worker(_ctx: *const (), _diss: *const (), worker: *mut()) { unsafe { Box::from_raw(worker as *mut $x); } } #[no_mangle] pub extern "C" fn plugkit_v1_examine(ctx: *mut (), _diss: *const (), worker: *mut(), layer: *const ()) -> u32 { use std::panic; use plugkit::context::Context; use plugkit::layer::Layer; unsafe { let w: &mut $x = &mut *(worker as *mut $x); let c: &mut Context = &mut *(ctx as *mut Context); let l: &Layer = &*(layer as *const Layer); let result = panic::catch_unwind(panic::AssertUnwindSafe(|| { w.examine(c, l) })); match result { Ok(conf) => conf as u32, Err(e) => { println!("{:?}", e); 0 }, } } } #[no_mangle] pub extern "C" fn plugkit_v1_analyze(ctx: *mut (), _diss: *const (), worker: *mut(), layer: *mut ()) { use std::panic; use plugkit::context::Context; use plugkit::layer::Layer; unsafe { let w: &mut $x = &mut *(worker as *mut $x); let c: &mut Context = &mut *(ctx as *mut Context); let l: &mut Layer = &mut *(layer as *mut Layer); let result = panic::catch_unwind(panic::AssertUnwindSafe(|| { w.analyze(c, l) })); match result { Ok(_) => {}, Err(e) => { println!("{:?}", e); }, }; } } }; }
use std::collections::HashMap; use std::net::{SocketAddr, UdpSocket}; use std::sync::{Arc, mpsc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use crate::network::MAX_PACKET_SIZE; pub struct NetworkAbuser { running: Mutex<bool>, socket: UdpSocket, sender: Mutex<mpsc::Sender<bool>>, send_thread: Mutex<Option<thread::JoinHandle<()>>>, receive_thread: Mutex<Option<thread::JoinHandle<()>>>, network_conditions: Arc<Mutex<NetworkConditions>>, } impl NetworkAbuser { pub fn new(bind: SocketAddr, source: SocketAddr, target: SocketAddr) -> Self { let socket = UdpSocket::bind(bind).unwrap(); let (sender, receiver) = mpsc::channel(); let packets = Arc::new(Mutex::new(Vec::new())); let network_conditions = Arc::new(Mutex::new(NetworkConditions::new())); let receive_thread = Mutex::new(Some({ let socket = socket.try_clone().unwrap(); let network_conditions = network_conditions.clone(); let sender = sender.clone(); let packets = packets.clone(); thread::spawn(move || network_abuser_receive_thread(socket, network_conditions, sender, source, target, packets)) })); let send_thread = Mutex::new(Some({ let socket = socket.try_clone().unwrap(); thread::spawn(move || network_abuser_send_thread(socket, receiver, packets)) })); Self { running: Mutex::new(true), socket, sender: Mutex::new(sender), send_thread, receive_thread, network_conditions, } } pub fn drop_every_nth(self, n: usize) -> Self { self.network_conditions.lock().unwrap().drop_every_nth = n; self } pub fn constant_latency(self, latency_ms: u64) -> Self { self.network_conditions.lock().unwrap().constant_latency = Duration::from_millis(latency_ms); self } pub fn intermittent_latency(self, latency_ms: u64, good_ms: u64, bad_ms: u64, offset_ms: i64) -> Self { self.network_conditions.lock().unwrap().intermittent_latencies.push(( Duration::from_millis(latency_ms), Duration::from_millis(good_ms), Duration::from_millis(bad_ms), if offset_ms >= 0 { Instant::now() + Duration::from_millis(offset_ms as u64) } else { Instant::now() - Duration::from_millis(offset_ms.abs() as u64) }, )); self } pub fn shutdown(&self) { let mut running = self.running.lock().unwrap(); if *running { self.socket.send_to(&[], self.socket.local_addr().unwrap()).unwrap(); self.receive_thread.lock().unwrap().take().unwrap().join().ok(); self.sender.lock().unwrap().send(true).unwrap(); self.send_thread.lock().unwrap().take().unwrap().join().ok(); *running = false; } } } impl Drop for NetworkAbuser { fn drop(&mut self) { self.shutdown(); } } struct NetworkConditions { pub drop_every_nth: usize, pub constant_latency: Duration, pub intermittent_latencies: Vec<(Duration, Duration, Duration, Instant)>, } impl NetworkConditions { pub fn new() -> Self { Self { drop_every_nth: 0, constant_latency: Duration::from_secs(0), intermittent_latencies: Vec::new(), } } } fn network_abuser_send_thread( socket: UdpSocket, receiver: mpsc::Receiver<bool>, packets: Arc<Mutex<Vec<(Instant, SocketAddr, Vec<u8>)>>>, ) { loop { let min_time = { let mut packets_guard = packets.lock().unwrap(); let mut min_time = Duration::from_secs(1); let mut removed_indices = 0; for i in 0..packets_guard.len() { let current_index = i - removed_indices; let (ttl, destination, ref payload) = packets_guard[current_index]; let now = Instant::now(); if ttl <= now { socket.send_to(payload, destination).unwrap(); packets_guard.remove(current_index); removed_indices += 1; } else { let remainder = ttl - now; if remainder < min_time { min_time = remainder; } } } min_time }; if let Ok(quit) = receiver.recv_timeout(Duration::from_nanos((min_time.as_nanos() / 2) as u64)) { if quit { break; } } } } fn network_abuser_receive_thread( socket: UdpSocket, network_conditions: Arc<Mutex<NetworkConditions>>, sender: mpsc::Sender<bool>, source: SocketAddr, target: SocketAddr, packets: Arc<Mutex<Vec<(Instant, SocketAddr, Vec<u8>)>>>, ) { let mut packet_numbers = HashMap::new(); packet_numbers.insert(source, 0usize); packet_numbers.insert(target, 0usize); loop { let mut buffer = vec![0u8; MAX_PACKET_SIZE]; let (size, origin) = socket.recv_from(&mut buffer).unwrap(); buffer.truncate(size); let received_at = Instant::now(); if origin == socket.local_addr().unwrap() { break; } else if !packet_numbers.contains_key(&origin) { continue; } let packet_number = packet_numbers.get_mut(&origin).unwrap(); *packet_number += 1; let ttl = { let guard = network_conditions.lock().unwrap(); if guard.drop_every_nth > 0 && *packet_number % guard.drop_every_nth == 0 { continue; } let now = Instant::now(); let mut intermittent_latency = Duration::from_secs(0); for &(latency, good, bad, origin) in guard.intermittent_latencies.iter() { let cycle_length = good + bad; if now < origin { continue; } // Duration has no modulo division.. :P let mut remainder = now.duration_since(origin); while remainder > cycle_length { remainder -= cycle_length; } if remainder > good { intermittent_latency += latency; } } received_at + guard.constant_latency + intermittent_latency }; { let mut guard = packets.lock().unwrap(); guard.push(( ttl, if origin == source { target } else { source }, buffer, )); } sender.send(false).unwrap(); } } #[cfg(test)] mod tests { use std::str::FromStr; use std::thread; use std::time::Duration; use lazy_static::lazy_static; use super::*; lazy_static! { static ref ACCESS: Mutex<()> = Mutex::new(()); // Ensures that tests run sequentially, thus not fighting over socket resources. static ref ABUSER: SocketAddr = SocketAddr::from_str("127.0.0.1:1234").unwrap(); static ref CLIENT: SocketAddr = SocketAddr::from_str("127.0.0.1:1235").unwrap(); } #[test] fn network_abuser_drop_every_nth() { log_level!(NONE); let _guard = ACCESS.lock().unwrap(); let _a = NetworkAbuser::new(*ABUSER, *CLIENT, *CLIENT) .drop_every_nth(3); let c = UdpSocket::bind(*CLIENT).unwrap(); c.send_to(&[1], *ABUSER).unwrap(); c.send_to(&[2], *ABUSER).unwrap(); c.send_to(&[3], *ABUSER).unwrap(); c.send_to(&[4], *ABUSER).unwrap(); thread::sleep(Duration::from_millis(200)); c.set_read_timeout(Some(Duration::from_millis(200))).unwrap(); let mut buffer = [0]; c.recv_from(&mut buffer).unwrap(); assert_eq!(buffer[0], 1); c.recv_from(&mut buffer).unwrap(); assert_eq!(buffer[0], 2); c.recv_from(&mut buffer).unwrap(); assert_eq!(buffer[0], 4); assert!(c.recv_from(&mut buffer).is_err()); } }
use crate::ast; use crate::macros; use crate::parsing; use crate::shared; use std::fmt; /// This file has been generated from `assets\tokens.yaml` /// DO NOT modify by hand! /// The `abstract` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Abstract { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Abstract { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Abstract { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Abstract => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "abstract")), } } } impl parsing::Peek for Abstract { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Abstract) } } impl macros::ToTokens for Abstract { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `alignof` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct AlignOf { /// Associated token. pub token: ast::Token, } impl crate::Spanned for AlignOf { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for AlignOf { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::AlignOf => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "alignof")), } } } impl parsing::Peek for AlignOf { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::AlignOf) } } impl macros::ToTokens for AlignOf { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `&`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Amp { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Amp { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Amp { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Amp => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "&")), } } } impl parsing::Peek for Amp { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Amp) } } impl macros::ToTokens for Amp { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `&&`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct AmpAmp { /// Associated token. pub token: ast::Token, } impl crate::Spanned for AmpAmp { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for AmpAmp { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::AmpAmp => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "&&")), } } } impl parsing::Peek for AmpAmp { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::AmpAmp) } } impl macros::ToTokens for AmpAmp { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `&=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct AmpEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for AmpEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for AmpEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::AmpEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "&=")), } } } impl parsing::Peek for AmpEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::AmpEq) } } impl macros::ToTokens for AmpEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `->`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Arrow { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Arrow { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Arrow { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Arrow => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "->")), } } } impl parsing::Peek for Arrow { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Arrow) } } impl macros::ToTokens for Arrow { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `as` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct As { /// Associated token. pub token: ast::Token, } impl crate::Spanned for As { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for As { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::As => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "as")), } } } impl parsing::Peek for As { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::As) } } impl macros::ToTokens for As { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `async` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Async { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Async { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Async { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Async => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "async")), } } } impl parsing::Peek for Async { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Async) } } impl macros::ToTokens for Async { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `@`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct At { /// Associated token. pub token: ast::Token, } impl crate::Spanned for At { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for At { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::At => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "@")), } } } impl parsing::Peek for At { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::At) } } impl macros::ToTokens for At { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `await` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Await { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Await { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Await { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Await => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "await")), } } } impl parsing::Peek for Await { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Await) } } impl macros::ToTokens for Await { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `!`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Bang { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Bang { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Bang { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Bang => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "!")), } } } impl parsing::Peek for Bang { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Bang) } } impl macros::ToTokens for Bang { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `!=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct BangEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for BangEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for BangEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::BangEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "!=")), } } } impl parsing::Peek for BangEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::BangEq) } } impl macros::ToTokens for BangEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `become` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Become { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Become { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Become { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Become => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "become")), } } } impl parsing::Peek for Become { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Become) } } impl macros::ToTokens for Become { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `break` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Break { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Break { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Break { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Break => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "break")), } } } impl parsing::Peek for Break { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Break) } } impl macros::ToTokens for Break { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `^`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Caret { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Caret { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Caret { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Caret => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "^")), } } } impl parsing::Peek for Caret { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Caret) } } impl macros::ToTokens for Caret { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `^=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct CaretEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for CaretEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for CaretEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::CaretEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "^=")), } } } impl parsing::Peek for CaretEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::CaretEq) } } impl macros::ToTokens for CaretEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `:`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Colon { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Colon { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Colon { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Colon => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, ":")), } } } impl parsing::Peek for Colon { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Colon) } } impl macros::ToTokens for Colon { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `::`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ColonColon { /// Associated token. pub token: ast::Token, } impl crate::Spanned for ColonColon { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for ColonColon { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::ColonColon => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "::")), } } } impl parsing::Peek for ColonColon { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::ColonColon) } } impl macros::ToTokens for ColonColon { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `,`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Comma { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Comma { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Comma { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Comma => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, ",")), } } } impl parsing::Peek for Comma { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Comma) } } impl macros::ToTokens for Comma { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `const` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Const { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Const { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Const { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Const => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "const")), } } } impl parsing::Peek for Const { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Const) } } impl macros::ToTokens for Const { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `continue` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Continue { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Continue { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Continue { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Continue => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "continue")), } } } impl parsing::Peek for Continue { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Continue) } } impl macros::ToTokens for Continue { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `crate` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Crate { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Crate { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Crate { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Crate => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "crate")), } } } impl parsing::Peek for Crate { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Crate) } } impl macros::ToTokens for Crate { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `-`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Dash { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Dash { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Dash { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Dash => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "-")), } } } impl parsing::Peek for Dash { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Dash) } } impl macros::ToTokens for Dash { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `-=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DashEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for DashEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for DashEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::DashEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "-=")), } } } impl parsing::Peek for DashEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::DashEq) } } impl macros::ToTokens for DashEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `default` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Default { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Default { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Default { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Default => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "default")), } } } impl parsing::Peek for Default { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Default) } } impl macros::ToTokens for Default { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `/`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Div { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Div { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Div { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Div => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "/")), } } } impl parsing::Peek for Div { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Div) } } impl macros::ToTokens for Div { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `do` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Do { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Do { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Do { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Do => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "do")), } } } impl parsing::Peek for Do { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Do) } } impl macros::ToTokens for Do { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `$`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Dollar { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Dollar { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Dollar { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Dollar => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "$")), } } } impl parsing::Peek for Dollar { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Dollar) } } impl macros::ToTokens for Dollar { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `.`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Dot { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Dot { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Dot { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Dot => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, ".")), } } } impl parsing::Peek for Dot { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Dot) } } impl macros::ToTokens for Dot { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `..`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DotDot { /// Associated token. pub token: ast::Token, } impl crate::Spanned for DotDot { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for DotDot { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::DotDot => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "..")), } } } impl parsing::Peek for DotDot { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::DotDot) } } impl macros::ToTokens for DotDot { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `..=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DotDotEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for DotDotEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for DotDotEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::DotDotEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "..=")), } } } impl parsing::Peek for DotDotEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::DotDotEq) } } impl macros::ToTokens for DotDotEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `else` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Else { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Else { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Else { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Else => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "else")), } } } impl parsing::Peek for Else { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Else) } } impl macros::ToTokens for Else { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `enum` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Enum { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Enum { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Enum { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Enum => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "enum")), } } } impl parsing::Peek for Enum { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Enum) } } impl macros::ToTokens for Enum { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Eq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Eq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Eq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Eq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "=")), } } } impl parsing::Peek for Eq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Eq) } } impl macros::ToTokens for Eq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `==`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct EqEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for EqEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for EqEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::EqEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "==")), } } } impl parsing::Peek for EqEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::EqEq) } } impl macros::ToTokens for EqEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `extern` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Extern { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Extern { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Extern { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Extern => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "extern")), } } } impl parsing::Peek for Extern { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Extern) } } impl macros::ToTokens for Extern { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `false` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct False { /// Associated token. pub token: ast::Token, } impl crate::Spanned for False { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for False { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::False => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "false")), } } } impl parsing::Peek for False { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::False) } } impl macros::ToTokens for False { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `final` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Final { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Final { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Final { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Final => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "final")), } } } impl parsing::Peek for Final { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Final) } } impl macros::ToTokens for Final { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `fn` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Fn { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Fn { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Fn { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Fn => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "fn")), } } } impl parsing::Peek for Fn { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Fn) } } impl macros::ToTokens for Fn { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `for` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct For { /// Associated token. pub token: ast::Token, } impl crate::Spanned for For { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for For { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::For => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "for")), } } } impl parsing::Peek for For { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::For) } } impl macros::ToTokens for For { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `>`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Gt { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Gt { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Gt { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Gt => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, ">")), } } } impl parsing::Peek for Gt { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Gt) } } impl macros::ToTokens for Gt { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `>=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct GtEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for GtEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for GtEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::GtEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, ">=")), } } } impl parsing::Peek for GtEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::GtEq) } } impl macros::ToTokens for GtEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `>>`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct GtGt { /// Associated token. pub token: ast::Token, } impl crate::Spanned for GtGt { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for GtGt { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::GtGt => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, ">>")), } } } impl parsing::Peek for GtGt { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::GtGt) } } impl macros::ToTokens for GtGt { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `>>=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct GtGtEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for GtGtEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for GtGtEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::GtGtEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, ">>=")), } } } impl parsing::Peek for GtGtEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::GtGtEq) } } impl macros::ToTokens for GtGtEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `if` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct If { /// Associated token. pub token: ast::Token, } impl crate::Spanned for If { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for If { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::If => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "if")), } } } impl parsing::Peek for If { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::If) } } impl macros::ToTokens for If { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `impl` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Impl { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Impl { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Impl { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Impl => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "impl")), } } } impl parsing::Peek for Impl { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Impl) } } impl macros::ToTokens for Impl { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `in` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct In { /// Associated token. pub token: ast::Token, } impl crate::Spanned for In { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for In { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::In => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "in")), } } } impl parsing::Peek for In { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::In) } } impl macros::ToTokens for In { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `is` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Is { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Is { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Is { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Is => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "is")), } } } impl parsing::Peek for Is { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Is) } } impl macros::ToTokens for Is { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `let` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Let { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Let { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Let { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Let => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "let")), } } } impl parsing::Peek for Let { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Let) } } impl macros::ToTokens for Let { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `loop` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Loop { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Loop { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Loop { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Loop => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "loop")), } } } impl parsing::Peek for Loop { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Loop) } } impl macros::ToTokens for Loop { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `<`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Lt { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Lt { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Lt { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Lt => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "<")), } } } impl parsing::Peek for Lt { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Lt) } } impl macros::ToTokens for Lt { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `<=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct LtEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for LtEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for LtEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::LtEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "<=")), } } } impl parsing::Peek for LtEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::LtEq) } } impl macros::ToTokens for LtEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `<<`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct LtLt { /// Associated token. pub token: ast::Token, } impl crate::Spanned for LtLt { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for LtLt { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::LtLt => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "<<")), } } } impl parsing::Peek for LtLt { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::LtLt) } } impl macros::ToTokens for LtLt { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `<<=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct LtLtEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for LtLtEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for LtLtEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::LtLtEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "<<=")), } } } impl parsing::Peek for LtLtEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::LtLtEq) } } impl macros::ToTokens for LtLtEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `macro` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Macro { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Macro { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Macro { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Macro => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "macro")), } } } impl parsing::Peek for Macro { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Macro) } } impl macros::ToTokens for Macro { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `match` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Match { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Match { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Match { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Match => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "match")), } } } impl parsing::Peek for Match { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Match) } } impl macros::ToTokens for Match { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `mod` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Mod { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Mod { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Mod { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Mod => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "mod")), } } } impl parsing::Peek for Mod { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Mod) } } impl macros::ToTokens for Mod { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `move` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Move { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Move { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Move { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Move => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "move")), } } } impl parsing::Peek for Move { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Move) } } impl macros::ToTokens for Move { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `not` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Not { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Not { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Not { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Not => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "not")), } } } impl parsing::Peek for Not { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Not) } } impl macros::ToTokens for Not { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `offsetof` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct OffsetOf { /// Associated token. pub token: ast::Token, } impl crate::Spanned for OffsetOf { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for OffsetOf { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::OffsetOf => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "offsetof")), } } } impl parsing::Peek for OffsetOf { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::OffsetOf) } } impl macros::ToTokens for OffsetOf { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `override` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Override { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Override { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Override { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Override => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "override")), } } } impl parsing::Peek for Override { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Override) } } impl macros::ToTokens for Override { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `%`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Perc { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Perc { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Perc { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Perc => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "%")), } } } impl parsing::Peek for Perc { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Perc) } } impl macros::ToTokens for Perc { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `%=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PercEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for PercEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for PercEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::PercEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "%=")), } } } impl parsing::Peek for PercEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::PercEq) } } impl macros::ToTokens for PercEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `|`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Pipe { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Pipe { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Pipe { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Pipe => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "|")), } } } impl parsing::Peek for Pipe { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Pipe) } } impl macros::ToTokens for Pipe { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// |=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PipeEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for PipeEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for PipeEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::PipeEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "|=")), } } } impl parsing::Peek for PipeEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::PipeEq) } } impl macros::ToTokens for PipeEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `||`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PipePipe { /// Associated token. pub token: ast::Token, } impl crate::Spanned for PipePipe { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for PipePipe { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::PipePipe => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "||")), } } } impl parsing::Peek for PipePipe { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::PipePipe) } } impl macros::ToTokens for PipePipe { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `+`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Plus { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Plus { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Plus { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Plus => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "+")), } } } impl parsing::Peek for Plus { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Plus) } } impl macros::ToTokens for Plus { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `+=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PlusEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for PlusEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for PlusEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::PlusEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "+=")), } } } impl parsing::Peek for PlusEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::PlusEq) } } impl macros::ToTokens for PlusEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `#`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Pound { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Pound { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Pound { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Pound => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "#")), } } } impl parsing::Peek for Pound { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Pound) } } impl macros::ToTokens for Pound { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `priv` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Priv { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Priv { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Priv { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Priv => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "priv")), } } } impl parsing::Peek for Priv { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Priv) } } impl macros::ToTokens for Priv { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `proc` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Proc { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Proc { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Proc { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Proc => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "proc")), } } } impl parsing::Peek for Proc { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Proc) } } impl macros::ToTokens for Proc { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `pub` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Pub { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Pub { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Pub { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Pub => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "pub")), } } } impl parsing::Peek for Pub { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Pub) } } impl macros::ToTokens for Pub { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `pure` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Pure { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Pure { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Pure { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Pure => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "pure")), } } } impl parsing::Peek for Pure { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Pure) } } impl macros::ToTokens for Pure { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `?`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct QuestionMark { /// Associated token. pub token: ast::Token, } impl crate::Spanned for QuestionMark { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for QuestionMark { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::QuestionMark => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "?")), } } } impl parsing::Peek for QuestionMark { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::QuestionMark) } } impl macros::ToTokens for QuestionMark { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `ref` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Ref { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Ref { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Ref { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Ref => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "ref")), } } } impl parsing::Peek for Ref { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Ref) } } impl macros::ToTokens for Ref { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `return` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Return { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Return { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Return { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Return => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "return")), } } } impl parsing::Peek for Return { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Return) } } impl macros::ToTokens for Return { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `=>`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Rocket { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Rocket { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Rocket { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Rocket => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "=>")), } } } impl parsing::Peek for Rocket { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Rocket) } } impl macros::ToTokens for Rocket { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `select` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Select { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Select { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Select { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Select => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "select")), } } } impl parsing::Peek for Select { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Select) } } impl macros::ToTokens for Select { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `Self` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SelfType { /// Associated token. pub token: ast::Token, } impl crate::Spanned for SelfType { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for SelfType { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::SelfType => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "Self")), } } } impl parsing::Peek for SelfType { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::SelfType) } } impl macros::ToTokens for SelfType { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `self` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SelfValue { /// Associated token. pub token: ast::Token, } impl crate::Spanned for SelfValue { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for SelfValue { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::SelfValue => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "self")), } } } impl parsing::Peek for SelfValue { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::SelfValue) } } impl macros::ToTokens for SelfValue { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `;`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SemiColon { /// Associated token. pub token: ast::Token, } impl crate::Spanned for SemiColon { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for SemiColon { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::SemiColon => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, ";")), } } } impl parsing::Peek for SemiColon { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::SemiColon) } } impl macros::ToTokens for SemiColon { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `sizeof` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SizeOf { /// Associated token. pub token: ast::Token, } impl crate::Spanned for SizeOf { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for SizeOf { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::SizeOf => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "sizeof")), } } } impl parsing::Peek for SizeOf { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::SizeOf) } } impl macros::ToTokens for SizeOf { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `/=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SlashEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for SlashEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for SlashEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::SlashEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "/=")), } } } impl parsing::Peek for SlashEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::SlashEq) } } impl macros::ToTokens for SlashEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `*`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Star { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Star { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Star { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Star => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "*")), } } } impl parsing::Peek for Star { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Star) } } impl macros::ToTokens for Star { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `*=`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct StarEq { /// Associated token. pub token: ast::Token, } impl crate::Spanned for StarEq { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for StarEq { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::StarEq => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "*=")), } } } impl parsing::Peek for StarEq { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::StarEq) } } impl macros::ToTokens for StarEq { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `static` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Static { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Static { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Static { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Static => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "static")), } } } impl parsing::Peek for Static { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Static) } } impl macros::ToTokens for Static { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `struct` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Struct { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Struct { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Struct { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Struct => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "struct")), } } } impl parsing::Peek for Struct { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Struct) } } impl macros::ToTokens for Struct { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `super` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Super { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Super { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Super { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Super => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "super")), } } } impl parsing::Peek for Super { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Super) } } impl macros::ToTokens for Super { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `~`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Tilde { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Tilde { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Tilde { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Tilde => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "~")), } } } impl parsing::Peek for Tilde { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Tilde) } } impl macros::ToTokens for Tilde { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `true` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct True { /// Associated token. pub token: ast::Token, } impl crate::Spanned for True { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for True { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::True => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "true")), } } } impl parsing::Peek for True { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::True) } } impl macros::ToTokens for True { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `typeof` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TypeOf { /// Associated token. pub token: ast::Token, } impl crate::Spanned for TypeOf { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for TypeOf { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::TypeOf => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "typeof")), } } } impl parsing::Peek for TypeOf { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::TypeOf) } } impl macros::ToTokens for TypeOf { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// `_`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Underscore { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Underscore { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Underscore { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Underscore => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "_")), } } } impl parsing::Peek for Underscore { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Underscore) } } impl macros::ToTokens for Underscore { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `unsafe` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Unsafe { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Unsafe { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Unsafe { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Unsafe => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "unsafe")), } } } impl parsing::Peek for Unsafe { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Unsafe) } } impl macros::ToTokens for Unsafe { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `use` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Use { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Use { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Use { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Use => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "use")), } } } impl parsing::Peek for Use { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Use) } } impl macros::ToTokens for Use { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `virtual` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Virtual { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Virtual { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Virtual { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Virtual => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "virtual")), } } } impl parsing::Peek for Virtual { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Virtual) } } impl macros::ToTokens for Virtual { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `while` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct While { /// Associated token. pub token: ast::Token, } impl crate::Spanned for While { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for While { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::While => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "while")), } } } impl parsing::Peek for While { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::While) } } impl macros::ToTokens for While { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// The `yield` keyword. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Yield { /// Associated token. pub token: ast::Token, } impl crate::Spanned for Yield { fn span(&self) -> runestick::Span { self.token.span() } } impl parsing::Parse for Yield { fn parse(p: &mut parsing::Parser<'_>) -> Result<Self, parsing::ParseError> { let token = p.next()?; match token.kind { ast::Kind::Yield => Ok(Self { token }), _ => Err(parsing::ParseError::expected(&token, "yield")), } } } impl parsing::Peek for Yield { fn peek(peeker: &mut parsing::Peeker<'_>) -> bool { matches!(peeker.nth(0), ast::Kind::Yield) } } impl macros::ToTokens for Yield { fn to_tokens(&self, _: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(self.token); } } /// Helper macro to reference a specific token. #[macro_export] macro_rules! T { ('(') => { $crate::ast::OpenParen }; (')') => { $crate::ast::CloseParen }; ('[') => { $crate::ast::OpenBracket }; (']') => { $crate::ast::CloseBracket }; ('{') => { $crate::ast::OpenBrace }; ('}') => { $crate::ast::CloseBrace }; (abstract) => { $crate::ast::generated::Abstract }; (alignof) => { $crate::ast::generated::AlignOf }; (as) => { $crate::ast::generated::As }; (async) => { $crate::ast::generated::Async }; (await) => { $crate::ast::generated::Await }; (become) => { $crate::ast::generated::Become }; (break) => { $crate::ast::generated::Break }; (const) => { $crate::ast::generated::Const }; (continue) => { $crate::ast::generated::Continue }; (crate) => { $crate::ast::generated::Crate }; (default) => { $crate::ast::generated::Default }; (do) => { $crate::ast::generated::Do }; (else) => { $crate::ast::generated::Else }; (enum) => { $crate::ast::generated::Enum }; (extern) => { $crate::ast::generated::Extern }; (false) => { $crate::ast::generated::False }; (final) => { $crate::ast::generated::Final }; (fn) => { $crate::ast::generated::Fn }; (for) => { $crate::ast::generated::For }; (if) => { $crate::ast::generated::If }; (impl) => { $crate::ast::generated::Impl }; (in) => { $crate::ast::generated::In }; (is) => { $crate::ast::generated::Is }; (let) => { $crate::ast::generated::Let }; (loop) => { $crate::ast::generated::Loop }; (macro) => { $crate::ast::generated::Macro }; (match) => { $crate::ast::generated::Match }; (mod) => { $crate::ast::generated::Mod }; (move) => { $crate::ast::generated::Move }; (not) => { $crate::ast::generated::Not }; (offsetof) => { $crate::ast::generated::OffsetOf }; (override) => { $crate::ast::generated::Override }; (priv) => { $crate::ast::generated::Priv }; (proc) => { $crate::ast::generated::Proc }; (pub) => { $crate::ast::generated::Pub }; (pure) => { $crate::ast::generated::Pure }; (ref) => { $crate::ast::generated::Ref }; (return) => { $crate::ast::generated::Return }; (select) => { $crate::ast::generated::Select }; (Self) => { $crate::ast::generated::SelfType }; (self) => { $crate::ast::generated::SelfValue }; (sizeof) => { $crate::ast::generated::SizeOf }; (static) => { $crate::ast::generated::Static }; (struct) => { $crate::ast::generated::Struct }; (super) => { $crate::ast::generated::Super }; (true) => { $crate::ast::generated::True }; (typeof) => { $crate::ast::generated::TypeOf }; (unsafe) => { $crate::ast::generated::Unsafe }; (use) => { $crate::ast::generated::Use }; (virtual) => { $crate::ast::generated::Virtual }; (while) => { $crate::ast::generated::While }; (yield) => { $crate::ast::generated::Yield }; (&) => { $crate::ast::generated::Amp }; (&&) => { $crate::ast::generated::AmpAmp }; (&=) => { $crate::ast::generated::AmpEq }; (->) => { $crate::ast::generated::Arrow }; (@) => { $crate::ast::generated::At }; (!) => { $crate::ast::generated::Bang }; (!=) => { $crate::ast::generated::BangEq }; (^) => { $crate::ast::generated::Caret }; (^=) => { $crate::ast::generated::CaretEq }; (:) => { $crate::ast::generated::Colon }; (::) => { $crate::ast::generated::ColonColon }; (,) => { $crate::ast::generated::Comma }; (-) => { $crate::ast::generated::Dash }; (-=) => { $crate::ast::generated::DashEq }; (/) => { $crate::ast::generated::Div }; ($) => { $crate::ast::generated::Dollar }; (.) => { $crate::ast::generated::Dot }; (..) => { $crate::ast::generated::DotDot }; (..=) => { $crate::ast::generated::DotDotEq }; (=) => { $crate::ast::generated::Eq }; (==) => { $crate::ast::generated::EqEq }; (>) => { $crate::ast::generated::Gt }; (>=) => { $crate::ast::generated::GtEq }; (>>) => { $crate::ast::generated::GtGt }; (>>=) => { $crate::ast::generated::GtGtEq }; (<) => { $crate::ast::generated::Lt }; (<=) => { $crate::ast::generated::LtEq }; (<<) => { $crate::ast::generated::LtLt }; (<<=) => { $crate::ast::generated::LtLtEq }; (%) => { $crate::ast::generated::Perc }; (%=) => { $crate::ast::generated::PercEq }; (|) => { $crate::ast::generated::Pipe }; (|=) => { $crate::ast::generated::PipeEq }; (||) => { $crate::ast::generated::PipePipe }; (+) => { $crate::ast::generated::Plus }; (+=) => { $crate::ast::generated::PlusEq }; (#) => { $crate::ast::generated::Pound }; (?) => { $crate::ast::generated::QuestionMark }; (=>) => { $crate::ast::generated::Rocket }; (;) => { $crate::ast::generated::SemiColon }; (/=) => { $crate::ast::generated::SlashEq }; (*) => { $crate::ast::generated::Star }; (*=) => { $crate::ast::generated::StarEq }; (~) => { $crate::ast::generated::Tilde }; (_) => { $crate::ast::generated::Underscore }; } /// Helper macro to reference a specific token kind, or short sequence of kinds. #[macro_export] macro_rules! K { (ident) => { $crate::ast::Kind::Ident(..) }; (ident ($($tt:tt)*)) => { $crate::ast::Kind::Ident($($tt)*) }; ('label) => { $crate::ast::Kind::Label(..) }; ('label ($($tt:tt)*)) => { $crate::ast::Kind::Label($($tt)*) }; (str) => { $crate::ast::Kind::Str(..) }; (str ($($tt:tt)*)) => { $crate::ast::Kind::Str($($tt)*) }; (bytestr) => { $crate::ast::Kind::ByteStr(..) }; (bytestr ($($tt:tt)*)) => { $crate::ast::Kind::ByteStr($($tt)*) }; (char) => { $crate::ast::Kind::Char(..) }; (char ($($tt:tt)*)) => { $crate::ast::Kind::Char($($tt)*) }; (byte) => { $crate::ast::Kind::Byte(..) }; (byte ($($tt:tt)*)) => { $crate::ast::Kind::Byte($($tt)*) }; (number) => { $crate::ast::Kind::Number(..) }; (number ($($tt:tt)*)) => { $crate::ast::Kind::Number($($tt)*) }; ('(') => { $crate::ast::Kind::Open($crate::ast::Delimiter::Parenthesis) }; (')') => { $crate::ast::Kind::Close($crate::ast::Delimiter::Parenthesis) }; ('[') => { $crate::ast::Kind::Open($crate::ast::Delimiter::Bracket) }; (']') => { $crate::ast::Kind::Close($crate::ast::Delimiter::Bracket) }; ('{') => { $crate::ast::Kind::Open($crate::ast::Delimiter::Brace) }; ('}') => { $crate::ast::Kind::Close($crate::ast::Delimiter::Brace) }; (abstract) => { $crate::ast::Kind::Abstract }; (alignof) => { $crate::ast::Kind::AlignOf }; (as) => { $crate::ast::Kind::As }; (async) => { $crate::ast::Kind::Async }; (await) => { $crate::ast::Kind::Await }; (become) => { $crate::ast::Kind::Become }; (break) => { $crate::ast::Kind::Break }; (const) => { $crate::ast::Kind::Const }; (continue) => { $crate::ast::Kind::Continue }; (crate) => { $crate::ast::Kind::Crate }; (default) => { $crate::ast::Kind::Default }; (do) => { $crate::ast::Kind::Do }; (else) => { $crate::ast::Kind::Else }; (enum) => { $crate::ast::Kind::Enum }; (extern) => { $crate::ast::Kind::Extern }; (false) => { $crate::ast::Kind::False }; (final) => { $crate::ast::Kind::Final }; (fn) => { $crate::ast::Kind::Fn }; (for) => { $crate::ast::Kind::For }; (if) => { $crate::ast::Kind::If }; (impl) => { $crate::ast::Kind::Impl }; (in) => { $crate::ast::Kind::In }; (is) => { $crate::ast::Kind::Is }; (let) => { $crate::ast::Kind::Let }; (loop) => { $crate::ast::Kind::Loop }; (macro) => { $crate::ast::Kind::Macro }; (match) => { $crate::ast::Kind::Match }; (mod) => { $crate::ast::Kind::Mod }; (move) => { $crate::ast::Kind::Move }; (not) => { $crate::ast::Kind::Not }; (offsetof) => { $crate::ast::Kind::OffsetOf }; (override) => { $crate::ast::Kind::Override }; (priv) => { $crate::ast::Kind::Priv }; (proc) => { $crate::ast::Kind::Proc }; (pub) => { $crate::ast::Kind::Pub }; (pure) => { $crate::ast::Kind::Pure }; (ref) => { $crate::ast::Kind::Ref }; (return) => { $crate::ast::Kind::Return }; (select) => { $crate::ast::Kind::Select }; (Self) => { $crate::ast::Kind::SelfType }; (self) => { $crate::ast::Kind::SelfValue }; (sizeof) => { $crate::ast::Kind::SizeOf }; (static) => { $crate::ast::Kind::Static }; (struct) => { $crate::ast::Kind::Struct }; (super) => { $crate::ast::Kind::Super }; (true) => { $crate::ast::Kind::True }; (typeof) => { $crate::ast::Kind::TypeOf }; (unsafe) => { $crate::ast::Kind::Unsafe }; (use) => { $crate::ast::Kind::Use }; (virtual) => { $crate::ast::Kind::Virtual }; (while) => { $crate::ast::Kind::While }; (yield) => { $crate::ast::Kind::Yield }; (&) => { $crate::ast::Kind::Amp }; (&&) => { $crate::ast::Kind::AmpAmp }; (&=) => { $crate::ast::Kind::AmpEq }; (->) => { $crate::ast::Kind::Arrow }; (@) => { $crate::ast::Kind::At }; (!) => { $crate::ast::Kind::Bang }; (!=) => { $crate::ast::Kind::BangEq }; (^) => { $crate::ast::Kind::Caret }; (^=) => { $crate::ast::Kind::CaretEq }; (:) => { $crate::ast::Kind::Colon }; (::) => { $crate::ast::Kind::ColonColon }; (,) => { $crate::ast::Kind::Comma }; (-) => { $crate::ast::Kind::Dash }; (-=) => { $crate::ast::Kind::DashEq }; (/) => { $crate::ast::Kind::Div }; ($) => { $crate::ast::Kind::Dollar }; (.) => { $crate::ast::Kind::Dot }; (..) => { $crate::ast::Kind::DotDot }; (..=) => { $crate::ast::Kind::DotDotEq }; (=) => { $crate::ast::Kind::Eq }; (==) => { $crate::ast::Kind::EqEq }; (>) => { $crate::ast::Kind::Gt }; (>=) => { $crate::ast::Kind::GtEq }; (>>) => { $crate::ast::Kind::GtGt }; (>>=) => { $crate::ast::Kind::GtGtEq }; (<) => { $crate::ast::Kind::Lt }; (<=) => { $crate::ast::Kind::LtEq }; (<<) => { $crate::ast::Kind::LtLt }; (<<=) => { $crate::ast::Kind::LtLtEq }; (%) => { $crate::ast::Kind::Perc }; (%=) => { $crate::ast::Kind::PercEq }; (|) => { $crate::ast::Kind::Pipe }; (|=) => { $crate::ast::Kind::PipeEq }; (||) => { $crate::ast::Kind::PipePipe }; (+) => { $crate::ast::Kind::Plus }; (+=) => { $crate::ast::Kind::PlusEq }; (#) => { $crate::ast::Kind::Pound }; (?) => { $crate::ast::Kind::QuestionMark }; (=>) => { $crate::ast::Kind::Rocket }; (;) => { $crate::ast::Kind::SemiColon }; (/=) => { $crate::ast::Kind::SlashEq }; (*) => { $crate::ast::Kind::Star }; (*=) => { $crate::ast::Kind::StarEq }; (~) => { $crate::ast::Kind::Tilde }; (_) => { $crate::ast::Kind::Underscore }; } /// The kind of the token. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Kind { /// En end-of-file marker. Eof, /// En error marker. Error, /// A close delimiter: `)`, `}`, or `]`. Close(ast::Delimiter), /// An open delimiter: `(`, `{`, or `[`. Open(ast::Delimiter), /// An identifier. Ident(ast::StringSource), /// A label, like `'loop`. Label(ast::StringSource), /// A byte literal. Byte(ast::CopySource<u8>), /// A byte string literal, including escape sequences. Like `b"hello\nworld"`. ByteStr(ast::StrSource), /// A characer literal. Char(ast::CopySource<char>), /// A number literal, like `42` or `3.14` or `0xff`. Number(ast::NumberSource), /// A string literal, including escape sequences. Like `"hello\nworld"`. Str(ast::StrSource), /// The `abstract` keyword. Abstract, /// The `alignof` keyword. AlignOf, /// `&`. Amp, /// `&&`. AmpAmp, /// `&=`. AmpEq, /// `->`. Arrow, /// The `as` keyword. As, /// The `async` keyword. Async, /// `@`. At, /// The `await` keyword. Await, /// `!`. Bang, /// `!=`. BangEq, /// The `become` keyword. Become, /// The `break` keyword. Break, /// `^`. Caret, /// `^=`. CaretEq, /// `:`. Colon, /// `::`. ColonColon, /// `,`. Comma, /// The `const` keyword. Const, /// The `continue` keyword. Continue, /// The `crate` keyword. Crate, /// `-`. Dash, /// `-=`. DashEq, /// The `default` keyword. Default, /// `/`. Div, /// The `do` keyword. Do, /// `$`. Dollar, /// `.`. Dot, /// `..`. DotDot, /// `..=`. DotDotEq, /// The `else` keyword. Else, /// The `enum` keyword. Enum, /// `=`. Eq, /// `==`. EqEq, /// The `extern` keyword. Extern, /// The `false` keyword. False, /// The `final` keyword. Final, /// The `fn` keyword. Fn, /// The `for` keyword. For, /// `>`. Gt, /// `>=`. GtEq, /// `>>`. GtGt, /// `>>=`. GtGtEq, /// The `if` keyword. If, /// The `impl` keyword. Impl, /// The `in` keyword. In, /// The `is` keyword. Is, /// The `let` keyword. Let, /// The `loop` keyword. Loop, /// `<`. Lt, /// `<=`. LtEq, /// `<<`. LtLt, /// `<<=`. LtLtEq, /// The `macro` keyword. Macro, /// The `match` keyword. Match, /// The `mod` keyword. Mod, /// The `move` keyword. Move, /// The `not` keyword. Not, /// The `offsetof` keyword. OffsetOf, /// The `override` keyword. Override, /// `%`. Perc, /// `%=`. PercEq, /// `|`. Pipe, /// |=`. PipeEq, /// `||`. PipePipe, /// `+`. Plus, /// `+=`. PlusEq, /// `#`. Pound, /// The `priv` keyword. Priv, /// The `proc` keyword. Proc, /// The `pub` keyword. Pub, /// The `pure` keyword. Pure, /// `?`. QuestionMark, /// The `ref` keyword. Ref, /// The `return` keyword. Return, /// `=>`. Rocket, /// The `select` keyword. Select, /// The `Self` keyword. SelfType, /// The `self` keyword. SelfValue, /// `;`. SemiColon, /// The `sizeof` keyword. SizeOf, /// `/=`. SlashEq, /// `*`. Star, /// `*=`. StarEq, /// The `static` keyword. Static, /// The `struct` keyword. Struct, /// The `super` keyword. Super, /// `~`. Tilde, /// The `true` keyword. True, /// The `typeof` keyword. TypeOf, /// `_`. Underscore, /// The `unsafe` keyword. Unsafe, /// The `use` keyword. Use, /// The `virtual` keyword. Virtual, /// The `while` keyword. While, /// The `yield` keyword. Yield, } impl From<ast::Token> for Kind { fn from(token: ast::Token) -> Self { token.kind } } impl Kind { /// Try to convert an identifier into a keyword. pub fn from_keyword(ident: &str) -> Option<Self> { match ident { "abstract" => Some(Self::Abstract), "alignof" => Some(Self::AlignOf), "as" => Some(Self::As), "async" => Some(Self::Async), "await" => Some(Self::Await), "become" => Some(Self::Become), "break" => Some(Self::Break), "const" => Some(Self::Const), "continue" => Some(Self::Continue), "crate" => Some(Self::Crate), "default" => Some(Self::Default), "do" => Some(Self::Do), "else" => Some(Self::Else), "enum" => Some(Self::Enum), "extern" => Some(Self::Extern), "false" => Some(Self::False), "final" => Some(Self::Final), "fn" => Some(Self::Fn), "for" => Some(Self::For), "if" => Some(Self::If), "impl" => Some(Self::Impl), "in" => Some(Self::In), "is" => Some(Self::Is), "let" => Some(Self::Let), "loop" => Some(Self::Loop), "macro" => Some(Self::Macro), "match" => Some(Self::Match), "mod" => Some(Self::Mod), "move" => Some(Self::Move), "not" => Some(Self::Not), "offsetof" => Some(Self::OffsetOf), "override" => Some(Self::Override), "priv" => Some(Self::Priv), "proc" => Some(Self::Proc), "pub" => Some(Self::Pub), "pure" => Some(Self::Pure), "ref" => Some(Self::Ref), "return" => Some(Self::Return), "select" => Some(Self::Select), "Self" => Some(Self::SelfType), "self" => Some(Self::SelfValue), "sizeof" => Some(Self::SizeOf), "static" => Some(Self::Static), "struct" => Some(Self::Struct), "super" => Some(Self::Super), "true" => Some(Self::True), "typeof" => Some(Self::TypeOf), "unsafe" => Some(Self::Unsafe), "use" => Some(Self::Use), "virtual" => Some(Self::Virtual), "while" => Some(Self::While), "yield" => Some(Self::Yield), _ => None, } } /// Get the kind as a descriptive string. fn as_str(self) -> &'static str { match self { Self::Eof => "eof", Self::Error => "error", Self::Close(delimiter) => delimiter.close(), Self::Open(delimiter) => delimiter.open(), Self::Ident(..) => "ident", Self::Label(..) => "label", Self::Byte { .. } => "byte", Self::ByteStr { .. } => "byte string", Self::Char { .. } => "char", Self::Number { .. } => "number", Self::Str { .. } => "string", Self::Abstract => "abstract", Self::AlignOf => "alignof", Self::Amp => "&", Self::AmpAmp => "&&", Self::AmpEq => "&=", Self::Arrow => "->", Self::As => "as", Self::Async => "async", Self::At => "@", Self::Await => "await", Self::Bang => "!", Self::BangEq => "!=", Self::Become => "become", Self::Break => "break", Self::Caret => "^", Self::CaretEq => "^=", Self::Colon => ":", Self::ColonColon => "::", Self::Comma => ",", Self::Const => "const", Self::Continue => "continue", Self::Crate => "crate", Self::Dash => "-", Self::DashEq => "-=", Self::Default => "default", Self::Div => "/", Self::Do => "do", Self::Dollar => "$", Self::Dot => ".", Self::DotDot => "..", Self::DotDotEq => "..=", Self::Else => "else", Self::Enum => "enum", Self::Eq => "=", Self::EqEq => "==", Self::Extern => "extern", Self::False => "false", Self::Final => "final", Self::Fn => "fn", Self::For => "for", Self::Gt => ">", Self::GtEq => ">=", Self::GtGt => ">>", Self::GtGtEq => ">>=", Self::If => "if", Self::Impl => "impl", Self::In => "in", Self::Is => "is", Self::Let => "let", Self::Loop => "loop", Self::Lt => "<", Self::LtEq => "<=", Self::LtLt => "<<", Self::LtLtEq => "<<=", Self::Macro => "macro", Self::Match => "match", Self::Mod => "mod", Self::Move => "move", Self::Not => "not", Self::OffsetOf => "offsetof", Self::Override => "override", Self::Perc => "%", Self::PercEq => "%=", Self::Pipe => "|", Self::PipeEq => "|=", Self::PipePipe => "||", Self::Plus => "+", Self::PlusEq => "+=", Self::Pound => "#", Self::Priv => "priv", Self::Proc => "proc", Self::Pub => "pub", Self::Pure => "pure", Self::QuestionMark => "?", Self::Ref => "ref", Self::Return => "return", Self::Rocket => "=>", Self::Select => "select", Self::SelfType => "Self", Self::SelfValue => "self", Self::SemiColon => ";", Self::SizeOf => "sizeof", Self::SlashEq => "/=", Self::Star => "*", Self::StarEq => "*=", Self::Static => "static", Self::Struct => "struct", Self::Super => "super", Self::Tilde => "~", Self::True => "true", Self::TypeOf => "typeof", Self::Underscore => "_", Self::Unsafe => "unsafe", Self::Use => "use", Self::Virtual => "virtual", Self::While => "while", Self::Yield => "yield", } } } impl fmt::Display for Kind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } impl macros::ToTokens for Kind { fn to_tokens(&self, context: &macros::MacroContext, stream: &mut macros::TokenStream) { stream.push(ast::Token { kind: *self, span: context.macro_span(), }); } } impl shared::Description for &Kind { fn description(self) -> &'static str { self.as_str() } }
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let t: usize = rd.get(); for _ in 0..t { let n: usize = rd.get(); let lr: Vec<(usize, usize)> = (0..n) .map(|_| { let l: usize = rd.get(); let r: usize = rd.get(); (l, r) }) .collect(); solve(n, lr); } } fn solve(_: usize, lr: Vec<(usize, usize)>) { use std::collections::BTreeMap; let mut start = BTreeMap::new(); for (l, r) in lr { start.entry(l).or_insert(Vec::new()).push(r); } use std::cmp::Reverse; use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); let mut cur = 1; loop { while let Some(Reverse(r)) = heap.pop() { if cur > r { println!("No"); return; } cur += 1; if let Some(v) = start.get(&cur) { for &v in v { heap.push(Reverse(v)); } } } if let Some((&nxt, v)) = start.range(cur..).next() { cur = nxt; for &v in v { heap.push(Reverse(v)); } } else { break; } } println!("Yes"); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use carnelian::{ set_node_color, AnimationMode, App, AppAssistant, Color, Coord, Point, Rect, Size, ViewAssistant, ViewAssistantContext, ViewAssistantPtr, ViewKey, }; use euclid::Vector2D; use failure::Error; use fidl_fuchsia_ui_input::{InputEvent::Pointer, PointerEvent, PointerEventPhase}; use fuchsia_scenic::{Circle, Rectangle, RoundedRectangle, SessionPtr, ShapeNode}; use rand::{thread_rng, Rng}; use std::collections::BTreeMap; const SHAPE_Z: Coord = -10.0; fn make_bounds(context: &ViewAssistantContext) -> Rect { Rect::new(Point::zero(), context.size) } struct ShapeDropAppAssistant; impl AppAssistant for ShapeDropAppAssistant { fn setup(&mut self) -> Result<(), Error> { Ok(()) } fn create_view_assistant( &mut self, _: ViewKey, session: &SessionPtr, ) -> Result<ViewAssistantPtr, Error> { Ok(Box::new(ShapeDropViewAssistant::new(session)?)) } } struct ShapeAnimator { shape: ShapeNode, location: Point, accel: Vector2D<f32>, velocity: Vector2D<f32>, running: bool, } impl ShapeAnimator { pub fn new(touch_handler: TouchHandler, location: Point) -> ShapeAnimator { ShapeAnimator { shape: touch_handler.shape, location: location, accel: Vector2D::new(0.0, 0.2), velocity: Vector2D::zero(), running: true, } } pub fn animate(&mut self, bounds: &Rect) { self.location += self.velocity; self.velocity += self.accel; self.shape.set_translation(self.location.x, self.location.y, SHAPE_Z); if self.location.y > bounds.max_y() { self.running = false; self.shape.detach(); } } } enum ShapeType { Rectangle, RoundedRectangle, Circle, } struct TouchHandler { shape: ShapeNode, size: Size, shape_type: ShapeType, } fn random_color_element() -> u8 { let mut rng = thread_rng(); let e: u8 = rng.gen_range(0, 128); e + 128 } fn random_color() -> Color { Color { r: random_color_element(), g: random_color_element(), b: random_color_element(), a: 0xff, } } impl TouchHandler { pub fn new(context: &mut ViewAssistantContext) -> TouchHandler { let mut rng = thread_rng(); let shape_type = match rng.gen_range(0, 3) { 0 => ShapeType::Rectangle, 1 => ShapeType::RoundedRectangle, _ => ShapeType::Circle, }; let mut t = TouchHandler { shape: ShapeNode::new(context.session().clone()), size: Size::new(60.0, 60.0), shape_type, }; t.setup(context); t } fn setup(&mut self, context: &mut ViewAssistantContext) { set_node_color(context.session(), &self.shape, &random_color()); match self.shape_type { ShapeType::Rectangle => { self.shape.set_shape(&Rectangle::new( context.session().clone(), self.size.width, self.size.height, )); } ShapeType::RoundedRectangle => { let corner_radius = (self.size.width / 8.0).ceil(); self.shape.set_shape(&RoundedRectangle::new( context.session().clone(), self.size.width, self.size.height, corner_radius, corner_radius, corner_radius, corner_radius, )); } ShapeType::Circle => { self.shape .set_shape(&Circle::new(context.session().clone(), self.size.width / 2.0)); } } context.root_node().add_child(&self.shape); } fn update(&mut self, context: &mut ViewAssistantContext, pointer_event: &PointerEvent) { let bounds = make_bounds(context); let location = Point::new(pointer_event.x, pointer_event.y) .clamp(bounds.origin, bounds.bottom_right()); self.shape.set_translation(location.x, location.y, SHAPE_Z); } } struct ShapeDropViewAssistant { background_node: ShapeNode, touch_handlers: BTreeMap<(u32, u32), TouchHandler>, animators: Vec<ShapeAnimator>, } fn make_pointer_event_key(pointer_event: &PointerEvent) -> (u32, u32) { (pointer_event.device_id, pointer_event.pointer_id) } impl ShapeDropViewAssistant { fn new(session: &SessionPtr) -> Result<ShapeDropViewAssistant, Error> { Ok(ShapeDropViewAssistant { background_node: ShapeNode::new(session.clone()), touch_handlers: BTreeMap::new(), animators: Vec::new(), }) } fn start_animating( &mut self, context: &mut ViewAssistantContext, pointer_event: &PointerEvent, ) { if let Some(handler) = self.touch_handlers.remove(&make_pointer_event_key(pointer_event)) { let bounds = make_bounds(context); let location = Point::new(pointer_event.x, pointer_event.y) .clamp(bounds.origin, bounds.bottom_right()); let animator = ShapeAnimator::new(handler, Point::new(location.x, location.y)); self.animators.push(animator); } } fn handle_pointer_event( &mut self, context: &mut ViewAssistantContext, pointer_event: &PointerEvent, ) { match pointer_event.phase { PointerEventPhase::Down => { let mut t = TouchHandler::new(context); t.update(context, pointer_event); self.touch_handlers.insert(make_pointer_event_key(pointer_event), t); } PointerEventPhase::Add => {} PointerEventPhase::Hover => {} PointerEventPhase::Move => { if let Some(handler) = self.touch_handlers.get_mut(&make_pointer_event_key(pointer_event)) { handler.update(context, pointer_event); } } PointerEventPhase::Up => { self.start_animating(context, pointer_event); } PointerEventPhase::Remove => { self.start_animating(context, pointer_event); } PointerEventPhase::Cancel => { self.start_animating(context, pointer_event); } } } } impl ViewAssistant for ShapeDropViewAssistant { fn setup(&mut self, context: &ViewAssistantContext) -> Result<(), Error> { context.root_node().add_child(&self.background_node); set_node_color( context.session(), &self.background_node, &Color::from_hash_code("#2F4F4F")?, ); Ok(()) } fn update(&mut self, context: &ViewAssistantContext) -> Result<(), Error> { let center_x = context.size.width * 0.5; let center_y = context.size.height * 0.5; self.background_node.set_shape(&Rectangle::new( context.session().clone(), context.size.width, context.size.height, )); self.background_node.set_translation(center_x, center_y, 0.0); let bounds = make_bounds(context); for animator in &mut self.animators { animator.animate(&bounds); } self.animators.retain(|animator| animator.running); Ok(()) } fn initial_animation_mode(&mut self) -> AnimationMode { return AnimationMode::EveryFrame; } fn handle_input_event( &mut self, context: &mut ViewAssistantContext, event: &fidl_fuchsia_ui_input::InputEvent, ) -> Result<(), Error> { match event { Pointer(pointer_event) => { self.handle_pointer_event(context, &pointer_event); } _ => (), } Ok(()) } } fn main() -> Result<(), Error> { let assistant = ShapeDropAppAssistant {}; App::run(Box::new(assistant)) }
//! Types used by the worker-host protocol. use serde::{self, Deserializer, Serializer}; use serde_bytes; use serde_derive::{Deserialize, Serialize}; use crate::{ common::{ crypto::{ hash::Hash, signature::{PublicKey, Signature}, }, roothash::{Block, ComputeResultsHeader}, runtime::RuntimeId, sgx::avr::AVR, }, storage::mkvs::{sync, WriteLog}, transaction::types::TxnBatch, }; /// Computed batch. #[derive(Debug, Serialize, Deserialize)] pub struct ComputedBatch { /// Compute results header. pub header: ComputeResultsHeader, /// Log that generates the I/O tree. pub io_write_log: WriteLog, /// Log of changes to the state tree. pub state_write_log: WriteLog, /// If this runtime uses a TEE, then this is the signature of the batch's /// BatchSigMessage with the node's RAK for this runtime. pub rak_sig: Signature, } /// Storage sync request. #[derive(Debug, Serialize, Deserialize)] pub enum StorageSyncRequest { SyncGet(sync::GetRequest), SyncGetPrefixes(sync::GetPrefixesRequest), SyncIterate(sync::IterateRequest), } /// Storage sync response. #[derive(Debug, Serialize, Deserialize)] pub enum StorageSyncResponse { ProofResponse(sync::ProofResponse), } /// Worker protocol message body. #[derive(Debug, Serialize, Deserialize)] pub enum Body { // An empty body. Empty {}, // An error response. Error { message: String, }, // Runtime worker interface. WorkerInfoRequest { runtime_id: RuntimeId, }, WorkerInfoResponse { protocol_version: u64, runtime_version: u64, }, WorkerPingRequest {}, WorkerShutdownRequest {}, WorkerAbortRequest {}, WorkerAbortResponse {}, WorkerCapabilityTEERakInitRequest { #[serde(with = "serde_bytes")] target_info: Vec<u8>, }, WorkerCapabilityTEERakInitResponse {}, WorkerCapabilityTEERakReportRequest {}, WorkerCapabilityTEERakReportResponse { rak_pub: PublicKey, #[serde(with = "serde_bytes")] report: Vec<u8>, nonce: String, }, WorkerCapabilityTEERakAvrRequest { avr: AVR, }, WorkerCapabilityTEERakAvrResponse {}, WorkerRPCCallRequest { #[serde(with = "serde_bytes")] request: Vec<u8>, state_root: Hash, }, WorkerRPCCallResponse { #[serde(with = "serde_bytes")] response: Vec<u8>, write_log: WriteLog, new_state_root: Hash, }, WorkerLocalRPCCallRequest { #[serde(with = "serde_bytes")] request: Vec<u8>, state_root: Hash, }, WorkerLocalRPCCallResponse { #[serde(with = "serde_bytes")] response: Vec<u8>, }, WorkerCheckTxBatchRequest { inputs: TxnBatch, block: Block, }, WorkerCheckTxBatchResponse { results: TxnBatch, }, WorkerExecuteTxBatchRequest { io_root: Hash, inputs: TxnBatch, block: Block, }, WorkerExecuteTxBatchResponse { batch: ComputedBatch, }, // Host interface. HostKeyManagerPolicyRequest {}, HostKeyManagerPolicyResponse { #[serde(with = "serde_bytes")] signed_policy_raw: Vec<u8>, }, HostRPCCallRequest { endpoint: String, #[serde(with = "serde_bytes")] request: Vec<u8>, }, HostRPCCallResponse { #[serde(with = "serde_bytes")] response: Vec<u8>, }, HostStorageSyncRequest { #[serde(flatten)] request: StorageSyncRequest, }, HostStorageSyncResponse { #[serde(flatten)] response: StorageSyncResponse, }, HostStorageSyncSerializedResponse { #[serde(with = "serde_bytes")] serialized: Vec<u8>, }, HostLocalStorageGetRequest { #[serde(with = "serde_bytes")] key: Vec<u8>, }, HostLocalStorageGetResponse { #[serde(with = "serde_bytes")] value: Vec<u8>, }, HostLocalStorageSetRequest { #[serde(with = "serde_bytes")] key: Vec<u8>, #[serde(with = "serde_bytes")] value: Vec<u8>, }, HostLocalStorageSetResponse {}, } #[derive(Clone, Copy, Debug)] #[repr(u8)] pub enum MessageType { /// Invalid message (should never be seen on the wire). Invalid = 0, /// Request. Request = 1, /// Response. Response = 2, } impl serde::Serialize for MessageType { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_u8(*self as u8) } } impl<'de> serde::Deserialize<'de> for MessageType { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { match u8::deserialize(deserializer)? { 1 => Ok(MessageType::Request), 2 => Ok(MessageType::Response), _ => Err(serde::de::Error::custom("invalid message type")), } } } /// Worker protocol message. #[derive(Debug, Serialize, Deserialize)] pub struct Message { /// Unique request identifier. pub id: u64, /// Message type. pub message_type: MessageType, /// Message body. pub body: Body, /// Opentracing's SpanContext serialized in binary format. #[serde(with = "serde_bytes")] pub span_context: Vec<u8>, }
use std::cmp::{Eq, PartialOrd, Ord, Ordering}; #[derive(PartialEq, Eq, Debug)] pub struct Orbit { pub base: String, pub orbiter: String, } impl Ord for Orbit { fn cmp(&self, other: &Self) -> Ordering { self.base.cmp(&other.base) } } impl PartialOrd for Orbit { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } pub fn data() -> Vec<Orbit> { "Z4X)3VF HXK)QWX X2G)R3L QPS)YML G5J)LMV J7Y)JRF MPW)6BZ N1M)24G 5DZ)PMN XVG)7Q5 8WN)NJ7 LPK)BCF B98)4XV R9C)Y1M 92F)918 JC2)HVF 5PT)W81 ZL7)XC4 FSP)1SK DY3)NF6 6BZ)F8Z PMN)Y4C CZ7)JWK J9S)PR3 3WY)8S2 TTH)2RR VRB)F5Y L1K)XVG 1M9)TGN X84)XRZ PX7)RGD GZW)61P SL3)CZ7 NY5)LSG T8B)QK4 DB7)16B KHL)2DD 5TR)YW2 Y4C)6XW H2R)CVP CVP)428 3CP)4MS V69)QZ4 LQZ)QMC Q4N)SRY 4FR)YQX 8C3)TX8 MMF)B98 WXW)9CW 4LV)XJN R85)YOU GW7)2WR 954)9LZ F2T)1KX P2S)B8G FSY)D18 9DV)YMQ K2G)SW4 VYK)78M RHH)78Z RLD)6WH JJT)FHQ 6D4)F83 BQ8)S4L LQZ)NXN NP3)9CY TJF)QFX DTT)LHX R73)JFD PJH)XHG FMG)34T JLG)CWS 1RC)KQ3 4LW)6XM ZWN)FL4 LQP)X25 TJF)X5L X7X)HDF 2PW)K23 4GZ)6JM T6T)7TN FVD)GG8 RQ6)DCR WQM)X84 CZY)JF6 TVG)LWH 94D)GH2 PM7)6W2 Z71)CBZ 1V2)3L5 YG9)KQ4 6DD)NJ4 24G)DFD C58)TM9 K6L)8XW TSP)5CH YJJ)48R 654)BZQ LHX)YNY HGB)LLK 32C)B1T 6NB)PFL 428)VPH LRH)7BQ FW2)WW1 QMC)MG1 THH)56B 98Z)TZX C2Q)FN7 G97)PZN R6Y)MXP NJ7)M8P DW7)TRX YNR)WZG GNK)3H7 W3X)L8Z YFR)2GN JF5)MNS QM5)RR4 XCY)4G5 NLG)1RC BJS)JBD DQM)S4H FL4)JP8 5BX)K4F HV1)XM1 DVY)1WT XDL)32C DDF)GVW DFD)FVD YNY)SAN W4H)Z6R RYF)Q98 86K)X58 M39)3VG 24M)CH4 4CX)5GL BY1)23Q VQD)WNX 6X4)WB8 N4X)TFV XJN)KW8 DTH)P83 PPL)TK6 K2G)F95 1HP)8DD 129)4LV RN9)76W 4SR)HQQ TT1)FZY 6GP)VZJ XWJ)YT5 VK5)YH6 KBL)924 X1C)1S5 QGQ)NJF XD3)L2W 6NZ)RSW HXF)JL7 NXK)VBT 4FM)8FR K2F)PYV K6X)QD6 JG3)8N7 L2K)2Y9 VJS)17H FK9)X9R 2NJ)6FS 11R)3LB SZZ)4FJ B43)LCJ P2N)Z81 48R)NKC VFL)654 69L)NP3 RLR)Z71 8FV)6ZJ YR4)42K YML)W3X 2GN)VJS 5KF)VJ5 JPL)9LY 9CY)8JB WB7)SZZ WZG)5R6 FZB)X5P 8S6)C9L 34T)L1K DNH)9JD GKS)4HL Y17)G6Q 47X)93F XKQ)46H NHW)5LP 21L)XBQ YRG)X1F LBP)6DV 6JM)488 58G)VQY YD2)C1R F5C)J7Y YKV)ZWC X9B)G9J JL7)4VM HP7)8V7 6C8)K36 BHJ)SJJ RMH)2VW VP6)K6X VFB)X7X 2VP)V18 PZN)PM5 ZDB)2KN PRT)425 JVX)MSQ R57)D1M S6F)DZL 7TT)D95 VF8)H1G F1Y)FRV KL9)NHJ 3BP)1B1 YQX)J1Y L1X)5DZ GKM)GJX 8PV)TVQ YD1)6XZ Q2G)GZW 2R9)BCQ RR4)2YH QWX)8FN PBJ)TN8 YYW)HXF 4GZ)TT4 C6T)2GS QXX)3JM CWS)7PJ 8JH)CFG DRD)8WN 76W)11R XKT)SDP PJR)M55 H5X)83Q WP1)R73 HG2)LPM SDP)DW7 SFB)P96 J1Y)BY1 KQ4)1VZ 5H8)L4D C5G)8TH 2X9)SVL D1J)ZNM 13V)C6T FYQ)JJC K4F)YD1 RV8)KPX HLN)89K G91)B99 F5Y)7TT 6GY)DTT CCV)5LY B9Z)DQS MHT)J86 HKQ)XPF JZF)RT3 5GL)2X9 KGH)DY4 RTD)MPW T58)41Z ZNM)M6Y N1M)RTB TZG)MFC 8P6)XFC X9M)RD7 19S)XKT G31)RLR DYP)5T7 SF1)954 RTB)1MV VBT)BQ4 Q96)8G6 LNV)24M KZ3)N4S H9P)BX6 82K)K74 1FJ)SN3 TDM)PC1 3V1)DK8 3X7)QJ8 L4D)G4G H86)XWJ 8FN)26D 8QY)M98 JRF)TTH 8TK)YLM SXM)KZ3 6RS)843 J7Y)H1T 2V7)XZ9 R9X)SFL JQC)THH 1B1)1X4 7QK)LRY VHR)SS8 ZXH)XKB F6R)6NZ P83)6YS XM1)9S4 8R2)YFR 7FR)LQP LHH)WN1 XFC)KYD PLL)2H5 NF6)WQM PMD)2V2 BQ4)PRT 2Y9)4HX PR3)ZX9 ZNV)K4T 18V)ZL7 4R1)VBK Y83)T8B FZY)S56 6W2)B7S NL3)W4Y C6T)TDX 1CR)3L1 XK9)SPT 96R)SF1 S7Z)H1C M8P)VP3 3Q7)XDB 2H5)F92 SVJ)HB4 XMQ)93Q YNP)XPL PM5)FTV 2SK)RJN JWH)4LW NJF)M39 TM5)Q3L ZYW)Y86 8DD)TN4 1NK)4DC JS9)NXK C9L)1P9 SYP)NX2 TCF)6S1 4CC)JSJ WWL)NL3 VZJ)C58 V26)WN2 56B)FWB CH4)Q6B DK8)BVX VQY)4H7 P7W)XP2 Q6H)2PW TN8)VFL TW3)KRJ G4G)VKY P74)DMF 6NT)NZF BM9)JWH W73)XKV 3KR)C5F TX8)9Q9 JVF)NHT DXH)H86 C1R)4N7 XZV)3CP 8LW)S6M W7M)MB3 822)YWX RGD)DB7 RX2)ZW3 GYX)ZH4 279)LKF 1KX)LRH ZX9)8WL ZW4)C5G Q25)VYK DFD)NYL GZ9)6L1 8DD)LHH FWZ)8FH HQQ)7CK ZHV)6X4 XRZ)XTW TMG)S1R 5XK)ZS6 L81)JF2 4V2)GQS 5KM)GQZ HRP)ZNV DVZ)G9Q L9P)3BN BCF)XKQ TS5)44R B8G)XDL C63)Y17 CBZ)T15 Z3X)XK9 WTG)TVG 6XW)HXK 4C6)P2R R2R)WKH 47R)Q4N ZBZ)H9P 4DC)KHL GG8)YK2 K2Q)5SV TYQ)6BS DLK)VFB KSJ)R57 BPV)K6L PFL)RZD 3L1)DNH 2VS)SNV K4X)G31 WKH)HKQ 5DZ)SFB 4B3)TR2 JC7)822 PPC)4SP S1R)65Z CY8)YKV 5LY)X4J Q3L)DXH K23)HLN HMX)LNL JJ4)RHH D95)8R2 LCJ)VNV 2ND)PJN B73)C2S 24D)NY5 1SK)JVF 67X)FPG XZP)G55 ZW4)V69 FRV)CK2 D6M)BJS XPL)RBB LZS)129 8JB)D81 J4T)Z4K 6D4)PCG M6Y)SVX CWS)RQ6 JC9)Q25 LMT)FWZ JP8)6D4 P74)H2D G6J)X3J VR9)4YF WHL)832 RT3)ZYW 8XW)F8L 4HL)X35 QXS)QGQ T15)BPV P2R)SPP 4S4)BHJ 3L5)76V 55S)3Q7 F8Z)X9K 6S6)HRR M18)BQ8 5SH)GY4 TT4)M18 LPB)82K G26)3VT KW8)VYL MNS)Y83 VTW)ZBZ G1X)H6Y 6XM)1TW D18)G26 LNL)L2K SD3)2CN B8L)P74 ZH4)TTQ 2DD)VHK 3FD)2SK L1D)RN9 WSF)Y99 4NH)P2N D81)GW7 1BJ)9QM 2MS)CHT W81)VXX QXJ)656 6YS)5YL K36)RMH GXX)GGF YLM)GT8 YP7)RLD 16B)FZB MQM)R6X 4YF)3SN XKV)X9M GT5)PPC FL4)BMM 46H)VK5 QZ4)YG9 9CW)6GP 1XX)PPL NHJ)X2G 25F)SL3 ZLY)RX2 41Z)WSF PJF)PLL SD3)R9W 2R9)2VS HZ4)7CJ R3L)YNR 1P9)BM9 TDX)LNV QQX)L1X H1G)8TK N9H)N2V 8VC)9X7 H1G)JLG CZG)5SH 318)H2R VZG)92F ZW3)WSX JJT)7NZ VYL)GNK V2B)98Z Y33)G1X CK2)6R2 Y86)2V7 4HX)6S6 FYX)MVZ 8YY)S93 X25)F2T F95)135 C94)L1D QBW)HP7 RX2)PJR JFV)51W BCQ)CZY T12)RNP 1X9)X9B CBZ)XYW D1M)HHL 1LH)21L 5ZG)2JJ 7TD)3D6 HQQ)TMZ 5D7)DDF KK4)8C4 918)1XX NLG)K67 SNV)TZG JZF)DNW SW4)XQY RYL)SVJ S6M)CD7 R6X)RHQ 2YH)DRD XP2)QC1 NS6)5D7 LWH)JS9 2YV)3M4 TM5)KL9 PCK)6DD V18)8P6 BTX)QG3 B99)HG2 1X9)K6T YD6)13V ZWK)BCX SRY)N9H HZ4)1HH KYD)GHV 6XZ)WWL G9Q)V2B 135)PJF PJN)NSF GHV)3L7 TVQ)PW8 HRR)1BJ RD7)6L7 9LY)9DV K74)S6F VP3)RCJ NX2)6NB VHK)KGH 9QM)XZW NZF)5Q8 VQY)ZWK YK2)FW2 X5P)69L WHD)QXX RSW)LC3 9S4)HRP TTQ)L6S RVV)4CC XPF)D64 NYV)K4X 6BS)XZP HDF)ZXH GQS)K2Q G5F)ML7 CHT)38Y 1HP)HMX N4X)HT2 N5W)X8C VGW)2ND 7CJ)TW3 DQK)XZQ S46)G5F GQZ)PX7 ZKR)8LW GVW)Y33 1MV)ZHV XK2)1YR DLK)R2R KPX)VP6 B1T)KJ7 COM)47X 7FR)XL9 HTH)648 2KN)GZ9 D3V)R6Y R9M)VHR 38Y)9CJ MFC)BBH 31T)HTH 5SV)L69 QH5)D1C RHQ)F4N 1YR)JL8 GWV)4NH 1MR)JVM 9LW)8PV WKH)KFS WN2)ZZY TFV)S7Z 69L)JJT 4H7)B8L DNW)1X9 17H)1V2 4FJ)V4T JSJ)LPB 93F)P7W QK4)4CL 648)62B G31)ZLY BVX)ZW4 XZW)DTH PHC)PWH VLP)M8B J58)R9C 4L2)THX NKC)WHL 4HX)L8T RVV)L9P JFD)GKS K2P)FMG DQS)XCY XBQ)FSP 4V2)HV1 3SN)T6Q Q73)PZV 9NZ)L3K H32)Z4X 8V7)Q73 PYV)C36 TGN)XD3 YHN)JCL Q96)XR4 8FR)GKM MPF)NHW X9R)4CP YMQ)D3V 1TW)JFV 4SP)RVV XP2)K2P H57)LMT T7T)877 2BB)G92 GGF)S18 QCW)8S6 V4T)LBP Y1M)RQ3 TMZ)ZDB S6M)YD6 6ZJ)F6R WB8)QQX 3M4)58G GY4)MYS 23X)TZQ XKB)JC7 9LW)T58 FPJ)XK2 JL8)WTG LC3)R85 3JM)DY3 BMM)3V1 FPG)7FL XR4)RV8 3VT)JQC 8WL)W73 DKH)TCF G9G)7XP 96Y)TDM NJ4)FPJ 5LP)YRG 3L7)X1C 1VZ)K2G JWK)VRB 7FL)5S5 4CP)6C8 JF2)CY8 L6S)1NK 88G)H5X H8B)28K LRY)W45 MG1)9NZ 2NJ)J9S PW8)PM7 XX1)96R 129)67X TN8)ML5 YY9)XMQ 42K)G91 2VS)T6T JKM)QXS WN1)2X4 BVB)4B9 GJX)7TD 9CJ)H32 7NZ)6GS KRJ)M9Y SNJ)G8G 76W)DXT 7J4)4V2 TQW)BVN 9YW)8FV SM2)H29 RQ3)35T H1C)1MR YHF)Q2G WHL)HZ4 4FR)C33 L9P)19S 8FH)5XK NYL)V4C 89K)XLZ XTW)GT5 9NF)7FR BBH)QT7 4G5)SXM B7S)1HP NX9)N4X DZP)6HK XWJ)6GG GQJ)R9X JXQ)QCJ VBT)JPL 4N7)VQD 7TN)13W HRP)32V M8B)9KL KFS)BVB LHH)5BX QCJ)FSY V97)318 S56)5KF 1S5)5BR 6R2)MQM FYX)1FJ GH2)ZKR 843)LDK LSG)RMS 32V)3WY TR2)18V GLZ)HGB ZZ5)GXX CH4)PHC 5MQ)JKC 924)88G FWB)KBL R9W)4FM 5Q8)G9G X3J)JC9 C2S)F5C 9Q9)KHZ 6HK)DLK Z81)5MQ 6GG)BZ2 9LZ)6JS 1WT)YR4 SS8)C63 1P9)YVX D64)7J4 XYW)PJX 6WH)W4H SVX)T7T 6W2)4XF 2X4)MPF DQS)JKM KQ3)B43 HHL)25F 1C6)L53 24M)TT1 L2W)VSB ML7)DVZ NS6)XZV RJN)PMD VPH)RYF PC1)J4T 425)3X7 XDB)VF8 5S5)QXJ 93Q)2NJ MB3)MMF GYX)4S4 6JS)JMT ZS6)LXH 1HH)2R9 NCP)5H8 G9J)6RS 76V)XX1 D6M)N83 VQT)5JJ 3BN)DV5 JKC)55S QFX)F1Y MVZ)NX9 J86)T12 2V2)BTX D1C)GWV W45)WHD 9XM)KKC TK6)ZZ5 F92)8QY F8L)RTD 8S2)N5W DZP)QH5 XZ9)C2Q M55)QMY SPT)2B8 LPM)K8T 4SP)H2F QJ8)FKN 7PJ)3BP XC4)FYQ TM9)2MS C33)8C3 TQ6)S38 35T)TSP 4MS)H82 SPP)KK4 YW2)YP7 S93)JF5 RNP)JJ4 Q6B)JVX VNV)TQW G8G)DZP N2V)9YW DFR)DQK G92)SD3 L3K)9NF H2F)279 SN3)G6J QD6)4JS FHQ)D1J 9X7)86K 1X4)YYW QG3)Y9T 6GS)4SR JJ4)WP1 FZT)WB7 5BR)S46 LTW)TYQ DXT)LQZ FZT)VTW W4Y)23X NRH)TQ6 MSQ)VZG HT2)KSJ B69)FK9 7BQ)79F CFG)D6M DV5)GQJ TR2)DYP 4C6)P2S XPF)2YV 65Z)5KM 3VG)C94 2KN)LPK 6L7)TMG ML5)H57 BX6)GYX 2VW)LTW 76V)LPH NXN)WXW PMD)VLP XHG)QM5 F34)5PN C7Q)94D X84)1M9 FN7)DKH 6FS)PJH MXP)JG3 2V7)MHT 417)9XM 3D6)H8B H1T)V97 WNX)J8R 78Z)NLG VZG)5PT QM5)N1M F83)W7M DMF)V26 N83)FZT JF6)1CR S4H)DVY HB4)GP4 H82)CCV Q89)F1H H2D)QPS 6L1)5TR 19S)DFR QC1)7QK FTV)YY9 8TH)4L2 DCR)Q89 2GS)G97 9JD)Z3X 3LB)6NT TN4)SVY 656)4R1 CD7)Q6H 5T7)NXQ BPV)417 NSF)MRC F4N)B69 HVF)RYL LMV)4GZ RZD)2VP P96)SM2 7CK)XVC YT5)24D M9Y)ZCM 61P)6J7 BZ2)DQM TRX)PBJ X58)5ZG PZV)7D1 G55)JZF 5CH)3KR Y99)1C6 DZL)QFC 5LY)R9M ZWC)GLZ YVX)F34 9KL)YHN 62B)VGW JVM)B73 DY4)1LH 8G6)L81 T6Q)NCP S4L)ZWN X8C)4CX SVY)K2F JF6)NS6 BM9)4FR GT8)3FD 832)YNP 6J7)QBW 4XF)Q96 1SK)31T Y1M)96Y 51W)TKW JMT)VR9 LLK)TJF 488)4C6 83Q)YHF Y9T)C7Q TZX)8VC VSB)B9Z VKY)47R 7D1)SYP 2WR)NYV X5L)8YY QMY)G5J 2B8)JXQ WSX)FYX V4C)8JH H9P)NRH 2JJ)6GY DXH)2BB 6S1)VQT 877)YD2 L53)TS5 K67)PCK 3VF)CZG MYS)YJJ 1MR)4B3 VNV)QCW LPH)TM5 13W)LZS K6T)J58 RBB)9LW 5KM)JC2 FKN)SNJ" /* "COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L" */ /* "COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L K)YOU I)SAN" */ .split_whitespace() .map(String::from) .map(|x| { let mut c = x.split(')').map(String::from); let a = c.next().unwrap(); let b = c.next().unwrap(); Orbit { base: a, orbiter: b, } }) .collect() }
use std::time::Instant; use crate::core::engine::EngineInit; use winit::event::Event; #[derive(Debug, Copy, Clone, PartialEq)] pub struct Dimensions { pub width: u32, pub height: u32, } #[derive(Debug, Copy, Clone, PartialEq)] pub struct InitialWindowInfo { pub initial_dimensions: Dimensions, pub title: &'static str, } impl InitialWindowInfo { pub(crate) fn build<T: 'static>( self, window_target: &winit::event_loop::EventLoopWindowTarget<T>, ) -> Result<Window, winit::error::OsError> { let winit_window = winit::window::WindowBuilder::new() .with_title(self.title) .with_inner_size(winit::dpi::LogicalSize::new( f64::from(self.initial_dimensions.width), f64::from(self.initial_dimensions.height), )) .with_min_inner_size(winit::dpi::LogicalSize::new(64, 64)) .build(window_target)?; let monitor = winit_window.primary_monitor().unwrap(); let monitor_pos = monitor.position(); let monitor_size = monitor.size(); let window_size = winit_window.outer_size(); if window_size.width > monitor_size.width || window_size.height > monitor_size.height { winit_window.set_maximized(true); } else { winit_window.set_outer_position(winit::dpi::PhysicalPosition { x: monitor_pos.x + ((monitor_size.width as i32 - window_size.width as i32) / 2), y: monitor_pos.y + ((monitor_size.height as i32 - window_size.height as i32) / 2), }); } Ok(Window::new(winit_window)) } } /// The window mode #[derive(PartialEq, Clone, Copy)] pub enum WindowMode { /// Window is windowed and not fullscreen Windowed, /// Full-sized window without borders, no real fullscreen Borderless, /// Exclusive fullscreen - more performant Exclusive, } pub struct Window { /// The winit window pub(crate) winit_window: winit::window::Window, /// Whether the cursor is visible and captured capture_cursor: bool, /// Whether the window is currently in focus focused: bool, /// The current window ode mode: WindowMode, } impl Window { fn new(winit_window: winit::window::Window) -> Self { Self { winit_window, capture_cursor: true, focused: true, // in the beginning, the windows is always focused mode: WindowMode::Windowed, } } /// Returns whether the window is currently in focus pub fn is_focused(&self) -> bool { self.focused } /// Sets the current window mode pub fn set_mode(&mut self, mode: WindowMode) { match mode { WindowMode::Windowed => self.winit_window.set_fullscreen(None), WindowMode::Borderless => self .winit_window .set_fullscreen(Some(winit::window::Fullscreen::Borderless(None))), WindowMode::Exclusive => { // select best video mode by ord let vm = self .winit_window .current_monitor() .expect("No monitor detected") .video_modes() .min() .expect("No video modes found"); self.winit_window .set_fullscreen(Some(winit::window::Fullscreen::Exclusive(vm))); } } self.mode = mode; } pub fn get_mode(&self) -> WindowMode { self.mode } pub fn get_capture_cursor(&self) -> bool { self.capture_cursor } /// Set the visibility of the mouse cursor and wether it should be captured (when window is focused) pub fn set_capture_cursor(&mut self, capture: bool) { self.capture_cursor = capture; self.actually_capture_cursor(capture); } // actually perform the capture fn actually_capture_cursor(&mut self, capture: bool) { self.winit_window.set_cursor_visible(!capture); self.winit_window .set_cursor_grab(capture) .expect("Could not enable cursor grab"); } // window is started with focused state fn on_start(&mut self) { self.actually_capture_cursor(self.capture_cursor); } // conditionally set the focus visibility depending on the user's choice on it's visibility // we want the cursor to be visible, whenever the window is not active fn on_focus(&mut self, focus: bool) { if focus { // gained focus if self.capture_cursor { self.actually_capture_cursor(true); } } else { // lost focus self.actually_capture_cursor(false); } self.focused = focus; } } pub fn start(engine_init: EngineInit) -> ! { let mut last_time = Instant::now(); let mut engine = engine_init.engine; engine.window.on_start(); engine_init.eventloop.run(move |event, _, controlflow| { *controlflow = winit::event_loop::ControlFlow::Poll; engine.input.borrow_mut().update(&event, &engine); match event { Event::WindowEvent { event, .. } => { match event { winit::event::WindowEvent::MouseInput { .. } | winit::event::WindowEvent::MouseWheel { .. } | winit::event::WindowEvent::CursorMoved { .. } | winit::event::WindowEvent::KeyboardInput { .. } => { if !engine.input.borrow().get_cursor_captured() { engine.gui_state.on_event(&engine.gui_context, &event); } } _ => { engine.gui_state.on_event(&engine.gui_context, &event); } } match event { winit::event::WindowEvent::CloseRequested => { *controlflow = winit::event_loop::ControlFlow::Exit } winit::event::WindowEvent::Focused(state) => { engine.window.on_focus(state); } _ => {} } } // render Event::MainEventsCleared => { #[cfg(feature = "profiler")] puffin::GlobalProfiler::lock().new_frame(); engine.input.borrow_mut().handle_builtin(&mut engine.window); let now = Instant::now(); let delta = (now - last_time).as_secs_f32(); last_time = now; engine.gameloop.update(&engine.scene, delta); engine.render(); engine.input.borrow_mut().rollover_state(); } _ => {} } }); }
use anyhow::Result; use pathfinder_common::trie::TrieNode; use pathfinder_common::{ BlockHash, BlockNumber, BlockTimestamp, ByteCodeOffset, CallParam, CallResultValue, CasmHash, ClassCommitment, ClassCommitmentLeafHash, ClassHash, ConstructorParam, ContractAddress, ContractAddressSalt, ContractNonce, ContractRoot, ContractStateHash, EntryPoint, EventCommitment, EventData, EventKey, Fee, GasPrice, L1ToL2MessageNonce, L1ToL2MessagePayloadElem, L2ToL1MessagePayloadElem, SequencerAddress, SierraHash, StarknetVersion, StateCommitment, StorageAddress, StorageCommitment, StorageValue, TransactionCommitment, TransactionHash, TransactionNonce, TransactionSignatureElem, }; use rusqlite::types::{FromSqlError, ToSqlOutput}; use rusqlite::RowIndex; use stark_hash::Felt; pub trait ToSql { fn to_sql(&self) -> ToSqlOutput<'_>; } pub trait TryIntoSql { fn try_into_sql(&self) -> Result<ToSqlOutput<'_>>; } pub trait TryIntoSqlInt { fn try_into_sql_int(&self) -> Result<i64>; } impl<Inner: ToSql> ToSql for Option<Inner> { fn to_sql(&self) -> ToSqlOutput<'_> { use rusqlite::types::Value; match self { Some(value) => value.to_sql(), None => ToSqlOutput::Owned(Value::Null), } } } impl ToSql for StarknetVersion { fn to_sql(&self) -> ToSqlOutput<'_> { use rusqlite::types::ValueRef; ToSqlOutput::Borrowed(ValueRef::Text(self.as_str().as_bytes())) } } impl ToSql for TrieNode { fn to_sql(&self) -> ToSqlOutput<'_> { use bitvec::order::Msb0; use bitvec::view::BitView; use rusqlite::types::Value; let mut buffer = Vec::with_capacity(65); match self { TrieNode::Binary { left, right } => { buffer.extend_from_slice(left.as_be_bytes()); buffer.extend_from_slice(right.as_be_bytes()); } TrieNode::Edge { child, path } => { buffer.extend_from_slice(child.as_be_bytes()); // Bit path must be written in MSB format. This means that the LSB // must be in the last bit position. Since we write a fixed number of // bytes (32) but the path length may vary, we have to ensure we are writing // to the end of the slice. buffer.resize(65, 0); buffer[32..][..32].view_bits_mut::<Msb0>()[256 - path.len()..] .copy_from_bitslice(path); buffer[64] = path.len() as u8; } } ToSqlOutput::Owned(Value::Blob(buffer)) } } to_sql_felt!( BlockHash, ByteCodeOffset, CallParam, CallResultValue, CasmHash, ClassCommitment, ClassCommitmentLeafHash, ClassHash, ConstructorParam, ContractAddress, ContractAddressSalt, ContractStateHash, ContractRoot, EntryPoint, EventCommitment, EventData, EventKey, Fee, L1ToL2MessageNonce, L1ToL2MessagePayloadElem, L2ToL1MessagePayloadElem, SequencerAddress, SierraHash, TransactionHash, StateCommitment, StorageAddress, StorageCommitment, TransactionCommitment, TransactionSignatureElem, ); to_sql_compressed_felt!(ContractNonce, StorageValue, TransactionNonce); to_sql_int!(BlockNumber, BlockTimestamp); to_sql_builtin!( String, &str, Vec<u8>, &[u8], isize, i64, i32, i16, i8, u32, u16, u8 ); try_into_sql!(usize, u64); try_into_sql_int!(usize, u64); /// Extends [rusqlite::Row] to provide getters for our own foreign types. This is a work-around /// for the orphan rule -- our types live in a separate crate and can therefore not implement the /// rusqlite traits. pub trait RowExt { fn get_blob<I: RowIndex>(&self, index: I) -> rusqlite::Result<&[u8]>; fn get_i64<I: RowIndex>(&self, index: I) -> rusqlite::Result<i64>; fn get_optional_i64<I: RowIndex>(&self, index: I) -> rusqlite::Result<Option<i64>>; fn get_optional_str<I: RowIndex>(&self, index: I) -> rusqlite::Result<Option<&str>>; fn get_optional_blob<I: RowIndex>(&self, index: I) -> rusqlite::Result<Option<&[u8]>>; fn get_felt<Index: RowIndex>(&self, index: Index) -> rusqlite::Result<Felt> { let blob = self.get_blob(index)?; let felt = Felt::from_be_slice(blob) .map_err(|e| rusqlite::types::FromSqlError::Other(e.into()))?; Ok(felt) } fn get_optional_felt<Index: RowIndex>(&self, index: Index) -> rusqlite::Result<Option<Felt>> { let Some(blob) = self.get_optional_blob(index)? else { return Ok(None); }; let felt = Felt::from_be_slice(blob) .map_err(|e| rusqlite::types::FromSqlError::Other(e.into()))?; Ok(Some(felt)) } fn get_optional_block_number<Index: RowIndex>( &self, index: Index, ) -> rusqlite::Result<Option<BlockNumber>> { let num = self .get_optional_i64(index)? // Always safe since we are fetching an i64 .map(|x| BlockNumber::new_or_panic(x as u64)); Ok(num) } fn get_optional_casm_hash<Index: RowIndex>( &self, index: Index, ) -> rusqlite::Result<Option<CasmHash>> { Ok(self.get_optional_felt(index)?.map(CasmHash)) } fn get_optional_storage_commitment<Index: RowIndex>( &self, index: Index, ) -> rusqlite::Result<Option<StorageCommitment>> { Ok(self.get_optional_felt(index)?.map(StorageCommitment)) } fn get_optional_class_commitment<Index: RowIndex>( &self, index: Index, ) -> rusqlite::Result<Option<ClassCommitment>> { Ok(self.get_optional_felt(index)?.map(ClassCommitment)) } fn get_block_number<Index: RowIndex>(&self, index: Index) -> rusqlite::Result<BlockNumber> { let num = self.get_i64(index)?; // Always safe since we are fetching an i64 Ok(BlockNumber::new_or_panic(num as u64)) } fn get_gas_price<Index: RowIndex>(&self, index: Index) -> rusqlite::Result<GasPrice> { let blob = self.get_blob(index)?; let gas_price = GasPrice::from_be_slice(blob).map_err(|e| FromSqlError::Other(e.into()))?; Ok(gas_price) } fn get_timestamp<Index: RowIndex>(&self, index: Index) -> rusqlite::Result<BlockTimestamp> { let num = self.get_i64(index)?; // Always safe since we are fetching an i64 Ok(BlockTimestamp::new_or_panic(num as u64)) } fn get_starknet_version<Index: RowIndex>( &self, index: Index, ) -> rusqlite::Result<StarknetVersion> { // Older starknet versions were stored as null, map those to empty string. let s = self .get_optional_str(index)? .unwrap_or_default() .to_string(); Ok(StarknetVersion::from(s)) } fn get_transaction_commitment<Index: RowIndex>( &self, index: Index, ) -> rusqlite::Result<TransactionCommitment> { Ok(self .get_optional_felt(index)? .map(TransactionCommitment) .unwrap_or_default()) } fn get_event_commitment<Index: RowIndex>( &self, index: Index, ) -> rusqlite::Result<EventCommitment> { Ok(self .get_optional_felt(index)? .map(EventCommitment) .unwrap_or_default()) } fn get_class_commitment<Index: RowIndex>( &self, index: Index, ) -> rusqlite::Result<ClassCommitment> { Ok(self .get_optional_felt(index)? .map(ClassCommitment) .unwrap_or_default()) } fn get_contract_address<Index: RowIndex>( &self, index: Index, ) -> rusqlite::Result<ContractAddress> { let felt = self.get_felt(index)?; let addr = ContractAddress::new(felt).ok_or(rusqlite::types::FromSqlError::Other( anyhow::anyhow!("contract address out of range").into(), ))?; Ok(addr) } fn get_storage_address<Index: RowIndex>( &self, index: Index, ) -> rusqlite::Result<StorageAddress> { let felt = self.get_felt(index)?; let addr = StorageAddress::new(felt).ok_or(rusqlite::types::FromSqlError::Other( anyhow::anyhow!("storage address out of range").into(), ))?; Ok(addr) } row_felt_wrapper!(get_block_hash, BlockHash); row_felt_wrapper!(get_class_hash, ClassHash); row_felt_wrapper!(get_state_commitment, StateCommitment); row_felt_wrapper!(get_storage_commitment, StorageCommitment); row_felt_wrapper!(get_sequencer_address, SequencerAddress); row_felt_wrapper!(get_contract_root, ContractRoot); row_felt_wrapper!(get_contract_nonce, ContractNonce); row_felt_wrapper!(get_storage_value, StorageValue); row_felt_wrapper!(get_transaction_hash, TransactionHash); fn get_trie_node<I: RowIndex>(&self, index: I) -> rusqlite::Result<TrieNode> { use anyhow::Context; use bitvec::order::Msb0; let data = self.get_blob(index)?; match data.len() { 64 => { // unwraps and indexing are safe due to length check == 64. let left: [u8; 32] = data[..32].try_into().unwrap(); let right: [u8; 32] = data[32..].try_into().unwrap(); let left = Felt::from_be_bytes(left) .context("Binary node's left hash is corrupt") .map_err(|e| FromSqlError::Other(e.into()))?; let right = Felt::from_be_bytes(right) .context("Binary node's right hash is corrupt") .map_err(|e| FromSqlError::Other(e.into()))?; Ok(TrieNode::Binary { left, right }) } 65 => { // unwraps and indexing are safe due to length check == 65. let child: [u8; 32] = data[..32].try_into().unwrap(); let path = data[32..64].to_vec(); let length = data[64] as usize; // Grab the __last__ `length` bits. Path is stored in MSB format, which means LSB // is always stored in the last bit. Since the path may vary in length we must take // the last bits. use bitvec::view::BitView; let path = path.view_bits::<Msb0>()[256 - length..].to_bitvec(); let child = Felt::from_be_bytes(child) .context("Edge node's child hash is corrupt.") .map_err(|e| FromSqlError::Other(e.into()))?; anyhow::Result::Ok(TrieNode::Edge { path, child }) } other => { Err(FromSqlError::Other(anyhow::anyhow!("Bad node length: {other}").into()).into()) } } } } impl<'a> RowExt for &rusqlite::Row<'a> { fn get_blob<I: RowIndex>(&self, index: I) -> rusqlite::Result<&[u8]> { self.get_ref(index)?.as_blob().map_err(|e| e.into()) } fn get_optional_blob<I: RowIndex>(&self, index: I) -> rusqlite::Result<Option<&[u8]>> { self.get_ref(index)?.as_blob_or_null().map_err(|e| e.into()) } fn get_i64<I: RowIndex>(&self, index: I) -> rusqlite::Result<i64> { self.get_ref(index)?.as_i64().map_err(|e| e.into()) } fn get_optional_i64<I: RowIndex>(&self, index: I) -> rusqlite::Result<Option<i64>> { self.get_ref(index)?.as_i64_or_null().map_err(|e| e.into()) } fn get_optional_str<I: RowIndex>(&self, index: I) -> rusqlite::Result<Option<&str>> { self.get_ref(index)?.as_str_or_null().map_err(|e| e.into()) } } /// Implements [ToSql] for the target [Felt](stark_hash::Felt) newtype. /// /// Writes the full underlying bytes (no compression). macro_rules! to_sql_felt { ($target:ty) => { impl ToSql for $target { fn to_sql(&self) -> rusqlite::types::ToSqlOutput<'_> { use rusqlite::types::{ToSqlOutput, ValueRef}; ToSqlOutput::Borrowed(ValueRef::Blob(self.as_inner().as_be_bytes())) } } }; ($head:ty, $($rest:ty),+ $(,)?) => { to_sql_felt!($head); to_sql_felt!($($rest),+); } } /// Implements [ToSql] for the target [Felt] newtype. /// /// Same as [to_sql_felt!] except it compresses the [Felt] by skipping leading zeros. /// /// [Felt]: stark_hash::Felt macro_rules! to_sql_compressed_felt { ($target:ty) => { impl ToSql for $target { fn to_sql(&self) -> rusqlite::types::ToSqlOutput<'_> { use rusqlite::types::{ToSqlOutput, ValueRef}; let bytes = self.0.as_be_bytes(); let num_zeroes = bytes.iter().take_while(|v| **v == 0).count(); ToSqlOutput::Borrowed(ValueRef::Blob(&bytes[num_zeroes..])) } } }; ($head:ty, $($rest:ty),+ $(,)?) => { to_sql_compressed_felt!($head); to_sql_compressed_felt!($($rest),+); } } /// Implements [ToSql] for the target integer newtype. macro_rules! to_sql_int { ($target:ty) => { impl ToSql for $target { fn to_sql(&self) -> rusqlite::types::ToSqlOutput<'_> { use rusqlite::types::{ToSqlOutput, Value}; ToSqlOutput::Owned(Value::Integer(self.get() as i64)) } } }; ($head:ty, $($rest:ty),+ $(,)?) => { to_sql_int!($head); to_sql_int!($($rest),+); } } macro_rules! to_sql_builtin { ($target:ty) => { impl ToSql for $target { fn to_sql(&self) -> rusqlite::types::ToSqlOutput<'_> { rusqlite::ToSql::to_sql(self).unwrap() } } }; ($head:ty, $($rest:ty),+ $(,)?) => { to_sql_builtin!($head); to_sql_builtin!($($rest),+); } } macro_rules! try_into_sql { ($target:ty) => { impl TryIntoSql for $target { fn try_into_sql(&self) -> anyhow::Result<rusqlite::types::ToSqlOutput<'_>> { use rusqlite::types::{ToSqlOutput, Value}; Ok(ToSqlOutput::Owned(Value::Integer(i64::try_from(*self)?))) } } }; ($head:ty, $($rest:ty),+ $(,)?) => { try_into_sql!($head); try_into_sql!($($rest),+); } } macro_rules! try_into_sql_int { ($target:ty) => { impl TryIntoSqlInt for $target { fn try_into_sql_int(&self) -> anyhow::Result<i64> { Ok(i64::try_from(*self)?) } } }; ($head:ty, $($rest:ty),+ $(,)?) => { try_into_sql_int!($head); try_into_sql_int!($($rest),+); } } macro_rules! row_felt_wrapper { ($fn_name:ident, $Type:ident) => { fn $fn_name<I: RowIndex>(&self, index: I) -> rusqlite::Result<$Type> { let felt = self.get_felt(index)?; Ok($Type(felt)) } }; } use { row_felt_wrapper, to_sql_builtin, to_sql_compressed_felt, to_sql_felt, to_sql_int, try_into_sql, try_into_sql_int, }; /// Used in combination with our own [ToSql] trait to provide functionality equivalent to /// [rusqlite::params!] for our own foreign types. macro_rules! params { [] => { rusqlite::params![] }; [$($param:expr),+ $(,)?] => { rusqlite::params![$(&$crate::params::ToSql::to_sql($param)),+] }; } macro_rules! named_params { () => { rusqlite::named_params![] }; // Note: It's a lot more work to support this as part of the same macro as // `params!`, unfortunately. ($($param_name:literal: $param_val:expr),+ $(,)?) => { rusqlite::named_params![$($param_name: $crate::params::ToSql::to_sql($param_val)),+] }; } pub(crate) use {named_params, params}; #[cfg(test)] mod tests { use super::*; use pathfinder_common::macro_prelude::*; #[test] fn to_sql() { // Exercises to_sql! and params! in a roundtrip to and from storage trip. let original = class_hash!("0xdeadbeef"); let db = rusqlite::Connection::open_in_memory().unwrap(); db.execute("CREATE TABLE test (data BLOB)", []).unwrap(); db.execute("INSERT INTO test VALUES(?)", params![&original]) .unwrap(); let result = db .query_row("SELECT data FROM test", [], |row| row.get_class_hash(0)) .unwrap(); assert_eq!(result, original); } }
use proconio::input; macro_rules! chmax { ($a: expr, $b: expr) => { $a = $a.max($b); }; } fn main() { input! { n: usize, m: usize, a: [i64; n], }; let inf = std::i64::MAX; let mut dp = vec![-inf; m + 1]; dp[0] = 0; for i in 0..n { let mut next = dp.clone(); for j in 0..=m { if dp[j] == -inf { continue; } chmax!(next[j], dp[j]); if j + 1 <= m { chmax!(next[j + 1], dp[j] + a[i] * (j + 1) as i64); } } dp = next; } assert_ne!(dp[m], -inf); println!("{}", dp[m]); }
//! Storage imports. use std::convert::TryInto; use oasis_contract_sdk_types::storage::StoreKind; use oasis_runtime_sdk::{context::Context, storage::Store}; use super::{memory::Region, OasisV1}; use crate::{ abi::{gas, ExecutionContext}, store, Config, Error, }; impl<Cfg: Config> OasisV1<Cfg> { /// Link storage functions. pub fn link_storage<C: Context>( instance: &mut wasm3::Instance<'_, '_, ExecutionContext<'_, C>>, ) -> Result<(), Error> { // storage.get(store, key) -> value let _ = instance.link_function( "storage", "get", |ctx, (store, key): (u32, (u32, u32))| -> Result<(u32, u32), wasm3::Trap> { // Make sure function was called in valid context. let ec = ctx.context.ok_or(wasm3::Trap::Abort)?; ensure_key_size(ec, key.1)?; // Charge base gas amount plus size-dependent gas. let total_gas = (|| { let base = ec.params.gas_costs.wasm_storage_get_base; let key = ec .params .gas_costs .wasm_storage_key_byte .checked_mul(key.1.into())?; let total = base.checked_add(key)?; Some(total) })() .ok_or(wasm3::Trap::Abort)?; gas::use_gas(ctx.instance, total_gas)?; // Read from contract state. let value = ctx.instance.runtime().try_with_memory( |memory| -> Result<_, wasm3::Trap> { let key = Region::from_arg(key).as_slice(&memory)?; Ok(get_instance_store(ec, store)?.get(key)) }, )??; let value = match value { Some(value) => value, None => return Ok((0, 0)), }; // Charge gas for size of value. gas::use_gas( ctx.instance, ec.params .gas_costs .wasm_storage_value_byte .checked_mul(value.len().try_into()?) .ok_or(wasm3::Trap::Abort)?, )?; // Create new region by calling `allocate`. // // This makes sure that the call context is unset to avoid any potential issues // with reentrancy as attempting to re-enter one of the linked functions will fail. let value_region = Self::allocate_and_copy(ctx.instance, &value)?; Ok(value_region.to_arg()) }, ); // storage.insert(store, key, value) let _ = instance.link_function( "storage", "insert", |ctx, (store, key, value): (u32, (u32, u32), (u32, u32))| { // Make sure function was called in valid context. let ec = ctx.context.ok_or(wasm3::Trap::Abort)?; ensure_key_size(ec, key.1)?; ensure_value_size(ec, value.1)?; // Charge base gas amount plus size-dependent gas. let total_gas = (|| { let base = ec.params.gas_costs.wasm_storage_insert_base; let key = ec .params .gas_costs .wasm_storage_key_byte .checked_mul(key.1.into())?; let value = ec .params .gas_costs .wasm_storage_value_byte .checked_mul(value.1.into())?; let total = base.checked_add(key)?.checked_add(value)?; Some(total) })() .ok_or(wasm3::Trap::Abort)?; gas::use_gas(ctx.instance, total_gas)?; // Insert into contract state. ctx.instance .runtime() .try_with_memory(|memory| -> Result<(), wasm3::Trap> { let key = Region::from_arg(key).as_slice(&memory)?; let value = Region::from_arg(value).as_slice(&memory)?; get_instance_store(ec, store)?.insert(key, value); Ok(()) })??; Ok(()) }, ); // storage.remove(store, key) let _ = instance.link_function( "storage", "remove", |ctx, (store, key): (u32, (u32, u32))| { // Make sure function was called in valid context. let ec = ctx.context.ok_or(wasm3::Trap::Abort)?; ensure_key_size(ec, key.1)?; // Charge base gas amount plus size-dependent gas. let total_gas = (|| { let base = ec.params.gas_costs.wasm_storage_remove_base; let key = ec .params .gas_costs .wasm_storage_key_byte .checked_mul(key.1.into())?; let total = base.checked_add(key)?; Some(total) })() .ok_or(wasm3::Trap::Abort)?; gas::use_gas(ctx.instance, total_gas)?; // Remove from contract state. ctx.instance .runtime() .try_with_memory(|memory| -> Result<(), wasm3::Trap> { let key = Region::from_arg(key).as_slice(&memory)?; get_instance_store(ec, store)?.remove(key); Ok(()) })??; Ok(()) }, ); Ok(()) } } /// Create a contract instance store. fn get_instance_store<'a, C: Context>( ec: &'a mut ExecutionContext<'_, C>, store_kind: u32, ) -> Result<impl Store + 'a, wasm3::Trap> { // Determine which store we should be using. let store_kind: StoreKind = store_kind.try_into().map_err(|_| wasm3::Trap::Abort)?; Ok(store::for_instance( ec.tx_context, ec.instance_info, store_kind, )?) } /// Make sure that the key size is within the range specified in module parameters. fn ensure_key_size<C: Context>(ec: &ExecutionContext<'_, C>, size: u32) -> Result<(), wasm3::Trap> { if size > ec.params.max_storage_key_size_bytes { // TODO: Consider returning a nicer error message. return Err(wasm3::Trap::Abort); } Ok(()) } /// Make sure that the value size is within the range specified in module parameters. fn ensure_value_size<C: Context>( ec: &ExecutionContext<'_, C>, size: u32, ) -> Result<(), wasm3::Trap> { if size > ec.params.max_storage_value_size_bytes { // TODO: Consider returning a nicer error message. return Err(wasm3::Trap::Abort); } Ok(()) }
use std::collections::HashMap; use std::sync::Arc; use crate::mysql::protocol; use crate::mysql::{MySql, MySqlValue}; use crate::row::{ColumnIndex, Row}; use serde::de::DeserializeOwned; #[derive(Debug)] pub struct MySqlRow<'c> { pub(super) row: protocol::Row<'c>, pub(super) names: Arc<HashMap<Box<str>, u16>>, } impl<'c> MySqlRow<'c> { pub fn json_decode_impl<T, I>(&self, index: I) -> crate::Result<T> where I: ColumnIndex<'c, Self>, T: DeserializeOwned { self.json_decode(index) } } impl crate::row::private_row::Sealed for MySqlRow<'_> {} impl<'c> Row<'c> for MySqlRow<'c> { type Database = MySql; fn len(&self) -> usize { self.row.len() } #[doc(hidden)] fn try_get_raw<I>(&self, index: I) -> crate::Result<MySqlValue<'c>> where I: ColumnIndex<'c, Self>, { let index = index.index(self)?; let column_ty = self.row.columns[index].clone(); let buffer = self.row.get(index); let value = match (self.row.binary, buffer) { (_, None) => MySqlValue::null(), (true, Some(buf)) => MySqlValue::binary(column_ty, buf), (false, Some(buf)) => MySqlValue::text(column_ty, buf), }; Ok(value) } } impl<'c> ColumnIndex<'c, MySqlRow<'c>> for usize { fn index(&self, row: &MySqlRow<'c>) -> crate::Result<usize> { let len = Row::len(row); if *self >= len { return Err(crate::Error::ColumnIndexOutOfBounds { len, index: *self }); } Ok(*self) } } impl<'c> ColumnIndex<'c, MySqlRow<'c>> for str { fn index(&self, row: &MySqlRow<'c>) -> crate::Result<usize> { row.names .get(self) .ok_or_else(|| crate::Error::ColumnNotFound((*self).into())) .map(|&index| index as usize) } }
use juniper::graphql_object; struct ObjA; #[graphql_object] impl ObjA { fn id(&self) -> &str { "funA" } #[graphql(name = "id")] fn id2(&self) -> &str { "funB" } } fn main() {}
use aoc; use std::collections::HashMap; type OpPrecedence = HashMap<char, usize>; type RPN = Vec<char>; // https://en.wikipedia.org/wiki/Shunting-yard_algorithm fn parse2(expr : &String, opm: &OpPrecedence) -> RPN { let mut rpn : Vec<char> = vec!(); let mut op : Vec<char> = vec!(); for t in expr.chars().filter(|c| *c != ' ') { match t { '(' => op.push(t), ')' => { while !op.is_empty() && *op.last().unwrap() != '(' { rpn.push(op.pop().unwrap()); } if *op.last().unwrap() == '(' { op.pop(); //discard } }, '+' | '*' => { while !op.is_empty() { let peek = *op.last().unwrap(); if peek == '(' { break; } // Check if new op has higher precedence than top of stack if opm.get(&peek).unwrap() < opm.get(&t).unwrap() { break; } rpn.push(op.pop().unwrap()); } op.push(t) }, _ => rpn.push(t) } } while !op.is_empty() { rpn.push(op.pop().unwrap()); } rpn } fn eval(expr : RPN) -> u64 { let mut out : Vec<u64> = vec!(); for token in expr { match token { '+' => { let op1 = out.pop().unwrap(); let op2 = out.pop().unwrap(); out.push(op1 + op2); }, '*' => { let op1 = out.pop().unwrap(); let op2 = out.pop().unwrap(); out.push(op1 * op2); }, _ => { out.push(token.to_digit(10).unwrap() as u64) } } } *out.last().unwrap() } fn main() { let lines = aoc::lines_from_file("input.txt"); let mut op_prec = HashMap::new(); op_prec.insert('+', 0); op_prec.insert('*', 0); let sum1 : u64 = lines.iter().map(|l| eval(parse2(l, &op_prec))).sum(); dbg!(sum1); // elevate + above * op_prec.insert('+', 1); let sum2 : u64 = lines.iter().map(|l| eval(parse2(l, &op_prec))).sum(); dbg!(sum2); }
use crate::{linalg::Vct, Deserialize, Flt, Serialize}; #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct BBox { pub min: Vct, pub max: Vct, } impl BBox { pub fn hit(&self, origin: &Vct, direct: &Vct) -> Option<(Flt, Flt)> { let inv_direct = Vct::new(1.0 / direct.x, 1.0 / direct.y, 1.0 / direct.z); let neg_index = [inv_direct.x < 0.0, inv_direct.y < 0.0, inv_direct.z < 0.0]; self.fast_hit(origin, &inv_direct, &neg_index) /* let a = (self.min - *origin) * *inv_direct; let b = (self.max - *origin) * *inv_direct; let min = a.min(b); let max = a.max(b); let t_min = min.x.max(min.y).max(min.z).max(0.0); let t_max = max.x.min(max.y).min(max.z); if t_min <= t_max { Some((t_min, t_max)) } else { None } */ } #[cfg_attr(rustfmt, rustfmt_skip)] pub fn fast_hit( &self, origin: &Vct, inv_direct: &Vct, neg_index: &[bool; 3], ) -> Option<(Flt, Flt)> { macro_rules! a { ($i:expr) => { if neg_index[$i] { self.max } else { self.min } }; } macro_rules! b { ($i:expr) => { if neg_index[$i] { self.min } else { self.max } }; } let mut t_min = (a!(0).x - origin.x) * inv_direct.x; let mut t_max = (b!(0).x - origin.x) * inv_direct.x; let ty_min = (a!(1).y - origin.y) * inv_direct.y; let ty_max = (b!(1).y - origin.y) * inv_direct.y; if t_min < 0.0 { t_min = 0.0; } if t_min > ty_max || ty_min > t_max { return None; } if ty_min > t_min { t_min = ty_min; } if ty_max < t_max { t_max = ty_max; } let tz_min = (a!(2).z - origin.z) * inv_direct.z; let tz_max = (b!(2).z - origin.z) * inv_direct.z; if t_min > tz_max || tz_min > t_max { return None; } if tz_min > t_min { t_min = tz_min; } if tz_max < t_max { t_max = tz_max; } if t_min < t_max { Some((t_min, t_max)) } else { None } } } #[cfg(test)] mod tests { use super::*; #[test] fn hit() { let b = BBox { min: Vct::new(0.0, 0.0, 0.0), max: Vct::new(1.0, 1.0, 1.0) }; let t = b.hit(&Vct::new(0.5, 0.5, 0.5), &Vct::new(1.0, 0.0, 0.0)); assert!(!t.is_none()); let t = t.unwrap(); assert!((t.0 - 0.0).abs() < 1e-5); assert!((t.1 - 0.5).abs() < 1e-5); let t = b.hit(&Vct::new(-0.5, 0.5, 0.5), &Vct::new(1.0, 0.0, 0.0)); assert!(!t.is_none()); let t = t.unwrap(); assert!((t.0 - 0.5).abs() < 1e-5); assert!((t.1 - 1.5).abs() < 1e-5); } }
use std::fs::File; use std::io::prelude::Write; use std::process::Command; use std::thread; use std::time; use crate::mqtt::AsyncClient; use crate::nodes::announce_blackbox_online; use crate::settings::SettingsMosquitto; use crate::INTERFACE_MQTT_USERNAME; pub static REGISTERED_TOPIC: &str = "registered"; pub static UNREGISTERED_TOPIC: &str = "unregistered"; pub static WEBINTERFACE_TOPIC: &str = INTERFACE_MQTT_USERNAME; pub static NEUTRONCOMMUNICATOR_TOPIC: &str = "neutron_communicators"; pub static TOPICS: &[&str] = &["registered/#", "unregistered/#", "external_interface/#", "neutron_communicators/#"]; pub static QOS: &[i32] = &[1, 1, 1, 1]; /** * Generates mosquitto(mqtt) configuration file. * Saved in <mqtt_conf_file_location>. */ pub fn generate_mosquitto_conf(settings: &SettingsMosquitto, restart_mqtt_docker_container: bool) { info!("Generating mosquitto broker configuration file..."); let config_no_ssl = format!("listener 8883\n persistence false\n log_type all\n log_dest stderr\n allow_anonymous false\n cafile /mosquitto/config/ca.crt\n certfile /mosquitto/config/server.crt\n keyfile /mosquitto/config/server.key\n require_certificate false\n auth_plugin /mosquitto/config/go-auth.so\n auth_opt_backends postgres\n auth_opt_pg_host database_postgres\n auth_opt_pg_port {}\n auth_opt_pg_dbname {}\n auth_opt_pg_user {}\n auth_opt_pg_password {}\n auth_opt_pg_userquery SELECT password FROM mqtt_users WHERE username = $1 limit 1\n auth_opt_pg_superquery SELECT COUNT(*) FROM mqtt_users WHERE username = $1 AND superuser = TRUE\n auth_opt_pg_aclquery SELECT topic FROM mqtt_acl WHERE (username = $1) AND (rw = $2 or rw = 3)", settings.db_port, settings.db_name, settings.db_username, settings.db_password); let mut file = File::create(settings.mosquitto_conf_save_location.to_string()).unwrap(); file.write_all(config_no_ssl.as_bytes()) .unwrap(); if restart_mqtt_docker_container { restart_mqtt_container(); } info!( "Generated MQTT config. Location: {}", settings.mosquitto_conf_save_location ); } /** * Restarts mosquitto broker docker container with "sudo docker restart <container_id>". */ fn restart_mqtt_container() { // First get container id so we can restart let container_id = Command::new("sudo") .arg("docker") .arg("ps") .arg("-a") .arg("-q") .arg("--filter") .arg("ancestor=mosquitto") .output() .expect("Failed to get mosquitto docker container id."); let out = Command::new("sudo") .arg("docker") .arg("restart") .arg( String::from_utf8_lossy(&container_id.stdout) .to_string() .replace("\n", ""), ) .output() .expect("Failed to restart mosquitto docker container."); debug!("Restarting mqtt container."); if !String::from_utf8_lossy(&out.stderr).to_owned().is_empty() { error!( "Could not restart MQTT broker docker container. {:?}", String::from_utf8_lossy(&out.stderr) ); } } /** * OnConnectionSuccess mqtt callback. */ pub fn on_mqtt_connect_success(cli: &AsyncClient, _msgid: u16) { info!("Connection succeeded."); info!("Subscribing to: {}", TOPICS[0]); info!("Subscribing to: {}", TOPICS[2]); announce_blackbox_online(cli); cli.subscribe(TOPICS[0], QOS[0]); cli.subscribe(TOPICS[2], QOS[2]); } /** * OnConnectionFail mqtt callback. */ pub fn on_mqtt_connect_failure(cli: &AsyncClient, _msgid: u16, rc: i32) { debug!("Connection attempt failed with error code {}.", rc); thread::sleep(time::Duration::from_millis(2500)); cli.reconnect_with_callbacks(on_mqtt_connect_success, on_mqtt_connect_failure); } /** * OnConnectionLost mqtt callback. */ pub fn on_mqtt_connection_lost(cli: &AsyncClient) { error!("Connection lost. Reconnecting..."); thread::sleep(time::Duration::from_millis(2500)); cli.reconnect_with_callbacks(on_mqtt_connect_success, on_mqtt_connect_failure); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { failure::{Error, ResultExt}, fidl::endpoints, fidl_fuchsia_io::DirectoryMarker, fidl_fuchsia_sys2 as fsys, fidl_fuchsia_test_breakpoints as fbreak, fidl_fuchsia_test_hub as fhub, fuchsia_async as fasync, fuchsia_component::client::connect_to_service, }; macro_rules! get_names_from_listing { ($dir_listing:ident) => { &mut $dir_listing.iter().map(|entry| &entry.name as &str) }; } struct Testing { hub_report: fhub::HubReportProxy, breakpoints: fbreak::BreakpointsProxy, } impl Testing { fn new() -> Result<Self, Error> { let hub_report = connect_to_service::<fhub::HubReportMarker>() .context("error connecting to HubReport")?; let breakpoints = connect_to_service::<fbreak::BreakpointsMarker>() .context("error connecting to Breakpoints")?; Ok(Self { hub_report, breakpoints }) } async fn report_directory_contents(&self, dir_path: &str) -> Result<(), Error> { let dir_proxy = io_util::open_directory_in_namespace(dir_path, io_util::OPEN_RIGHT_READABLE) .expect("Unable to open directory in namespace"); let dir_listing = files_async::readdir(&dir_proxy).await.expect("readdir failed"); self.hub_report .list_directory(dir_path, get_names_from_listing!(dir_listing)) .await .context("list directory failed")?; Ok(()) } async fn register_breakpoints(&self, event_types: Vec<fbreak::EventType>) -> Result<(), Error> { self.breakpoints .register(&mut event_types.into_iter()) .await .context("register breakpoints failed")?; Ok(()) } async fn report_file_content(&self, path: &str) -> Result<(), Error> { let resolved_url_proxy = io_util::open_file_in_namespace(path, io_util::OPEN_RIGHT_READABLE) .expect("Unable to open the file."); let resolved_url_file_content = io_util::read_file(&resolved_url_proxy).await?; self.hub_report .report_file_content(path, &resolved_url_file_content) .await .context("report file content failed")?; Ok(()) } async fn expect_breakpoint( &self, event_type: fbreak::EventType, components: Vec<&str>, ) -> Result<(), Error> { self.breakpoints .expect(event_type, &mut components.into_iter()) .await .context("expect breakpoint failed")?; Ok(()) } async fn resume_breakpoint(&self) -> Result<(), Error> { self.breakpoints.resume().await.context("resume breakpoint failed")?; Ok(()) } } #[fasync::run_singlethreaded] async fn main() -> Result<(), Error> { // Create a dynamic child component let realm = connect_to_service::<fsys::RealmMarker>().context("error connecting to realm")?; let mut collection_ref = fsys::CollectionRef { name: String::from("coll") }; let child_decl = fsys::ChildDecl { name: Some(String::from("simple_instance")), url: Some(String::from("fuchsia-pkg://fuchsia.com/hub_integration_test#meta/simple.cm")), startup: Some(fsys::StartupMode::Lazy), }; realm .create_child(&mut collection_ref, child_decl) .await .context("create_child failed")? .expect("failed to create child"); let testing = Testing::new()?; // Register breakpoints for relevant events testing .register_breakpoints(vec![ fbreak::EventType::StopInstance, fbreak::EventType::PreDestroyInstance, fbreak::EventType::PostDestroyInstance, ]) .await?; // Read the children of this component and pass the results to the integration test // via HubReport. testing.report_directory_contents("/hub/children").await?; // Read the hub of the dynamic child and pass the results to the integration test // via HubReport testing.report_directory_contents("/hub/children/coll:simple_instance").await?; // Read the instance id of the dynamic child and pass the results to the integration test // via HubReport testing.report_file_content("/hub/children/coll:simple_instance/id").await?; // Read the children of the dynamic child and pass the results to the integration test // via HubReport testing.report_directory_contents("/hub/children/coll:simple_instance/children").await?; // Bind to the dynamic child let mut child_ref = fsys::ChildRef { name: "simple_instance".to_string(), collection: Some("coll".to_string()), }; let (_dir_proxy, server_end) = endpoints::create_proxy::<DirectoryMarker>().unwrap(); realm.bind_child(&mut child_ref, server_end).await?.expect("failed to bind to child"); // Read the hub of the dynamic child and pass the results to the integration test // via HubReport testing.report_directory_contents("/hub/children/coll:simple_instance").await?; // Read the children of the dynamic child and pass the results to the integration test // via HubReport testing.report_directory_contents("/hub/children/coll:simple_instance/children").await?; // Read the instance id of the dynamic child's static child and pass the results to the // integration test via HubReport testing.report_file_content("/hub/children/coll:simple_instance/children/child/id").await?; // Delete the dynamic child let mut child_ref = fsys::ChildRef { name: "simple_instance".to_string(), collection: Some("coll".to_string()), }; realm .destroy_child(&mut child_ref) .await .context("delete_child failed")? .expect("failed to delete child"); // Wait for the dynamic child to begin deletion testing .expect_breakpoint(fbreak::EventType::PreDestroyInstance, vec!["coll:simple_instance:1"]) .await?; testing.report_directory_contents("/hub/children").await?; testing.report_directory_contents("/hub/deleting").await?; testing.report_directory_contents("/hub/deleting/coll:simple_instance:1").await?; testing.resume_breakpoint().await?; // Wait for the dynamic child to stop testing .expect_breakpoint(fbreak::EventType::StopInstance, vec!["coll:simple_instance:1"]) .await?; testing.report_directory_contents("/hub/deleting/coll:simple_instance:1").await?; testing.resume_breakpoint().await?; // Wait for the dynamic child's static child to begin deletion testing .expect_breakpoint( fbreak::EventType::PreDestroyInstance, vec!["coll:simple_instance:1", "child:0"], ) .await?; testing.report_directory_contents("/hub/deleting/coll:simple_instance:1/children").await?; testing.report_directory_contents("/hub/deleting/coll:simple_instance:1/deleting").await?; testing .report_directory_contents("/hub/deleting/coll:simple_instance:1/deleting/child:0") .await?; testing.resume_breakpoint().await?; // Wait for the dynamic child's static child to be destroyed testing .expect_breakpoint( fbreak::EventType::PostDestroyInstance, vec!["coll:simple_instance:1", "child:0"], ) .await?; testing.report_directory_contents("/hub/deleting/coll:simple_instance:1/deleting").await?; testing.resume_breakpoint().await?; // Wait for the dynamic child to be destroyed testing .expect_breakpoint(fbreak::EventType::PostDestroyInstance, vec!["coll:simple_instance:1"]) .await?; testing.report_directory_contents("/hub/deleting").await?; testing.resume_breakpoint().await?; Ok(()) }
use crate::context::UpstreamContext; use core::cell::UnsafeCell; /// A leaf component representing IRQ logic. /// /// Being an interrupt, it has no sense of *inbound* messages, but /// can producer `::OutboundMessage`s to its containing parent /// `Component` or `Kernel`. pub trait Interrupt: Sized { /// The type of message sent to its parent. type OutboundMessage; /// The IRQ number to which this `Interrupt` should respond. fn irq(&self) -> u8; /// The action to undertake when the associated interrupt line is triggered. fn on_interrupt(&mut self, context: &InterruptContext<Self>); } /// The context provided to the `Interrupt` during it's `on_interrupt(...)` invocation. pub struct InterruptContext<I: Interrupt> where I: 'static, { _interrupt: &'static ConnectedInterrupt<I>, upstream: &'static dyn UpstreamContext<I::OutboundMessage>, } impl<I: Interrupt> InterruptContext<I> { fn new( interrupt: &'static ConnectedInterrupt<I>, upstream: &'static dyn UpstreamContext<I::OutboundMessage>, ) -> Self { Self { _interrupt: interrupt, upstream, } } /// Send a message, *synchronously*, upstream to the containing /// parent `Component` or `Kernel`, which *must* implement /// `Handler<C::OutboundMessage>` to be able to accomodate /// messages from this child. /// /// This method is immediate and synchronous, avoiding any /// FIFOs. By the time it returns, the parent's associated /// `Handler<M>` will have been called and fulled executed. /// /// The component is *not* directly linked to the outbound /// messages, so if differentiation between components that /// can produce similar messages is required, a discriminant /// (possibly using a `PhantomData` field) may be required. pub fn send(&self, message: I::OutboundMessage) { self.upstream.send(message) } } /// Wrapper for an `Interrupt` to be held by the `Kernel` /// or a `Component` parent of this interrupt. Interrupts shall /// not be held directly, but only through a `ConnectedInterrupt<I>` /// which handles message routing. pub struct ConnectedInterrupt<I: Interrupt> where I: 'static, { interrupt: UnsafeCell<I>, context: UnsafeCell<Option<InterruptContext<I>>>, } impl<I: Interrupt> ConnectedInterrupt<I> { /// Create a new wrapped `ConnectedInterrupt<I>` from an `Interrupt`. pub fn new(interrupt: I) -> Self { Self { interrupt: UnsafeCell::new(interrupt), context: UnsafeCell::new(None), } } /// Start this interrupt. /// /// This method should be invoked with the `ctx` passed to it's /// parent's own `start(...)` method. pub fn start(&'static self, upstream: &'static dyn UpstreamContext<I::OutboundMessage>) { let context = InterruptContext::new(self, upstream); unsafe { context .upstream .register_irq((&*self.interrupt.get()).irq(), self); (&mut *self.context.get()).replace(context); } } } impl<I: Interrupt> Interruptable for ConnectedInterrupt<I> { fn interrupt(&self) { unsafe { (&mut *self.interrupt.get()).on_interrupt((&*self.context.get()).as_ref().unwrap()); } } } #[doc(hidden)] pub trait Interruptable { fn interrupt(&self); }
//#[path = "./lib.rs"] //mod lib; //use lib::*; fn main() { //let ptr = RcCell::new(123); //let foo = ptr.borrow(); //println!("{}", foo); }
use atomsh::{CWD, REPORT, PROMPT, INCOMPLETE_PROMPT, Error, Environment, Value, parse, PRELUDE_FILENAME, HISTORY_FILENAME}; use rustyline::{ error::ReadlineError, Editor, Helper, Modifiers, KeyEvent, Cmd }; use std::{borrow::Cow::{self, Borrowed, Owned}, env::current_dir, fs::read_to_string, sync::{Arc, Mutex}}; use rustyline::completion::{Completer, FilenameCompleter, Pair}; use rustyline::config::OutputStreamType; use rustyline::highlight::{Highlighter, MatchingBracketHighlighter}; use rustyline::hint::{Hinter, HistoryHinter}; use rustyline::validate::{MatchingBracketValidator, Validator, ValidationContext, ValidationResult}; use rustyline::{CompletionType, Config, Context, EditMode}; use rustyline_derive::Helper; #[derive(Helper)] struct AtomHelper { completer: FilenameCompleter, highlighter: MatchingBracketHighlighter, validator: MatchingBracketValidator, hinter: HistoryHinter, colored_prompt: String, env: Environment } impl AtomHelper { fn set_prompt(&mut self, prompt: impl ToString) { self.colored_prompt = prompt.to_string(); } fn update_env(&mut self, env: &Environment) { self.env = env.clone(); } } impl Completer for AtomHelper { type Candidate = Pair; fn complete( &self, line: &str, pos: usize, ctx: &Context<'_>, ) -> Result<(usize, Vec<Pair>), ReadlineError> { if let Ok(mut path) = self.env.get_cwd() { let mut segment = String::new(); if !line.is_empty() { for (i, ch) in line.chars().enumerate() { if ch.is_whitespace() || ch == ';' || ch == '\'' || ch == '(' || ch == ')' || ch == '{' || ch == '}' || ch == '"' { segment = String::new(); } else { segment.push(ch); } if i == pos { break; } } if !segment.is_empty() { path.push(segment.clone()); } } let path_str = (Value::Path(path).to_string() + if segment.is_empty() { "/" } else { "" }).replace("/./", "/").replace("//", "/"); let (pos, mut pairs) = self.completer.complete(path_str.as_str(), path_str.len(), ctx)?; for pair in &mut pairs { pair.replacement = String::from(line) + &pair.replacement.replace(&path_str, ""); } Ok((pos, pairs)) } else { self.completer.complete(line, pos, ctx) } } } impl Hinter for AtomHelper { type Hint = String; fn hint(&self, line: &str, pos: usize, ctx: &Context<'_>) -> Option<String> { self.hinter.hint(line, pos, ctx) } } impl Highlighter for AtomHelper { fn highlight_prompt<'b, 's: 'b, 'p: 'b>( &'s self, prompt: &'p str, default: bool, ) -> Cow<'b, str> { if default { Borrowed(&self.colored_prompt) } else { Borrowed(prompt) } } fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> { Owned("\x1b[1m".to_owned() + hint + "\x1b[m") } fn highlight<'l>(&self, line: &'l str, pos: usize) -> Cow<'l, str> { self.highlighter.highlight(line, pos) } fn highlight_char(&self, line: &str, pos: usize) -> bool { self.highlighter.highlight_char(line, pos) } } impl Validator for AtomHelper { fn validate( &self, _: &mut ValidationContext, ) -> rustyline::Result<ValidationResult> { Ok(ValidationResult::Valid(None)) } fn validate_while_typing(&self) -> bool { self.validator.validate_while_typing() } } fn readline(prompt: impl ToString, rl: &mut Editor<impl Helper>) -> String { loop { match rl.readline(&prompt.to_string()) { Ok(line) => { return line }, Err(ReadlineError::Interrupted) => { return String::new(); }, Err(ReadlineError::Eof) => { return String::new(); }, Err(err) => { eprintln!("error: {:?}", err); } } } } fn repl(atomic_rl: Arc<Mutex<Editor<AtomHelper>>>, atomic_env: Arc<Mutex<Environment>>) -> Result<(), Error> { loop { let mut env = atomic_env.lock().unwrap(); let mut rl = atomic_rl.lock().unwrap(); let prompt = format!("{}", Value::Apply(Box::new(env.get(PROMPT)?), vec![Value::Path(env.get_cwd()?)]).eval(&mut env)?); rl.helper_mut().expect("No helper").set_prompt(format!("{}", prompt)); rl.helper_mut().expect("No helper").update_env(&env); let mut text = readline(prompt, &mut rl); if let Ok(parsed) = parse(&text) { let _ = Value::Apply(Box::new(env.get(REPORT)?), vec![match parsed.eval(&mut env) { Ok(val) => val, Err(e) => Value::Error(Box::new(e)) }]).eval(&mut env); rl.add_history_entry(text.as_str()); } else if text.trim() != "" { rl.bind_sequence(KeyEvent::new('\t', Modifiers::NONE), Cmd::Insert(1, String::from(" "))); loop { let err_prompt = format!("{}", Value::Apply(Box::new(env.get(INCOMPLETE_PROMPT)?), vec![Value::Path(env.get_cwd()?)]).eval(&mut env)?); rl.helper_mut().expect("No helper").set_prompt(format!("{}", &err_prompt)); rl.helper_mut().expect("No helper").update_env(&env); let tmp = readline(&err_prompt, &mut rl); match parse(&text) { Ok(parsed) => { let _ = Value::Apply(Box::new(env.get(REPORT)?), vec![match parsed.eval(&mut env) { Ok(val) => val, Err(e) => Value::Error(Box::new(e)) }]).eval(&mut env); rl.add_history_entry(text.as_str()); break } Err(e) => { if tmp.trim() == "" { let _ = Value::Apply(Box::new(env.get(REPORT)?), vec![ Value::Error(Box::new(e)) ]).eval(&mut env); break } else { text += &tmp } } } } rl.unbind_sequence(KeyEvent::new('\t', Modifiers::NONE)); } if rl.save_history(&env.get_home_dir()?.join(HISTORY_FILENAME)).is_err() { eprintln!("could not save history") } } } fn main() -> Result<(), Error> { let mut env = Environment::new(); let config = Config::builder() .history_ignore_dups(true) .history_ignore_space(true) .auto_add_history(false) .completion_type(CompletionType::List) .edit_mode(EditMode::Emacs) .output_stream(OutputStreamType::Stdout) .build(); let mut rl = Editor::with_config(config); let h = AtomHelper { completer: FilenameCompleter::new(), highlighter: MatchingBracketHighlighter::new(), hinter: HistoryHinter {}, colored_prompt: "".to_owned(), validator: MatchingBracketValidator::new(), env: env.clone() }; rl.set_helper(Some(h)); if rl.load_history(&env.get_home_dir()?.join(HISTORY_FILENAME)).is_err() { println!("No previous history."); } if let Ok(home_dir) = env.get_home_dir() { if let Ok(contents) = read_to_string(home_dir.join(PRELUDE_FILENAME)) { match parse(contents) { Ok(parsed) => match parsed.eval(&mut env) { Ok(_) => {} Err(e) => eprintln!("error in {}: {}", PRELUDE_FILENAME, e) } Err(e) => eprintln!("invalid syntax in {}\n{}", PRELUDE_FILENAME, e) } } else { eprintln!("could not read {}", PRELUDE_FILENAME) } } else { eprintln!("could not read {}", PRELUDE_FILENAME) } if let Ok(path) = current_dir() { Value::Define( String::from(CWD), Box::new(Value::Path(path)) ).eval(&mut env)?; } let atomic_rl = Arc::new(Mutex::new(rl)); let atomic_env = Arc::new(Mutex::new(env)); let atomic_rl_clone = atomic_rl.clone(); let atomic_env_clone = atomic_env.clone(); if ctrlc::set_handler(move || { let _ = repl(atomic_rl_clone.clone(), atomic_env_clone.clone()); }).is_err() { eprintln!("could not establish CTRL+C handler") } repl(atomic_rl, atomic_env)?; Ok(()) }
//! Internal data types for use within PICL use std::collections::{HashMap, HashSet}; use std::fmt; use super::float::LF64; use super::list::List; /// A LispList is a list of LispVals pub type LispList = List<LispVal>; #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub enum LispVal { // Literals Nil, Bool(bool), Str(String), Symbol(String), Keyword(String), Float(LF64), Int(i64), Complex(LF64, LF64), // Collection types List(LispList), Vector(Vec<LispVal>), Map(HashMap<String, LispVal>), Set(HashSet<LispVal>), // Procedures // BuiltinProc(fn(List) -> LispVal, String), Proc(Procedure), } impl fmt::Display for LispVal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { LispVal::Nil => write!(f, "()"), LispVal::Bool(ref v) => match v { &true => write!(f, "#t"), &false => write!(f, "#f"), }, LispVal::Str(ref v) => write!(f, "\"{}\"", v), LispVal::Symbol(ref v) => write!(f, "{}", v), LispVal::Keyword(ref v) => write!(f, ":{}", v), LispVal::Float(ref v) => write!(f, "{}", v), LispVal::Int(ref v) => write!(f, "{}", v), LispVal::Complex(ref r, ref c) => write!(f, "{}+i{}", r, c), // LispVal::List(ref v) => write!(f, "{}", v), // LispVal::Vector(ref v) => write!(f, "{}", v), // LispVal::Map(ref v) => write!(f, "{}", v), // LispVal::Set(ref v) => write!(f, "{}", v), // LispVal::BuiltinProc(v, ref s) => write!(f, "Procedure: {}", s), LispVal::Proc(ref v) => write!(f, "{}", v), } } } /// A user defined procedure /// An execution environment is generated when the procedure is called. #[derive(Debug, Clone)] pub struct Procedure { name: String, params: LispList, body: LispList, } impl fmt::Display for Procedure { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Procedure: {}", self.name) } }
use exitfailure::ExitFailure; use failure::ResultExt; use log::{info, warn}; use structopt::StructOpt; #[derive(StructOpt)] struct Cli { pattern: String, #[structopt(parse(from_os_str))] path: std::path::PathBuf, } #[test] fn find_a_match() { let mut result = Vec::new(); cli_grep::find_matches("lorem ipsum\ndolor sit amet", "lorem", &mut result); assert_eq!(result, b"lorem ipsum\n"); } fn main() -> Result<(), ExitFailure> { env_logger::init(); info!("starting up"); let args = Cli::from_args(); println!("{}", args.pattern); println!("{}", args.path.display()); let content = std::fs::read_to_string(&args.path) .with_context(|_| format!("could not read file `{}`", args.path.display()))?; cli_grep::find_matches(&content, &args.pattern, &mut std::io::stdout()); warn!("oops, nothing implemented!"); Ok(()) }
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; mod config; mod models; mod routes; mod views; use jfs::Store; use models::file_stores::FileStores; fn main() { let file_store = FileStores { articles: Store::new("articles").unwrap(), shops: Store::new("shops").unwrap(), prices: Store::new("prices").unwrap(), }; rocket::custom(config::from_env()) .manage(file_store) .mount("/", routes![routes::prices::list]) .mount( "/prices", routes![ routes::prices::list, routes::prices::add_price_page, routes::prices::edit_price_page, routes::prices::create, routes::prices::save, routes::prices::remove ], ) .mount( "/articles", routes![ routes::articles::list, routes::articles::edit_page, routes::articles::create, routes::articles::save, ], ) .mount( "/shops", routes![ routes::shops::list, routes::shops::edit_page, routes::shops::create, routes::shops::save, ], ) .launch(); }
// table.rs // defining structs and implementations for tables, rows and maybe columns use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct Table { pub num_rows: u32, pub pages: u32, pub columns: Vec<String>, pub rows: Vec<Vec<u8>> } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct Row { pub row_number: u32, pub id: String, pub username: String, pub email: String } // Todo possibly create a struct that holds column name and data. impl Table { pub fn add_row(&mut self, data: &Vec<&str>) { let new_row = Row { row_number: self.num_rows, id: "lkajsdflkajdfs".to_string(), username: "Alec".to_string(), email: "owo@somethingweeb.com".to_string() }; println!("{:?}", data); let encoded: Vec<u8> = bincode::serialize(&new_row).unwrap(); self.rows.push(encoded); self.num_rows += 1; } } // dev branch(last few commits) -> only add last few commits to hotfix branch(lots of commits behind) -> dev branch // dev branch === hotfix branch // # replay every commit *after* quickfix1 up to quickfix2 HEAD. // git rebase --onto master quickfix1 quickfix2
use std::{ fs, path, io::{ Read, Write }, }; use sgx_types::*; use sgx_urts::SgxEnclave; static ENCLAVE_TOKEN: &'static str = "enclave.token"; static ENCLAVE_FILE: &'static str = "enclave.signed.so"; lazy_static! { // NOTE Gives us enc. as global but now can't destroy it! pub static ref ENCLAVE: SgxEnclave = { let mut launch_token: sgx_launch_token_t = [0; 1024]; let mut launch_token_updated: i32 = 0; let mut home_dir = path::PathBuf::new(); let use_token = match dirs::home_dir() { Some(path) => { println!("✔ [App] Home dir is {}", path.display()); home_dir = path; true }, None => { println!("✘ [App] Cannot get home dir"); false } }; let token_file: path::PathBuf = home_dir.join(ENCLAVE_TOKEN);; if use_token == true { match fs::File::open(&token_file) { Err(_) => { println!( "✘ [App] Open token file {} error! Will create one.", token_file.as_path().to_str().unwrap() ); }, Ok(mut f) => { println!("✔ [App] Open token file success! "); match f.read(&mut launch_token) { Ok(1024) => { println!("✔ [App] Token file valid!"); }, _ => println!("✔[App] Token file invalid, will create new token file"), } } } } let debug = 1; let mut misc_attr = sgx_misc_attribute_t {secs_attr: sgx_attributes_t { flags:0, xfrm:0}, misc_select:0}; let enclave = match SgxEnclave::create( ENCLAVE_FILE, debug, &mut launch_token, &mut launch_token_updated, &mut misc_attr ) { Ok(enc) => enc, Err(e) => panic!("[-] Failed to create enclave: {}", e), }; if use_token == true && launch_token_updated != 0 { match fs::File::create(&token_file) { Ok(mut f) => { match f.write_all(&launch_token) { Ok(()) => println!("[+] Saved updated launch token!"), Err(_) => println!("[-] Failed to save updated launch token!"), } }, Err(_) => { println!("[-] Failed to save updated enclave token, but doesn't matter"); }, } } enclave }; }
//! The dram module contains a dram structure and implementation for dram access. use crate::bus::*; /// Default dram size (128MiB). pub const DRAM_SIZE: u64 = 1024 * 1024 * 128; /// The dynamic random access dram (DRAM). #[derive(Debug)] pub struct Dram { pub dram: Vec<u8>, } impl Dram { /// Create a new `Dram` instance with default dram size. pub fn new(code: Vec<u8>) -> Dram { let mut dram = vec![0; DRAM_SIZE as usize]; dram.splice(..code.len(), code.iter().cloned()); Self { dram } } /// Load bytes from the little-endiam dram. pub fn load(&self, addr: u64, size: u64) -> Result<u64, ()> { match size { 8 => Ok(self.load8(addr)), 16 => Ok(self.load16(addr)), 32 => Ok(self.load32(addr)), 64 => Ok(self.load64(addr)), _ => Err(()), } } /// Store bytes to the little-endiam dram. pub fn store(&mut self, addr: u64, size: u64, value: u64) -> Result<(), ()> { match size { 8 => Ok(self.store8(addr, value)), 16 => Ok(self.store16(addr, value)), 32 => Ok(self.store32(addr, value)), 64 => Ok(self.store64(addr, value)), _ => Err(()), } } /// Load a byte from the little-endian dram. fn load8(&self, addr: u64) -> u64 { let index = (addr - DRAM_BASE) as usize; self.dram[index] as u64 } /// Load 2 bytes from the little-endian dram. fn load16(&self, addr: u64) -> u64 { let index = (addr - DRAM_BASE) as usize; return (self.dram[index] as u64) | ((self.dram[index + 1] as u64) << 8); } /// Load 4 bytes from the little-endian dram. fn load32(&self, addr: u64) -> u64 { let index = (addr - DRAM_BASE) as usize; return (self.dram[index] as u64) | ((self.dram[index + 1] as u64) << 8) | ((self.dram[index + 2] as u64) << 16) | ((self.dram[index + 3] as u64) << 24); } /// Load 8 bytes from the little-endian dram. fn load64(&self, addr: u64) -> u64 { let index = (addr - DRAM_BASE) as usize; return (self.dram[index] as u64) | ((self.dram[index + 1] as u64) << 8) | ((self.dram[index + 2] as u64) << 16) | ((self.dram[index + 3] as u64) << 24) | ((self.dram[index + 4] as u64) << 32) | ((self.dram[index + 5] as u64) << 40) | ((self.dram[index + 6] as u64) << 48) | ((self.dram[index + 7] as u64) << 56); } /// Store a byte to the little-endian dram. fn store8(&mut self, addr: u64, value: u64) { let index = (addr - DRAM_BASE) as usize; self.dram[index] = value as u8 } /// Store 2 bytes to the little-endian dram. fn store16(&mut self, addr: u64, value: u64) { let index = (addr - DRAM_BASE) as usize; self.dram[index] = (value & 0xff) as u8; self.dram[index + 1] = ((value >> 8) & 0xff) as u8; } /// Store 4 bytes to the little-endian dram. fn store32(&mut self, addr: u64, value: u64) { let index = (addr - DRAM_BASE) as usize; self.dram[index] = (value & 0xff) as u8; self.dram[index + 1] = ((value >> 8) & 0xff) as u8; self.dram[index + 2] = ((value >> 16) & 0xff) as u8; self.dram[index + 3] = ((value >> 24) & 0xff) as u8; } /// Store 8 bytes to the little-endian dram. fn store64(&mut self, addr: u64, value: u64) { let index = (addr - DRAM_BASE) as usize; self.dram[index] = (value & 0xff) as u8; self.dram[index + 1] = ((value >> 8) & 0xff) as u8; self.dram[index + 2] = ((value >> 16) & 0xff) as u8; self.dram[index + 3] = ((value >> 24) & 0xff) as u8; self.dram[index + 4] = ((value >> 32) & 0xff) as u8; self.dram[index + 5] = ((value >> 40) & 0xff) as u8; self.dram[index + 6] = ((value >> 48) & 0xff) as u8; self.dram[index + 7] = ((value >> 56) & 0xff) as u8; } }
mod dhcp; mod repository; mod util; use crate::dhcp::{DhcpOptions, DhcpPacket, DhcpServer, MessageType}; use anyhow::{anyhow, Context}; use log::{debug, error}; use std::env; use std::net::UdpSocket; use std::sync::Arc; use std::thread; const BOOTREQUEST: u8 = 1; #[allow(dead_code)] const BOOTREPLY: u8 = 2; fn main() -> anyhow::Result<()> { env::set_var("RUST_LOG", "debug"); env_logger::init(); let svr_soc = UdpSocket::bind("0.0.0.0:0").context("Failed to bind socket")?; svr_soc.set_broadcast(true)?; let dhcp_svr = Arc::new(DhcpServer::new().context("Failed to start DHCP server")?); loop { let mut recv_buf = [0u8; 1024]; let (size, src) = svr_soc .recv_from(&mut recv_buf) .context("A datagram could not be receive")?; debug!("receive data from {}, size: {}", src, size); let transmission_soc = svr_soc.try_clone().expect("Failed to create client socket"); let dhcp_svr = dhcp_svr.clone(); thread::spawn(move || { let dhcp_packet = match DhcpPacket::new(recv_buf[..size].to_vec()) { Some(packet) if packet.op() == BOOTREQUEST => packet, Some(_) | None => return, }; let result = handle_dhcp(&dhcp_packet, &transmission_soc, dhcp_svr); if let Err(e) = result { error!("{}", e); } }); } } fn handle_dhcp( packet: &DhcpPacket, transmission_soc: &UdpSocket, server: Arc<DhcpServer>, ) -> anyhow::Result<()> { let message = packet .option(DhcpOptions::MessageType) .context("Specified option was not found")?; let message_type = MessageType(message[0]); match message_type { MessageType::DHCPDISCOVER => server.offer_network_addr(packet, transmission_soc), MessageType::DHCPREQUEST => match packet.option(DhcpOptions::ServerIdentifier) { Some(svr_id) => server.allocate_ip_addr(&svr_id, packet, transmission_soc), None => server.reallocate_ip_addr(packet, transmission_soc), }, MessageType::DHCPRELEASE => server.release_ip_addr(packet), _ => Err(anyhow!( "{:x}: received unimplemented message, message type: {}", packet.transaction_id(), message_type.0 )), } }
mod udpserv; pub use udpserv::*; mod udpsock; pub use udpsock::*; mod cache; pub use cache::*; mod udpxmgr; pub use udpxmgr::*; mod ustub; pub use ustub::*; use os_socketaddr::OsSocketAddr; use std::io; use std::net::SocketAddr; use std::os::unix::io::RawFd; #[link(name = "recvmsg", kind = "static")] extern "C" { static udp_sas_IPV6_RECVORIGDSTADDR: libc::c_int; static udp_sas_IP_RECVORIGDSTADDR: libc::c_int; // https://docs.rs/crate/udp_sas/0.1.3/source/src/lib.rs fn udp_sas_recv( sock: libc::c_int, buf: *mut u8, buf_len: libc::size_t, flags: libc::c_int, src: *mut libc::sockaddr, src_len: libc::socklen_t, dst: *mut libc::sockaddr, dst_len: libc::socklen_t, ) -> libc::ssize_t; fn udp_sas_socket(src: *const libc::sockaddr, src_len: libc::socklen_t) -> libc::c_int; } use self::udp_sas_IPV6_RECVORIGDSTADDR as IPV6_RECVORIGDSTADDR; use self::udp_sas_IP_RECVORIGDSTADDR as IP_RECVORIGDSTADDR; macro_rules! try_io { ($x:expr) => { match $x { -1 => { return Err(io::Error::last_os_error()); } x => x, } }; } fn getsockopt<T>( socket: RawFd, level: libc::c_int, name: libc::c_int, value: &mut T, ) -> io::Result<libc::socklen_t> { unsafe { let mut len = std::mem::size_of::<T>() as libc::socklen_t; try_io!(libc::getsockopt( socket, level, name, value as *mut T as *mut libc::c_void, &mut len )); Ok(len) } } fn setsockopt<T>( socket: RawFd, level: libc::c_int, name: libc::c_int, value: &T, ) -> io::Result<()> { unsafe { try_io!(libc::setsockopt( socket, level, name, value as *const T as *const libc::c_void, std::mem::size_of::<T>() as libc::socklen_t )); Ok(()) } } pub fn set_ip_recv_origdstaddr(socket: RawFd) -> io::Result<()> { unsafe { let mut domain = libc::c_int::default(); getsockopt(socket, libc::SOL_SOCKET, libc::SO_DOMAIN, &mut domain)?; let (level, option) = match domain { libc::AF_INET => (libc::IPPROTO_IP, IP_RECVORIGDSTADDR), libc::AF_INET6 => (libc::IPPROTO_IPV6, IPV6_RECVORIGDSTADDR), _ => { return Err(io::Error::new(io::ErrorKind::Other, "not an inet socket")); } }; setsockopt(socket, level, option, &(1 as libc::c_int)) } } pub fn recv_sas( socket: RawFd, buf: &mut [u8], ) -> io::Result<(usize, Option<SocketAddr>, Option<SocketAddr>)> { let mut src = OsSocketAddr::new(); let mut dst = OsSocketAddr::new(); let nb = { unsafe { udp_sas_recv( socket, buf.as_mut_ptr(), buf.len(), 0, src.as_mut_ptr(), src.capacity() as libc::socklen_t, dst.as_mut_ptr(), dst.capacity() as libc::socklen_t, ) } }; if nb < 0 { Err(io::Error::last_os_error()) } else { Ok((nb as usize, src.into(), dst.into())) } } pub fn sas_socket(bind_addr: &SocketAddr) -> std::result::Result<RawFd, io::Error> { let dst: OsSocketAddr = (*bind_addr).into(); let rawfd = unsafe { udp_sas_socket(dst.as_ptr(), dst.len() as libc::socklen_t) }; if rawfd < 0 { Err(io::Error::last_os_error()) } else { Ok(rawfd) } }
use math::primes; use std::cmp; use std::collections::HashMap; pub fn demo(n: u64) { println!("{:?}", lcm(n)); } fn lcm(n: u64) -> u64 { let mut common: HashMap<u64, u64> = HashMap::new(); for i in 2..n { let mut i_primes: HashMap<u64, u64> = HashMap::new(); for prime in primes::prime_factors(i).into_iter() { let count = i_primes.entry(prime).or_insert(0); *count += 1; } for (prime, count) in i_primes.into_iter() { let common_count = common.entry(prime).or_insert(count); *common_count = cmp::max(common_count.clone(), count); } } common.iter().fold(1, |acc, (prime, count)| { use num::traits::ToPrimitive; acc * prime.pow(count.clone().to_u32().unwrap()) }) }
//! Internal search functions. use arrayvec::ArrayVec; use reason_othello::game::GameState; /// TODO: document pub fn window(state: GameState, alpha: i8, beta: i8) -> i8 { window_fastest_first(state, state.board.count_empties(), alpha, beta) } /// Window search, using "fastest first" move ordering which first /// explores moves where the opponent has the fewest legal moves. fn window_fastest_first(state: GameState, empties: u8, mut alpha: i8, beta: i8) -> i8 { // Below this depth, stop sorting moves. const MAX_SORT_DEPTH: u8 = 6; if empties < MAX_SORT_DEPTH { return window_unsorted(state, empties, alpha, beta); } let moves = state.board.get_moves(); if moves.is_empty() { // Both players pass: game ends if state.just_passed { return state.board.score_absolute_difference(); } // I pass, but my opponent may have moves return -window_fastest_first(state.pass(), empties, -beta, -alpha); } // Precompute all next states and their moves let mut next_states: ArrayVec<[_; 32]> = moves.map(|mv| state.apply_move(mv)).collect(); next_states.sort_unstable_by_key(|s| s.board.get_moves().num_moves()); // Visit states by lowest-mobility first for next_state in next_states { let score = -window_fastest_first(next_state, empties - 1, -beta, -alpha); // Fail high: this branch has a line so good for me my opponent won't allow it. if score >= beta { return beta; } // This branch is better than any line I could force before: update current lower bound if score > alpha { alpha = score } } alpha } /// Window search without move ordering, which is faster for shallow trees. fn window_unsorted(state: GameState, empties: u8, mut alpha: i8, beta: i8) -> i8 { let moves = state.board.get_moves(); if moves.is_empty() || empties == 0 { if state.just_passed || empties == 0 { return state.board.score_absolute_difference(); } return -window_unsorted(state.pass(), empties, -beta, -alpha); } for mv in moves { let score = -window_unsorted(state.apply_move(mv), empties - 1, -beta, -alpha); if score >= beta { return beta; } if score > alpha { alpha = score } } alpha }
#![allow(non_camel_case_types, dead_code, unused)] // Functions here are copied from the `IOKit-sys` (https://crates.io/crates/iokit-sys) crate // and rewritten to use `core_foundation` types. use core_foundation::base::{mach_port_t, CFAllocatorRef}; use core_foundation::dictionary::{CFDictionaryRef, CFMutableDictionaryRef}; use libc::c_char; use mach::{boolean, kern_return}; pub type io_object_t = mach_port_t; pub type io_registry_entry_t = io_object_t; pub type io_service_t = io_object_t; pub type io_iterator_t = io_object_t; pub type IOOptionBits = u32; pub const IOPM_SERVICE_NAME: *const c_char = b"IOPMPowerSource\0".as_ptr() as *const c_char; extern "C" { // https://developer.apple.com/documentation/iokit/kiomasterportdefault pub static kIOMasterPortDefault: mach_port_t; // https://developer.apple.com/documentation/iokit/1514652-iomasterport // Should be deallocated with `mach_port_deallocate(mach_task_self(), masterPort)` pub fn IOMasterPort(bootstrapPort: mach_port_t, masterPort: *mut mach_port_t) -> kern_return::kern_return_t; // https://developer.apple.com/documentation/iokit/1514687-ioservicematching // The dictionary is commonly passed to IOServiceGetMatchingServices or IOServiceAddNotification // which will consume a reference, otherwise it should be released with CFRelease by the caller. pub fn IOServiceMatching(name: *const c_char) -> CFMutableDictionaryRef; // https://developer.apple.com/documentation/iokit/1514494-ioservicegetmatchingservices?language=objc // An `existing` iterator handle is returned on success, and should be released by the caller // when the iteration is finished. pub fn IOServiceGetMatchingServices( masterPort: mach_port_t, matching: CFDictionaryRef, existing: *mut io_iterator_t, ) -> kern_return::kern_return_t; // https://developer.apple.com/documentation/iokit/1514310-ioregistryentrycreatecfpropertie // The caller should release `properties` with CFRelease. pub fn IORegistryEntryCreateCFProperties( entry: io_registry_entry_t, properties: *mut CFMutableDictionaryRef, allocator: CFAllocatorRef, options: IOOptionBits, ) -> kern_return::kern_return_t; // https://developer.apple.com/documentation/iokit/1514741-ioiteratornext // The element should be released by the caller when it is finished. pub fn IOIteratorNext(iterator: io_iterator_t) -> io_object_t; pub fn IOIteratorIsValid(iterator: io_iterator_t) -> boolean::boolean_t; pub fn IOObjectRelease(object: io_object_t) -> kern_return::kern_return_t; }
use std::any::Any; use std::sync::Arc; use tokio::net::TcpListener; use tokio_util::sync::CancellationToken; use tonic::{body::BoxBody, transport::NamedService, Code}; use tonic_health::server::HealthReporter; use trace_http::ctx::TraceHeaderParser; use crate::server_type::{RpcError, ServerType}; /// Returns the name of the gRPC service S. pub fn service_name<S: NamedService>(_: &S) -> &'static str { S::NAME } #[derive(Debug)] pub struct RpcBuilderInput { pub socket: TcpListener, pub trace_header_parser: TraceHeaderParser, pub shutdown: CancellationToken, } #[derive(Debug)] pub struct RpcBuilder<T> { pub inner: T, pub health_reporter: HealthReporter, pub shutdown: CancellationToken, pub socket: TcpListener, } /// Adds a gRPC service to the builder, and registers it with the /// health reporter #[macro_export] macro_rules! add_service { ($builder:ident, $svc:expr) => { let $builder = { // `inner` might be required to be `mut` or not depending if we're acting on: // - a `Server`, no service added yet, no `mut` required // - a `Router`, some service was added already, `mut` required #[allow(unused_mut)] { use $crate::rpc::{service_name, RpcBuilder}; let RpcBuilder { mut inner, mut health_reporter, shutdown, socket, } = $builder; let service = $svc; let status = $crate::reexport::tonic_health::ServingStatus::Serving; health_reporter .set_service_status(service_name(&service), status) .await; let inner = inner.add_service(service); RpcBuilder { inner, health_reporter, shutdown, socket, } } }; }; } /// Creates a [`RpcBuilder`] from [`RpcBuilderInput`]. /// /// The resulting builder can be used w/ [`add_service`]. After adding all services it should /// be used w/ [`serve_builder!`](crate::serve_builder). #[macro_export] macro_rules! setup_builder { ($input:ident, $server_type:ident) => {{ #[allow(unused_imports)] use $crate::{add_service, rpc::RpcBuilder, server_type::ServerType}; let RpcBuilderInput { socket, trace_header_parser, shutdown, } = $input; let (health_reporter, health_service) = $crate::reexport::tonic_health::server::health_reporter(); let reflection_service = $crate::reexport::tonic_reflection::server::Builder::configure() .register_encoded_file_descriptor_set( $crate::reexport::generated_types::FILE_DESCRIPTOR_SET, ) .build() .expect("gRPC reflection data broken"); let builder = $crate::reexport::tonic::transport::Server::builder(); let builder = builder .layer($crate::reexport::trace_http::tower::TraceLayer::new( trace_header_parser, $server_type.metric_registry(), $server_type.trace_collector(), true, $server_type.name(), )) .layer( $crate::reexport::tower_http::catch_panic::CatchPanicLayer::custom( $crate::rpc::handle_panic, ), ); let builder = RpcBuilder { inner: builder, health_reporter, shutdown, socket, }; add_service!(builder, health_service); add_service!(builder, reflection_service); add_service!( builder, $crate::reexport::service_grpc_testing::make_server() ); builder }}; } /// Serve a server constructed using [`RpcBuilder`]. #[macro_export] macro_rules! serve_builder { ($builder:ident) => {{ use $crate::reexport::tokio_stream::wrappers::TcpListenerStream; use $crate::rpc::RpcBuilder; let RpcBuilder { inner, shutdown, socket, .. } = $builder; let stream = TcpListenerStream::new(socket); inner .serve_with_incoming_shutdown(stream, shutdown.cancelled()) .await?; }}; } pub fn handle_panic(err: Box<dyn Any + Send + 'static>) -> http::Response<BoxBody> { let message = if let Some(s) = err.downcast_ref::<String>() { s.clone() } else if let Some(s) = err.downcast_ref::<&str>() { s.to_string() } else { "unknown internal error".to_string() }; http::Response::builder() .status(http::StatusCode::OK) .header(http::header::CONTENT_TYPE, "application/grpc") .header("grpc-status", Code::Internal as u32) .header("grpc-message", message) // we don't want to leak the panic message .body(tonic::body::empty_body()) .unwrap() } /// Instantiate a server listening on the specified address /// implementing the IOx, Storage, and Flight gRPC interfaces, the /// underlying hyper server instance. Resolves when the server has /// shutdown. pub async fn serve( socket: TcpListener, server_type: Arc<dyn ServerType>, trace_header_parser: TraceHeaderParser, shutdown: CancellationToken, ) -> Result<(), RpcError> { let builder_input = RpcBuilderInput { socket, trace_header_parser, shutdown, }; server_type.server_grpc(builder_input).await }
use super::{ PositionIterInternal, PyBytes, PyBytesRef, PyInt, PyListRef, PySlice, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, }; use crate::{ atomic_func, buffer::FormatSpec, bytesinner::bytes_to_hex, class::PyClassImpl, common::{ borrow::{BorrowedValue, BorrowedValueMut}, hash::PyHash, lock::OnceCell, }, convert::ToPyObject, function::Either, function::{FuncArgs, OptionalArg, PyComparisonValue}, protocol::{ BufferDescriptor, BufferMethods, PyBuffer, PyIterReturn, PyMappingMethods, PySequenceMethods, VecBuffer, }, sliceable::SequenceIndexOp, types::{ AsBuffer, AsMapping, AsSequence, Comparable, Constructor, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, Unconstructible, }, AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, }; use crossbeam_utils::atomic::AtomicCell; use itertools::Itertools; use once_cell::sync::Lazy; use rustpython_common::lock::PyMutex; use std::{cmp::Ordering, fmt::Debug, mem::ManuallyDrop, ops::Range}; #[derive(FromArgs)] pub struct PyMemoryViewNewArgs { object: PyObjectRef, } #[pyclass(module = false, name = "memoryview")] #[derive(Debug)] pub struct PyMemoryView { // avoid double release when memoryview had released the buffer before drop buffer: ManuallyDrop<PyBuffer>, // the released memoryview does not mean the buffer is destroyed // because the possible another memeoryview is viewing from it released: AtomicCell<bool>, // start does NOT mean the bytes before start will not be visited, // it means the point we starting to get the absolute position via // the needle start: usize, format_spec: FormatSpec, // memoryview's options could be different from buffer's options desc: BufferDescriptor, hash: OnceCell<PyHash>, // exports // memoryview has no exports count by itself // instead it relay on the buffer it viewing to maintain the count } impl Constructor for PyMemoryView { type Args = PyMemoryViewNewArgs; fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult { let zelf = Self::from_object(&args.object, vm)?; zelf.into_ref_with_type(vm, cls).map(Into::into) } } impl PyMemoryView { fn parse_format(format: &str, vm: &VirtualMachine) -> PyResult<FormatSpec> { FormatSpec::parse(format.as_bytes(), vm) } /// this should be the main entrance to create the memoryview /// to avoid the chained memoryview pub fn from_object(obj: &PyObject, vm: &VirtualMachine) -> PyResult<Self> { if let Some(other) = obj.payload::<Self>() { Ok(other.new_view()) } else { let buffer = PyBuffer::try_from_borrowed_object(vm, obj)?; PyMemoryView::from_buffer(buffer, vm) } } /// don't use this function to create the memoryview if the buffer is exporting /// via another memoryview, use PyMemoryView::new_view() or PyMemoryView::from_object /// to reduce the chain pub fn from_buffer(buffer: PyBuffer, vm: &VirtualMachine) -> PyResult<Self> { // when we get a buffer means the buffered object is size locked // so we can assume the buffer's options will never change as long // as memoryview is still alive let format_spec = Self::parse_format(&buffer.desc.format, vm)?; let desc = buffer.desc.clone(); Ok(PyMemoryView { buffer: ManuallyDrop::new(buffer), released: AtomicCell::new(false), start: 0, format_spec, desc, hash: OnceCell::new(), }) } /// don't use this function to create the memeoryview if the buffer is exporting /// via another memoryview, use PyMemoryView::new_view() or PyMemoryView::from_object /// to reduce the chain pub fn from_buffer_range( buffer: PyBuffer, range: Range<usize>, vm: &VirtualMachine, ) -> PyResult<Self> { let mut zelf = Self::from_buffer(buffer, vm)?; zelf.init_range(range, 0); zelf.init_len(); Ok(zelf) } /// this should be the only way to create a memoryview from another memoryview pub fn new_view(&self) -> Self { let zelf = PyMemoryView { buffer: self.buffer.clone(), released: AtomicCell::new(false), start: self.start, format_spec: self.format_spec.clone(), desc: self.desc.clone(), hash: OnceCell::new(), }; zelf.buffer.retain(); zelf } fn try_not_released(&self, vm: &VirtualMachine) -> PyResult<()> { if self.released.load() { Err(vm.new_value_error("operation forbidden on released memoryview object".to_owned())) } else { Ok(()) } } fn getitem_by_idx(&self, i: isize, vm: &VirtualMachine) -> PyResult { if self.desc.ndim() != 1 { return Err(vm.new_not_implemented_error( "multi-dimensional sub-views are not implemented".to_owned(), )); } let (shape, stride, suboffset) = self.desc.dim_desc[0]; let index = i .wrapped_at(shape) .ok_or_else(|| vm.new_index_error("index out of range".to_owned()))?; let index = index as isize * stride + suboffset; let pos = (index + self.start as isize) as usize; self.unpack_single(pos, vm) } fn getitem_by_slice(&self, slice: &PySlice, vm: &VirtualMachine) -> PyResult { let mut other = self.new_view(); other.init_slice(slice, 0, vm)?; other.init_len(); Ok(other.into_ref(&vm.ctx).into()) } fn getitem_by_multi_idx(&self, indexes: &[isize], vm: &VirtualMachine) -> PyResult { let pos = self.pos_from_multi_index(indexes, vm)?; let bytes = self.buffer.obj_bytes(); format_unpack(&self.format_spec, &bytes[pos..pos + self.desc.itemsize], vm) } fn setitem_by_idx(&self, i: isize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if self.desc.ndim() != 1 { return Err(vm.new_not_implemented_error("sub-views are not implemented".to_owned())); } let (shape, stride, suboffset) = self.desc.dim_desc[0]; let index = i .wrapped_at(shape) .ok_or_else(|| vm.new_index_error("index out of range".to_owned()))?; let index = index as isize * stride + suboffset; let pos = (index + self.start as isize) as usize; self.pack_single(pos, value, vm) } fn setitem_by_multi_idx( &self, indexes: &[isize], value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { let pos = self.pos_from_multi_index(indexes, vm)?; self.pack_single(pos, value, vm) } fn pack_single(&self, pos: usize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let mut bytes = self.buffer.obj_bytes_mut(); // TODO: Optimize let data = self.format_spec.pack(vec![value], vm).map_err(|_| { vm.new_type_error(format!( "memoryview: invalid type for format '{}'", &self.desc.format )) })?; bytes[pos..pos + self.desc.itemsize].copy_from_slice(&data); Ok(()) } fn unpack_single(&self, pos: usize, vm: &VirtualMachine) -> PyResult { let bytes = self.buffer.obj_bytes(); // TODO: Optimize self.format_spec .unpack(&bytes[pos..pos + self.desc.itemsize], vm) .map(|x| { if x.len() == 1 { x.fast_getitem(0) } else { x.into() } }) } fn pos_from_multi_index(&self, indexes: &[isize], vm: &VirtualMachine) -> PyResult<usize> { match indexes.len().cmp(&self.desc.ndim()) { Ordering::Less => { return Err(vm.new_not_implemented_error("sub-views are not implemented".to_owned())) } Ordering::Greater => { return Err(vm.new_type_error(format!( "cannot index {}-dimension view with {}-element tuple", self.desc.ndim(), indexes.len() ))) } Ordering::Equal => (), } let pos = self.desc.position(indexes, vm)?; let pos = (pos + self.start as isize) as usize; Ok(pos) } fn init_len(&mut self) { let product: usize = self.desc.dim_desc.iter().map(|x| x.0).product(); self.desc.len = product * self.desc.itemsize; } fn init_range(&mut self, range: Range<usize>, dim: usize) { let (shape, stride, _) = self.desc.dim_desc[dim]; debug_assert!(shape >= range.len()); let mut is_adjusted = false; for (_, _, suboffset) in self.desc.dim_desc.iter_mut().rev() { if *suboffset != 0 { *suboffset += stride * range.start as isize; is_adjusted = true; break; } } if !is_adjusted { // no suboffset set, stride must be positive self.start += stride as usize * range.start; } let newlen = range.len(); self.desc.dim_desc[dim].0 = newlen; } fn init_slice(&mut self, slice: &PySlice, dim: usize, vm: &VirtualMachine) -> PyResult<()> { let (shape, stride, _) = self.desc.dim_desc[dim]; let slice = slice.to_saturated(vm)?; let (range, step, slice_len) = slice.adjust_indices(shape); let mut is_adjusted_suboffset = false; for (_, _, suboffset) in self.desc.dim_desc.iter_mut().rev() { if *suboffset != 0 { *suboffset += stride * range.start as isize; is_adjusted_suboffset = true; break; } } if !is_adjusted_suboffset { // no suboffset set, stride must be positive self.start += stride as usize * if step.is_negative() { range.end - 1 } else { range.start }; } self.desc.dim_desc[dim].0 = slice_len; self.desc.dim_desc[dim].1 *= step; Ok(()) } fn _to_list( &self, bytes: &[u8], mut index: isize, dim: usize, vm: &VirtualMachine, ) -> PyResult<PyListRef> { let (shape, stride, suboffset) = self.desc.dim_desc[dim]; if dim + 1 == self.desc.ndim() { let mut v = Vec::with_capacity(shape); for _ in 0..shape { let pos = index + suboffset; let pos = (pos + self.start as isize) as usize; let obj = format_unpack(&self.format_spec, &bytes[pos..pos + self.desc.itemsize], vm)?; v.push(obj); index += stride; } return Ok(vm.ctx.new_list(v)); } let mut v = Vec::with_capacity(shape); for _ in 0..shape { let obj = self._to_list(bytes, index + suboffset, dim + 1, vm)?.into(); v.push(obj); index += stride; } Ok(vm.ctx.new_list(v)) } fn eq(zelf: &Py<Self>, other: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { if zelf.is(other) { return Ok(true); } if zelf.released.load() { return Ok(false); } if let Some(other) = other.payload::<Self>() { if other.released.load() { return Ok(false); } } let other = match PyBuffer::try_from_borrowed_object(vm, other) { Ok(buf) => buf, Err(_) => return Ok(false), }; if !is_equiv_shape(&zelf.desc, &other.desc) { return Ok(false); } let a_itemsize = zelf.desc.itemsize; let b_itemsize = other.desc.itemsize; let a_format_spec = &zelf.format_spec; let b_format_spec = &Self::parse_format(&other.desc.format, vm)?; if zelf.desc.ndim() == 0 { let a_val = format_unpack(a_format_spec, &zelf.buffer.obj_bytes()[..a_itemsize], vm)?; let b_val = format_unpack(b_format_spec, &other.obj_bytes()[..b_itemsize], vm)?; return vm.bool_eq(&a_val, &b_val); } // TODO: optimize cmp by format let mut ret = Ok(true); let a_bytes = zelf.buffer.obj_bytes(); let b_bytes = other.obj_bytes(); zelf.desc.zip_eq(&other.desc, false, |a_range, b_range| { let a_range = (a_range.start + zelf.start as isize) as usize ..(a_range.end + zelf.start as isize) as usize; let b_range = b_range.start as usize..b_range.end as usize; let a_val = match format_unpack(a_format_spec, &a_bytes[a_range], vm) { Ok(val) => val, Err(e) => { ret = Err(e); return true; } }; let b_val = match format_unpack(b_format_spec, &b_bytes[b_range], vm) { Ok(val) => val, Err(e) => { ret = Err(e); return true; } }; ret = vm.bool_eq(&a_val, &b_val); if let Ok(b) = ret { !b } else { true } }); ret } fn obj_bytes(&self) -> BorrowedValue<[u8]> { if self.desc.is_contiguous() { BorrowedValue::map(self.buffer.obj_bytes(), |x| { &x[self.start..self.start + self.desc.len] }) } else { BorrowedValue::map(self.buffer.obj_bytes(), |x| &x[self.start..]) } } fn obj_bytes_mut(&self) -> BorrowedValueMut<[u8]> { if self.desc.is_contiguous() { BorrowedValueMut::map(self.buffer.obj_bytes_mut(), |x| { &mut x[self.start..self.start + self.desc.len] }) } else { BorrowedValueMut::map(self.buffer.obj_bytes_mut(), |x| &mut x[self.start..]) } } fn as_contiguous(&self) -> Option<BorrowedValue<[u8]>> { self.desc.is_contiguous().then(|| { BorrowedValue::map(self.buffer.obj_bytes(), |x| { &x[self.start..self.start + self.desc.len] }) }) } fn _as_contiguous_mut(&self) -> Option<BorrowedValueMut<[u8]>> { self.desc.is_contiguous().then(|| { BorrowedValueMut::map(self.buffer.obj_bytes_mut(), |x| { &mut x[self.start..self.start + self.desc.len] }) }) } fn append_to(&self, buf: &mut Vec<u8>) { if let Some(bytes) = self.as_contiguous() { buf.extend_from_slice(&bytes); } else { buf.reserve(self.desc.len); let bytes = &*self.buffer.obj_bytes(); self.desc.for_each_segment(true, |range| { let start = (range.start + self.start as isize) as usize; let end = (range.end + self.start as isize) as usize; buf.extend_from_slice(&bytes[start..end]); }) } } fn contiguous_or_collect<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R { let borrowed; let mut collected; let v = if let Some(bytes) = self.as_contiguous() { borrowed = bytes; &*borrowed } else { collected = vec![]; self.append_to(&mut collected); &collected }; f(v) } /// clone data from memoryview /// keep the shape, convert to contiguous pub fn to_contiguous(&self, vm: &VirtualMachine) -> PyBuffer { let mut data = vec![]; self.append_to(&mut data); if self.desc.ndim() == 0 { return VecBuffer::from(data) .into_ref(&vm.ctx) .into_pybuffer_with_descriptor(self.desc.clone()); } let mut dim_desc = self.desc.dim_desc.clone(); dim_desc.last_mut().unwrap().1 = self.desc.itemsize as isize; dim_desc.last_mut().unwrap().2 = 0; for i in (0..dim_desc.len() - 1).rev() { dim_desc[i].1 = dim_desc[i + 1].1 * dim_desc[i + 1].0 as isize; dim_desc[i].2 = 0; } let desc = BufferDescriptor { len: self.desc.len, readonly: self.desc.readonly, itemsize: self.desc.itemsize, format: self.desc.format.clone(), dim_desc, }; VecBuffer::from(data) .into_ref(&vm.ctx) .into_pybuffer_with_descriptor(desc) } } impl Py<PyMemoryView> { fn setitem_by_slice( &self, slice: &PySlice, src: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { if self.desc.ndim() != 1 { return Err(vm.new_not_implemented_error("sub-view are not implemented".to_owned())); } let mut dest = self.new_view(); dest.init_slice(slice, 0, vm)?; dest.init_len(); if self.is(&src) { return if !is_equiv_structure(&self.desc, &dest.desc) { Err(vm.new_value_error( "memoryview assignment: lvalue and rvalue have different structures".to_owned(), )) } else { // assign self[:] to self Ok(()) }; }; let src = if let Some(src) = src.downcast_ref::<PyMemoryView>() { if self.buffer.obj.is(&src.buffer.obj) { src.to_contiguous(vm) } else { AsBuffer::as_buffer(src, vm)? } } else { PyBuffer::try_from_object(vm, src)? }; if !is_equiv_structure(&src.desc, &dest.desc) { return Err(vm.new_value_error( "memoryview assignment: lvalue and rvalue have different structures".to_owned(), )); } let mut bytes_mut = dest.buffer.obj_bytes_mut(); let src_bytes = src.obj_bytes(); dest.desc.zip_eq(&src.desc, true, |a_range, b_range| { let a_range = (a_range.start + dest.start as isize) as usize ..(a_range.end + dest.start as isize) as usize; let b_range = b_range.start as usize..b_range.end as usize; bytes_mut[a_range].copy_from_slice(&src_bytes[b_range]); false }); Ok(()) } } #[pyclass(with( Py, Hashable, Comparable, AsBuffer, AsMapping, AsSequence, Constructor, Iterable, Representable ))] impl PyMemoryView { #[pymethod] pub fn release(&self) { if self.released.compare_exchange(false, true).is_ok() { self.buffer.release(); } } #[pygetset] fn obj(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> { self.try_not_released(vm).map(|_| self.buffer.obj.clone()) } #[pygetset] fn nbytes(&self, vm: &VirtualMachine) -> PyResult<usize> { self.try_not_released(vm).map(|_| self.desc.len) } #[pygetset] fn readonly(&self, vm: &VirtualMachine) -> PyResult<bool> { self.try_not_released(vm).map(|_| self.desc.readonly) } #[pygetset] fn itemsize(&self, vm: &VirtualMachine) -> PyResult<usize> { self.try_not_released(vm).map(|_| self.desc.itemsize) } #[pygetset] fn ndim(&self, vm: &VirtualMachine) -> PyResult<usize> { self.try_not_released(vm).map(|_| self.desc.ndim()) } #[pygetset] fn shape(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> { self.try_not_released(vm)?; Ok(vm.ctx.new_tuple( self.desc .dim_desc .iter() .map(|(shape, _, _)| shape.to_pyobject(vm)) .collect(), )) } #[pygetset] fn strides(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> { self.try_not_released(vm)?; Ok(vm.ctx.new_tuple( self.desc .dim_desc .iter() .map(|(_, stride, _)| stride.to_pyobject(vm)) .collect(), )) } #[pygetset] fn suboffsets(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> { self.try_not_released(vm)?; Ok(vm.ctx.new_tuple( self.desc .dim_desc .iter() .map(|(_, _, suboffset)| suboffset.to_pyobject(vm)) .collect(), )) } #[pygetset] fn format(&self, vm: &VirtualMachine) -> PyResult<PyStr> { self.try_not_released(vm) .map(|_| PyStr::from(self.desc.format.clone())) } #[pygetset] fn contiguous(&self, vm: &VirtualMachine) -> PyResult<bool> { self.try_not_released(vm).map(|_| self.desc.is_contiguous()) } #[pygetset] fn c_contiguous(&self, vm: &VirtualMachine) -> PyResult<bool> { self.try_not_released(vm).map(|_| self.desc.is_contiguous()) } #[pygetset] fn f_contiguous(&self, vm: &VirtualMachine) -> PyResult<bool> { // TODO: fortain order self.try_not_released(vm) .map(|_| self.desc.ndim() <= 1 && self.desc.is_contiguous()) } #[pymethod(magic)] fn enter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { zelf.try_not_released(vm).map(|_| zelf) } #[pymethod(magic)] fn exit(&self, _args: FuncArgs) { self.release(); } #[pymethod(magic)] fn getitem(zelf: PyRef<Self>, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { zelf.try_not_released(vm)?; if zelf.desc.ndim() == 0 { // 0-d memoryview can be referenced using mv[...] or mv[()] only if needle.is(&vm.ctx.ellipsis) { return Ok(zelf.into()); } if let Some(tuple) = needle.payload::<PyTuple>() { if tuple.is_empty() { return zelf.unpack_single(0, vm); } } return Err(vm.new_type_error("invalid indexing of 0-dim memory".to_owned())); } match SubscriptNeedle::try_from_object(vm, needle)? { SubscriptNeedle::Index(i) => zelf.getitem_by_idx(i, vm), SubscriptNeedle::Slice(slice) => zelf.getitem_by_slice(&slice, vm), SubscriptNeedle::MultiIndex(indices) => zelf.getitem_by_multi_idx(&indices, vm), } } #[pymethod(magic)] fn delitem(&self, _needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if self.desc.readonly { return Err(vm.new_type_error("cannot modify read-only memory".to_owned())); } Err(vm.new_type_error("cannot delete memory".to_owned())) } #[pymethod(magic)] fn len(&self, vm: &VirtualMachine) -> PyResult<usize> { self.try_not_released(vm)?; Ok(if self.desc.ndim() == 0 { 1 } else { // shape for dim[0] self.desc.dim_desc[0].0 }) } #[pymethod] fn tobytes(&self, vm: &VirtualMachine) -> PyResult<PyBytesRef> { self.try_not_released(vm)?; let mut v = vec![]; self.append_to(&mut v); Ok(PyBytes::from(v).into_ref(&vm.ctx)) } #[pymethod] fn tolist(&self, vm: &VirtualMachine) -> PyResult<PyListRef> { self.try_not_released(vm)?; let bytes = self.buffer.obj_bytes(); if self.desc.ndim() == 0 { return Ok(vm.ctx.new_list(vec![format_unpack( &self.format_spec, &bytes[..self.desc.itemsize], vm, )?])); } self._to_list(&bytes, 0, 0, vm) } #[pymethod] fn toreadonly(&self, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { self.try_not_released(vm)?; let mut other = self.new_view(); other.desc.readonly = true; Ok(other.into_ref(&vm.ctx)) } #[pymethod] fn hex( &self, sep: OptionalArg<Either<PyStrRef, PyBytesRef>>, bytes_per_sep: OptionalArg<isize>, vm: &VirtualMachine, ) -> PyResult<String> { self.try_not_released(vm)?; self.contiguous_or_collect(|x| bytes_to_hex(x, sep, bytes_per_sep, vm)) } fn cast_to_1d(&self, format: PyStrRef, vm: &VirtualMachine) -> PyResult<Self> { let format_spec = Self::parse_format(format.as_str(), vm)?; let itemsize = format_spec.size(); if self.desc.len % itemsize != 0 { return Err( vm.new_type_error("memoryview: length is not a multiple of itemsize".to_owned()) ); } Ok(Self { buffer: self.buffer.clone(), released: AtomicCell::new(false), start: self.start, format_spec, desc: BufferDescriptor { len: self.desc.len, readonly: self.desc.readonly, itemsize, format: format.to_string().into(), dim_desc: vec![(self.desc.len / itemsize, itemsize as isize, 0)], }, hash: OnceCell::new(), }) } #[pymethod] fn cast(&self, args: CastArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { self.try_not_released(vm)?; if !self.desc.is_contiguous() { return Err(vm.new_type_error( "memoryview: casts are restricted to C-contiguous views".to_owned(), )); } let CastArgs { format, shape } = args; if let OptionalArg::Present(shape) = shape { if self.desc.is_zero_in_shape() { return Err(vm.new_type_error( "memoryview: cannot cast view with zeros in shape or strides".to_owned(), )); } let tup; let list; let list_borrow; let shape = match shape { Either::A(shape) => { tup = shape; tup.as_slice() } Either::B(shape) => { list = shape; list_borrow = list.borrow_vec(); &list_borrow } }; let shape_ndim = shape.len(); // TODO: MAX_NDIM if self.desc.ndim() != 1 && shape_ndim != 1 { return Err( vm.new_type_error("memoryview: cast must be 1D -> ND or ND -> 1D".to_owned()) ); } let mut other = self.cast_to_1d(format, vm)?; let itemsize = other.desc.itemsize; // 0 ndim is single item if shape_ndim == 0 { other.desc.dim_desc = vec![]; other.desc.len = itemsize; return Ok(other.into_ref(&vm.ctx)); } let mut product_shape = itemsize; let mut dim_descriptor = Vec::with_capacity(shape_ndim); for x in shape { let x = usize::try_from_borrowed_object(vm, x)?; if x > isize::MAX as usize / product_shape { return Err(vm.new_value_error( "memoryview.cast(): product(shape) > SSIZE_MAX".to_owned(), )); } product_shape *= x; dim_descriptor.push((x, 0, 0)); } dim_descriptor.last_mut().unwrap().1 = itemsize as isize; for i in (0..dim_descriptor.len() - 1).rev() { dim_descriptor[i].1 = dim_descriptor[i + 1].1 * dim_descriptor[i + 1].0 as isize; } if product_shape != other.desc.len { return Err(vm.new_type_error( "memoryview: product(shape) * itemsize != buffer size".to_owned(), )); } other.desc.dim_desc = dim_descriptor; Ok(other.into_ref(&vm.ctx)) } else { Ok(self.cast_to_1d(format, vm)?.into_ref(&vm.ctx)) } } } #[pyclass] impl Py<PyMemoryView> { #[pymethod(magic)] fn setitem( &self, needle: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { self.try_not_released(vm)?; if self.desc.readonly { return Err(vm.new_type_error("cannot modify read-only memory".to_owned())); } if value.is(&vm.ctx.none) { return Err(vm.new_type_error("cannot delete memory".to_owned())); } if self.desc.ndim() == 0 { // TODO: merge branches when we got conditional if let if needle.is(&vm.ctx.ellipsis) { return self.pack_single(0, value, vm); } else if let Some(tuple) = needle.payload::<PyTuple>() { if tuple.is_empty() { return self.pack_single(0, value, vm); } } return Err(vm.new_type_error("invalid indexing of 0-dim memory".to_owned())); } match SubscriptNeedle::try_from_object(vm, needle)? { SubscriptNeedle::Index(i) => self.setitem_by_idx(i, value, vm), SubscriptNeedle::Slice(slice) => self.setitem_by_slice(&slice, value, vm), SubscriptNeedle::MultiIndex(indices) => self.setitem_by_multi_idx(&indices, value, vm), } } #[pymethod(magic)] fn reduce_ex(&self, _proto: usize, vm: &VirtualMachine) -> PyResult { self.reduce(vm) } #[pymethod(magic)] fn reduce(&self, vm: &VirtualMachine) -> PyResult { Err(vm.new_type_error("cannot pickle 'memoryview' object".to_owned())) } } #[derive(FromArgs)] struct CastArgs { #[pyarg(any)] format: PyStrRef, #[pyarg(any, optional)] shape: OptionalArg<Either<PyTupleRef, PyListRef>>, } enum SubscriptNeedle { Index(isize), Slice(PyRef<PySlice>), MultiIndex(Vec<isize>), // MultiSlice(Vec<PySliceRef>), } impl TryFromObject for SubscriptNeedle { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { // TODO: number protocol if let Some(i) = obj.payload::<PyInt>() { Ok(Self::Index(i.try_to_primitive(vm)?)) } else if obj.payload_is::<PySlice>() { Ok(Self::Slice(unsafe { obj.downcast_unchecked::<PySlice>() })) } else if let Ok(i) = obj.try_index(vm) { Ok(Self::Index(i.try_to_primitive(vm)?)) } else { if let Some(tuple) = obj.payload::<PyTuple>() { if tuple.iter().all(|x| x.payload_is::<PyInt>()) { let v = tuple .iter() .map(|x| { unsafe { x.downcast_unchecked_ref::<PyInt>() } .try_to_primitive::<isize>(vm) }) .try_collect()?; return Ok(Self::MultiIndex(v)); } else if tuple.iter().all(|x| x.payload_is::<PySlice>()) { return Err(vm.new_not_implemented_error( "multi-dimensional slicing is not implemented".to_owned(), )); } } Err(vm.new_type_error("memoryview: invalid slice key".to_owned())) } } } static BUFFER_METHODS: BufferMethods = BufferMethods { obj_bytes: |buffer| buffer.obj_as::<PyMemoryView>().obj_bytes(), obj_bytes_mut: |buffer| buffer.obj_as::<PyMemoryView>().obj_bytes_mut(), release: |buffer| buffer.obj_as::<PyMemoryView>().buffer.release(), retain: |buffer| buffer.obj_as::<PyMemoryView>().buffer.retain(), }; impl AsBuffer for PyMemoryView { fn as_buffer(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyBuffer> { if zelf.released.load() { Err(vm.new_value_error("operation forbidden on released memoryview object".to_owned())) } else { Ok(PyBuffer::new( zelf.to_owned().into(), zelf.desc.clone(), &BUFFER_METHODS, )) } } } impl Drop for PyMemoryView { fn drop(&mut self) { if self.released.load() { unsafe { self.buffer.drop_without_release() }; } else { unsafe { ManuallyDrop::drop(&mut self.buffer) }; } } } impl AsMapping for PyMemoryView { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: PyMappingMethods = PyMappingMethods { length: atomic_func!(|mapping, vm| PyMemoryView::mapping_downcast(mapping).len(vm)), subscript: atomic_func!(|mapping, needle, vm| { let zelf = PyMemoryView::mapping_downcast(mapping); PyMemoryView::getitem(zelf.to_owned(), needle.to_owned(), vm) }), ass_subscript: atomic_func!(|mapping, needle, value, vm| { let zelf = PyMemoryView::mapping_downcast(mapping); if let Some(value) = value { zelf.setitem(needle.to_owned(), value, vm) } else { Err(vm.new_type_error("cannot delete memory".to_owned())) } }), }; &AS_MAPPING } } impl AsSequence for PyMemoryView { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: Lazy<PySequenceMethods> = Lazy::new(|| PySequenceMethods { length: atomic_func!(|seq, vm| { let zelf = PyMemoryView::sequence_downcast(seq); zelf.try_not_released(vm)?; zelf.len(vm) }), item: atomic_func!(|seq, i, vm| { let zelf = PyMemoryView::sequence_downcast(seq); zelf.try_not_released(vm)?; zelf.getitem_by_idx(i, vm) }), ..PySequenceMethods::NOT_IMPLEMENTED }); &AS_SEQUENCE } } impl Comparable for PyMemoryView { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { match op { PyComparisonOp::Ne => { Self::eq(zelf, other, vm).map(|x| PyComparisonValue::Implemented(!x)) } PyComparisonOp::Eq => Self::eq(zelf, other, vm).map(PyComparisonValue::Implemented), _ => Err(vm.new_type_error(format!( "'{}' not supported between instances of '{}' and '{}'", op.operator_token(), zelf.class().name(), other.class().name() ))), } } } impl Hashable for PyMemoryView { fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> { zelf.hash .get_or_try_init(|| { zelf.try_not_released(vm)?; if !zelf.desc.readonly { return Err( vm.new_value_error("cannot hash writable memoryview object".to_owned()) ); } Ok(zelf.contiguous_or_collect(|bytes| vm.state.hash_secret.hash_bytes(bytes))) }) .map(|&x| x) } } impl PyPayload for PyMemoryView { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.memoryview_type } } impl Representable for PyMemoryView { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { let repr = if zelf.released.load() { format!("<released memory at {:#x}>", zelf.get_id()) } else { format!("<memory at {:#x}>", zelf.get_id()) }; Ok(repr) } } pub(crate) fn init(ctx: &Context) { PyMemoryView::extend_class(ctx, ctx.types.memoryview_type); PyMemoryViewIterator::extend_class(ctx, ctx.types.memoryviewiterator_type); } fn format_unpack( format_spec: &FormatSpec, bytes: &[u8], vm: &VirtualMachine, ) -> PyResult<PyObjectRef> { format_spec.unpack(bytes, vm).map(|x| { if x.len() == 1 { x.fast_getitem(0) } else { x.into() } }) } fn is_equiv_shape(a: &BufferDescriptor, b: &BufferDescriptor) -> bool { if a.ndim() != b.ndim() { return false; } let a_iter = a.dim_desc.iter().map(|x| x.0); let b_iter = b.dim_desc.iter().map(|x| x.0); for (a_shape, b_shape) in a_iter.zip(b_iter) { if a_shape != b_shape { return false; } // if both shape is 0, ignore the rest if a_shape == 0 { break; } } true } fn is_equiv_format(a: &BufferDescriptor, b: &BufferDescriptor) -> bool { // TODO: skip @ a.itemsize == b.itemsize && a.format == b.format } fn is_equiv_structure(a: &BufferDescriptor, b: &BufferDescriptor) -> bool { is_equiv_format(a, b) && is_equiv_shape(a, b) } impl Iterable for PyMemoryView { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { Ok(PyMemoryViewIterator { internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), } .into_pyobject(vm)) } } #[pyclass(module = false, name = "memory_iterator")] #[derive(Debug, Traverse)] pub struct PyMemoryViewIterator { internal: PyMutex<PositionIterInternal<PyRef<PyMemoryView>>>, } impl PyPayload for PyMemoryViewIterator { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.memoryviewiterator_type } } #[pyclass(with(Constructor, IterNext, Iterable))] impl PyMemoryViewIterator { #[pymethod(magic)] fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef { self.internal .lock() .builtins_iter_reduce(|x| x.clone().into(), vm) } } impl Unconstructible for PyMemoryViewIterator {} impl SelfIter for PyMemoryViewIterator {} impl IterNext for PyMemoryViewIterator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.internal.lock().next(|mv, pos| { let len = mv.len(vm)?; Ok(if pos >= len { PyIterReturn::StopIteration(None) } else { PyIterReturn::Return(mv.getitem_by_idx(pos.try_into().unwrap(), vm)?) }) }) } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. pub use wlan_common as common; pub mod ap; pub mod auth; pub mod buffer; pub mod client; pub mod device; pub mod error; pub mod timer; mod rates_writer; pub use rates_writer::*; mod eth_writer; pub use eth_writer::*;
use crate::impl_vk_handle; use crate::prelude::*; use utilities::prelude::*; use std::collections::HashMap; use std::sync::{Arc, Mutex}; pub struct SamplerBuilder { create_info: VkSamplerCreateInfo, } impl SamplerBuilder { pub fn min_mag_filter(mut self, min_filter: VkFilter, mag_filter: VkFilter) -> Self { self.create_info.minFilter = min_filter; self.create_info.magFilter = mag_filter; self } pub fn map_map_mode(mut self, mode: VkSamplerMipmapMode) -> Self { self.create_info.mipmapMode = mode; self } pub fn address_mode( mut self, u: VkSamplerAddressMode, v: VkSamplerAddressMode, w: VkSamplerAddressMode, ) -> Self { self.create_info.addressModeU = u; self.create_info.addressModeV = v; self.create_info.addressModeW = w; self } pub fn min_load_bias(mut self, bias: f32) -> Self { self.create_info.mipLodBias = bias; self } pub fn anisotropy(mut self, anisotropy: f32) -> Self { self.create_info.anisotropyEnable = VK_TRUE; self.create_info.maxAnisotropy = anisotropy; self } pub fn compare(mut self, compare_op: VkCompareOp) -> Self { self.create_info.compareEnable = VK_TRUE; self.create_info.compareOp = compare_op; self } pub fn min_max_lod(mut self, min_lod: f32, max_lod: f32) -> Self { self.create_info.minLod = min_lod; self.create_info.maxLod = max_lod; self } pub fn border_color(mut self, border_color: VkBorderColor) -> Self { self.create_info.borderColor = border_color; self } pub fn coordinates<T>(mut self, unnormalized_coordinates: T) -> Self where T: Into<VkBool32>, { self.create_info.unnormalizedCoordinates = unnormalized_coordinates.into(); self } pub fn build(self, device: &Device) -> VerboseResult<Arc<Sampler>> { device.create_sampler_from_manager(self.create_info) } } #[derive(Debug)] pub struct Sampler { sampler: VkSampler, } impl Sampler { pub fn nearest_sampler() -> SamplerBuilder { SamplerBuilder { create_info: VkSamplerCreateInfo::new( 0, VK_FILTER_NEAREST, VK_FILTER_NEAREST, VK_SAMPLER_MIPMAP_MODE_NEAREST, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, 0.0, false, 1.0, false, VK_COMPARE_OP_NEVER, 0.0, 0.0, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, false, ), } } pub fn pretty_sampler() -> SamplerBuilder { SamplerBuilder { create_info: VkSamplerCreateInfo::new( 0, VK_FILTER_LINEAR, VK_FILTER_LINEAR, VK_SAMPLER_MIPMAP_MODE_LINEAR, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, 0.0, true, 8.0, false, VK_COMPARE_OP_NEVER, 0.0, 0.0, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, false, ), } } } impl_vk_handle!(Sampler, VkSampler, sampler); pub struct SamplerManager { samplers: HashMap<VkSamplerCreateInfo, Arc<Sampler>>, } unsafe impl Sync for SamplerManager {} unsafe impl Send for SamplerManager {} impl SamplerManager { pub fn new() -> Mutex<Self> { Mutex::new(SamplerManager { samplers: HashMap::new(), }) } pub fn create_sampler( &mut self, create_info: VkSamplerCreateInfo, device: &Device, ) -> VerboseResult<Arc<Sampler>> { match self.samplers.get(&create_info) { Some(sampler) => Ok(sampler.clone()), None => { let new_sampler = Arc::new(Sampler { sampler: device.create_sampler(&create_info)?, }); self.samplers.insert(create_info, new_sampler.clone()); Ok(new_sampler) } } } /// This will destroy all VkSampler handles, no matter if they are in use or not pub unsafe fn clear(&mut self, device: &Device) { self.samplers .iter() .for_each(|(_, sampler)| device.destroy_sampler(sampler.vk_handle())); self.samplers.clear(); } }
use super::constants; use super::Card; #[derive(Debug, Clone)] pub struct Hand { id: u32, values: Vec<Card>, } impl Hand { pub fn new(id: u32, values: Vec<Card>) -> Hand { Hand { id, values: values.to_vec(), } } pub fn get_owner(&self) -> String { if self.id == constants::DEALER_ID { String::from("Dealer") } else { String::from("Player") } } pub fn get(&self) -> Vec<Card> { self.values.to_vec() } pub fn add(&mut self, new_card: Card) { self.values.push(new_card); } pub fn split(&mut self) -> Hand { let card = self.values.remove(1); let hand_two = Hand::new(constants::PLAYER_ID, vec![card]); hand_two } fn hand_contains_at_least(&self, card_name: &str, number: usize) -> bool { let card_name_string = card_name.to_string(); let matches: Vec<Card> = self.get() .iter() .filter(|c| c.name == card_name_string) .cloned() .collect(); matches.len() >= number } pub fn total(&self) -> u32 { let mut total = 0; for c in &self.values { total += c.value; } // Only treat an ace as 11 if you won't go bust. let ace_as_eleven_total = total + 10; let hand_has_ace = self.hand_contains_at_least(&constants::ACE, 1); if !hand_has_ace || ace_as_eleven_total > constants::BLACKJACK_MAXIMUM { total } else { ace_as_eleven_total } } pub fn is_blackjack(&self) -> bool { self.values.len() == 2 && self.hand_contains_at_least(&constants::ACE, 1) && self.total() == constants::BLACKJACK_MAXIMUM } pub fn can_split(&self) -> bool { let cards = self.get(); let card_one = cards.get(0).unwrap(); let card_two = cards.get(1).unwrap(); cards.len() == 2 && card_one.name == card_two.name } pub fn is_valid(&self) -> bool { self.total() <= constants::BLACKJACK_MAXIMUM } }