text
stringlengths
8
4.13M
use failure::Error; pub mod maybe_unavaliable; pub use self::maybe_unavaliable::MaybeUnavailable; /// Returns a string describing the error and the full chain. pub fn format_error(error: &Error) -> String { let mut buf = format!("Error: {}\n", error); for cause in error.iter_causes() { buf += &format!("Caused by: {}\n", cause); } buf }
use anyhow::{anyhow, Result}; use ropey::Rope; use std::path::PathBuf; use crate::import_string; use crate::parser::{ImportFinder, Lang}; fn infer_langauge_from_suffix(file_name: &PathBuf) -> Result<Lang> { let suffix = file_name .extension() .and_then(|os_str| os_str.to_str()) .ok_or_else(|| anyhow!("Missing suffix on file"))?; match suffix { "ts" => Ok(Lang::TypeScript), "tsx" => Ok(Lang::TypeScriptTsx), suffix => Err(anyhow!("{:?} files are not supported", suffix)), } } fn replace_rel_imports<F>(source_code: &str, lang: Lang, replacer: F) -> Result<String> where F: Fn(&String) -> Result<String>, { let mut import_finder = ImportFinder::new(&source_code, lang)?; let mut rope = Rope::from_str(&source_code); for text_slice in import_finder.find_imports() { let (start_idx, end_idx) = text_slice.to_index_range(&rope); let old_import = rope.slice(start_idx..end_idx).to_string(); if !old_import.starts_with('.') { continue; } let new_import = replacer(&old_import)?; if old_import.eq(&new_import) { continue; } rope.remove(start_idx..end_idx); rope.insert(start_idx, &new_import); } Ok(rope.to_string()) } pub fn replace_imports<F>(source_file: &PathBuf, source_code: &str, replacer: F) -> Result<String> where F: Fn(&String) -> Result<String>, { let lang = infer_langauge_from_suffix(&source_file)?; let mut import_finder = ImportFinder::new(&source_code, lang)?; let mut rope = Rope::from_str(&source_code); for text_slice in import_finder.find_imports() { let (start_idx, end_idx) = text_slice.to_index_range(&rope); let old_import = rope.slice(start_idx..end_idx).to_string(); if !old_import.starts_with('.') { continue; } let new_import = replacer(&old_import)?; if old_import.eq(&new_import) { continue; } rope.remove(start_idx..end_idx); rope.insert(start_idx, &new_import); } Ok(rope.to_string()) } pub fn move_source_file( source_code: String, source_file: &PathBuf, target_file: &PathBuf, ) -> Result<String> { let lang = infer_langauge_from_suffix(&source_file)?; replace_rel_imports(&source_code, lang, |import_string| { let args = import_string::SourceFileRename { import_string, old_location: source_file, new_location: target_file, }; import_string::rename_source_file(&args) }) } pub fn move_required_file( source_code: &str, source_file: &PathBuf, old_import_location: &PathBuf, new_import_location: &PathBuf, ) -> Result<String> { let lang = infer_langauge_from_suffix(&source_file)?; replace_rel_imports(&source_code, lang, |import_string| { let args = import_string::RequiredFileRename { source_file, import_string, old_location: old_import_location, new_location: new_import_location, }; import_string::rename_required_file(&args) }) } #[cfg(test)] mod tests { use anyhow::Result; use std::path::PathBuf; #[test] fn it_updates_imports_0() -> Result<()> { let code: String = r#" import some from '../../some'; import other from '../../other'; function main() { console.log("hullo world"); } "# .into(); let source: PathBuf = "/src/a/b/c/d/source.ts".into(); let target: PathBuf = "/src/a/b/c/d/e/target.ts".into(); let new_source_code = super::move_source_file(code, &source, &target)?; let new_import_0: String = "import some from '../../../some';".into(); let new_import_1: String = "import other from '../../../other';".into(); assert!(new_source_code.contains(&new_import_0)); assert!(new_source_code.contains(&new_import_1)); Ok(()) } #[test] fn it_updates_imports_1() -> Result<()> { let code: String = r#" import some from '../../some'; import other from '../../other'; function main() { console.log("hullo world"); } "# .into(); let source: PathBuf = "/src/a/b/c/d/source.ts".into(); let target: PathBuf = "/src/a/target.ts".into(); let new_source_code = super::move_source_file(code, &source, &target)?; let new_import_0: String = "import some from './b/some';".into(); let new_import_1: String = "import other from './b/other';".into(); assert!(new_source_code.contains(&new_import_0)); assert!(new_source_code.contains(&new_import_1)); Ok(()) } }
use bitflags::bitflags; bitflags! { /// `GRND_*` flags for use with [`getrandom`]. /// /// [`getrandom`]: crate::rand::getrandom #[repr(transparent)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct GetRandomFlags: u32 { /// `GRND_RANDOM` const RANDOM = linux_raw_sys::general::GRND_RANDOM; /// `GRND_NONBLOCK` const NONBLOCK = linux_raw_sys::general::GRND_NONBLOCK; /// `GRND_INSECURE` const INSECURE = linux_raw_sys::general::GRND_INSECURE; } }
use crate::worker::{component::DATABASE, vtable}; use spatialos_sdk_sys::worker::*; use std::{ ffi::{CStr, CString}, ptr, }; pub struct ConnectionParameters { pub worker_type: CString, pub network: NetworkParameters, pub send_queue_capacity: u32, pub receive_queue_capacity: u32, pub log_message_queue_capacity: u32, pub built_in_metrics_report_period_millis: u32, pub protocol_logging: ProtocolLoggingParameters, pub enable_protocol_logging_at_startup: bool, pub thread_affinity: ThreadAffinityParameters, use_internal_serialization: bool, } impl ConnectionParameters { pub fn new<T: AsRef<str>>(worker_type: T) -> Self { let mut params = ConnectionParameters::default(); params.worker_type = CString::new(worker_type.as_ref()).expect("`worker_type` contains a null byte"); params } pub fn with_protocol_logging<T: AsRef<str>>(mut self, log_prefix: T) -> Self { self.enable_protocol_logging_at_startup = true; self.protocol_logging.log_prefix = CString::new(log_prefix.as_ref()).expect("`log_prefix` contained a null byte"); self } pub fn using_tcp(self) -> Self { self.using_tcp_with_params(TcpNetworkParameters::default()) } pub fn using_tcp_with_params(mut self, params: TcpNetworkParameters) -> Self { self.network.protocol = ProtocolType::Tcp(params); self } pub fn using_udp(self) -> Self { self.using_udp_with_params(UdpNetworkParameters::default()) } pub fn using_udp_with_params(mut self, params: UdpNetworkParameters) -> Self { self.network.protocol = ProtocolType::Udp(params); self } pub fn using_external_ip(mut self, use_external_ip: bool) -> Self { self.network.use_external_ip = use_external_ip; self } pub fn with_connection_timeout(mut self, timeout_millis: u64) -> Self { self.network.connection_timeout_millis = timeout_millis; self } pub fn enable_internal_serialization(mut self) -> Self { self.use_internal_serialization = true; self } pub fn default() -> Self { ConnectionParameters { worker_type: CString::new("").unwrap(), network: NetworkParameters::default(), send_queue_capacity: WORKER_DEFAULTS_SEND_QUEUE_CAPACITY, receive_queue_capacity: WORKER_DEFAULTS_RECEIVE_QUEUE_CAPACITY, log_message_queue_capacity: WORKER_DEFAULTS_LOG_MESSAGE_QUEUE_CAPACITY, built_in_metrics_report_period_millis: WORKER_DEFAULTS_BUILT_IN_METRICS_REPORT_PERIOD_MILLIS, protocol_logging: ProtocolLoggingParameters::default(), enable_protocol_logging_at_startup: false, thread_affinity: ThreadAffinityParameters::default(), use_internal_serialization: false, } } pub(crate) fn flatten(&self) -> IntermediateConnectionParameters<'_> { let protocol = match &self.network.protocol { ProtocolType::Tcp(params) => IntermediateProtocolType::Tcp(params.to_worker_sdk()), ProtocolType::Udp(params) => IntermediateProtocolType::Udp { security_type: params.security_type.to_worker_sdk(), kcp: params.kcp.as_ref().map(KcpParameters::to_worker_sdk), erasure_codec: params .erasure_codec .as_ref() .map(ErasureCodecParameters::to_worker_sdk), heartbeat: params .heartbeat .as_ref() .map(HeartbeatParameters::to_worker_sdk), flow_control: params .flow_control .as_ref() .map(FlowControlParameters::to_worker_sdk), }, }; IntermediateConnectionParameters { params: self, protocol, } } } pub enum ProtocolType { Tcp(TcpNetworkParameters), Udp(UdpNetworkParameters), } pub struct NetworkParameters { pub use_external_ip: bool, pub protocol: ProtocolType, pub connection_timeout_millis: u64, pub default_command_timeout_millis: u32, } impl NetworkParameters { pub fn default() -> Self { NetworkParameters { use_external_ip: false, protocol: ProtocolType::Tcp(TcpNetworkParameters::default()), connection_timeout_millis: u64::from(WORKER_DEFAULTS_CONNECTION_TIMEOUT_MILLIS), default_command_timeout_millis: WORKER_DEFAULTS_DEFAULT_COMMAND_TIMEOUT_MILLIS, } } } // TCP pub struct TcpNetworkParameters { pub multiplex_level: u8, pub send_buffer_size: u32, pub receive_buffer_size: u32, pub no_delay: bool, } impl TcpNetworkParameters { pub fn default() -> Self { TcpNetworkParameters { multiplex_level: WORKER_DEFAULTS_TCP_MULTIPLEX_LEVEL as u8, send_buffer_size: WORKER_DEFAULTS_TCP_SEND_BUFFER_SIZE, receive_buffer_size: WORKER_DEFAULTS_TCP_RECEIVE_BUFFER_SIZE, no_delay: WORKER_DEFAULTS_TCP_NO_DELAY != 0, } } pub(crate) fn to_worker_sdk(&self) -> Worker_TcpNetworkParameters { Worker_TcpNetworkParameters { multiplex_level: self.multiplex_level, send_buffer_size: self.send_buffer_size, receive_buffer_size: self.receive_buffer_size, no_delay: self.no_delay as u8, } } } // UDP pub enum SecurityType { Insecure, DTLS, } impl SecurityType { pub fn default() -> Self { SecurityType::Insecure } pub(crate) fn to_worker_sdk(&self) -> u8 { (match self { SecurityType::Insecure => { Worker_NetworkSecurityType_WORKER_NETWORK_SECURITY_TYPE_INSECURE } SecurityType::DTLS => Worker_NetworkSecurityType_WORKER_NETWORK_SECURITY_TYPE_DTLS, }) as u8 } } pub struct KcpParameters { pub fast_retransmission: bool, pub early_retransmission: bool, pub non_concessional_flow_control: bool, pub multiplex_level: u32, pub update_interval_millis: u32, pub min_rto_millis: u32, } impl KcpParameters { pub fn default() -> Self { KcpParameters { fast_retransmission: WORKER_DEFAULTS_KCP_FAST_RETRANSMISSION != 0, early_retransmission: WORKER_DEFAULTS_KCP_EARLY_RETRANSMISSION != 0, non_concessional_flow_control: WORKER_DEFAULTS_KCP_NON_CONCESSIONAL_FLOW_CONTROL != 0, multiplex_level: WORKER_DEFAULTS_KCP_MULTIPLEX_LEVEL, update_interval_millis: WORKER_DEFAULTS_KCP_UPDATE_INTERVAL_MILLIS, min_rto_millis: WORKER_DEFAULTS_KCP_MIN_RTO_MILLIS, } } pub(crate) fn to_worker_sdk(&self) -> Worker_Alpha_KcpParameters { Worker_Alpha_KcpParameters { fast_retransmission: self.fast_retransmission as u8, early_retransmission: self.early_retransmission as u8, non_concessional_flow_control: self.non_concessional_flow_control as u8, multiplex_level: self.multiplex_level, update_interval_millis: self.update_interval_millis, min_rto_millis: self.min_rto_millis, } } } pub struct FlowControlParameters { pub downstream_window_size_bytes: u32, pub upstream_window_size_bytes: u32, } impl FlowControlParameters { pub fn default() -> Self { FlowControlParameters { downstream_window_size_bytes: WORKER_DEFAULTS_FLOW_CONTROL_DOWNSTREAM_WINDOW_SIZE_BYTES, upstream_window_size_bytes: WORKER_DEFAULTS_FLOW_CONTROL_UPSTREAM_WINDOW_SIZE_BYTES, } } pub(crate) fn to_worker_sdk(&self) -> Worker_Alpha_FlowControlParameters { Worker_Alpha_FlowControlParameters { downstream_window_size_bytes: self.downstream_window_size_bytes, upstream_window_size_bytes: self.upstream_window_size_bytes, } } } pub struct ErasureCodecParameters { pub original_packet_count: u8, pub recovery_packet_count: u8, pub window_size: u8, } impl ErasureCodecParameters { pub fn default() -> Self { ErasureCodecParameters { original_packet_count: WORKER_DEFAULTS_ERASURE_CODEC_ORIGINAL_PACKET_COUNT as u8, recovery_packet_count: WORKER_DEFAULTS_ERASURE_CODEC_RECOVERY_PACKET_COUNT as u8, window_size: WORKER_DEFAULTS_ERASURE_CODEC_WINDOW_SIZE as u8, } } pub(crate) fn to_worker_sdk(&self) -> Worker_ErasureCodecParameters { Worker_ErasureCodecParameters { original_packet_count: self.original_packet_count, recovery_packet_count: self.recovery_packet_count, window_size: self.window_size, } } } pub struct HeartbeatParameters { pub interval_millis: u64, pub timeout_millis: u64, } impl HeartbeatParameters { pub fn default() -> Self { HeartbeatParameters { interval_millis: u64::from(WORKER_DEFAULTS_HEARTBEAT_INTERVAL_MILLIS), timeout_millis: u64::from(WORKER_DEFAULTS_HEARTBEAT_TIMEOUT_MILLIS), } } pub(crate) fn to_worker_sdk(&self) -> Worker_HeartbeatParameters { Worker_HeartbeatParameters { interval_millis: self.interval_millis, timeout_millis: self.timeout_millis, } } } pub struct UdpNetworkParameters { pub security_type: SecurityType, pub kcp: Option<KcpParameters>, pub erasure_codec: Option<ErasureCodecParameters>, pub heartbeat: Option<HeartbeatParameters>, pub flow_control: Option<FlowControlParameters>, } impl UdpNetworkParameters { pub fn default() -> Self { UdpNetworkParameters { security_type: SecurityType::Insecure, kcp: Some(KcpParameters::default()), erasure_codec: None, heartbeat: None, flow_control: Some(FlowControlParameters::default()), } } } /// Parameters for configuring protocol logging. If enabled, logs all protocol /// messages sent and received. /// /// Note that all parameters are kept private and the struct can only be initialized /// with default values in order to make it possible to add new parameters without a /// breaking change. /// /// If you would like to use a method-chaining style when initializing the parameters, /// the [tap] crate is recommended. The examples below demonstrate this. /// /// # Parameters /// /// * `log_prefx: WORKER_DEFAULTS_LOG_PREFIX` - Log file names are prefixed with /// this prefix, are numbered, and have the extension `.log`. /// * `max_log_files: WORKER_DEFAULTS_MAX_LOG_FILES` - Maximum number of log files /// to keep. Note that logs from any previous protocol logging sessions will be /// overwritten. /// * `max_log_file_size: WORKER_DEFAULTS_MAX_LOG_FILE_SIZE_BYTES` - Once the size /// of a log file reaches this size, a new log file is created. /// /// # Examples /// /// ``` /// use spatialos_sdk::worker::parameters::ProtocolLoggingParameters; /// use tap::*; /// /// let params = ProtocolLoggingParameters::new() /// .tap(|params| params.set_prefix("log-prefix-")) /// .tap(|params| params.set_max_log_files(10)); /// ``` #[derive(Debug, Clone)] pub struct ProtocolLoggingParameters { log_prefix: CString, max_log_files: u32, max_log_file_size_bytes: u32, } impl ProtocolLoggingParameters { pub fn new() -> Self { Default::default() } /// Sets the prefix string to be used for log file names. /// /// # Panics /// /// This will panic if `prefix` contains a 0 byte. This is a requirement imposed /// by the underlying SpatialOS API. pub fn set_prefix<T: AsRef<str>>(&mut self, prefix: T) { self.log_prefix = CString::new(prefix.as_ref()).expect("`prefix` contained a null byte"); } /// Sets the maximum number of log files to keep. pub fn set_max_log_files(&mut self, max_log_files: u32) { self.max_log_files = max_log_files; } /// Sets the maximum size in bytes that a single log file can be. /// /// Once an individual log file exceeds this size, a new file will be created. pub fn set_max_log_file_size(&mut self, max_file_size: u32) { self.max_log_file_size_bytes = max_file_size; } /// Converts the logging parameters into the equivalent C API type. /// /// # Safety /// /// The returned `Worker_ProtocolLoggingParameters` borrows data owned by `self`, /// and therefore must not outlive `self`. pub(crate) fn to_worker_sdk(&self) -> Worker_ProtocolLoggingParameters { Worker_ProtocolLoggingParameters { log_prefix: self.log_prefix.as_ptr(), max_log_files: self.max_log_files, max_log_file_size_bytes: self.max_log_file_size_bytes, } } } impl Default for ProtocolLoggingParameters { fn default() -> Self { ProtocolLoggingParameters { log_prefix: CStr::from_bytes_with_nul(&WORKER_DEFAULTS_LOG_PREFIX[..]) .unwrap() .to_owned(), max_log_files: WORKER_DEFAULTS_MAX_LOG_FILES, max_log_file_size_bytes: WORKER_DEFAULTS_MAX_LOG_FILE_SIZE_BYTES, } } } pub struct ThreadAffinityParameters { pub receive_threads_affinity_mask: u64, pub send_threads_affinity_mask: u64, pub temporary_threads_affinity_mask: u64, } impl ThreadAffinityParameters { pub fn default() -> Self { ThreadAffinityParameters { receive_threads_affinity_mask: 0, send_threads_affinity_mask: 0, temporary_threads_affinity_mask: 0, } } pub(crate) fn to_worker_sdk(&self) -> Worker_ThreadAffinityParameters { Worker_ThreadAffinityParameters { receive_threads_affinity_mask: self.receive_threads_affinity_mask, send_threads_affinity_mask: self.send_threads_affinity_mask, temporary_threads_affinity_mask: self.temporary_threads_affinity_mask, } } } /// Helper struct for converting `ConnectionParameters` into `Worker_ConnectionParameters`. pub(crate) struct IntermediateConnectionParameters<'a> { params: &'a ConnectionParameters, protocol: IntermediateProtocolType, } impl<'a> IntermediateConnectionParameters<'a> { pub(crate) fn as_raw(&self) -> Worker_ConnectionParameters { let partial_network_params = Worker_NetworkParameters { use_external_ip: self.params.network.use_external_ip as u8, connection_timeout_millis: self.params.network.connection_timeout_millis, default_command_timeout_millis: self.params.network.default_command_timeout_millis, ..Worker_NetworkParameters::default() }; let network = match &self.protocol { IntermediateProtocolType::Tcp(tcp) => Worker_NetworkParameters { connection_type: Worker_NetworkConnectionType_WORKER_NETWORK_CONNECTION_TYPE_TCP as u8, tcp: *tcp, ..partial_network_params }, IntermediateProtocolType::Udp { security_type, kcp, erasure_codec, heartbeat, flow_control, } => { let kcp = kcp .as_ref() .map(|param| param as *const _) .unwrap_or(ptr::null()); let erasure_codec = erasure_codec .as_ref() .map(|param| param as *const _) .unwrap_or(ptr::null()); let heartbeat = heartbeat .as_ref() .map(|param| param as *const _) .unwrap_or(ptr::null()); let flow_control = flow_control .as_ref() .map(|param| param as *const _) .unwrap_or(ptr::null()); Worker_NetworkParameters { connection_type: Worker_NetworkConnectionType_WORKER_NETWORK_CONNECTION_TYPE_MODULAR_UDP as u8, modular_udp: Worker_Alpha_ModularUdpNetworkParameters { security_type: *security_type, downstream_kcp: kcp, upstream_kcp: kcp, downstream_erasure_codec: erasure_codec, upstream_erasure_codec: erasure_codec, downstream_heartbeat: heartbeat, upstream_heartbeat: heartbeat, flow_control, }, ..partial_network_params } } }; Worker_ConnectionParameters { worker_type: self.params.worker_type.as_ptr(), network, send_queue_capacity: self.params.send_queue_capacity, receive_queue_capacity: self.params.receive_queue_capacity, log_message_queue_capacity: self.params.log_message_queue_capacity, built_in_metrics_report_period_millis: self .params .built_in_metrics_report_period_millis, protocol_logging: self.params.protocol_logging.to_worker_sdk(), enable_protocol_logging_at_startup: self.params.enable_protocol_logging_at_startup as u8, enable_dynamic_components: 0, thread_affinity: self.params.thread_affinity.to_worker_sdk(), component_vtable_count: if self.params.use_internal_serialization { DATABASE.len() as u32 } else { 0 }, component_vtables: if self.params.use_internal_serialization { DATABASE.to_worker_sdk() } else { ptr::null() }, default_component_vtable: if self.params.use_internal_serialization { ptr::null() } else { &vtable::PASSTHROUGH_VTABLE }, } } } enum IntermediateProtocolType { Tcp(Worker_TcpNetworkParameters), Udp { security_type: u8, kcp: Option<Worker_Alpha_KcpParameters>, erasure_codec: Option<Worker_ErasureCodecParameters>, heartbeat: Option<Worker_HeartbeatParameters>, flow_control: Option<Worker_Alpha_FlowControlParameters>, }, }
use bytes::{Buf, Bytes}; use crate::error::Error; use crate::mssql::io::MssqlBufExt; #[allow(dead_code)] #[derive(Debug)] pub(crate) struct Info { pub(crate) number: u32, pub(crate) state: u8, pub(crate) class: u8, pub(crate) message: String, pub(crate) server: String, pub(crate) procedure: String, pub(crate) line: u32, } impl Info { pub(crate) fn get(buf: &mut Bytes) -> Result<Self, Error> { let len = buf.get_u16_le(); let mut data = buf.split_to(len as usize); let number = data.get_u32_le(); let state = data.get_u8(); let class = data.get_u8(); let message = data.get_us_varchar()?; let server = data.get_b_varchar()?; let procedure = data.get_b_varchar()?; let line = data.get_u32_le(); Ok(Self { number, state, class, message, server, procedure, line, }) } } #[test] fn test_get() { #[rustfmt::skip] let mut buf = Bytes::from_static(&[ 0x74, 0, 0x47, 0x16, 0, 0, 1, 0, 0x27, 0, 0x43, 0, 0x68, 0, 0x61, 0, 0x6e, 0, 0x67, 0, 0x65, 0, 0x64, 0, 0x20, 0, 0x6c, 0, 0x61, 0, 0x6e, 0, 0x67, 0, 0x75, 0, 0x61, 0, 0x67, 0, 0x65, 0, 0x20, 0, 0x73, 0, 0x65, 0, 0x74, 0, 0x74, 0, 0x69, 0, 0x6e, 0, 0x67, 0, 0x20, 0, 0x74, 0, 0x6f, 0, 0x20, 0, 0x75, 0, 0x73, 0, 0x5f, 0, 0x65, 0, 0x6e, 0, 0x67, 0, 0x6c, 0, 0x69, 0, 0x73, 0, 0x68, 0, 0x2e, 0, 0xc, 0x61, 0, 0x62, 0, 0x64, 0, 0x30, 0, 0x62, 0, 0x36, 0, 0x37, 0, 0x62, 0, 0x64, 0, 0x34, 0, 0x39, 0, 0x33, 0, 0, 1, 0, 0, 0, 0xad, 0x36, 0, 1, 0x74, 0, 0, 4, 0x16, 0x4d, 0, 0x69, 0, 0x63, 0, 0x72, 0, 0x6f, 0, 0x73, 0, 0x6f, 0, 0x66, 0, 0x74, 0, 0x20, 0, 0x53, 0, 0x51, 0, 0x4c, 0, 0x20, 0, 0x53, 0, 0x65, 0, 0x72, 0, 0x76, 0, 0x65, 0, 0x72, 0, 0, 0, 0, 0, 0xf, 0, 0x10, 0x7f, 0xe3, 0x13, 0, 4, 4, 0x34, 0, 0x30, 0, 0x39, 0, 0x36, 0, 4, 0x34, 0, 0x30, 0, 0x39, 0, 0x36, 0, 0xfd, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]); let info = Info::get(&mut buf).unwrap(); assert_eq!(info.number, 5703); assert_eq!(info.state, 1); assert_eq!(info.class, 0); assert_eq!(info.message, "Changed language setting to us_english."); assert_eq!(info.server, "abd0b67bd493"); assert_eq!(info.procedure, ""); assert_eq!(info.line, 1); }
use super::device::IoKitDevice; use super::traits::DataSource; use crate::platform::traits::BatteryDevice; use crate::units::energy::watt_hour; use crate::units::power::milliwatt; use crate::units::{ElectricCharge, ElectricCurrent, ElectricPotential, ThermodynamicTemperature, Time}; use crate::Result; /// This data source is not using uom types, because it is easier to create test suites /// from the `ioreg` tool output that way (which values are in mV, mA, mAh and mWh). #[derive(Debug, Default)] struct TestDataSource { fully_charged: bool, external_connected: bool, is_charging: bool, voltage: u32, amperage: i32, design_capacity: u32, max_capacity: u32, current_capacity: u32, temperature: Option<f32>, cycle_count: Option<u32>, } impl DataSource for TestDataSource { fn refresh(&mut self) -> Result<()> { Ok(()) } fn fully_charged(&self) -> bool { self.fully_charged } fn external_connected(&self) -> bool { self.external_connected } fn is_charging(&self) -> bool { self.is_charging } fn voltage(&self) -> ElectricPotential { millivolt!(self.voltage) } fn amperage(&self) -> ElectricCurrent { milliampere!(self.amperage.abs()) } fn design_capacity(&self) -> ElectricCharge { milliampere_hour!(self.design_capacity) } fn max_capacity(&self) -> ElectricCharge { milliampere_hour!(self.max_capacity) } fn current_capacity(&self) -> ElectricCharge { milliampere_hour!(self.current_capacity) } fn temperature(&self) -> Option<ThermodynamicTemperature> { self.temperature.map(|value| celsius!(value)) } fn cycle_count(&self) -> Option<u32> { self.cycle_count } fn time_remaining(&self) -> Option<Time> { None } fn manufacturer(&self) -> Option<&str> { None } fn device_name(&self) -> Option<&str> { None } fn serial_number(&self) -> Option<&str> { None } } // Based on the https://github.com/svartalf/rust-battery/issues/8 #[test] fn test_energy_calculation() { let data = TestDataSource { current_capacity: 3938, design_capacity: 4315, max_capacity: 4119, voltage: 12818, amperage: -1037, ..Default::default() }; let device: IoKitDevice = data.into(); // TODO: It would be nice to use some approximate equal asserts here, // but for now it is enough to check if values are kinda similar to expected // and we are not comparing milliwatts to megawatts assert_eq!(device.energy_rate().get::<milliwatt>().floor(), 13292.0); assert_eq!(device.energy().get::<watt_hour>().floor(), 50.0); assert_eq!(device.energy_full().get::<watt_hour>().floor(), 52.0); assert_eq!(device.energy_full_design().get::<watt_hour>().floor(), 55.0); }
use std::{collections::HashMap, fmt, path::Path, time::Instant}; use httpserv::*; #[derive(Debug)] pub enum ArgFail { InvalidFormat(String), } impl fmt::Display for ArgFail { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ArgFail::InvalidFormat(s) => { write!(f, "'{}' is incorrectly formatted", s) } } } } fn get_cfg(args: impl Iterator<Item = String>) -> Result<Config, ArgFail> { let mut args = args.skip(1); let root = Path::new(&args.next().unwrap_or(".".into())).to_path_buf(); let hostname = args.next().unwrap_or("localhost:8080".into()); let mut mappings = HashMap::new(); mappings.insert("html".into(), "text/html;charset=utf-8".into()); mappings.insert("css".into(), "text/css;charset=utf-8".into()); mappings.insert("js".into(), "text/javascript;charset=utf-8".into()); mappings.insert("png".into(), "image/png".into()); mappings.insert("jpg".into(), "image/jpeg".into()); mappings.insert("jpeg".into(), "image/jpeg".into()); mappings.insert("ico".into(), "image/vnd.microsoft.icon".into()); mappings.insert("svg".into(), "image/svg+xml".into()); mappings.insert("wasm".into(), "application/wasm".into()); mappings.insert("pdf".into(), "application/pdf".into()); mappings.insert("pdf".into(), "application/pdf".into()); mappings.insert("zip".into(), "application/zip".into()); for pair in args { let eq_idx = pair .find("=") .ok_or_else(|| ArgFail::InvalidFormat(pair.clone()))?; let (ext, mime) = pair.split_at(eq_idx); let (_, mime) = mime.split_at(1); mappings.insert(ext.into(), mime.into()); } Ok(Config { root, hostname, mappings, log: true, }) } fn main() { let load_start = Instant::now(); let cfg = match get_cfg(std::env::args()) { Ok(c) => c, Err(e) => { println!("Failed to get config: {:?}", e); return; } }; let mut server = match Httpserv::new(cfg) { Ok(s) => s, Err(e) => { println!("Failed to launch server: {:?}", e); return; } }; println!( "Launched in {}us; listening on {}; serving from {}", (Instant::now() - load_start).as_micros(), server.config().hostname, server.config().root.display() ); server.run(); } #[cfg(test)] mod tests { use super::*; use std::ffi::OsStr; #[test] fn with_no_args() { let cfg = get_cfg(vec!["".into()].into_iter()); if let Ok(cfg) = cfg { assert_eq!( cfg.root, Path::new(".").to_path_buf(), "default root not cwd" ); assert_eq!( cfg.hostname, "localhost:8080", "default hostname not localhost:8080" ); assert_eq!( cfg.mappings.get(OsStr::new("html")), Some(&"text/html;charset=utf-8".into()), "mappings[html] is wrong" ); assert_eq!( cfg.mappings.get(OsStr::new("css")), Some(&"text/css;charset=utf-8".into()), "mappings[css] is wrong" ); assert_eq!( cfg.mappings.get(OsStr::new("js")), Some(&"text/javascript;charset=utf-8".into()), "mappings[js] is wrong" ); assert_eq!( cfg.mappings.get(OsStr::new("png")), Some(&"image/png".into()), "mappings[png] is wrong" ); assert_eq!( cfg.mappings.get(OsStr::new("jpg")), Some(&"image/jpeg".into()), "mappings[jpg] is wrong" ); assert_eq!( cfg.mappings.get(OsStr::new("jpeg")), Some(&"image/jpeg".into()), "mappings[jpeg] is wrong" ); assert_eq!( cfg.mappings.get(OsStr::new("ico")), Some(&"image/vnd.microsoft.icon".into()), "mappings[ico] is wrong" ); assert_eq!( cfg.mappings.get(OsStr::new("svg")), Some(&"image/svg+xml".into()), "mappings[svg] is wrong" ); assert!(cfg.log, "not logging timings by default"); } else { assert!(false, "Getting config returned error"); } } #[test] fn given_root() { let cfg = get_cfg(vec!["", "foo/bar/../baz"].into_iter().map(Into::into)); if let Ok(cfg) = cfg { assert_eq!( cfg.root, Path::new("foo/bar/../baz").to_path_buf(), "given root doesn't match" ); } else { assert!(false, "Getting config returned error"); } } #[test] fn given_hostname() { let cfg = get_cfg(vec!["", "", "laksdla:12313"].into_iter().map(Into::into)); if let Ok(cfg) = cfg { assert_eq!( cfg.hostname, "laksdla:12313", "given hostname doesn't match" ); } else { assert!(false, "Getting config returned error"); } } #[test] fn given_mappings() { let cfg = get_cfg(vec!["", "", "", "a=b", "c=d"].into_iter().map(Into::into)); if let Ok(cfg) = cfg { assert_eq!( cfg.mappings.get(OsStr::new("html")), Some(&"text/html;charset=utf-8".into()), "Old mapping was changed" ); assert_eq!( cfg.mappings.get(OsStr::new("css")), Some(&"text/css;charset=utf-8".into()), "Old mapping was changed" ); assert_eq!( cfg.mappings.get(OsStr::new("js")), Some(&"text/javascript;charset=utf-8".into()), "Old mapping was changed" ); assert_eq!( cfg.mappings.get(OsStr::new("png")), Some(&"image/png".into()), "Old mapping was changed" ); assert_eq!( cfg.mappings.get(OsStr::new("jpg")), Some(&"image/jpeg".into()), "Old mapping was changed" ); assert_eq!( cfg.mappings.get(OsStr::new("jpeg")), Some(&"image/jpeg".into()), "Old mapping was changed" ); assert_eq!( cfg.mappings.get(OsStr::new("ico")), Some(&"image/vnd.microsoft.icon".into()), "Old mapping was changed" ); assert_eq!( cfg.mappings.get(OsStr::new("svg")), Some(&"image/svg+xml".into()), "Old mapping was changed" ); assert_eq!( cfg.mappings.get(OsStr::new("a")), Some(&"b".into()), "mappings[a] is wrong" ); assert_eq!( cfg.mappings.get(OsStr::new("c")), Some(&"d".into()), "mappings[c] is wrong" ); } else { assert!(false, "Getting config returned error"); } } #[test] fn overwritten_mappings() { let cfg = get_cfg( vec!["", "", "", "ico=foobar", "jpg=baz"] .into_iter() .map(Into::into), ); if let Ok(cfg) = cfg { assert_eq!( cfg.mappings.get(OsStr::new("ico")), Some(&"foobar".into()), "overwritten mappings[ico] is wrong" ); assert_eq!( cfg.mappings.get(OsStr::new("jpg")), Some(&"baz".into()), "overwritten mappings[jpg] is wrong" ); } else { assert!(false, "Getting config returned error"); } } }
// Copyright 2021 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. mod query_affect; pub mod query_ctx; mod query_ctx_shared; mod session; mod session_ctx; mod session_info; mod session_mgr; mod session_mgr_status; mod session_status; mod session_type; pub use common_catalog::table_context::TableContext; pub use query_affect::QueryAffect; pub use query_ctx::QueryContext; pub use query_ctx_shared::QueryContextShared; pub use session::Session; pub use session_ctx::SessionContext; pub use session_info::ProcessInfo; pub use session_mgr::SessionManager; pub use session_mgr_status::SessionManagerStatus; pub use session_status::SessionStatus; pub use session_type::SessionType;
// "Tifflin" Kernel - Networking Stack // - By John Hodge (thePowersGang) // // Modules/network/tcp.rs //! Transmission Control Protocol (Layer 4) use shared_map::SharedMap; use kernel::sync::Mutex; use kernel::lib::ring_buffer::{RingBuf,AtomicRingBuf}; use core::sync::atomic::{AtomicUsize, Ordering}; use crate::nic::SparsePacket; use crate::Address; const IPV4_PROTO_TCP: u8 = 6; const MAX_WINDOW_SIZE: u32 = 0x100000; // 4MiB const DEF_WINDOW_SIZE: u32 = 0x4000; // 16KiB pub fn init() { ::ipv4::register_handler(IPV4_PROTO_TCP, rx_handler_v4).unwrap(); } #[path="tcp-lib/"] /// Library types just for TCP mod lib { pub mod rx_buffer; } use self::lib::rx_buffer::RxBuffer; static CONNECTIONS: SharedMap<Quad, Mutex<Connection>> = SharedMap::new(); static PROTO_CONNECTIONS: SharedMap<Quad, ProtoConnection> = SharedMap::new(); static SERVERS: SharedMap<(Option<Address>,u16), Server> = SharedMap::new(); static S_PORTS: Mutex<PortPool> = Mutex::new(PortPool::new()); /// Find the local source address for the given remote address // TODO: Shouldn't this get an interface handle instead? fn get_outbound_ip_for(addr: &Address) -> Option<Address> { match addr { Address::Ipv4(addr) => crate::ipv4::route_lookup(crate::ipv4::Address::zero(), *addr).map(|(laddr, _, _)| Address::Ipv4(laddr)), } } /// Allocate a port for the given local address fn allocate_port(_addr: &Address) -> Option<u16> { // TODO: Could store bitmap against the interface (having a separate bitmap for each interface) S_PORTS.lock().allocate() } fn release_port(_addr: &Address, idx: u16) { S_PORTS.lock().release(idx) } fn rx_handler_v4(int: &::ipv4::Interface, src_addr: ::ipv4::Address, pkt: ::nic::PacketReader) { rx_handler(Address::Ipv4(src_addr), Address::Ipv4(int.addr()), pkt) } fn rx_handler(src_addr: Address, dest_addr: Address, mut pkt: ::nic::PacketReader) { let pre_header_reader = pkt.clone(); let hdr = match PktHeader::read(&mut pkt) { Ok(v) => v, Err(_) => { log_error!("Undersized packet: Ran out of data reading header"); return ; }, }; log_debug!("hdr = {:?}", hdr); let hdr_len = hdr.get_header_size(); if hdr_len < pre_header_reader.remain() { log_error!("Undersized or invalid packet: Header length is {} but packet length is {}", hdr_len, pre_header_reader.remain()); return ; } // TODO: Validate checksum. { let packet_len = pre_header_reader.remain(); // Pseudo header for checksum let sum_pseudo = match (src_addr,dest_addr) { (Address::Ipv4(s), Address::Ipv4(d)) => ::ipv4::calculate_checksum([ // Big endian stores MSB first, so write the high word first (s.as_u32() >> 16) as u16, (s.as_u32() >> 0) as u16, (d.as_u32() >> 16) as u16, (d.as_u32() >> 0) as u16, IPV4_PROTO_TCP as u16, packet_len as u16, ].iter().copied()), }; let sum_header = hdr.checksum(); let sum_options_and_data = { let mut pkt = pkt.clone(); let psum_whole = !::ipv4::calculate_checksum( (0 .. (pre_header_reader.remain() - hdr_len) / 2).map(|_| pkt.read_u16n().unwrap()) ); // Final byte is decoded as if there was a zero after it (so as 0x??00) let psum_partial = if pkt.remain() > 0 { (pkt.read_u8().unwrap() as u16) << 8} else { 0 }; ::ipv4::calculate_checksum([psum_whole, psum_partial].iter().copied()) }; let sum_total = ::ipv4::calculate_checksum([ !sum_pseudo, !sum_header, !sum_options_and_data ].iter().copied()); if sum_total != 0 { log_error!("Incorrect checksum: 0x{:04x} != 0", sum_total); } } // Options while pkt.remain() > pre_header_reader.remain() - hdr_len { match pkt.read_u8().unwrap() { _ => {}, } } let quad = Quad::new(dest_addr, hdr.dest_port, src_addr, hdr.source_port); // Search for active connections with this quad if let Some(c) = CONNECTIONS.get(&quad) { c.lock().handle(&quad, &hdr, pkt); } // Search for proto-connections // - Proto-connections are lighter weight than full-blown connections, reducing the impact of a SYN flood else if hdr.flags == FLAG_ACK { if let Some(c) = PROTO_CONNECTIONS.take(&quad) { // Check the SEQ/ACK numbers, and create the actual connection if hdr.sequence_number == c.seen_seq + 1 && hdr.acknowledgement_number == c.sent_seq { // Make the full connection struct CONNECTIONS.insert(quad, Mutex::new(Connection::new_inbound(&hdr))); // Add the connection onto the server's accept queue let server = Option::or( SERVERS.get( &(Some(dest_addr), hdr.dest_port) ), SERVERS.get( &(None, hdr.dest_port) ) ).expect("Can't find server"); server.accept_queue.push(quad).expect("Acceped connection with full accept queue"); } else { // - Bad ACK, put the proto connection back into the list PROTO_CONNECTIONS.insert(quad, c); } } } // If none found, look for servers on the destination (if SYN) else if hdr.flags & !FLAG_ACK == FLAG_SYN { if let Some(s) = Option::or( SERVERS.get( &(Some(dest_addr), hdr.dest_port) ), SERVERS.get( &(None, hdr.dest_port) ) ) { // Decrement the server's accept space if s.accept_space.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| if v == 0 { None } else { Some(v - 1) }).is_err() { // Reject if no space // - Send a RST quad.send_packet(hdr.acknowledgement_number, hdr.sequence_number, FLAG_RST, 0, &[]); } else { // - Add the quad as a proto-connection and send the SYN-ACK let pc = ProtoConnection::new(hdr.sequence_number); quad.send_packet(pc.sent_seq, pc.seen_seq, FLAG_SYN|FLAG_ACK, hdr.window_size, &[]); PROTO_CONNECTIONS.insert(quad, pc); } } else { // Send a RST quad.send_packet(hdr.acknowledgement_number, hdr.sequence_number, FLAG_RST|(!hdr.flags & FLAG_ACK), 0, &[]); } } // Otherwise, drop } #[derive(Copy,Clone,PartialOrd,PartialEq,Ord,Eq)] struct Quad { local_addr: Address, local_port: u16, remote_addr: Address, remote_port: u16, } impl ::core::fmt::Debug for Quad { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "Quad({:?}:{} -> {:?}:{})", self.local_addr, self.local_port, self.remote_addr, self.remote_port) } } impl Quad { fn new(local_addr: Address, local_port: u16, remote_addr: Address, remote_port: u16) -> Quad { Quad { local_addr, local_port, remote_addr, remote_port } } fn send_packet(&self, seq: u32, ack: u32, flags: u8, window_size: u16, data: &[u8]) { // Make a header // TODO: Any options required? let options_bytes = &[]; let opts_len_rounded = ((options_bytes.len() + 3) / 4) * 4; let hdr = PktHeader { source_port: self.local_port, dest_port: self.remote_port, sequence_number: seq, acknowledgement_number: ack, data_offset: ((5 + opts_len_rounded/4) << 4) as u8 | 0, flags: flags, window_size: window_size, checksum: 0, // To be filled afterwards urgent_pointer: 0, }.as_bytes(); // Calculate checksum // Create sparse packet chain let data_pkt = SparsePacket::new_root(data); // - Padding required to make the header a multiple of 4 bytes long let opt_pad_pkt = SparsePacket::new_chained(&[0; 3][.. opts_len_rounded - options_bytes.len()], &data_pkt); let opt_pkt = SparsePacket::new_chained(options_bytes, &opt_pad_pkt); let hdr_pkt = SparsePacket::new_chained(&hdr, &opt_pkt); // Pass packet downstream match self.local_addr { Address::Ipv4(a) => crate::ipv4::send_packet(a, self.remote_addr.unwrap_ipv4(), IPV4_PROTO_TCP, hdr_pkt), } } } #[derive(Debug)] struct PktHeader { source_port: u16, dest_port: u16, sequence_number: u32, acknowledgement_number: u32, /// Packed: top 4 bits are header size in 4byte units, bottom 4 are reserved data_offset: u8, /// Bitfield: /// 0: FIN /// 1: SYN /// 2: RST /// 3: PSH /// 4: ACK /// 5: URG /// 6: ECE /// 7: CWR flags: u8, window_size: u16, checksum: u16, urgent_pointer: u16, //options: [u8], } const FLAG_FIN: u8 = 1 << 0; const FLAG_SYN: u8 = 1 << 1; const FLAG_RST: u8 = 1 << 2; const FLAG_PSH: u8 = 1 << 3; const FLAG_ACK: u8 = 1 << 4; impl PktHeader { fn read(reader: &mut ::nic::PacketReader) -> Result<Self, ()> { Ok(PktHeader { source_port: reader.read_u16n()?, dest_port: reader.read_u16n()?, sequence_number: reader.read_u32n()?, acknowledgement_number: reader.read_u32n()?, data_offset: reader.read_u8()?, flags: reader.read_u8()?, window_size: reader.read_u16n()?, checksum: reader.read_u16n()?, urgent_pointer: reader.read_u16n()?, }) // TODO: Check checksum? } fn get_header_size(&self) -> usize { (self.data_offset >> 4) as usize * 4 } fn as_bytes(&self) -> [u8; 5*4] { [ (self.source_port >> 8) as u8, (self.source_port >> 0) as u8, (self.dest_port >> 8) as u8, (self.dest_port >> 0) as u8, (self.sequence_number >> 24) as u8, (self.sequence_number >> 16) as u8, (self.sequence_number >> 8) as u8, (self.sequence_number >> 0) as u8, (self.acknowledgement_number >> 24) as u8, (self.acknowledgement_number >> 16) as u8, (self.acknowledgement_number >> 8) as u8, (self.acknowledgement_number >> 0) as u8, self.data_offset, self.flags, (self.window_size >> 8) as u8, (self.window_size >> 0) as u8, (self.checksum >> 8) as u8, (self.checksum >> 0) as u8, (self.urgent_pointer >> 8) as u8, (self.urgent_pointer >> 0) as u8, ] } fn as_u16s(&self) -> [u16; 5*2] { [ self.source_port, self.dest_port, (self.sequence_number >> 16) as u16, (self.sequence_number >> 0) as u16, (self.acknowledgement_number >> 16) as u16, (self.acknowledgement_number >> 0) as u16, (self.data_offset as u16) << 8 | (self.flags as u16), self.window_size, self.checksum, self.urgent_pointer, ] } fn checksum(&self) -> u16 { ::ipv4::calculate_checksum(self.as_u16s().iter().cloned()) } } struct Connection { state: ConnectionState, /// Sequence number of the next expected remote byte next_rx_seq: u32, /// Last ACKed sequence number last_rx_ack: u32, /// Received bytes rx_buffer: RxBuffer, /// Sequence number of the first byte in the RX buffer rx_buffer_seq: u32, rx_window_size_max: u32, rx_window_size: u32, /// Sequence number of last transmitted byte last_tx_seq: u32, /// Buffer of transmitted but not ACKed bytes tx_buffer: RingBuf<u8>, /// Offset of bytes actually sent (not just buffered) tx_bytes_sent: usize, /// Last received transmit window size tx_window_size: u32, } #[derive(Copy,Clone,Debug,PartialEq)] enum ConnectionState { //Closed, // Unused SynSent, // SYN sent by local, waiting for SYN-ACK //SynReceived, // Server only, handled by PROTO_CONNECTIONS Established, FinWait1, // FIN sent, waiting for reply (ACK or FIN) FinWait2, // sent FIN acked, waiting for FIN from peer Closing, // Waiting for ACK of FIN (FIN sent and recieved) TimeWait, // Waiting for timeout after local close ForceClose, // RST recieved, waiting for user close CloseWait, // FIN recieved, waiting for user to close (error set, wait for node close) LastAck, // FIN sent and recieved, waiting for ACK Finished, } impl Connection { /// Create a new connection from the ACK in a SYN-SYN,ACK-ACK fn new_inbound(hdr: &PktHeader) -> Self { Connection { state: ConnectionState::Established, next_rx_seq: hdr.sequence_number, last_rx_ack: hdr.sequence_number, rx_buffer_seq: hdr.sequence_number, rx_buffer: RxBuffer::new(2*DEF_WINDOW_SIZE as usize), rx_window_size_max: MAX_WINDOW_SIZE, // Can be updated by the user rx_window_size: DEF_WINDOW_SIZE, last_tx_seq: hdr.acknowledgement_number, tx_buffer: RingBuf::new(2048),//hdr.window_size as usize), tx_bytes_sent: 0, tx_window_size: hdr.window_size as u32, } } fn new_outbound(quad: &Quad, sequence_number: u32) -> Self { log_trace!("Connection::new_outbound({:?}, {:#x})", quad, sequence_number); let mut rv = Connection { state: ConnectionState::SynSent, next_rx_seq: 0, last_rx_ack: 0, rx_buffer_seq: 0, rx_buffer: RxBuffer::new(2*DEF_WINDOW_SIZE as usize), rx_window_size_max: MAX_WINDOW_SIZE, // Can be updated by the user rx_window_size: DEF_WINDOW_SIZE, last_tx_seq: sequence_number, tx_buffer: RingBuf::new(2048), tx_bytes_sent: 0, tx_window_size: 0,//hdr.window_size as u32, }; rv.send_packet(quad, FLAG_SYN, &[]); rv } /// Handle inbound data fn handle(&mut self, quad: &Quad, hdr: &PktHeader, mut pkt: ::nic::PacketReader) { match self.state { //ConnectionState::Closed => return, ConnectionState::Finished => return, _ => {}, } // Synchronisation request if hdr.flags & FLAG_SYN != 0 { // TODO: Send an ACK of the last recieved byte (should this be conditional?) if self.last_rx_ack != self.next_rx_seq { } //self.next_rx_seq = hdr.sequence_number; } // ACK of sent data if hdr.flags & FLAG_ACK != 0 { let in_flight = (self.last_tx_seq - hdr.acknowledgement_number) as usize; if in_flight > self.tx_buffer.len() { // TODO: Error, something funky has happened } else { let n_bytes = self.tx_buffer.len() - in_flight; log_debug!("{:?} ACQ {} bytes", quad, n_bytes); for _ in 0 .. n_bytes { self.tx_buffer.pop_front(); } } } // Update the window size if it changes if self.tx_window_size != hdr.window_size as u32 { self.tx_window_size = hdr.window_size as u32; } let new_state = match self.state { //ConnectionState::Closed => return, // SYN sent by local, waiting for SYN-ACK ConnectionState::SynSent => { if hdr.flags & FLAG_SYN != 0 { self.next_rx_seq += 1; if hdr.flags & FLAG_ACK != 0 { // Now established // TODO: Send ACK back self.send_ack(quad, "SYN-ACK"); ConnectionState::Established } else { // Why did we get a plain SYN in this state? self.state } } else { // Ignore non-SYN self.state } }, ConnectionState::Established => if hdr.flags & FLAG_RST != 0 { // RST received, do an unclean close (reset by peer) // TODO: Signal to user that the connection is closing (error) ConnectionState::ForceClose } else if hdr.flags & FLAG_FIN != 0 { // FIN received, start a clean shutdown self.next_rx_seq += 1; // TODO: Signal to user that the connection is closing (EOF) ConnectionState::CloseWait } else { if pkt.remain() == 0 { // Pure ACK, no change if hdr.flags == FLAG_ACK { log_trace!("{:?} ACK only", quad); } else if self.next_rx_seq != hdr.sequence_number { log_trace!("{:?} Empty packet, unexpected seqeunce number {:x} != {:x}", quad, hdr.sequence_number, self.next_rx_seq); } else { // Counts as one byte self.next_rx_seq += 1; self.send_ack(quad, "Empty"); } } else if hdr.sequence_number - self.next_rx_seq + pkt.remain() as u32 > MAX_WINDOW_SIZE { // Completely out of sequence } else { // In sequence. let mut start_ofs = (hdr.sequence_number - self.next_rx_seq) as i32; while start_ofs < 0 { pkt.read_u8().unwrap(); start_ofs += 1; } let mut ofs = start_ofs as usize; while let Ok(b) = pkt.read_u8() { match self.rx_buffer.insert( (self.next_rx_seq - self.rx_buffer_seq) as usize + ofs, &[b]) { Ok(_) => {}, Err(e) => { log_error!("{:?} RX buffer push {:?}", quad, e); break; }, } ofs += 1; } // Better idea: Have an ACQ point, and a window point. Buffer is double the window // Once the window point reaches 25% of the window from the ACK point if start_ofs == 0 { self.next_rx_seq += ofs as u32; // Calculate a maximum window size based on how much space is left in the buffer let buffered_len = self.next_rx_seq - self.rx_buffer_seq; // How much data the user has buffered let cur_max_window = 2*self.rx_window_size_max - buffered_len; // NOTE: 2* for some flex so the window can stay at max size if cur_max_window < self.rx_window_size { // Reduce the window size and send an ACQ (with the updated size) while cur_max_window < self.rx_window_size { self.rx_window_size /= 2; } self.send_ack(quad, "Constrain window"); } else if self.next_rx_seq - self.last_rx_ack > self.rx_window_size/2 { // Send an ACK now, we've recieved a burst of data self.send_ack(quad, "Data burst"); } else { // TODO: Schedule an ACK in a few hundred milliseconds } } if hdr.flags & FLAG_PSH != 0 { // TODO: Prod the user that there's new data? } } self.state }, ConnectionState::CloseWait => { // Ignore all packets while waiting for the user to complete teardown self.state }, ConnectionState::LastAck => // Waiting for ACK in FIN,FIN/ACK,ACK if hdr.flags & FLAG_ACK != 0 { ConnectionState::Finished } else { self.state }, ConnectionState::FinWait1 => // FIN sent, waiting for reply (ACK or FIN) if hdr.flags & FLAG_FIN != 0 { // TODO: Check the sequence number vs the sequence for the FIN self.send_ack(quad, "SYN-ACK"); ConnectionState::Closing } else if hdr.flags & FLAG_ACK != 0 { // TODO: Check the sequence number vs the sequence for the FIN ConnectionState::FinWait2 } else { self.state }, ConnectionState::FinWait2 => if hdr.flags & FLAG_FIN != 0 { // Got a FIN after the ACK, close ConnectionState::TimeWait } else { self.state }, ConnectionState::Closing => if hdr.flags & FLAG_ACK != 0 { // TODO: Check the sequence number vs the sequence for the FIN ConnectionState::TimeWait } else { self.state }, ConnectionState::ForceClose => self.state, ConnectionState::TimeWait => self.state, ConnectionState::Finished => return, }; self.state_update(quad, new_state); } fn state_update(&mut self, quad: &Quad, new_state: ConnectionState) { if self.state != new_state { log_trace!("{:?} {:?} -> {:?}", quad, self.state, new_state); self.state = new_state; // TODO: If transitioning to `Finished`, release the local port? // - Only for client connections. if let ConnectionState::Finished = self.state { release_port(&quad.local_addr, quad.local_port); } } } fn state_to_error(&self) -> Result<(), ConnError> { match self.state { ConnectionState::SynSent => { todo!("(quad=?) send/recv before established"); }, ConnectionState::Established => Ok( () ), ConnectionState::FinWait1 | ConnectionState::FinWait2 | ConnectionState::Closing | ConnectionState::TimeWait => Err( ConnError::LocalClosed ), ConnectionState::ForceClose => Err( ConnError::RemoteReset ), ConnectionState::CloseWait | ConnectionState::LastAck => Err( ConnError::RemoteClosed ), ConnectionState::Finished => Err( ConnError::LocalClosed ), } } fn send_data(&mut self, quad: &Quad, buf: &[u8]) -> Result<usize, ConnError> { // TODO: Is it valid to send before the connection is fully established? self.state_to_error()?; // 1. Determine how much data we can send (based on the TX window) let max_len = usize::saturating_sub(self.tx_window_size as usize, self.tx_buffer.len()); let rv = ::core::cmp::min(buf.len(), max_len); // Add the data to the TX buffer for &b in &buf[..rv] { self.tx_buffer.push_back(b).expect("Incorrectly calculated `max_len` in tcp::Connection::send_data"); } // If the buffer is full enough, do a send if self.tx_buffer.len() - self.tx_bytes_sent > 1400 /*|| self.first_tx_time.map(|t| now() - t > MAX_TX_DELAY).unwrap_or(false)*/ { // Trigger a TX self.flush_send(quad); } else { // Kick a short timer, which will send data after it expires // - Keep kicking the timer as data flows through // - Have a maximum elapsed time with no packet sent. //if self.tx_timer.reset(MIN_TX_DELAY) == timer::ResetResult::WasStopped //{ // self.first_tx_time = Some(now()); //} } todo!("{:?} send_data( min({}, {})={} )", quad, max_len, buf.len(), rv); } fn flush_send(&mut self, quad: &Quad) { loop { let nbytes = self.tx_buffer.len() - self.tx_bytes_sent; todo!("{:?} tx {}", quad, nbytes); } //self.first_tx_time = None; } fn recv_data(&mut self, _quad: &Quad, buf: &mut [u8]) -> Result<usize, ConnError> { self.state_to_error()?; //let valid_len = self.rx_buffer.valid_len(); //let acked_len = u32::wrapping_sub(self.next_rx_seq, self.rx_buffer_seq); //let len = usize::min(valid_len, buf.len()); Ok( self.rx_buffer.take(buf) ) } fn send_packet(&mut self, quad: &Quad, flags: u8, data: &[u8]) { log_debug!("{:?} send_packet({:02x} {}b)", quad, flags, data.len()); quad.send_packet(self.last_tx_seq, self.next_rx_seq, flags, self.rx_window_size as u16, data); } fn send_ack(&mut self, quad: &Quad, msg: &str) { log_debug!("{:?} send_ack({:?})", quad, msg); // - TODO: Cancel any pending ACK // - Send a new ACK self.send_packet(quad, FLAG_ACK, &[]); } fn close(&mut self, quad: &Quad) -> Result<(), ConnError> { let new_state = match self.state { ConnectionState::SynSent => { todo!("{:?} close before established", quad); }, ConnectionState::FinWait1 | ConnectionState::FinWait2 | ConnectionState::Closing | ConnectionState::TimeWait => return Err( ConnError::LocalClosed ), ConnectionState::LastAck => return Err( ConnError::RemoteClosed ), ConnectionState::Finished => return Err( ConnError::LocalClosed ), ConnectionState::CloseWait => { self.send_packet(quad, FLAG_FIN|FLAG_ACK, &[]); ConnectionState::LastAck }, ConnectionState::ForceClose => { ConnectionState::Finished }, ConnectionState::Established => { self.send_packet(quad, FLAG_FIN, &[]); ConnectionState::FinWait1 }, }; self.state_update(quad, new_state); Ok( () ) } } struct ProtoConnection { seen_seq: u32, sent_seq: u32, } impl ProtoConnection { fn new(seen_seq: u32) -> ProtoConnection { ProtoConnection { seen_seq: seen_seq, sent_seq: 1, // TODO: Random } } } struct Server { // Amount of connections that can still be accepted accept_space: AtomicUsize, // Established connections waiting for the user to accept accept_queue: AtomicRingBuf<Quad>, } pub struct ConnectionHandle(Quad); #[derive(Debug)] pub enum ConnError { NoRoute, LocalClosed, RemoteRefused, RemoteClosed, RemoteReset, NoPortAvailable, } impl ConnectionHandle { pub fn connect(addr: Address, port: u16) -> Result<ConnectionHandle, ConnError> { log_trace!("ConnectionHandle::connect({:?}, {})", addr, port); // 1. Determine the local address for this remote address let local_addr = match get_outbound_ip_for(&addr) { Some(a) => a, None => return Err(ConnError::NoRoute), }; // 2. Pick a local port let local_port = match allocate_port(&local_addr) { Some(p) => p, None => return Err(ConnError::NoPortAvailable), }; // 3. Create the quad and allocate the connection structure let quad = Quad::new(local_addr, local_port, addr, port, ); log_trace!("ConnectionHandle::connect: quad={:?}", quad); // 4. Send the opening SYN (by creating the outbound connection structure) let conn = Connection::new_outbound(&quad, 0x10000u32); CONNECTIONS.insert(quad, Mutex::new(conn)); Ok( ConnectionHandle(quad) ) } pub fn send_data(&self, buf: &[u8]) -> Result<usize, ConnError> { match CONNECTIONS.get(&self.0) { None => panic!("Connection {:?} removed before handle dropped", self.0), Some(v) => v.lock().send_data(&self.0, buf), } } pub fn recv_data(&self, buf: &mut [u8]) -> Result<usize, ConnError> { match CONNECTIONS.get(&self.0) { None => panic!("Connection {:?} removed before handle dropped", self.0), Some(v) => v.lock().recv_data(&self.0, buf), } } pub fn close(&mut self) -> Result<(), ConnError> { match CONNECTIONS.get(&self.0) { None => panic!("Connection {:?} removed before handle dropped", self.0), Some(v) => v.lock().close(&self.0), } } } impl ::core::ops::Drop for ConnectionHandle { fn drop(&mut self) { // Mark the connection to close } } const MIN_DYN_PORT: u16 = 0xC000; const N_DYN_PORTS: usize = (1<<16) - MIN_DYN_PORT as usize; struct PortPool { bitmap: [u32; N_DYN_PORTS / 32], //n_free_ports: u16, next_port: u16, } impl PortPool { const fn new() -> PortPool { PortPool { bitmap: [0; N_DYN_PORTS / 32], //n_free_ports: N_DYN_PORTS as u16, next_port: MIN_DYN_PORT, } } fn ofs_mask(idx: u16) -> Option<(usize, u32)> { if idx >= MIN_DYN_PORT { let ofs = (idx - MIN_DYN_PORT) as usize / 32; let mask = 1 << (idx % 32); Some( (ofs, mask) ) } else { None } } fn take(&mut self, idx: u16) -> Result<(),()> { let (ofs,mask) = match Self::ofs_mask(idx) { Some(v) => v, None => return Ok(()), }; if self.bitmap[ofs] & mask != 0 { Err( () ) } else { self.bitmap[ofs] |= mask; Ok( () ) } } fn release(&mut self, idx: u16) { let (ofs,mask) = match Self::ofs_mask(idx) { Some(v) => v, None => return, }; self.bitmap[ofs] &= !mask; } fn allocate(&mut self) -> Option<u16> { // Strategy: Linear ('cos it's easy) for idx in self.next_port ..= 0xFFFF { match self.take(idx) { Ok(_) => { self.next_port = idx; return Some(idx); }, _ => {}, } } for idx in MIN_DYN_PORT .. self.next_port { match self.take(idx) { Ok(_) => { self.next_port = idx; return Some(idx); }, _ => {}, } } None } }
/* Copyright 2020 Timo Saarinen 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 super::*; /// VTG - track made good and speed over ground #[derive(Clone, Debug, PartialEq)] pub struct VtgData { /// Navigation system pub source: NavigationSystem, /// Course over ground (CoG), degrees True pub cog_true: Option<f64>, /// Course over ground (CoG), degrees Magnetic pub cog_magnetic: Option<f64>, /// Speed over ground (SoG), knots pub sog_knots: Option<f64>, /// Speed over ground (SoG), km/h pub sog_kph: Option<f64>, /// FAA mode indicator pub faa_mode: Option<FaaMode>, } // ------------------------------------------------------------------------------------------------- /// xxVTG: Track Made Good and Ground Speed pub(crate) fn handle( sentence: &str, nav_system: NavigationSystem, ) -> Result<ParsedMessage, ParseError> { let split: Vec<&str> = sentence.split(',').collect(); Ok(ParsedMessage::Vtg(VtgData { source: nav_system, cog_true: pick_number_field(&split, 1).ok().unwrap_or(None), cog_magnetic: pick_number_field(&split, 3).ok().unwrap_or(None), sog_knots: pick_number_field(&split, 5).ok().unwrap_or(None), sog_kph: pick_number_field(&split, 7).ok().unwrap_or(None), faa_mode: FaaMode::new(split.get(9).unwrap_or(&"")).ok(), })) } // ------------------------------------------------------------------------------------------------- #[cfg(test)] mod test { use super::*; #[test] fn test_parse_bdvtg() { let mut p = NmeaParser::new(); match p.parse_sentence("$BDVTG,054.7,T,034.4,M,005.5,N,010.2,K,D*31") { Ok(ps) => { match ps { // The expected result ParsedMessage::Vtg(vtg) => { assert_eq!(vtg.source, NavigationSystem::Beidou); assert::close(vtg.cog_true.unwrap_or(0.0), 54.7, 0.1); assert::close(vtg.cog_magnetic.unwrap_or(0.0), 34.4, 0.1); assert::close(vtg.sog_knots.unwrap_or(0.0), 5.5, 0.1); assert::close(vtg.sog_kph.unwrap_or(0.0), 10.2, 0.1); assert_eq!(vtg.faa_mode, Some(FaaMode::Differential)); } _ => { assert!(false); } } } Err(e) => { assert_eq!(e.to_string(), "OK"); } } } }
// Remove target_arch when upstream metadata generator supports other targets #![cfg(all(windows, target_arch = "x86_64", target_env = "msvc"))] use test_win32_static_simple::*; use windows::core::*; use StaticComponent::Win32::Simple::*; #[test] fn test() -> Result<()> { unsafe { SimpleFunction(); Ok(()) } }
// 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. #[cfg(test)] use { crate::fidl_clone::FIDLClone, crate::input::monitor_mic_mute, crate::registry::service_context::ServiceContext, crate::tests::fakes::input_device_registry_service::InputDeviceRegistryService, crate::tests::fakes::service_registry::ServiceRegistry, fidl_fuchsia_ui_input::MediaButtonsEvent, futures::stream::StreamExt, parking_lot::RwLock, std::sync::Arc, }; #[fuchsia_async::run_singlethreaded(test)] async fn test_input() { let service_registry = ServiceRegistry::create(); let input_device_registry_service = Arc::new(RwLock::new(InputDeviceRegistryService::new())); let initial_event = MediaButtonsEvent { volume: Some(1), mic_mute: Some(true) }; input_device_registry_service.read().send_media_button_event(initial_event.clone()); service_registry.write().register_service(input_device_registry_service.clone()); let service_context = Arc::new(RwLock::new(ServiceContext::new(ServiceRegistry::serve( service_registry.clone(), )))); let (input_tx, mut input_rx) = futures::channel::mpsc::unbounded::<MediaButtonsEvent>(); assert!(monitor_mic_mute(service_context.clone(), input_tx).is_ok()); if let Some(event) = input_rx.next().await { assert_eq!(initial_event, event); } let second_event = MediaButtonsEvent { volume: Some(0), mic_mute: Some(false) }; input_device_registry_service.read().send_media_button_event(second_event.clone()); if let Some(event) = input_rx.next().await { assert_eq!(second_event, event); } }
use std::mem; use std::sync::Arc; use arraydeque::ArrayDeque; use crossbeam_channel::Receiver; use spin::{Mutex, MutexGuard}; use super::constants::INORDER_QUEUE_SIZE; use super::runq::{RunQueue, ToKey}; pub struct InnerJob<P, B> { // peer (used by worker to schedule/handle inorder queue), // when the peer is None, the job is complete peer: Option<P>, pub body: B, } pub struct Job<P, B> { inner: Arc<Mutex<InnerJob<P, B>>>, } impl<P, B> Clone for Job<P, B> { fn clone(&self) -> Job<P, B> { Job { inner: self.inner.clone(), } } } impl<P, B> Job<P, B> { pub fn new(peer: P, body: B) -> Job<P, B> { Job { inner: Arc::new(Mutex::new(InnerJob { peer: Some(peer), body, })), } } } impl<P, B> Job<P, B> { /// Returns a mutex guard to the inner job if complete pub fn complete(&self) -> Option<MutexGuard<InnerJob<P, B>>> { self.inner .try_lock() .and_then(|m| if m.peer.is_none() { Some(m) } else { None }) } } pub struct InorderQueue<P, B> { queue: Mutex<ArrayDeque<[Job<P, B>; INORDER_QUEUE_SIZE]>>, } impl<P, B> InorderQueue<P, B> { pub fn new() -> InorderQueue<P, B> { InorderQueue { queue: Mutex::new(ArrayDeque::new()), } } /// Add a new job to the in-order queue /// /// # Arguments /// /// - `job`: The job added to the back of the queue /// /// # Returns /// /// True if the element was added, /// false to indicate that the queue is full. pub fn send(&self, job: Job<P, B>) -> bool { self.queue.lock().push_back(job).is_ok() } /// Consume completed jobs from the in-order queue /// /// # Arguments /// /// - `f`: function to apply to the body of each jobof each job. /// - `limit`: maximum number of jobs to handle before returning /// /// # Returns /// /// A boolean indicating if the limit was reached: /// true indicating that the limit was reached, /// while false implies that the queue is empty or an uncompleted job was reached. #[inline(always)] pub fn handle<F: Fn(&mut B)>(&self, f: F, mut limit: usize) -> bool { // take the mutex let mut queue = self.queue.lock(); while limit > 0 { // attempt to extract front element let front = queue.pop_front(); let elem = match front { Some(elem) => elem, _ => { return false; } }; // apply function if job complete let ret = if let Some(mut guard) = elem.complete() { mem::drop(queue); f(&mut guard.body); queue = self.queue.lock(); false } else { true }; // job not complete yet, return job to front if ret { queue.push_front(elem).unwrap(); return false; } limit -= 1; } // did not complete all jobs true } } /// Allows easy construction of a parallel worker. /// Applicable for both decryption and encryption workers. #[inline(always)] pub fn worker_parallel< P: ToKey, // represents a peer (atomic reference counted pointer) B, // inner body type (message buffer, key material, ...) D, // device W: Fn(&P, &mut B), Q: Fn(&D) -> &RunQueue<P>, >( device: D, queue: Q, receiver: Receiver<Job<P, B>>, work: W, ) { log::trace!("router worker started"); loop { // handle new job let peer = { // get next job let job = match receiver.recv() { Ok(job) => job, _ => return, }; // lock the job let mut job = job.inner.lock(); // take the peer from the job let peer = job.peer.take().unwrap(); // process job work(&peer, &mut job.body); peer }; // process inorder jobs for peer queue(&device).insert(peer); } }
//! Audio wave. //! //! This modules has all methods and structs required to work with audio waves meant to be played via the [`ndsp`](crate::services::ndsp) service. use super::{AudioFormat, NdspError}; use crate::linear::LinearAllocator; /// Informational struct holding the raw audio data and playback info. /// /// You can play audio [`Wave`]s by using [`Channel::queue_wave()`](super::Channel::queue_wave). pub struct Wave { /// Data block of the audio wave (and its format information). buffer: Box<[u8], LinearAllocator>, audio_format: AudioFormat, // Holding the data with the raw format is necessary since `libctru` will access it. pub(crate) raw_data: ctru_sys::ndspWaveBuf, played_on_channel: Option<u8>, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[repr(u8)] /// Playback status of a [`Wave`]. pub enum Status { /// Wave has never been used. Free = ctru_sys::NDSP_WBUF_FREE as u8, /// Wave is currently queued for usage. Queued = ctru_sys::NDSP_WBUF_QUEUED as u8, /// Wave is currently playing. Playing = ctru_sys::NDSP_WBUF_PLAYING as u8, /// Wave has finished playing. Done = ctru_sys::NDSP_WBUF_DONE as u8, } impl Wave { /// Build a new playable wave object from a raw buffer on [LINEAR memory](`crate::linear`) and some info. /// /// # Example /// /// ```no_run /// # #![feature(allocator_api)] /// # fn main() { /// # /// use ctru::linear::LinearAllocator; /// use ctru::services::ndsp::{AudioFormat, wave::Wave}; /// /// // Zeroed box allocated in the LINEAR memory. /// let audio_data = Box::new_in([0u8; 96], LinearAllocator); /// /// let wave = Wave::new(audio_data, AudioFormat::PCM16Stereo, false); /// # } /// ``` pub fn new( buffer: Box<[u8], LinearAllocator>, audio_format: AudioFormat, looping: bool, ) -> Self { let sample_count = buffer.len() / audio_format.size(); // Signal to the DSP processor the buffer's RAM sector. // This step may seem delicate, but testing reports failure most of the time, while still having no repercussions on the resulting audio. unsafe { let _r = ctru_sys::DSP_FlushDataCache(buffer.as_ptr().cast(), buffer.len() as u32); } let address = ctru_sys::tag_ndspWaveBuf__bindgen_ty_1 { data_vaddr: buffer.as_ptr().cast(), }; let raw_data = ctru_sys::ndspWaveBuf { __bindgen_anon_1: address, // Buffer data virtual address nsamples: sample_count as u32, adpcm_data: std::ptr::null_mut(), offset: 0, looping, // The ones after this point aren't supposed to be setup by the user status: 0, sequence_id: 0, next: std::ptr::null_mut(), }; Self { buffer, audio_format, raw_data, played_on_channel: None, } } /// Returns a slice to the audio data (on the LINEAR memory). pub fn get_buffer(&self) -> &[u8] { &self.buffer } /// Returns a mutable slice to the audio data (on the LINEAR memory). /// /// # Errors /// /// This function will return an error if the [`Wave`] is currently busy, /// with the id to the channel in which it's queued. pub fn get_buffer_mut(&mut self) -> Result<&mut [u8], NdspError> { match self.status() { Status::Playing | Status::Queued => { Err(NdspError::WaveBusy(self.played_on_channel.unwrap())) } _ => Ok(&mut self.buffer), } } /// Returns this wave's playback status. /// /// # Example /// /// ```no_run /// # #![feature(allocator_api)] /// # fn main() { /// # /// # use ctru::linear::LinearAllocator; /// # let _audio_data = Box::new_in([0u8; 96], LinearAllocator); /// # /// use ctru::services::ndsp::{AudioFormat, wave::{Wave, Status}}; /// /// // Provide your own audio data. /// let wave = Wave::new(_audio_data, AudioFormat::PCM16Stereo, false); /// /// // The `Wave` is free if never played before. /// assert!(matches!(wave.status(), Status::Free)); /// # } /// ``` pub fn status(&self) -> Status { self.raw_data.status.try_into().unwrap() } /// Returns the amount of samples *read* by the NDSP process. /// /// # Notes /// /// This value varies depending on [`Wave::set_sample_count`]. pub fn sample_count(&self) -> usize { self.raw_data.nsamples as usize } /// Returns the format of the audio data. pub fn format(&self) -> AudioFormat { self.audio_format } // Set the internal flag for the id of the channel playing this wave. // // Internal Use Only. pub(crate) fn set_channel(&mut self, id: u8) { self.played_on_channel = Some(id) } /// Set the amount of samples to be read. /// /// # Note /// /// /// This function doesn't resize the internal buffer. Operations of this kind are particularly useful to allocate memory pools /// for VBR (Variable BitRate) formats, like OGG Vorbis. /// /// # Errors /// /// This function will return an error if the sample size exceeds the buffer's capacity /// or if the [`Wave`] is currently queued. pub fn set_sample_count(&mut self, sample_count: usize) -> Result<(), NdspError> { match self.status() { Status::Playing | Status::Queued => { return Err(NdspError::WaveBusy(self.played_on_channel.unwrap())); } _ => (), } let max_count = self.buffer.len() / self.audio_format.size(); if sample_count > max_count { return Err(NdspError::SampleCountOutOfBounds(sample_count, max_count)); } self.raw_data.nsamples = sample_count as u32; Ok(()) } } impl TryFrom<u8> for Status { type Error = &'static str; fn try_from(value: u8) -> Result<Self, Self::Error> { match value { 0 => Ok(Self::Free), 1 => Ok(Self::Queued), 2 => Ok(Self::Playing), 3 => Ok(Self::Done), _ => Err("Invalid Wave Status code"), } } } impl Drop for Wave { fn drop(&mut self) { // This was the only way I found I could check for improper drops of `Wave`. // A panic was considered, but it would cause issues with drop order against `Ndsp`. match self.status() { Status::Free | Status::Done => (), // If the status flag is "unfinished" _ => { // The unwrap is safe, since it must have a value in the case the status is "unfinished". unsafe { ctru_sys::ndspChnWaveBufClear(self.played_on_channel.unwrap().into()) }; } } unsafe { // Flag the buffer's RAM sector as unused // This step has no real effect in normal applications and is skipped even by devkitPRO's own examples. let _r = ctru_sys::DSP_InvalidateDataCache( self.buffer.as_ptr().cast(), self.buffer.len().try_into().unwrap(), ); } } }
#![feature(const_fn)] #![feature(use_nested_groups)] #![feature(duration_extras)] extern crate ggez; extern crate rand; mod coord; mod block; mod color; mod shapes; mod consts; mod square; mod gamestate; use ggez::event; use ggez::Context; use ggez::graphics; use std::time::{Duration, Instant}; use std::thread::sleep; use gamestate::Gamestate; use consts::{FPS, NANOS_IN_SEC, WINDOW_HEIGHT, WINDOW_WIDTH}; fn main() { let mut ctx = &mut ggez::ContextBuilder::new("eventloop", "ggez") .window_setup(ggez::conf::WindowSetup::default().title("Tetris")) .window_mode(ggez::conf::WindowMode::default().dimensions(WINDOW_WIDTH, WINDOW_HEIGHT)) .build() .expect("Failed to build ggez context"); let mut events = event::Events::new(ctx).unwrap(); let font = ggez::graphics::Font::new(ctx, "/3572.ttf", 15).expect("!"); let mut exit = false; let mut now = Instant::now(); let mut after = Instant::now(); while !exit { let mut gamestate = Gamestate::new(); while !gamestate.game_over() && !exit { gamestate.input(&mut ctx, &mut events, &mut exit); gamestate.frame(); gamestate.draw(&mut ctx, &font); wait(&mut now, &mut after); } if !want_to_continue(&mut ctx, &mut events) { break; } } } fn wait(now: &mut Instant, after: &mut Instant) { *after = Instant::now(); let frame = after.duration_since(*now).subsec_nanos(); if NANOS_IN_SEC / FPS > frame as f32 { sleep(Duration::from_nanos( (NANOS_IN_SEC / FPS) as u64 - frame as u64, )); } *now = Instant::now(); } fn want_to_continue(ctx: &mut Context, events: &mut event::Events) -> bool { graphics::set_color(ctx, graphics::Color::from_rgb(0, 0, 0)).expect("HA LOL"); let font = ggez::graphics::Font::new(ctx, "/3572.ttf", 40).expect("!"); let text = graphics::Text::new(ctx, &("GAME OVER".to_string()), &font).expect("!"); graphics::draw( ctx, &text, graphics::Point2::new((WINDOW_WIDTH / 2 - 140) as f32, (WINDOW_HEIGHT / 2 - 30) as f32), 0.0, ).expect("!"); graphics::present(ctx); let mut ask = true; let mut answer = false; while ask { for event in events.poll() { ctx.process_event(&event); match event { event::Event::Quit { .. } | event::Event::KeyDown { keycode: Some(event::Keycode::Escape), .. } => { answer = false; ask = false; } event::Event::KeyDown { keycode: Some(event::Keycode::Return), .. } => { answer = true; ask = false; } _ => {} } } } answer }
pub mod to_term; use std::backtrace::Backtrace; use std::convert::TryInto; use std::ops::Range; use anyhow::*; use thiserror::Error; use liblumen_alloc::erts::exception::{self, ArcError, Exception, InternalException}; use liblumen_alloc::erts::term::prelude::*; use liblumen_alloc::Process; pub struct PartRange { pub byte_offset: usize, pub byte_len: usize, } impl From<PartRange> for Range<usize> { fn from(part_range: PartRange) -> Self { part_range.byte_offset..part_range.byte_offset + part_range.byte_len } } /// Converts `binary` to a list of bytes, each representing the value of one byte. /// /// ## Arguments /// /// * `binary` - a heap, reference counted, or subbinary. /// * `position` - 0-based index into the bytes of `binary`. `position` can be +1 the last index in /// the binary if `length` is negative. /// * `length` - the length of the part. A negative length will begin the part from the end of the /// of the binary. /// /// ## Returns /// /// * `Ok(Term)` - the list of bytes /// * `Err(BadArgument)` - binary is not a binary; position is invalid; length is invalid. pub fn bin_to_list( binary: Term, position: Term, length: Term, process: &Process, ) -> exception::Result<Term> { let position_usize: usize = position .try_into() .context("position must be non-negative")?; let length_isize: isize = length.try_into().context("length must be an integer")?; match binary.decode().unwrap() { TypedTerm::HeapBinary(heap_binary) => { let available_byte_count = heap_binary.full_byte_len(); let part_range = start_length_to_part_range(position_usize, length_isize, available_byte_count)?; let range: Range<usize> = part_range.into(); let byte_slice: &[u8] = &heap_binary.as_bytes()[range]; let byte_iter = byte_slice.iter(); let byte_term_iter = byte_iter.map(|byte| (*byte).into()); let list = process.list_from_iter(byte_term_iter); Ok(list) } TypedTerm::ProcBin(process_binary) => { let available_byte_count = process_binary.full_byte_len(); let part_range = start_length_to_part_range(position_usize, length_isize, available_byte_count)?; let range: Range<usize> = part_range.into(); let byte_slice: &[u8] = &process_binary.as_bytes()[range]; let byte_iter = byte_slice.iter(); let byte_term_iter = byte_iter.map(|byte| (*byte).into()); let list = process.list_from_iter(byte_term_iter); Ok(list) } TypedTerm::BinaryLiteral(process_binary) => { let available_byte_count = process_binary.full_byte_len(); let part_range = start_length_to_part_range(position_usize, length_isize, available_byte_count)?; let range: Range<usize> = part_range.into(); let byte_slice: &[u8] = &process_binary.as_bytes()[range]; let byte_iter = byte_slice.iter(); let byte_term_iter = byte_iter.map(|byte| (*byte).into()); let list = process.list_from_iter(byte_term_iter); Ok(list) } TypedTerm::SubBinary(subbinary) => { let available_byte_count = subbinary.full_byte_len(); let part_range = start_length_to_part_range(position_usize, length_isize, available_byte_count)?; let list = if subbinary.is_aligned() { let range: Range<usize> = part_range.into(); let byte_slice: &[u8] = &unsafe { subbinary.as_bytes_unchecked() }[range]; let byte_iter = byte_slice.iter(); let byte_term_iter = byte_iter.map(|byte| (*byte).into()); process.list_from_iter(byte_term_iter) } else { let mut byte_iter = subbinary.full_byte_iter(); // skip byte_offset for _ in 0..part_range.byte_offset { byte_iter.next(); } for _ in part_range.byte_len..byte_iter.len() { byte_iter.next_back(); } let byte_term_vec: Vec<Term> = byte_iter.map(|byte| byte.into()).collect(); process.list_from_slice(&byte_term_vec) }; Ok(list) } _ => Err(TypeError) .context(format!("binary ({}) must be a binary", binary)) .map_err(From::from), } } pub fn start_length_to_part_range( start: usize, length: isize, available_byte_count: usize, ) -> Result<PartRange, PartRangeError> { if start <= available_byte_count { if length >= 0 { let non_negative_length = length as usize; let end = start + non_negative_length; if end <= available_byte_count { Ok(PartRange { byte_offset: start, byte_len: non_negative_length, }) } else { Err(PartRangeError::EndNonNegativeLength { end, available_byte_count, backtrace: Backtrace::capture(), }) } } else { let start_isize = start as isize; let end = start_isize + length; if 0 <= start_isize + length { let byte_offset = (start_isize + length) as usize; let byte_len = (-length) as usize; Ok(PartRange { byte_offset, byte_len, }) } else { Err(PartRangeError::EndNegativeLength { end, backtrace: Backtrace::capture(), }) } } } else { Err(PartRangeError::Start { start, available_byte_count, backtrace: Backtrace::capture(), }) } } #[derive(Debug, Error)] pub enum PartRangeError { #[error("start ({start}) exceeds available_byte_count ({available_byte_count})")] Start { start: usize, available_byte_count: usize, backtrace: Backtrace, }, #[error("end ({end}) exceeds available_byte_count ({available_byte_count})")] EndNonNegativeLength { end: usize, available_byte_count: usize, backtrace: Backtrace, }, #[error("end ({end}) is less than or equal to 0")] EndNegativeLength { end: isize, backtrace: Backtrace }, } impl From<PartRangeError> for Exception { fn from(err: PartRangeError) -> Self { InternalException::from(ArcError::from_err(err)).into() } }
use crate::grid_graph::{GridGraph, Node}; use crate::pbf_reader::{read_or_create_graph}; use crate::persistence::navigator::Navigator; use crate::persistence::in_memory_routing_repo::{ShipRoute, RouteRequest}; use crate::dijkstra::{Dijkstra}; use crate::nearest_neighbor::NearestNeighbor; use crate::config::Config; use std::time::Instant; pub(crate) struct InMemoryGraph { graph: GridGraph, dijkstra: Option<Dijkstra>, nearest_neighbor: Option<NearestNeighbor> } impl Navigator for InMemoryGraph { fn new() -> InMemoryGraph { let config = Config::global(); if config.build_graph_on_startup() { let graph = read_or_create_graph(config.coastlines_file(), config.force_rebuild_graph()); let dijkstra = Some(Dijkstra::new(graph.adjacency_array(), graph.nodes.len() as u32 - 1)); let nearest_neighbor = Some(NearestNeighbor::new(&graph.nodes)); InMemoryGraph { graph, dijkstra, nearest_neighbor } } else { InMemoryGraph { graph: GridGraph::default(), dijkstra: None, nearest_neighbor: None } } } fn build_graph(&mut self) { /*let polygons = //let polygons = read_file("./iceland-coastlines.osm.pbf"); let polygon_test = PointInPolygonTest::new(polygons); */ // assign new value to the GRAPH reference // self.graph = read_or_create_graph("./iceland-coastlines.osm.pbf"); // self.graph = read_or_create_graph("./planet-coastlines.pbf.sec"); let config = Config::global(); self.graph = read_or_create_graph(config.coastlines_file(), config.force_rebuild_graph()); self.dijkstra = Some(Dijkstra::new(self.graph.adjacency_array(), self.get_number_nodes() - 1)); self.nearest_neighbor = Some(NearestNeighbor::new(&self.graph.nodes)); } fn calculate_route(&mut self, route_request: RouteRequest) -> Option<ShipRoute> { if let Some(dijkstra) = self.dijkstra.as_mut() { let start_node = self.nearest_neighbor.as_ref().unwrap().find_nearest_neighbor(&route_request.start()); let end_node = self.nearest_neighbor.as_ref().unwrap().find_nearest_neighbor(&route_request.end()); let start_time = Instant::now(); dijkstra.change_source_node(start_node); if let Some(route_and_distance) = dijkstra.find_route(end_node) { let route: Vec<u32> = route_and_distance.0; let distance = route_and_distance.1; let nodes_route: Vec<Node> = route.into_iter().map(|i| {self.graph.nodes[i as usize]}).collect(); println!("Calculated route from {} to {} with distance {} in {} ms", start_node, end_node, distance, start_time.elapsed().as_millis()); return Some(ShipRoute::new(nodes_route, distance)); } else { println!("Could not calculate route. Dijkstra is not initialized"); } } None } fn get_number_nodes(&self) -> u32 { self.graph.nodes.len() as u32 } }
// Minimize Deviation in Array // https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/583/week-5-january-29th-january-31st/3622/ pub struct Solution; use std::collections::BinaryHeap; impl Solution { pub fn minimum_deviation(nums: Vec<i32>) -> i32 { let mut heap = BinaryHeap::with_capacity(nums.len()); let mut max = 0; for num in nums { let mut base = num; while base & 1 == 0 { base >>= 1; } if base > max { max = base; } heap.push((-base, -num)); } let min = -heap.peek().unwrap().0; let mut dev = max - min; loop { let (n_base, n_num) = heap.pop().unwrap(); if n_base & 1 == 0 && n_base <= n_num { // We can't multiply anymore break dev; } let new_base = (-n_base) << 1; max = max.max(new_base); let min = new_base.min(-heap.peek().unwrap().0); dev = dev.min(max - min); heap.push((-new_base, n_num)); } } } #[cfg(test)] mod tests { use super::*; #[test] fn example1() { assert_eq!(Solution::minimum_deviation(vec![1, 2, 3, 4]), 1); } #[test] fn example2() { assert_eq!(Solution::minimum_deviation(vec![4, 1, 5, 20, 3]), 3); } #[test] fn example3() { assert_eq!(Solution::minimum_deviation(vec![2, 10, 8]), 3); } #[test] fn fail1() { assert_eq!(Solution::minimum_deviation(vec![10, 5, 10, 1]), 3); } #[test] fn fail2() { assert_eq!( Solution::minimum_deviation(vec![610, 778, 846, 733, 395]), 236 ); } }
extern crate actix; extern crate futures; extern crate tokio; use actix::Actor; use actix::StreamHandler; use std::io; use tokio::io::WriteHalf; use tokio::net::TcpStream; use crate::codec::{P2PCodec, Request}; pub struct Session { /// Unique session id id: usize, /// Framed wrapper to send messages through the TCP connection _framed: actix::io::FramedWrite<WriteHalf<TcpStream>, P2PCodec>, } /// Session helper methods impl Session { /// Method to create a new session pub fn new(_framed: actix::io::FramedWrite<WriteHalf<TcpStream>, P2PCodec>) -> Session { Session { id: 0, _framed } } } /// Implement actor trait for Session impl Actor for Session { type Context = actix::Context<Self>; fn started(&mut self, _ctx: &mut Self::Context) { println!("Session started!"); } } /// Implement write handler for Session impl actix::io::WriteHandler<io::Error> for Session {} /// Implement `StreamHandler`trait in order to use `Framed` with an actor impl StreamHandler<Request, io::Error> for Session { /// This is main event loop for client requests fn handle(&mut self, msg: Request, _ctx: &mut Self::Context) { // Handler different types of requests match msg { Request::Message(message) => { println!("Peer {} message received `{}`", self.id, message); } } } }
extern crate oop_sample; use oop_sample::{Draw, Screen, Button}; use std::fmt::Display; struct SelectBox { width: u32, height: u32, options: Vec<String>, } impl Draw for SelectBox { fn draw(&self) { println!("selectbox drawn width: {} height: {} label {:?}", self.width, self.height, self.options); } } struct DrawableValue<T> { value: Box<T> } impl<T> Draw for DrawableValue<T> where T: Display{ fn draw(&self) { println!("value drawn value: {}", self.value); } } fn main() { let screen = Screen { components: vec![ Box::new(SelectBox { width: 75, height: 10, options: vec![ // はい String::from("Yes"), // 多分 String::from("Maybe"), // いいえ String::from("No") ], }), Box::new(Button { width: 50, height: 10, // 了解 label: String::from("OK"), }), Box::new(DrawableValue{ value: Box::new( String::from("hello woorld"), ) }), ], }; screen.run(); }
// Copyright (c) 2018 Aigbe Research // phy.rs - LTE/5G Physical Layer Implementation in Rust // Compliance: // 3GPP TS 36.211 // 3GPP TS 36.212 // 3GPP TS 36.216 // 3GPP TS 36.213 // 3GPP TS 36.214 // LTE pub use common::*; pub mod common; pub use ts_36_211::*; pub mod ts_36_211; // Physical channels and modulation pub mod ts_36_212; // Multiplexing and channel coding pub mod ts_36_213; // Physical layer for relaying operation pub mod ts_36_214; // Physical layer procedures pub mod ts_36_216; // Physical layer - Measurements // 5G NR // ts_38_211 NR - Physical channels and modulation // ts_38_212 NR - Multiplexing and channel coding // ts_38_213 NR - Physical layer procedures for control // ts_38_214 NR - Physical layer procedures for data // ts_38_215 NR - Physical layer measurements
/*! A very simple application which suggests to guess a random number. It shows how derive macro parses generics. Requires the following features: `cargo run --example generic_d --features "combobox"` */ extern crate native_windows_gui as nwg; extern crate native_windows_derive as nwd; use std::fmt::Display; use std::cell::RefCell; use std::time::{SystemTime, UNIX_EPOCH}; use nwd::NwgUi; use nwg::NativeUi; #[derive(NwgUi)] pub struct GuessApp<VALIDATOR, T: Display + Default + 'static, const W: i32, const H: i32> where VALIDATOR: Fn(Option<&T>) -> Result<String, String> + 'static { #[nwg_control(size: (W, H), position: (300, 300), title: "Guess the number", flags: "WINDOW|VISIBLE")] #[nwg_events(OnWindowClose: [nwg::stop_thread_dispatch()])] window: nwg::Window, #[nwg_control(collection: data.combo_items.borrow_mut().take().unwrap_or_default(), size: (280, 40), position: (10, 10))] combobox: nwg::ComboBox<T>, combo_items: RefCell<Option<Vec<T>>>, #[nwg_control(text: "Check", size: (280, 35), position: (10, 60))] #[nwg_events(OnButtonClick: [GuessApp::guess])] button: nwg::Button, validator: VALIDATOR, } impl<VALIDATOR, T, const W: i32, const H: i32> GuessApp<VALIDATOR, T, W, H> where VALIDATOR: Fn(Option<&T>) -> Result<String, String>, T: Display + Default { fn guess(&self) { let validation = match self.combobox.selection() { Some(s) => (self.validator)(self.combobox.collection().get(s)), None => Err("Please select any value".to_owned()), }; match validation { Err(error) => { nwg::modal_error_message(&self.window, "Fail", &error); } Ok(success) => { nwg::modal_info_message(&self.window, "Congratulation", &success); nwg::stop_thread_dispatch(); } }; } } fn main() { nwg::init().expect("Failed to init Native Windows GUI"); nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font"); let random_number = (SystemTime::now() .duration_since(UNIX_EPOCH).expect("Clock may have gone backwards") .as_millis() % 100) as i8; let validator = move |c: Option<&i8>| { c.filter(|x| **x == random_number) .map(|x| format!("You guessed my number: {}", *x)) .ok_or("Wrong number. Try again".to_owned()) }; let combo_items = (-2..=2).into_iter().map(|i| random_number + i).collect(); const WIDTH: i32 = 300; const HEIGHT: i32 = 110; let basic_app = GuessApp::<_, _, WIDTH, HEIGHT> { validator, combo_items: Some(combo_items).into(), window: Default::default(), button: Default::default(), combobox: Default::default(), }; let _ui = GuessApp::build_ui(basic_app).expect("Failed to build UI"); nwg::dispatch_thread_events(); }
use std::collections::HashMap; use std::io::{Read, Result as IOResult}; use crate::StringRead; pub struct Entities { pub entities: Vec<Entity> } impl Entities { pub fn read(read: &mut dyn Read) -> IOResult<Entities> { let mut entities = Vec::<Entity>::new(); let text = read.read_null_terminated_string().unwrap(); let mut remaining_text = text.as_str(); loop { let block_begin = remaining_text.find('{'); if block_begin.is_none() { break; } let block_begin = block_begin.unwrap(); remaining_text = &remaining_text[block_begin + 1..]; let block_end = remaining_text.find('}').expect("Unfinished block"); let block = &remaining_text[..block_end]; entities.push(Entity { key_values: parse_key_value(block, true) }); } Ok(Self { entities }) } } pub struct Entity { key_values: HashMap<String, String> } impl Entity { pub fn get(&self, key: &str) -> Option<&str> { let lower_key = key.to_lowercase(); self.key_values.get(&lower_key).map(|s| s.as_str()) } pub fn class_name(&self) -> EntityClass { let class_name = self.key_values.get("classname").unwrap().as_str(); match class_name { "prop_detail" => EntityClass::PropDetail, "prop_static" => EntityClass::PropStatic, "prop_physics" => EntityClass::PropPhysics, "prop_ragdoll" => EntityClass::PropRagdoll, "prop_dynamic" => EntityClass::PropDynamic, "prop_physics_multiplayer" => EntityClass::PropPhysicsMultiplayer, "prop_physics_override" => EntityClass::PropPhysicsOverride, "prop_dynamic_override" => EntityClass::PropDynamicOverride, _ => EntityClass::Unknown(class_name.to_string()) } } } pub fn parse_key_value(text: &str, turn_keys_lower_case: bool) -> HashMap<String, String> { let mut data = HashMap::<String, String>::new(); let text = text.replace("\r\n", "\n"); let lines = text.trim().split('\n'); for line in lines { let space_pos = line.find(' ').unwrap(); let key = (&line[..space_pos]).trim().trim_matches('\"').trim(); let value = (&line[space_pos + 1..]).trim().trim_matches('\"').trim(); let owned_key = if turn_keys_lower_case { key.to_lowercase() } else { key.to_string() }; data.insert(owned_key, value.to_string()); } data } #[derive(Eq, PartialEq, Hash, Debug)] pub enum EntityClass { PropDetail, PropStatic, PropPhysics, PropRagdoll, PropDynamic, PropPhysicsMultiplayer, PropPhysicsOverride, PropDynamicOverride, Unknown(String) }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IKnownPerceptionFrameKindStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IKnownPerceptionFrameKindStatics { type Vtable = IKnownPerceptionFrameKindStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3ae651d6_9669_4106_9fae_4835c1b96104); } #[repr(C)] #[doc(hidden)] pub struct IKnownPerceptionFrameKindStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionControlGroup(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionControlGroup { type Vtable = IPerceptionControlGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x172c4882_2fd9_4c4e_ba34_fdf20a73dde5); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionControlGroup_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionControlGroupFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionControlGroupFactory { type Vtable = IPerceptionControlGroupFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2f1af2e0_baf1_453b_bed4_cd9d4619154c); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionControlGroupFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ids: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionCorrelation(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionCorrelation { type Vtable = IPerceptionCorrelation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb4131a82_dff5_4047_8a19_3b4d805f7176); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionCorrelation_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Numerics"))] usize, #[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::Numerics::Quaternion) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Numerics"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionCorrelationFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionCorrelationFactory { type Vtable = IPerceptionCorrelationFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd4a6c425_2884_4a8f_8134_2835d7286cbf); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionCorrelationFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, targetid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, position: super::super::super::Foundation::Numerics::Vector3, orientation: super::super::super::Foundation::Numerics::Quaternion, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Numerics"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionCorrelationGroup(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionCorrelationGroup { type Vtable = IPerceptionCorrelationGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x752a0906_36a7_47bb_9b79_56cc6b746770); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionCorrelationGroup_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionCorrelationGroupFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionCorrelationGroupFactory { type Vtable = IPerceptionCorrelationGroupFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7dfe2088_63df_48ed_83b1_4ab829132995); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionCorrelationGroupFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, relativelocations: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionFaceAuthenticationGroup(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionFaceAuthenticationGroup { type Vtable = IPerceptionFaceAuthenticationGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe8019814_4a91_41b0_83a6_881a1775353e); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionFaceAuthenticationGroup_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionFaceAuthenticationGroupFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionFaceAuthenticationGroupFactory { type Vtable = IPerceptionFaceAuthenticationGroupFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe68a05d4_b60c_40f4_bcb9_f24d46467320); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionFaceAuthenticationGroupFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ids: ::windows::core::RawPtr, starthandler: ::windows::core::RawPtr, stophandler: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionFrame(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionFrame { type Vtable = IPerceptionFrame_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7cfe7825_54bb_4d9d_bec5_8ef66151d2ac); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionFrame_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPerceptionFrameProvider(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionFrameProvider { type Vtable = IPerceptionFrameProvider_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x794f7ab9_b37d_3b33_a10d_30626419ce65); } impl IPerceptionFrameProvider { #[cfg(feature = "deprecated")] pub fn FrameProviderInfo(&self) -> ::windows::core::Result<PerceptionFrameProviderInfo> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionFrameProviderInfo>(result__) } } #[cfg(feature = "deprecated")] pub fn Available(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Collections")] pub fn Properties(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IPropertySet> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IPropertySet>(result__) } } #[cfg(feature = "deprecated")] pub fn Start(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn Stop(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] pub fn SetProperty<'a, Param0: ::windows::core::IntoParam<'a, PerceptionPropertyChangeRequest>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for IPerceptionFrameProvider { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{794f7ab9-b37d-3b33-a10d-30626419ce65}"); } impl ::core::convert::From<IPerceptionFrameProvider> for ::windows::core::IUnknown { fn from(value: IPerceptionFrameProvider) -> Self { value.0 .0 } } impl ::core::convert::From<&IPerceptionFrameProvider> for ::windows::core::IUnknown { fn from(value: &IPerceptionFrameProvider) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPerceptionFrameProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IPerceptionFrameProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IPerceptionFrameProvider> for ::windows::core::IInspectable { fn from(value: IPerceptionFrameProvider) -> Self { value.0 } } impl ::core::convert::From<&IPerceptionFrameProvider> for ::windows::core::IInspectable { fn from(value: &IPerceptionFrameProvider) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IPerceptionFrameProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IPerceptionFrameProvider { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<IPerceptionFrameProvider> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: IPerceptionFrameProvider) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&IPerceptionFrameProvider> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &IPerceptionFrameProvider) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for IPerceptionFrameProvider { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for &IPerceptionFrameProvider { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(C)] #[doc(hidden)] pub struct IPerceptionFrameProvider_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionFrameProviderInfo(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionFrameProviderInfo { type Vtable = IPerceptionFrameProviderInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcca959e8_797e_4e83_9b87_036a74142fc4); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionFrameProviderInfo_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPerceptionFrameProviderManager(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionFrameProviderManager { type Vtable = IPerceptionFrameProviderManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa959ce07_ead3_33df_8ec1_b924abe019c4); } impl IPerceptionFrameProviderManager { #[cfg(feature = "deprecated")] pub fn GetFrameProvider<'a, Param0: ::windows::core::IntoParam<'a, PerceptionFrameProviderInfo>>(&self, frameproviderinfo: Param0) -> ::windows::core::Result<IPerceptionFrameProvider> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), frameproviderinfo.into_param().abi(), &mut result__).from_abi::<IPerceptionFrameProvider>(result__) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for IPerceptionFrameProviderManager { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{a959ce07-ead3-33df-8ec1-b924abe019c4}"); } impl ::core::convert::From<IPerceptionFrameProviderManager> for ::windows::core::IUnknown { fn from(value: IPerceptionFrameProviderManager) -> Self { value.0 .0 } } impl ::core::convert::From<&IPerceptionFrameProviderManager> for ::windows::core::IUnknown { fn from(value: &IPerceptionFrameProviderManager) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPerceptionFrameProviderManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IPerceptionFrameProviderManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IPerceptionFrameProviderManager> for ::windows::core::IInspectable { fn from(value: IPerceptionFrameProviderManager) -> Self { value.0 } } impl ::core::convert::From<&IPerceptionFrameProviderManager> for ::windows::core::IInspectable { fn from(value: &IPerceptionFrameProviderManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IPerceptionFrameProviderManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a IPerceptionFrameProviderManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<IPerceptionFrameProviderManager> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: IPerceptionFrameProviderManager) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&IPerceptionFrameProviderManager> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &IPerceptionFrameProviderManager) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for IPerceptionFrameProviderManager { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for &IPerceptionFrameProviderManager { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(C)] #[doc(hidden)] pub struct IPerceptionFrameProviderManager_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, frameproviderinfo: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionFrameProviderManagerServiceStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionFrameProviderManagerServiceStatics { type Vtable = IPerceptionFrameProviderManagerServiceStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xae8386e6_cad9_4359_8f96_8eae51810526); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionFrameProviderManagerServiceStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, manager: ::windows::core::RawPtr, frameproviderinfo: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, manager: ::windows::core::RawPtr, frameproviderinfo: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, manager: ::windows::core::RawPtr, faceauthenticationgroup: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, manager: ::windows::core::RawPtr, faceauthenticationgroup: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, manager: ::windows::core::RawPtr, controlgroup: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, manager: ::windows::core::RawPtr, controlgroup: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, manager: ::windows::core::RawPtr, correlationgroup: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, manager: ::windows::core::RawPtr, correlationgroup: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, provider: ::windows::core::RawPtr, available: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, provider: ::windows::core::RawPtr, frame: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionPropertyChangeRequest(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionPropertyChangeRequest { type Vtable = IPerceptionPropertyChangeRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c5aeb51_350b_4df8_9414_59e09815510b); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionPropertyChangeRequest_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::PerceptionFrameSourcePropertyChangeStatus) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::PerceptionFrameSourcePropertyChangeStatus) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionVideoFrameAllocator(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionVideoFrameAllocator { type Vtable = IPerceptionVideoFrameAllocator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4c38a7da_fdd8_4ed4_a039_2a6f9b235038); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionVideoFrameAllocator_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Media")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, frame: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Media"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IPerceptionVideoFrameAllocatorFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPerceptionVideoFrameAllocatorFactory { type Vtable = IPerceptionVideoFrameAllocatorFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1a58b0e1_e91a_481e_b876_a89e2bbc6b33); } #[repr(C)] #[doc(hidden)] pub struct IPerceptionVideoFrameAllocatorFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Graphics_Imaging"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, maxoutstandingframecountforwrite: u32, format: super::super::super::Graphics::Imaging::BitmapPixelFormat, resolution: super::super::super::Foundation::Size, alpha: super::super::super::Graphics::Imaging::BitmapAlphaMode, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Graphics_Imaging")))] usize, ); pub struct KnownPerceptionFrameKind {} impl KnownPerceptionFrameKind { #[cfg(feature = "deprecated")] pub fn Color() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IKnownPerceptionFrameKindStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } #[cfg(feature = "deprecated")] pub fn Depth() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IKnownPerceptionFrameKindStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } #[cfg(feature = "deprecated")] pub fn Infrared() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IKnownPerceptionFrameKindStatics(|this| unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) }) } pub fn IKnownPerceptionFrameKindStatics<R, F: FnOnce(&IKnownPerceptionFrameKindStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<KnownPerceptionFrameKind, IKnownPerceptionFrameKindStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for KnownPerceptionFrameKind { const NAME: &'static str = "Windows.Devices.Perception.Provider.KnownPerceptionFrameKind"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PerceptionControlGroup(pub ::windows::core::IInspectable); impl PerceptionControlGroup { #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Collections")] pub fn FrameProviderIds(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Collections")] pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(ids: Param0) -> ::windows::core::Result<PerceptionControlGroup> { Self::IPerceptionControlGroupFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), ids.into_param().abi(), &mut result__).from_abi::<PerceptionControlGroup>(result__) }) } pub fn IPerceptionControlGroupFactory<R, F: FnOnce(&IPerceptionControlGroupFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PerceptionControlGroup, IPerceptionControlGroupFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PerceptionControlGroup { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.Provider.PerceptionControlGroup;{172c4882-2fd9-4c4e-ba34-fdf20a73dde5})"); } unsafe impl ::windows::core::Interface for PerceptionControlGroup { type Vtable = IPerceptionControlGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x172c4882_2fd9_4c4e_ba34_fdf20a73dde5); } impl ::windows::core::RuntimeName for PerceptionControlGroup { const NAME: &'static str = "Windows.Devices.Perception.Provider.PerceptionControlGroup"; } impl ::core::convert::From<PerceptionControlGroup> for ::windows::core::IUnknown { fn from(value: PerceptionControlGroup) -> Self { value.0 .0 } } impl ::core::convert::From<&PerceptionControlGroup> for ::windows::core::IUnknown { fn from(value: &PerceptionControlGroup) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionControlGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PerceptionControlGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PerceptionControlGroup> for ::windows::core::IInspectable { fn from(value: PerceptionControlGroup) -> Self { value.0 } } impl ::core::convert::From<&PerceptionControlGroup> for ::windows::core::IInspectable { fn from(value: &PerceptionControlGroup) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionControlGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PerceptionControlGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PerceptionControlGroup {} unsafe impl ::core::marker::Sync for PerceptionControlGroup {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PerceptionCorrelation(pub ::windows::core::IInspectable); impl PerceptionCorrelation { #[cfg(feature = "deprecated")] pub fn TargetId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Numerics")] pub fn Position(&self) -> ::windows::core::Result<super::super::super::Foundation::Numerics::Vector3> { let this = self; unsafe { let mut result__: super::super::super::Foundation::Numerics::Vector3 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Numerics::Vector3>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Numerics")] pub fn Orientation(&self) -> ::windows::core::Result<super::super::super::Foundation::Numerics::Quaternion> { let this = self; unsafe { let mut result__: super::super::super::Foundation::Numerics::Quaternion = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Numerics::Quaternion>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Numerics")] pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::Numerics::Vector3>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::Numerics::Quaternion>>(targetid: Param0, position: Param1, orientation: Param2) -> ::windows::core::Result<PerceptionCorrelation> { Self::IPerceptionCorrelationFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), targetid.into_param().abi(), position.into_param().abi(), orientation.into_param().abi(), &mut result__).from_abi::<PerceptionCorrelation>(result__) }) } pub fn IPerceptionCorrelationFactory<R, F: FnOnce(&IPerceptionCorrelationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PerceptionCorrelation, IPerceptionCorrelationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PerceptionCorrelation { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.Provider.PerceptionCorrelation;{b4131a82-dff5-4047-8a19-3b4d805f7176})"); } unsafe impl ::windows::core::Interface for PerceptionCorrelation { type Vtable = IPerceptionCorrelation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb4131a82_dff5_4047_8a19_3b4d805f7176); } impl ::windows::core::RuntimeName for PerceptionCorrelation { const NAME: &'static str = "Windows.Devices.Perception.Provider.PerceptionCorrelation"; } impl ::core::convert::From<PerceptionCorrelation> for ::windows::core::IUnknown { fn from(value: PerceptionCorrelation) -> Self { value.0 .0 } } impl ::core::convert::From<&PerceptionCorrelation> for ::windows::core::IUnknown { fn from(value: &PerceptionCorrelation) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionCorrelation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PerceptionCorrelation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PerceptionCorrelation> for ::windows::core::IInspectable { fn from(value: PerceptionCorrelation) -> Self { value.0 } } impl ::core::convert::From<&PerceptionCorrelation> for ::windows::core::IInspectable { fn from(value: &PerceptionCorrelation) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionCorrelation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PerceptionCorrelation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PerceptionCorrelation {} unsafe impl ::core::marker::Sync for PerceptionCorrelation {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PerceptionCorrelationGroup(pub ::windows::core::IInspectable); impl PerceptionCorrelationGroup { #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Collections")] pub fn RelativeLocations(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<PerceptionCorrelation>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<PerceptionCorrelation>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Collections")] pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<PerceptionCorrelation>>>(relativelocations: Param0) -> ::windows::core::Result<PerceptionCorrelationGroup> { Self::IPerceptionCorrelationGroupFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), relativelocations.into_param().abi(), &mut result__).from_abi::<PerceptionCorrelationGroup>(result__) }) } pub fn IPerceptionCorrelationGroupFactory<R, F: FnOnce(&IPerceptionCorrelationGroupFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PerceptionCorrelationGroup, IPerceptionCorrelationGroupFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PerceptionCorrelationGroup { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.Provider.PerceptionCorrelationGroup;{752a0906-36a7-47bb-9b79-56cc6b746770})"); } unsafe impl ::windows::core::Interface for PerceptionCorrelationGroup { type Vtable = IPerceptionCorrelationGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x752a0906_36a7_47bb_9b79_56cc6b746770); } impl ::windows::core::RuntimeName for PerceptionCorrelationGroup { const NAME: &'static str = "Windows.Devices.Perception.Provider.PerceptionCorrelationGroup"; } impl ::core::convert::From<PerceptionCorrelationGroup> for ::windows::core::IUnknown { fn from(value: PerceptionCorrelationGroup) -> Self { value.0 .0 } } impl ::core::convert::From<&PerceptionCorrelationGroup> for ::windows::core::IUnknown { fn from(value: &PerceptionCorrelationGroup) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionCorrelationGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PerceptionCorrelationGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PerceptionCorrelationGroup> for ::windows::core::IInspectable { fn from(value: PerceptionCorrelationGroup) -> Self { value.0 } } impl ::core::convert::From<&PerceptionCorrelationGroup> for ::windows::core::IInspectable { fn from(value: &PerceptionCorrelationGroup) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionCorrelationGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PerceptionCorrelationGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PerceptionCorrelationGroup {} unsafe impl ::core::marker::Sync for PerceptionCorrelationGroup {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PerceptionFaceAuthenticationGroup(pub ::windows::core::IInspectable); impl PerceptionFaceAuthenticationGroup { #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Collections")] pub fn FrameProviderIds(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Collections")] pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param1: ::windows::core::IntoParam<'a, PerceptionStartFaceAuthenticationHandler>, Param2: ::windows::core::IntoParam<'a, PerceptionStopFaceAuthenticationHandler>>(ids: Param0, starthandler: Param1, stophandler: Param2) -> ::windows::core::Result<PerceptionFaceAuthenticationGroup> { Self::IPerceptionFaceAuthenticationGroupFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), ids.into_param().abi(), starthandler.into_param().abi(), stophandler.into_param().abi(), &mut result__).from_abi::<PerceptionFaceAuthenticationGroup>(result__) }) } pub fn IPerceptionFaceAuthenticationGroupFactory<R, F: FnOnce(&IPerceptionFaceAuthenticationGroupFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PerceptionFaceAuthenticationGroup, IPerceptionFaceAuthenticationGroupFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PerceptionFaceAuthenticationGroup { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.Provider.PerceptionFaceAuthenticationGroup;{e8019814-4a91-41b0-83a6-881a1775353e})"); } unsafe impl ::windows::core::Interface for PerceptionFaceAuthenticationGroup { type Vtable = IPerceptionFaceAuthenticationGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe8019814_4a91_41b0_83a6_881a1775353e); } impl ::windows::core::RuntimeName for PerceptionFaceAuthenticationGroup { const NAME: &'static str = "Windows.Devices.Perception.Provider.PerceptionFaceAuthenticationGroup"; } impl ::core::convert::From<PerceptionFaceAuthenticationGroup> for ::windows::core::IUnknown { fn from(value: PerceptionFaceAuthenticationGroup) -> Self { value.0 .0 } } impl ::core::convert::From<&PerceptionFaceAuthenticationGroup> for ::windows::core::IUnknown { fn from(value: &PerceptionFaceAuthenticationGroup) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionFaceAuthenticationGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PerceptionFaceAuthenticationGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PerceptionFaceAuthenticationGroup> for ::windows::core::IInspectable { fn from(value: PerceptionFaceAuthenticationGroup) -> Self { value.0 } } impl ::core::convert::From<&PerceptionFaceAuthenticationGroup> for ::windows::core::IInspectable { fn from(value: &PerceptionFaceAuthenticationGroup) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionFaceAuthenticationGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PerceptionFaceAuthenticationGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PerceptionFaceAuthenticationGroup {} unsafe impl ::core::marker::Sync for PerceptionFaceAuthenticationGroup {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PerceptionFrame(pub ::windows::core::IInspectable); impl PerceptionFrame { #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn RelativeTime(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn SetRelativeTime<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TimeSpan>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation_Collections")] pub fn Properties(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::ValueSet> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::ValueSet>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn FrameData(&self) -> ::windows::core::Result<super::super::super::Foundation::IMemoryBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IMemoryBuffer>(result__) } } } unsafe impl ::windows::core::RuntimeType for PerceptionFrame { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.Provider.PerceptionFrame;{7cfe7825-54bb-4d9d-bec5-8ef66151d2ac})"); } unsafe impl ::windows::core::Interface for PerceptionFrame { type Vtable = IPerceptionFrame_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7cfe7825_54bb_4d9d_bec5_8ef66151d2ac); } impl ::windows::core::RuntimeName for PerceptionFrame { const NAME: &'static str = "Windows.Devices.Perception.Provider.PerceptionFrame"; } impl ::core::convert::From<PerceptionFrame> for ::windows::core::IUnknown { fn from(value: PerceptionFrame) -> Self { value.0 .0 } } impl ::core::convert::From<&PerceptionFrame> for ::windows::core::IUnknown { fn from(value: &PerceptionFrame) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionFrame { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PerceptionFrame { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PerceptionFrame> for ::windows::core::IInspectable { fn from(value: PerceptionFrame) -> Self { value.0 } } impl ::core::convert::From<&PerceptionFrame> for ::windows::core::IInspectable { fn from(value: &PerceptionFrame) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionFrame { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PerceptionFrame { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PerceptionFrame {} unsafe impl ::core::marker::Sync for PerceptionFrame {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PerceptionFrameProviderInfo(pub ::windows::core::IInspectable); impl PerceptionFrameProviderInfo { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PerceptionFrameProviderInfo, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "deprecated")] pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] pub fn SetId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] pub fn SetDisplayName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn DeviceKind(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] pub fn SetDeviceKind<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn FrameKind(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] pub fn SetFrameKind<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn Hidden(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "deprecated")] pub fn SetHidden(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() } } } unsafe impl ::windows::core::RuntimeType for PerceptionFrameProviderInfo { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.Provider.PerceptionFrameProviderInfo;{cca959e8-797e-4e83-9b87-036a74142fc4})"); } unsafe impl ::windows::core::Interface for PerceptionFrameProviderInfo { type Vtable = IPerceptionFrameProviderInfo_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcca959e8_797e_4e83_9b87_036a74142fc4); } impl ::windows::core::RuntimeName for PerceptionFrameProviderInfo { const NAME: &'static str = "Windows.Devices.Perception.Provider.PerceptionFrameProviderInfo"; } impl ::core::convert::From<PerceptionFrameProviderInfo> for ::windows::core::IUnknown { fn from(value: PerceptionFrameProviderInfo) -> Self { value.0 .0 } } impl ::core::convert::From<&PerceptionFrameProviderInfo> for ::windows::core::IUnknown { fn from(value: &PerceptionFrameProviderInfo) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionFrameProviderInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PerceptionFrameProviderInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PerceptionFrameProviderInfo> for ::windows::core::IInspectable { fn from(value: PerceptionFrameProviderInfo) -> Self { value.0 } } impl ::core::convert::From<&PerceptionFrameProviderInfo> for ::windows::core::IInspectable { fn from(value: &PerceptionFrameProviderInfo) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionFrameProviderInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PerceptionFrameProviderInfo { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PerceptionFrameProviderInfo {} unsafe impl ::core::marker::Sync for PerceptionFrameProviderInfo {} pub struct PerceptionFrameProviderManagerService {} impl PerceptionFrameProviderManagerService { #[cfg(feature = "deprecated")] pub fn RegisterFrameProviderInfo<'a, Param0: ::windows::core::IntoParam<'a, IPerceptionFrameProviderManager>, Param1: ::windows::core::IntoParam<'a, PerceptionFrameProviderInfo>>(manager: Param0, frameproviderinfo: Param1) -> ::windows::core::Result<()> { Self::IPerceptionFrameProviderManagerServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), manager.into_param().abi(), frameproviderinfo.into_param().abi()).ok() }) } #[cfg(feature = "deprecated")] pub fn UnregisterFrameProviderInfo<'a, Param0: ::windows::core::IntoParam<'a, IPerceptionFrameProviderManager>, Param1: ::windows::core::IntoParam<'a, PerceptionFrameProviderInfo>>(manager: Param0, frameproviderinfo: Param1) -> ::windows::core::Result<()> { Self::IPerceptionFrameProviderManagerServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), manager.into_param().abi(), frameproviderinfo.into_param().abi()).ok() }) } #[cfg(feature = "deprecated")] pub fn RegisterFaceAuthenticationGroup<'a, Param0: ::windows::core::IntoParam<'a, IPerceptionFrameProviderManager>, Param1: ::windows::core::IntoParam<'a, PerceptionFaceAuthenticationGroup>>(manager: Param0, faceauthenticationgroup: Param1) -> ::windows::core::Result<()> { Self::IPerceptionFrameProviderManagerServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), manager.into_param().abi(), faceauthenticationgroup.into_param().abi()).ok() }) } #[cfg(feature = "deprecated")] pub fn UnregisterFaceAuthenticationGroup<'a, Param0: ::windows::core::IntoParam<'a, IPerceptionFrameProviderManager>, Param1: ::windows::core::IntoParam<'a, PerceptionFaceAuthenticationGroup>>(manager: Param0, faceauthenticationgroup: Param1) -> ::windows::core::Result<()> { Self::IPerceptionFrameProviderManagerServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), manager.into_param().abi(), faceauthenticationgroup.into_param().abi()).ok() }) } #[cfg(feature = "deprecated")] pub fn RegisterControlGroup<'a, Param0: ::windows::core::IntoParam<'a, IPerceptionFrameProviderManager>, Param1: ::windows::core::IntoParam<'a, PerceptionControlGroup>>(manager: Param0, controlgroup: Param1) -> ::windows::core::Result<()> { Self::IPerceptionFrameProviderManagerServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), manager.into_param().abi(), controlgroup.into_param().abi()).ok() }) } #[cfg(feature = "deprecated")] pub fn UnregisterControlGroup<'a, Param0: ::windows::core::IntoParam<'a, IPerceptionFrameProviderManager>, Param1: ::windows::core::IntoParam<'a, PerceptionControlGroup>>(manager: Param0, controlgroup: Param1) -> ::windows::core::Result<()> { Self::IPerceptionFrameProviderManagerServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), manager.into_param().abi(), controlgroup.into_param().abi()).ok() }) } #[cfg(feature = "deprecated")] pub fn RegisterCorrelationGroup<'a, Param0: ::windows::core::IntoParam<'a, IPerceptionFrameProviderManager>, Param1: ::windows::core::IntoParam<'a, PerceptionCorrelationGroup>>(manager: Param0, correlationgroup: Param1) -> ::windows::core::Result<()> { Self::IPerceptionFrameProviderManagerServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), manager.into_param().abi(), correlationgroup.into_param().abi()).ok() }) } #[cfg(feature = "deprecated")] pub fn UnregisterCorrelationGroup<'a, Param0: ::windows::core::IntoParam<'a, IPerceptionFrameProviderManager>, Param1: ::windows::core::IntoParam<'a, PerceptionCorrelationGroup>>(manager: Param0, correlationgroup: Param1) -> ::windows::core::Result<()> { Self::IPerceptionFrameProviderManagerServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), manager.into_param().abi(), correlationgroup.into_param().abi()).ok() }) } #[cfg(feature = "deprecated")] pub fn UpdateAvailabilityForProvider<'a, Param0: ::windows::core::IntoParam<'a, IPerceptionFrameProvider>>(provider: Param0, available: bool) -> ::windows::core::Result<()> { Self::IPerceptionFrameProviderManagerServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), provider.into_param().abi(), available).ok() }) } #[cfg(feature = "deprecated")] pub fn PublishFrameForProvider<'a, Param0: ::windows::core::IntoParam<'a, IPerceptionFrameProvider>, Param1: ::windows::core::IntoParam<'a, PerceptionFrame>>(provider: Param0, frame: Param1) -> ::windows::core::Result<()> { Self::IPerceptionFrameProviderManagerServiceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), provider.into_param().abi(), frame.into_param().abi()).ok() }) } pub fn IPerceptionFrameProviderManagerServiceStatics<R, F: FnOnce(&IPerceptionFrameProviderManagerServiceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PerceptionFrameProviderManagerService, IPerceptionFrameProviderManagerServiceStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for PerceptionFrameProviderManagerService { const NAME: &'static str = "Windows.Devices.Perception.Provider.PerceptionFrameProviderManagerService"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PerceptionPropertyChangeRequest(pub ::windows::core::IInspectable); impl PerceptionPropertyChangeRequest { #[cfg(feature = "deprecated")] pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] pub fn Value(&self) -> ::windows::core::Result<::windows::core::IInspectable> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::IInspectable>(result__) } } #[cfg(feature = "deprecated")] pub fn Status(&self) -> ::windows::core::Result<super::PerceptionFrameSourcePropertyChangeStatus> { let this = self; unsafe { let mut result__: super::PerceptionFrameSourcePropertyChangeStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::PerceptionFrameSourcePropertyChangeStatus>(result__) } } #[cfg(feature = "deprecated")] pub fn SetStatus(&self, value: super::PerceptionFrameSourcePropertyChangeStatus) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "deprecated")] #[cfg(feature = "Foundation")] pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::super::Foundation::Deferral> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Deferral>(result__) } } } unsafe impl ::windows::core::RuntimeType for PerceptionPropertyChangeRequest { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.Provider.PerceptionPropertyChangeRequest;{3c5aeb51-350b-4df8-9414-59e09815510b})"); } unsafe impl ::windows::core::Interface for PerceptionPropertyChangeRequest { type Vtable = IPerceptionPropertyChangeRequest_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3c5aeb51_350b_4df8_9414_59e09815510b); } impl ::windows::core::RuntimeName for PerceptionPropertyChangeRequest { const NAME: &'static str = "Windows.Devices.Perception.Provider.PerceptionPropertyChangeRequest"; } impl ::core::convert::From<PerceptionPropertyChangeRequest> for ::windows::core::IUnknown { fn from(value: PerceptionPropertyChangeRequest) -> Self { value.0 .0 } } impl ::core::convert::From<&PerceptionPropertyChangeRequest> for ::windows::core::IUnknown { fn from(value: &PerceptionPropertyChangeRequest) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionPropertyChangeRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PerceptionPropertyChangeRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PerceptionPropertyChangeRequest> for ::windows::core::IInspectable { fn from(value: PerceptionPropertyChangeRequest) -> Self { value.0 } } impl ::core::convert::From<&PerceptionPropertyChangeRequest> for ::windows::core::IInspectable { fn from(value: &PerceptionPropertyChangeRequest) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionPropertyChangeRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PerceptionPropertyChangeRequest { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PerceptionPropertyChangeRequest {} unsafe impl ::core::marker::Sync for PerceptionPropertyChangeRequest {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PerceptionStartFaceAuthenticationHandler(::windows::core::IUnknown); impl PerceptionStartFaceAuthenticationHandler { pub fn new<F: FnMut(&::core::option::Option<PerceptionFaceAuthenticationGroup>) -> ::windows::core::Result<bool> + 'static>(invoke: F) -> Self { let com = PerceptionStartFaceAuthenticationHandler_box::<F> { vtable: &PerceptionStartFaceAuthenticationHandler_box::<F>::VTABLE, count: ::windows::core::RefCount::new(1), invoke, }; unsafe { core::mem::transmute(::windows::core::alloc::boxed::Box::new(com)) } } pub fn Invoke<'a, Param0: ::windows::core::IntoParam<'a, PerceptionFaceAuthenticationGroup>>(&self, sender: Param0) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).3)(::core::mem::transmute_copy(this), sender.into_param().abi(), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for PerceptionStartFaceAuthenticationHandler { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"delegate({74816d2a-2090-4670-8c48-ef39e7ff7c26})"); } unsafe impl ::windows::core::Interface for PerceptionStartFaceAuthenticationHandler { type Vtable = PerceptionStartFaceAuthenticationHandler_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x74816d2a_2090_4670_8c48_ef39e7ff7c26); } #[repr(C)] #[doc(hidden)] pub struct PerceptionStartFaceAuthenticationHandler_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sender: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(C)] struct PerceptionStartFaceAuthenticationHandler_box<F: FnMut(&::core::option::Option<PerceptionFaceAuthenticationGroup>) -> ::windows::core::Result<bool> + 'static> { vtable: *const PerceptionStartFaceAuthenticationHandler_abi, invoke: F, count: ::windows::core::RefCount, } impl<F: FnMut(&::core::option::Option<PerceptionFaceAuthenticationGroup>) -> ::windows::core::Result<bool> + 'static> PerceptionStartFaceAuthenticationHandler_box<F> { const VTABLE: PerceptionStartFaceAuthenticationHandler_abi = PerceptionStartFaceAuthenticationHandler_abi(Self::QueryInterface, Self::AddRef, Self::Release, Self::Invoke); unsafe extern "system" fn QueryInterface(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; *interface = if iid == &<PerceptionStartFaceAuthenticationHandler as ::windows::core::Interface>::IID || iid == &<::windows::core::IUnknown as ::windows::core::Interface>::IID || iid == &<::windows::core::IAgileObject as ::windows::core::Interface>::IID { &mut (*this).vtable as *mut _ as _ } else { ::core::ptr::null_mut() }; if (*interface).is_null() { ::windows::core::HRESULT(0x8000_4002) } else { (*this).count.add_ref(); ::windows::core::HRESULT(0) } } unsafe extern "system" fn AddRef(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; (*this).count.add_ref() } unsafe extern "system" fn Release(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; let remaining = (*this).count.release(); if remaining == 0 { ::windows::core::alloc::boxed::Box::from_raw(this); } remaining } unsafe extern "system" fn Invoke(this: ::windows::core::RawPtr, sender: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; match ((*this).invoke)(&*(&sender as *const <PerceptionFaceAuthenticationGroup as ::windows::core::Abi>::Abi as *const <PerceptionFaceAuthenticationGroup as ::windows::core::DefaultType>::DefaultType)) { ::core::result::Result::Ok(ok__) => { *result__ = ::core::mem::transmute_copy(&ok__); ::core::mem::forget(ok__); ::windows::core::HRESULT(0) } ::core::result::Result::Err(err) => err.into(), } } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PerceptionStopFaceAuthenticationHandler(::windows::core::IUnknown); impl PerceptionStopFaceAuthenticationHandler { pub fn new<F: FnMut(&::core::option::Option<PerceptionFaceAuthenticationGroup>) -> ::windows::core::Result<()> + 'static>(invoke: F) -> Self { let com = PerceptionStopFaceAuthenticationHandler_box::<F> { vtable: &PerceptionStopFaceAuthenticationHandler_box::<F>::VTABLE, count: ::windows::core::RefCount::new(1), invoke, }; unsafe { core::mem::transmute(::windows::core::alloc::boxed::Box::new(com)) } } pub fn Invoke<'a, Param0: ::windows::core::IntoParam<'a, PerceptionFaceAuthenticationGroup>>(&self, sender: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).3)(::core::mem::transmute_copy(this), sender.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for PerceptionStopFaceAuthenticationHandler { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"delegate({387ee6aa-89cd-481e-aade-dd92f70b2ad7})"); } unsafe impl ::windows::core::Interface for PerceptionStopFaceAuthenticationHandler { type Vtable = PerceptionStopFaceAuthenticationHandler_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x387ee6aa_89cd_481e_aade_dd92f70b2ad7); } #[repr(C)] #[doc(hidden)] pub struct PerceptionStopFaceAuthenticationHandler_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sender: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(C)] struct PerceptionStopFaceAuthenticationHandler_box<F: FnMut(&::core::option::Option<PerceptionFaceAuthenticationGroup>) -> ::windows::core::Result<()> + 'static> { vtable: *const PerceptionStopFaceAuthenticationHandler_abi, invoke: F, count: ::windows::core::RefCount, } impl<F: FnMut(&::core::option::Option<PerceptionFaceAuthenticationGroup>) -> ::windows::core::Result<()> + 'static> PerceptionStopFaceAuthenticationHandler_box<F> { const VTABLE: PerceptionStopFaceAuthenticationHandler_abi = PerceptionStopFaceAuthenticationHandler_abi(Self::QueryInterface, Self::AddRef, Self::Release, Self::Invoke); unsafe extern "system" fn QueryInterface(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; *interface = if iid == &<PerceptionStopFaceAuthenticationHandler as ::windows::core::Interface>::IID || iid == &<::windows::core::IUnknown as ::windows::core::Interface>::IID || iid == &<::windows::core::IAgileObject as ::windows::core::Interface>::IID { &mut (*this).vtable as *mut _ as _ } else { ::core::ptr::null_mut() }; if (*interface).is_null() { ::windows::core::HRESULT(0x8000_4002) } else { (*this).count.add_ref(); ::windows::core::HRESULT(0) } } unsafe extern "system" fn AddRef(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; (*this).count.add_ref() } unsafe extern "system" fn Release(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; let remaining = (*this).count.release(); if remaining == 0 { ::windows::core::alloc::boxed::Box::from_raw(this); } remaining } unsafe extern "system" fn Invoke(this: ::windows::core::RawPtr, sender: ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; ((*this).invoke)(&*(&sender as *const <PerceptionFaceAuthenticationGroup as ::windows::core::Abi>::Abi as *const <PerceptionFaceAuthenticationGroup as ::windows::core::DefaultType>::DefaultType)).into() } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PerceptionVideoFrameAllocator(pub ::windows::core::IInspectable); impl PerceptionVideoFrameAllocator { #[cfg(feature = "deprecated")] pub fn AllocateFrame(&self) -> ::windows::core::Result<PerceptionFrame> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PerceptionFrame>(result__) } } #[cfg(feature = "deprecated")] #[cfg(feature = "Media")] pub fn CopyFromVideoFrame<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Media::VideoFrame>>(&self, frame: Param0) -> ::windows::core::Result<PerceptionFrame> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), frame.into_param().abi(), &mut result__).from_abi::<PerceptionFrame>(result__) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "deprecated")] #[cfg(all(feature = "Foundation", feature = "Graphics_Imaging"))] pub fn Create<'a, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::Size>>(maxoutstandingframecountforwrite: u32, format: super::super::super::Graphics::Imaging::BitmapPixelFormat, resolution: Param2, alpha: super::super::super::Graphics::Imaging::BitmapAlphaMode) -> ::windows::core::Result<PerceptionVideoFrameAllocator> { Self::IPerceptionVideoFrameAllocatorFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), maxoutstandingframecountforwrite, format, resolution.into_param().abi(), alpha, &mut result__).from_abi::<PerceptionVideoFrameAllocator>(result__) }) } pub fn IPerceptionVideoFrameAllocatorFactory<R, F: FnOnce(&IPerceptionVideoFrameAllocatorFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PerceptionVideoFrameAllocator, IPerceptionVideoFrameAllocatorFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for PerceptionVideoFrameAllocator { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Perception.Provider.PerceptionVideoFrameAllocator;{4c38a7da-fdd8-4ed4-a039-2a6f9b235038})"); } unsafe impl ::windows::core::Interface for PerceptionVideoFrameAllocator { type Vtable = IPerceptionVideoFrameAllocator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4c38a7da_fdd8_4ed4_a039_2a6f9b235038); } impl ::windows::core::RuntimeName for PerceptionVideoFrameAllocator { const NAME: &'static str = "Windows.Devices.Perception.Provider.PerceptionVideoFrameAllocator"; } impl ::core::convert::From<PerceptionVideoFrameAllocator> for ::windows::core::IUnknown { fn from(value: PerceptionVideoFrameAllocator) -> Self { value.0 .0 } } impl ::core::convert::From<&PerceptionVideoFrameAllocator> for ::windows::core::IUnknown { fn from(value: &PerceptionVideoFrameAllocator) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PerceptionVideoFrameAllocator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a PerceptionVideoFrameAllocator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PerceptionVideoFrameAllocator> for ::windows::core::IInspectable { fn from(value: PerceptionVideoFrameAllocator) -> Self { value.0 } } impl ::core::convert::From<&PerceptionVideoFrameAllocator> for ::windows::core::IInspectable { fn from(value: &PerceptionVideoFrameAllocator) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PerceptionVideoFrameAllocator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a PerceptionVideoFrameAllocator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<PerceptionVideoFrameAllocator> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: PerceptionVideoFrameAllocator) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&PerceptionVideoFrameAllocator> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &PerceptionVideoFrameAllocator) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for PerceptionVideoFrameAllocator { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for &PerceptionVideoFrameAllocator { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for PerceptionVideoFrameAllocator {} unsafe impl ::core::marker::Sync for PerceptionVideoFrameAllocator {}
use std::sync::mpsc; use std::sync::mpsc::{Receiver, Sender}; use std::thread; use crate::gui; use crate::i2c; use crate::protocol::{Button, Device, IncomingMsg}; // Represents all messages sent between modules #[derive(Clone, Debug)] pub enum Event { I2C(i2c::I2CEvent), Serial(SerialEvent), Gui(gui::GuiEvent), } impl From<IncomingMsg> for Event { fn from(message: IncomingMsg) -> Self { match message { IncomingMsg::CreateWindow(new_window) => { Event::Gui(gui::GuiEvent::CreateWindow(new_window)) } IncomingMsg::DestroyWindow(id) => Event::Gui(gui::GuiEvent::DestroyWindow(id)), IncomingMsg::On(button, device) => Event::I2C(i2c::I2CEvent::On(button, device)), IncomingMsg::Off(button, device) => Event::I2C(i2c::I2CEvent::Off(button, device)), } } } // Represents a message sent to the interface module // These messages are usually sent to the client #[derive(Clone, Debug)] pub enum SerialEvent { Pressed(Device, Button), Released(Device, Button), } // Main thread of altctrl // Handles the setup of all the modules in the project // Handles message schedule pub fn start(interface: fn(Sender<Event>, Receiver<SerialEvent>)) { //Outcoming message channel for all modules let (tx, rx) = mpsc::channel(); //Incoming message channels for specific modules let (gui_tx, gui_rx) = mpsc::channel(); let (serial_tx, serial_rx) = mpsc::channel(); let clone_tx = tx.clone(); //Launch the interface module thread::spawn(move || { interface(clone_tx, serial_rx); }); let clone_tx = tx.clone(); //Launch the gui module thread::spawn(move || { gui::launch(clone_tx, gui_rx); }); //Initalizes the data structure for the i2c module let mut i2c_struct = i2c::initialize(tx.clone()); //Handles message scheduling in a loop loop { for event in rx.iter() { match event { Event::I2C(i2c_event) => i2c::handle(i2c_event, &mut i2c_struct), Event::Serial(serial_event) => serial_tx.send(serial_event).unwrap(), Event::Gui(gui_event) => gui_tx.send(gui_event).unwrap(), } } } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/quuid.h // dst-file: /src/core/quuid.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::qstring::*; // 773 use super::qbytearray::*; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QUuid_Class_Size() -> c_int; // proto: void QUuid::QUuid(const QString & ); fn C_ZN5QUuidC2ERK7QString(arg0: *mut c_void) -> u64; // proto: QByteArray QUuid::toRfc4122(); fn C_ZNK5QUuid9toRfc4122Ev(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QString QUuid::toString(); fn C_ZNK5QUuid8toStringEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QUuid::isNull(); fn C_ZNK5QUuid6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: static QUuid QUuid::createUuidV5(const QUuid & ns, const QString & baseData); fn C_ZN5QUuid12createUuidV5ERKS_RK7QString(arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: static QUuid QUuid::createUuid(); fn C_ZN5QUuid10createUuidEv() -> *mut c_void; // proto: void QUuid::QUuid(uint l, ushort w1, ushort w2, uchar b1, uchar b2, uchar b3, uchar b4, uchar b5, uchar b6, uchar b7, uchar b8); fn C_ZN5QUuidC2Ejtthhhhhhhh(arg0: c_uint, arg1: c_ushort, arg2: c_ushort, arg3: c_uchar, arg4: c_uchar, arg5: c_uchar, arg6: c_uchar, arg7: c_uchar, arg8: c_uchar, arg9: c_uchar, arg10: c_uchar) -> u64; // proto: void QUuid::QUuid(const QByteArray & ); fn C_ZN5QUuidC2ERK10QByteArray(arg0: *mut c_void) -> u64; // proto: static QUuid QUuid::createUuidV3(const QUuid & ns, const QString & baseData); fn C_ZN5QUuid12createUuidV3ERKS_RK7QString(arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: void QUuid::QUuid(); fn C_ZN5QUuidC2Ev() -> u64; // proto: QByteArray QUuid::toByteArray(); fn C_ZNK5QUuid11toByteArrayEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QUuid::QUuid(const char * ); fn C_ZN5QUuidC2EPKc(arg0: *mut c_char) -> u64; // proto: static QUuid QUuid::createUuidV5(const QUuid & ns, const QByteArray & baseData); fn C_ZN5QUuid12createUuidV5ERKS_RK10QByteArray(arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; // proto: static QUuid QUuid::fromRfc4122(const QByteArray & ); fn C_ZN5QUuid11fromRfc4122ERK10QByteArray(arg0: *mut c_void) -> *mut c_void; // proto: static QUuid QUuid::createUuidV3(const QUuid & ns, const QByteArray & baseData); fn C_ZN5QUuid12createUuidV3ERKS_RK10QByteArray(arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void; } // <= ext block end // body block begin => // class sizeof(QUuid)=16 #[derive(Default)] pub struct QUuid { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QUuid { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QUuid { return QUuid{qclsinst: qthis, ..Default::default()}; } } // proto: void QUuid::QUuid(const QString & ); impl /*struct*/ QUuid { pub fn new<T: QUuid_new>(value: T) -> QUuid { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QUuid_new { fn new(self) -> QUuid; } // proto: void QUuid::QUuid(const QString & ); impl<'a> /*trait*/ QUuid_new for (&'a QString) { fn new(self) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuidC2ERK7QString()}; let ctysz: c_int = unsafe{QUuid_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_ZN5QUuidC2ERK7QString(arg0)}; let rsthis = QUuid{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QByteArray QUuid::toRfc4122(); impl /*struct*/ QUuid { pub fn toRfc4122<RetType, T: QUuid_toRfc4122<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toRfc4122(self); // return 1; } } pub trait QUuid_toRfc4122<RetType> { fn toRfc4122(self , rsthis: & QUuid) -> RetType; } // proto: QByteArray QUuid::toRfc4122(); impl<'a> /*trait*/ QUuid_toRfc4122<QByteArray> for () { fn toRfc4122(self , rsthis: & QUuid) -> QByteArray { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK5QUuid9toRfc4122Ev()}; let mut ret = unsafe {C_ZNK5QUuid9toRfc4122Ev(rsthis.qclsinst)}; let mut ret1 = QByteArray::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QString QUuid::toString(); impl /*struct*/ QUuid { pub fn toString<RetType, T: QUuid_toString<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toString(self); // return 1; } } pub trait QUuid_toString<RetType> { fn toString(self , rsthis: & QUuid) -> RetType; } // proto: QString QUuid::toString(); impl<'a> /*trait*/ QUuid_toString<QString> for () { fn toString(self , rsthis: & QUuid) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK5QUuid8toStringEv()}; let mut ret = unsafe {C_ZNK5QUuid8toStringEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QUuid::isNull(); impl /*struct*/ QUuid { pub fn isNull<RetType, T: QUuid_isNull<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isNull(self); // return 1; } } pub trait QUuid_isNull<RetType> { fn isNull(self , rsthis: & QUuid) -> RetType; } // proto: bool QUuid::isNull(); impl<'a> /*trait*/ QUuid_isNull<i8> for () { fn isNull(self , rsthis: & QUuid) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK5QUuid6isNullEv()}; let mut ret = unsafe {C_ZNK5QUuid6isNullEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: static QUuid QUuid::createUuidV5(const QUuid & ns, const QString & baseData); impl /*struct*/ QUuid { pub fn createUuidV5_s<RetType, T: QUuid_createUuidV5_s<RetType>>( overload_args: T) -> RetType { return overload_args.createUuidV5_s(); // return 1; } } pub trait QUuid_createUuidV5_s<RetType> { fn createUuidV5_s(self ) -> RetType; } // proto: static QUuid QUuid::createUuidV5(const QUuid & ns, const QString & baseData); impl<'a> /*trait*/ QUuid_createUuidV5_s<QUuid> for (&'a QUuid, &'a QString) { fn createUuidV5_s(self ) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuid12createUuidV5ERKS_RK7QString()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN5QUuid12createUuidV5ERKS_RK7QString(arg0, arg1)}; let mut ret1 = QUuid::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: static QUuid QUuid::createUuid(); impl /*struct*/ QUuid { pub fn createUuid_s<RetType, T: QUuid_createUuid_s<RetType>>( overload_args: T) -> RetType { return overload_args.createUuid_s(); // return 1; } } pub trait QUuid_createUuid_s<RetType> { fn createUuid_s(self ) -> RetType; } // proto: static QUuid QUuid::createUuid(); impl<'a> /*trait*/ QUuid_createUuid_s<QUuid> for () { fn createUuid_s(self ) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuid10createUuidEv()}; let mut ret = unsafe {C_ZN5QUuid10createUuidEv()}; let mut ret1 = QUuid::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QUuid::QUuid(uint l, ushort w1, ushort w2, uchar b1, uchar b2, uchar b3, uchar b4, uchar b5, uchar b6, uchar b7, uchar b8); impl<'a> /*trait*/ QUuid_new for (u32, u16, u16, u8, u8, u8, u8, u8, u8, u8, u8) { fn new(self) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuidC2Ejtthhhhhhhh()}; let ctysz: c_int = unsafe{QUuid_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0 as c_uint; let arg1 = self.1 as c_ushort; let arg2 = self.2 as c_ushort; let arg3 = self.3 as c_uchar; let arg4 = self.4 as c_uchar; let arg5 = self.5 as c_uchar; let arg6 = self.6 as c_uchar; let arg7 = self.7 as c_uchar; let arg8 = self.8 as c_uchar; let arg9 = self.9 as c_uchar; let arg10 = self.10 as c_uchar; let qthis: u64 = unsafe {C_ZN5QUuidC2Ejtthhhhhhhh(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10)}; let rsthis = QUuid{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QUuid::QUuid(const QByteArray & ); impl<'a> /*trait*/ QUuid_new for (&'a QByteArray) { fn new(self) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuidC2ERK10QByteArray()}; let ctysz: c_int = unsafe{QUuid_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_ZN5QUuidC2ERK10QByteArray(arg0)}; let rsthis = QUuid{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: static QUuid QUuid::createUuidV3(const QUuid & ns, const QString & baseData); impl /*struct*/ QUuid { pub fn createUuidV3_s<RetType, T: QUuid_createUuidV3_s<RetType>>( overload_args: T) -> RetType { return overload_args.createUuidV3_s(); // return 1; } } pub trait QUuid_createUuidV3_s<RetType> { fn createUuidV3_s(self ) -> RetType; } // proto: static QUuid QUuid::createUuidV3(const QUuid & ns, const QString & baseData); impl<'a> /*trait*/ QUuid_createUuidV3_s<QUuid> for (&'a QUuid, &'a QString) { fn createUuidV3_s(self ) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuid12createUuidV3ERKS_RK7QString()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN5QUuid12createUuidV3ERKS_RK7QString(arg0, arg1)}; let mut ret1 = QUuid::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QUuid::QUuid(); impl<'a> /*trait*/ QUuid_new for () { fn new(self) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuidC2Ev()}; let ctysz: c_int = unsafe{QUuid_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN5QUuidC2Ev()}; let rsthis = QUuid{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QByteArray QUuid::toByteArray(); impl /*struct*/ QUuid { pub fn toByteArray<RetType, T: QUuid_toByteArray<RetType>>(& self, overload_args: T) -> RetType { return overload_args.toByteArray(self); // return 1; } } pub trait QUuid_toByteArray<RetType> { fn toByteArray(self , rsthis: & QUuid) -> RetType; } // proto: QByteArray QUuid::toByteArray(); impl<'a> /*trait*/ QUuid_toByteArray<QByteArray> for () { fn toByteArray(self , rsthis: & QUuid) -> QByteArray { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK5QUuid11toByteArrayEv()}; let mut ret = unsafe {C_ZNK5QUuid11toByteArrayEv(rsthis.qclsinst)}; let mut ret1 = QByteArray::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QUuid::QUuid(const char * ); impl<'a> /*trait*/ QUuid_new for (&'a String) { fn new(self) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuidC2EPKc()}; let ctysz: c_int = unsafe{QUuid_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.as_ptr() as *mut c_char; let qthis: u64 = unsafe {C_ZN5QUuidC2EPKc(arg0)}; let rsthis = QUuid{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: static QUuid QUuid::createUuidV5(const QUuid & ns, const QByteArray & baseData); impl<'a> /*trait*/ QUuid_createUuidV5_s<QUuid> for (&'a QUuid, &'a QByteArray) { fn createUuidV5_s(self ) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuid12createUuidV5ERKS_RK10QByteArray()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN5QUuid12createUuidV5ERKS_RK10QByteArray(arg0, arg1)}; let mut ret1 = QUuid::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: static QUuid QUuid::fromRfc4122(const QByteArray & ); impl /*struct*/ QUuid { pub fn fromRfc4122_s<RetType, T: QUuid_fromRfc4122_s<RetType>>( overload_args: T) -> RetType { return overload_args.fromRfc4122_s(); // return 1; } } pub trait QUuid_fromRfc4122_s<RetType> { fn fromRfc4122_s(self ) -> RetType; } // proto: static QUuid QUuid::fromRfc4122(const QByteArray & ); impl<'a> /*trait*/ QUuid_fromRfc4122_s<QUuid> for (&'a QByteArray) { fn fromRfc4122_s(self ) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuid11fromRfc4122ERK10QByteArray()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN5QUuid11fromRfc4122ERK10QByteArray(arg0)}; let mut ret1 = QUuid::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: static QUuid QUuid::createUuidV3(const QUuid & ns, const QByteArray & baseData); impl<'a> /*trait*/ QUuid_createUuidV3_s<QUuid> for (&'a QUuid, &'a QByteArray) { fn createUuidV3_s(self ) -> QUuid { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN5QUuid12createUuidV3ERKS_RK10QByteArray()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN5QUuid12createUuidV3ERKS_RK10QByteArray(arg0, arg1)}; let mut ret1 = QUuid::inheritFrom(ret as u64); return ret1; // return 1; } } // <= body block end
use std::convert::TryFrom; use std::io; #[derive(Debug, PartialEq)] enum ParamMode { Immediate, Position, } #[derive(Debug, PartialEq)] enum OpCode { Add, Mul, Input, Output, JumpIfTrue, JumpIfFalse, LessThan, Equals, Halt, } #[derive(Debug, PartialEq)] struct Instruction { op: OpCode, mode_p1: ParamMode, mode_p2: ParamMode, mode_p3: ParamMode, } pub fn intcode_computer( xs: &mut [isize], inputs: &[isize], ) -> Result<Vec<isize>, &'static str> { const MAX_ITERATIONS: isize = 10_000; let mut index: usize = 0; let mut ctr = 0; let mut input = inputs.iter(); let mut outputs = Vec::new(); while index < xs.len() && ctr < MAX_ITERATIONS { ctr += 1; let instr = parse_instruction(xs[index]).unwrap(); use OpCode::*; match instr.op { Add => { let param1 = extract_param(xs, index + 1, instr.mode_p1); let param2 = extract_param(xs, index + 2, instr.mode_p2); let idx_output = usize::try_from(xs[index + 3]).unwrap(); xs[idx_output] = param1 + param2; index += 4; } Mul => { let param1 = extract_param(xs, index + 1, instr.mode_p1); let param2 = extract_param(xs, index + 2, instr.mode_p2); let idx_output = usize::try_from(xs[index + 3]).unwrap(); xs[idx_output] = param1 * param2; index += 4; } Input => { match input.next() { Some(param) => { let idx_output = usize::try_from(xs[index + 1]).unwrap(); xs[idx_output] = param.clone(); } None => return Err("Could not read input"), }; index += 2; } Output => { let idx_output = usize::try_from(xs[index + 1]).unwrap(); outputs.push(xs[idx_output]); index += 2; } JumpIfTrue => { let param1 = extract_param(xs, index + 1, instr.mode_p1); let param2 = extract_param(xs, index + 2, instr.mode_p2); if param1 != 0 { index = usize::try_from(param2).unwrap(); } else { index += 3; } } JumpIfFalse => { let param1 = extract_param(xs, index + 1, instr.mode_p1); let param2 = extract_param(xs, index + 2, instr.mode_p2); if param1 == 0 { index = usize::try_from(param2).unwrap(); } else { index += 3; } } LessThan => { let param1 = extract_param(xs, index + 1, instr.mode_p1); let param2 = extract_param(xs, index + 2, instr.mode_p2); let idx_output = usize::try_from(xs[index + 3]).unwrap(); xs[idx_output] = if param1 < param2 { 1 } else { 0 }; index += 4; } Equals => { let param1 = extract_param(xs, index + 1, instr.mode_p1); let param2 = extract_param(xs, index + 2, instr.mode_p2); let idx_output = usize::try_from(xs[index + 3]).unwrap(); xs[idx_output] = if param1 == param2 { 1 } else { 0 }; index += 4; } Halt => { index += xs.len(); } } } if ctr > MAX_ITERATIONS { Err("Crossed MAX_ITERATIONS") } else { Ok(outputs) } } fn extract_param(xs: &[isize], index: usize, mode: ParamMode) -> isize { let param = xs[index]; match mode { ParamMode::Immediate => param, ParamMode::Position => xs[usize::try_from(param).unwrap()], } } fn parse_instruction(instr: isize) -> Result<Instruction, &'static str> { // Extract op code use OpCode::*; use ParamMode::*; let instr_step1 = instr / 100; let opcode = instr - (100 * instr_step1); let opcode = match opcode { 1 => Add, 2 => Mul, 3 => Input, 4 => Output, 5 => JumpIfTrue, 6 => JumpIfFalse, 7 => LessThan, 8 => Equals, 99 => Halt, _ => { dbg!(opcode); return Err("Unknown op code"); } }; // Param Mode for 1st param let instr_step2 = instr_step1 / 10; let mode_1 = instr_step1 - (10 * instr_step2); let mode_1 = match mode_1 { 0 => Position, 1 => Immediate, _ => { return { dbg!(mode_1); Err("Unknown parameter mode") } } }; // Param Mode for 2nd param let instr_step3 = instr_step2 / 10; let mode_2 = instr_step2 - (10 * instr_step3); let mode_2 = match mode_2 { 0 => Position, 1 => Immediate, _ => { dbg!(mode_2); return Err("Unknown parameter mode"); } }; // Param Mode for 1st param let instr_step4 = instr_step3 / 10; let mode_3 = instr_step3 - (10 * instr_step4); let mode_3 = match mode_3 { 0 => Position, 1 => return Err("Parameter Mode for output cannot be Immediate"), _ => { dbg!(mode_3); return Err("Unknown parameter mode"); } }; Ok(Instruction { op: opcode, mode_p1: mode_1, mode_p2: mode_2, mode_p3: mode_3, }) }
use std::borrow::Cow; use std::collections::{BTreeSet, HashSet}; use serde::{Deserialize, Serialize}; use crate::position_map::PositionMap; use crate::{Error, FieldId, FieldsMap, IndexedPos, SResult}; #[derive(Clone, Debug, Serialize, Deserialize, Default)] pub struct Schema { fields_map: FieldsMap, primary_key: Option<FieldId>, ranked: HashSet<FieldId>, displayed: Option<BTreeSet<FieldId>>, searchable: Option<Vec<FieldId>>, pub indexed_position: PositionMap, } impl Schema { pub fn with_primary_key(name: &str) -> Schema { let mut fields_map = FieldsMap::default(); let field_id = fields_map.insert(name).unwrap(); let mut indexed_position = PositionMap::default(); indexed_position.push(field_id); Schema { fields_map, primary_key: Some(field_id), ranked: HashSet::new(), displayed: None, searchable: None, indexed_position, } } pub fn primary_key(&self) -> Option<&str> { self.primary_key.map(|id| self.fields_map.name(id).unwrap()) } pub fn set_primary_key(&mut self, name: &str) -> SResult<FieldId> { if self.primary_key.is_some() { return Err(Error::PrimaryKeyAlreadyPresent); } let id = self.insert(name)?; self.primary_key = Some(id); Ok(id) } pub fn id(&self, name: &str) -> Option<FieldId> { self.fields_map.id(name) } pub fn name<I: Into<FieldId>>(&self, id: I) -> Option<&str> { self.fields_map.name(id) } pub fn names(&self) -> impl Iterator<Item = &str> { self.fields_map.iter().map(|(k, _)| k.as_ref()) } /// add `name` to the list of known fields pub fn insert(&mut self, name: &str) -> SResult<FieldId> { self.fields_map.insert(name) } /// Adds `name` to the list of known fields, and in the last position of the indexed_position map. This /// field is taken into acccount when `searchableAttribute` or `displayedAttributes` is set to `"*"` pub fn insert_with_position(&mut self, name: &str) -> SResult<(FieldId, IndexedPos)> { let field_id = self.fields_map.insert(name)?; let position = self .is_searchable(field_id) .unwrap_or_else(|| self.indexed_position.push(field_id)); Ok((field_id, position)) } pub fn ranked(&self) -> &HashSet<FieldId> { &self.ranked } fn displayed(&self) -> Cow<BTreeSet<FieldId>> { match &self.displayed { Some(displayed) => Cow::Borrowed(displayed), None => Cow::Owned(self.indexed_position.field_pos().map(|(f, _)| f).collect()), } } pub fn is_displayed_all(&self) -> bool { self.displayed.is_none() } pub fn displayed_names(&self) -> BTreeSet<&str> { self.displayed() .iter() .filter_map(|&f| self.name(f)) .collect() } fn searchable(&self) -> Cow<[FieldId]> { match &self.searchable { Some(searchable) => Cow::Borrowed(&searchable), None => Cow::Owned(self.indexed_position.field_pos().map(|(f, _)| f).collect()), } } pub fn searchable_names(&self) -> Vec<&str> { self.searchable() .iter() .filter_map(|a| self.name(*a)) .collect() } pub(crate) fn set_ranked(&mut self, name: &str) -> SResult<FieldId> { let id = self.fields_map.insert(name)?; self.ranked.insert(id); Ok(id) } pub fn clear_ranked(&mut self) { self.ranked.clear(); } pub fn is_ranked(&self, id: FieldId) -> bool { self.ranked.get(&id).is_some() } pub fn is_displayed(&self, id: FieldId) -> bool { match &self.displayed { Some(displayed) => displayed.contains(&id), None => true, } } pub fn is_searchable(&self, id: FieldId) -> Option<IndexedPos> { match &self.searchable { Some(searchable) if searchable.contains(&id) => self.indexed_position.field_to_pos(id), None => self.indexed_position.field_to_pos(id), _ => None, } } pub fn is_searchable_all(&self) -> bool { self.searchable.is_none() } pub fn indexed_pos_to_field_id<I: Into<IndexedPos>>(&self, pos: I) -> Option<FieldId> { self.indexed_position.pos_to_field(pos.into()) } pub fn update_ranked<S: AsRef<str>>( &mut self, data: impl IntoIterator<Item = S>, ) -> SResult<()> { self.ranked.clear(); for name in data { self.set_ranked(name.as_ref())?; } Ok(()) } pub fn update_displayed<S: AsRef<str>>( &mut self, data: impl IntoIterator<Item = S>, ) -> SResult<()> { let mut displayed = BTreeSet::new(); for name in data { let id = self.fields_map.insert(name.as_ref())?; displayed.insert(id); } self.displayed.replace(displayed); Ok(()) } pub fn update_searchable<S: AsRef<str>>(&mut self, data: Vec<S>) -> SResult<()> { let mut searchable = Vec::with_capacity(data.len()); for (pos, name) in data.iter().enumerate() { let id = self.insert(name.as_ref())?; self.indexed_position.insert(id, IndexedPos(pos as u16)); searchable.push(id); } self.searchable.replace(searchable); Ok(()) } pub fn set_all_searchable(&mut self) { self.searchable.take(); } pub fn set_all_displayed(&mut self) { self.displayed.take(); } } #[cfg(test)] mod test { use super::*; #[test] fn test_with_primary_key() { let schema = Schema::with_primary_key("test"); assert_eq!( format!("{:?}", schema), r##"Schema { fields_map: FieldsMap { name_map: {"test": FieldId(0)}, id_map: {FieldId(0): "test"}, next_id: FieldId(1) }, primary_key: Some(FieldId(0)), ranked: {}, displayed: None, searchable: None, indexed_position: PositionMap { pos_to_field: [FieldId(0)], field_to_pos: {FieldId(0): IndexedPos(0)} } }"## ); } #[test] fn primary_key() { let schema = Schema::with_primary_key("test"); assert_eq!(schema.primary_key(), Some("test")); } #[test] fn test_insert_with_position_base() { let mut schema = Schema::default(); let (id, position) = schema.insert_with_position("foo").unwrap(); assert!(schema.searchable.is_none()); assert!(schema.displayed.is_none()); assert_eq!(id, 0.into()); assert_eq!(position, 0.into()); let (id, position) = schema.insert_with_position("bar").unwrap(); assert_eq!(id, 1.into()); assert_eq!(position, 1.into()); } #[test] fn test_insert_with_position_primary_key() { let mut schema = Schema::with_primary_key("test"); let (id, position) = schema.insert_with_position("foo").unwrap(); assert!(schema.searchable.is_none()); assert!(schema.displayed.is_none()); assert_eq!(id, 1.into()); assert_eq!(position, 1.into()); let (id, position) = schema.insert_with_position("test").unwrap(); assert_eq!(id, 0.into()); assert_eq!(position, 0.into()); } #[test] fn test_insert() { let mut schema = Schema::default(); let field_id = schema.insert("foo").unwrap(); assert!(schema.fields_map.name(field_id).is_some()); assert!(schema.searchable.is_none()); assert!(schema.displayed.is_none()); } #[test] fn test_update_searchable() { let mut schema = Schema::default(); schema.update_searchable(vec!["foo", "bar"]).unwrap(); assert_eq!( format!("{:?}", schema.indexed_position), r##"PositionMap { pos_to_field: [FieldId(0), FieldId(1)], field_to_pos: {FieldId(0): IndexedPos(0), FieldId(1): IndexedPos(1)} }"## ); assert_eq!( format!("{:?}", schema.searchable), r##"Some([FieldId(0), FieldId(1)])"## ); schema.update_searchable(vec!["bar"]).unwrap(); assert_eq!( format!("{:?}", schema.searchable), r##"Some([FieldId(1)])"## ); assert_eq!( format!("{:?}", schema.indexed_position), r##"PositionMap { pos_to_field: [FieldId(1), FieldId(0)], field_to_pos: {FieldId(0): IndexedPos(1), FieldId(1): IndexedPos(0)} }"## ); } #[test] fn test_update_displayed() { let mut schema = Schema::default(); schema.update_displayed(vec!["foobar"]).unwrap(); assert_eq!( format!("{:?}", schema.displayed), r##"Some({FieldId(0)})"## ); assert_eq!( format!("{:?}", schema.indexed_position), r##"PositionMap { pos_to_field: [], field_to_pos: {} }"## ); } #[test] fn test_is_searchable_all() { let mut schema = Schema::default(); assert!(schema.is_searchable_all()); schema.update_searchable(vec!["foo"]).unwrap(); assert!(!schema.is_searchable_all()); } #[test] fn test_is_displayed_all() { let mut schema = Schema::default(); assert!(schema.is_displayed_all()); schema.update_displayed(vec!["foo"]).unwrap(); assert!(!schema.is_displayed_all()); } #[test] fn test_searchable_names() { let mut schema = Schema::default(); assert_eq!(format!("{:?}", schema.searchable_names()), r##"[]"##); schema.insert_with_position("foo").unwrap(); schema.insert_with_position("bar").unwrap(); assert_eq!( format!("{:?}", schema.searchable_names()), r##"["foo", "bar"]"## ); schema.update_searchable(vec!["hello", "world"]).unwrap(); assert_eq!( format!("{:?}", schema.searchable_names()), r##"["hello", "world"]"## ); schema.set_all_searchable(); assert_eq!( format!("{:?}", schema.searchable_names()), r##"["hello", "world", "foo", "bar"]"## ); } #[test] fn test_displayed_names() { let mut schema = Schema::default(); assert_eq!(format!("{:?}", schema.displayed_names()), r##"{}"##); schema.insert_with_position("foo").unwrap(); schema.insert_with_position("bar").unwrap(); assert_eq!( format!("{:?}", schema.displayed_names()), r##"{"bar", "foo"}"## ); schema.update_displayed(vec!["hello", "world"]).unwrap(); assert_eq!( format!("{:?}", schema.displayed_names()), r##"{"hello", "world"}"## ); schema.set_all_displayed(); assert_eq!( format!("{:?}", schema.displayed_names()), r##"{"bar", "foo"}"## ); } #[test] fn test_set_all_searchable() { let mut schema = Schema::default(); assert!(schema.is_searchable_all()); schema.update_searchable(vec!["foobar"]).unwrap(); assert!(!schema.is_searchable_all()); schema.set_all_searchable(); assert!(schema.is_searchable_all()); } #[test] fn test_set_all_displayed() { let mut schema = Schema::default(); assert!(schema.is_displayed_all()); schema.update_displayed(vec!["foobar"]).unwrap(); assert!(!schema.is_displayed_all()); schema.set_all_displayed(); assert!(schema.is_displayed_all()); } }
use core::ops::{Deref, Range, RangeFrom, RangeFull, RangeTo}; use core::str::{CharIndices, Chars, FromStr}; use nom::error::{ErrorKind, ParseError}; use nom::{ AsBytes, Compare, CompareResult, Err, ExtendInto, FindSubstring, FindToken, IResult, InputIter, InputLength, InputTake, InputTakeAtPosition, Offset, ParseTo, Slice, }; /// Tracks location information and user-defined metadata for nom's source input. #[derive(Debug, Clone)] pub struct TrackedLocation<T, X> { /// The offset represents the current byte position relative to the original input offset: usize, /// Tracks the current line number (starts at 1) line: usize, /// Tracks the current character number (starts at 1, UTF8-aware) char: usize, /// A slice representing the remaining input input: T, /// Any user-defined metadata that should be tracked in addition to the location pub metadata: X, /// Tracks a reference to the remaining input from the heredoc's start line pub(crate) remaining_input: Option<Box<Self>>, } impl<T, X> Deref for TrackedLocation<T, X> { type Target = T; fn deref(&self) -> &Self::Target { &self.input } } impl<T: AsBytes, X> TrackedLocation<T, X> { pub fn new_with_metadata(program: T, metadata: X) -> Self { Self { offset: 0, line: 1, char: 1, input: program, metadata: metadata, remaining_input: None, } } pub fn offset(&self) -> usize { self.offset } pub fn line(&self) -> usize { self.line } pub fn char(&self) -> usize { self.char } pub fn input(&self) -> &T { &self.input } pub fn metadata(&self) -> &X { &self.metadata } pub fn beginning_of_line(&self) -> bool { self.char == 1 } } impl<T: AsBytes, X: Default> TrackedLocation<T, X> { pub fn new(program: T) -> Self { Self { offset: 0, line: 1, char: 1, input: program, metadata: X::default(), remaining_input: None, } } pub fn new_with_pos(program: T, offset: usize, line: usize, char: usize) -> Self { Self { offset: offset, line: line, char: char, input: program, metadata: X::default(), remaining_input: None, } } } impl<T: AsBytes, X> TrackedLocation<T, X> { pub fn new_with_pos_and_meta( program: T, offset: usize, line: usize, char: usize, metadata: X, ) -> Self { Self { offset: offset, line: line, char: char, input: program, metadata: metadata, remaining_input: None, } } } impl<T: AsBytes, X: Default> From<T> for TrackedLocation<T, X> { fn from(program: T) -> Self { Self::new_with_metadata(program, X::default()) } } impl<T: PartialEq, X> PartialEq for TrackedLocation<T, X> { fn eq(&self, other: &Self) -> bool { self.offset == other.offset && self.line == other.line && self.char == other.char && self.input == other.input } } impl<T: Eq, X> Eq for TrackedLocation<T, X> {} impl<T: AsBytes, X> AsBytes for TrackedLocation<T, X> { fn as_bytes(&self) -> &[u8] { self.input.as_bytes() } } impl<T: InputLength, X> InputLength for TrackedLocation<T, X> { fn input_len(&self) -> usize { self.input.input_len() } } impl<T, X> InputTake for TrackedLocation<T, X> where Self: Slice<RangeFrom<usize>> + Slice<RangeTo<usize>>, { fn take(&self, count: usize) -> Self { self.slice(..count) } fn take_split(&self, count: usize) -> (Self, Self) { (self.slice(count..), self.slice(..count)) } } impl<T, X> InputTakeAtPosition for TrackedLocation<T, X> where T: InputTakeAtPosition + InputLength + InputIter, Self: Slice<RangeFrom<usize>> + Slice<RangeTo<usize>> + Clone, { type Item = <T as InputIter>::Item; fn split_at_position_complete<P, E: ParseError<Self>>( &self, predicate: P, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool, { match self.split_at_position(predicate) { Err(Err::Incomplete(_)) => Ok(self.take_split(self.input_len())), res => res, } } fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool, { match self.input.position(predicate) { Some(n) => Ok(self.take_split(n)), None => Err(Err::Incomplete(nom::Needed::Size(unsafe { std::num::NonZeroUsize::new_unchecked(1) }))), } } fn split_at_position1<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool, { match self.input.position(predicate) { Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))), Some(n) => Ok(self.take_split(n)), None => Err(Err::Incomplete(nom::Needed::Size(unsafe { std::num::NonZeroUsize::new_unchecked(1) }))), } } fn split_at_position1_complete<P, E: ParseError<Self>>( &self, predicate: P, e: ErrorKind, ) -> IResult<Self, Self, E> where P: Fn(Self::Item) -> bool, { match self.input.position(predicate) { Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))), Some(n) => Ok(self.take_split(n)), None => { if self.input.input_len() == 0 { Err(Err::Error(E::from_error_kind(self.clone(), e))) } else { Ok(self.take_split(self.input_len())) } } } } } impl<'a, X> InputIter for TrackedLocation<&'a str, X> { type Item = char; type Iter = CharIndices<'a>; type IterElem = Chars<'a>; fn iter_indices(&self) -> Self::Iter { self.input.iter_indices() } fn iter_elements(&self) -> Self::IterElem { self.input.iter_elements() } fn position<P>(&self, predicate: P) -> Option<usize> where P: Fn(Self::Item) -> bool, { self.input.position(predicate) } fn slice_index(&self, count: usize) -> Option<usize> { self.input.slice_index(count) } } impl<'a, X> IntoIterator for TrackedLocation<&'a str, X> { type Item = char; type IntoIter = Chars<'a>; fn into_iter(self) -> Self::IntoIter { self.input.chars() } } impl<'a, A: Compare<B>, B: Into<TrackedLocation<B, X>>, X> Compare<B> for TrackedLocation<A, X> { fn compare(&self, other: B) -> CompareResult { self.input.compare(other.into().input) } fn compare_no_case(&self, other: B) -> CompareResult { self.input.compare_no_case(other.into().input) } } impl<T, X> Offset for TrackedLocation<T, X> { fn offset(&self, second: &Self) -> usize { second.offset - self.offset } } impl<'a, T: Clone, X: Clone> Slice<RangeFull> for TrackedLocation<T, X> { fn slice(&self, _range: RangeFull) -> Self { self.clone() } } impl<'a, X: Clone> Slice<RangeFrom<usize>> for TrackedLocation<&'a str, X> { fn slice(&self, range: RangeFrom<usize>) -> Self { if range.start == 0 { return self.clone(); } let next_fragment = self.input.slice(range); if let Some(j) = &self.remaining_input { if next_fragment.input_len() == 0 { return (**j).to_owned(); } }; self.next_from_slice(next_fragment) } } impl<'a, X: Clone> Slice<RangeTo<usize>> for TrackedLocation<&'a str, X> { fn slice(&self, range: RangeTo<usize>) -> Self { self.next_from_slice(self.input.slice(range)) } } impl<'a, X: Clone> Slice<Range<usize>> for TrackedLocation<&'a str, X> { fn slice(&self, range: Range<usize>) -> Self { self.next_from_slice(self.input.slice(range)) } } impl<'a, X: Clone> TrackedLocation<&'a str, X> { fn next_from_slice(&self, next_fragment: &'a str) -> Self { let consumed_len = self.input.offset(&next_fragment); if let Some(j) = &self.remaining_input { if self.input.input_len() == 0 { return (**j).to_owned(); } }; if consumed_len == 0 { return Self { line: self.line, char: self.char, offset: self.offset, input: next_fragment, metadata: self.metadata.clone(), remaining_input: self.remaining_input.clone(), }; } let consumed = self.input.slice(..consumed_len); let next_offset = self.offset + consumed_len; let consumed_as_bytes = consumed.as_bytes(); let iter = memchr::Memchr::new(b'\n', consumed_as_bytes); let number_of_lines = iter.count(); let next_line = self.line + number_of_lines; let next_char = if number_of_lines == 0 { self.char + consumed.chars().count() } else { 1 + consumed.chars().rev().position(|c| c == '\n').unwrap() }; Self { line: next_line, char: next_char, offset: next_offset, input: next_fragment, metadata: self.metadata.clone(), remaining_input: self.remaining_input.clone(), } } } impl<T: FindToken<Token>, Token, X> FindToken<Token> for TrackedLocation<T, X> { fn find_token(&self, token: Token) -> bool { self.input.find_token(token) } } impl<'a, T: FindSubstring<&'a str>, X> FindSubstring<&'a str> for TrackedLocation<T, X> { fn find_substring(&self, substr: &'a str) -> Option<usize> { self.input.find_substring(substr) } } impl<R: FromStr, T: ParseTo<R>, X> ParseTo<R> for TrackedLocation<T, X> { fn parse_to(&self) -> Option<R> { self.input.parse_to() } } impl<T: ToString, X> std::fmt::Display for TrackedLocation<T, X> { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { fmt.write_str(&self.input.to_string()) } } impl<T: ToString, X> From<TrackedLocation<T, X>> for String { fn from(v: TrackedLocation<T, X>) -> Self { v.to_string() } } impl<'a, I, E, T, X> ExtendInto for TrackedLocation<T, X> where E: Default + Extend<I>, T: ExtendInto<Item = I, Extender = E>, Self: Clone + IntoIterator<Item = I>, { type Item = I; type Extender = E; fn new_builder(&self) -> Self::Extender { Self::Extender::default() } fn extend_into(&self, acc: &mut Self::Extender) { acc.extend(self.clone().into_iter()) } } /// Captures the current position within the input #[allow(unused)] pub fn position<T, E>(i: T) -> IResult<T, T, E> where E: ParseError<T>, T: InputIter + InputTake, { nom::bytes::complete::take(0usize)(i) } #[cfg(test)] mod tests { use super::*; type Input<'a> = TrackedLocation<&'a str, ()>; #[test] fn test_continuations() { let mut i = Input::new("foobar"); let j = Input::new_with_pos("baz", 12, 4, 0); assert_eq!(6, i.input_len()); i.remaining_input = Some(Box::new(j)); assert_eq!(6, i.input_len()); assert_eq!( Input::new_with_pos("baz", 12, 4, 0), nom::combinator::rest::<Input, (Input, nom::error::ErrorKind)>(i) .unwrap() .0 ); } }
use protoc_rust::Customize; use std::{fs::create_dir_all, io::Result}; fn main() -> Result<()> { let out_dir = "src/proto/.generated"; create_dir_all(out_dir)?; let result = protoc_rust::run(protoc_rust::Args { out_dir, input: &["proto/chunk_save.proto", "proto/player.proto"], includes: &["proto"], customize: Customize { ..Default::default() }, }); result.expect("protoc"); Ok(()) }
#![feature(proc_macro_hygiene, decl_macro)] extern crate base64; extern crate chrono; extern crate tempfile; #[macro_use] extern crate diesel; extern crate postgres; #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; extern crate jpeg_decoder; extern crate multipart; extern crate png; extern crate serde; extern crate serde_json; extern crate sha2; mod data; mod db; mod error; mod events; mod http; mod http_multipart; mod image; mod limits; mod schema; mod tripcode; fn main() { self::http::start(); }
/* * File : parse.rs * Purpose: routines for parsing using input into useful data * Program: red * About : command-line text editor * Authors: Tommy Lincoln <pajamapants3000@gmail.com> * License: MIT; See LICENSE! * Notes : Notes on successful compilation * Created: 10/26/2016 */ // Bring in to namespace {{{ use std::str::Bytes; use ::regex::{Regex, Captures}; use error::*; use io::*; use buf::*; use ops::Operations; use ::{EditorState, EditorMode}; // ^^^ Bring in to namespace ^^^ }}} // *** Attributes *** {{{ // ^^^ Attributes ^^^ }}} // *** Constants *** {{{ const ADDR_REGEX_FWDSEARCH: &'static str = r#"/([^/]*)/"#; const ADDR_REGEX_REVSEARCH: &'static str = r#"\?([^\?]*)\?"#; const ADDR_REGEX_RITHMETIC: &'static str = r#"\s*(\d*|.|$)\s*(((\+|-)\s*(\d*))+)\s*"#; const ADDR_REGEX_ADDORSUBT: &'static str = r#"\s*((\+|-)\s*(\d*))\s*(((\+|-)\s*(\d*))*)\s*"#; const ADDR_REGEX_MARKER: &'static str = r#"'([:lower:])"#; const SUB_REGEX_PARAMETER: &'static str = r#"/(.*)/(.*)/(.*)"#; const SUB_REGEX_BACKREF: &'static str = r#"\\([0-9])"#; // ^^^ Constants ^^^ }}} // *** Data Structures *** {{{ pub struct Command<'a, 'b> {// {{{ pub address_initial: usize, pub address_final: usize, pub operation: char, pub parameters: &'a str, pub operations: &'b Operations, // tagging along for the ride }// }}} pub struct Substitution {// {{{ pub to_match: String, pub to_sub: String, pub which: WhichMatch, }// }}} pub enum WhichMatch { Number( usize ), Global, } // ^^^ Data Structures ^^^ }}} // *** Functions *** {{{ /// Parses invocation {{{ pub fn parse_invocation( invoc_input: Vec<String>, state: &mut EditorState ) {//{{{ let mut indx: usize = 1; while indx < invoc_input.len() { if invoc_input[indx] == "-s" || invoc_input[indx] == "-" { state.show_help = false; state.show_messages = false; //println!( "help and messages turned off (except this one)" ); println!( "SILENT MODE ACTIVE" ); } else if invoc_input[indx] == "-p" { if indx + 1 < invoc_input.len() { indx += 1; state.prompt = invoc_input[indx].clone(); println!( "prompt set to {}", &state.prompt ); } else { println!( "no prompt provided to \"-p\" flag" ); } } else if &invoc_input[indx][0..1] == "-" { println!( "unrecognized flag: {}", invoc_input[indx] ); } else { if state.source.len() == 0 { state.source = invoc_input[indx].clone(); } else { println!( "only the first commnand or file name accepted" ); } } indx += 1; } }//}}} //}}}} /// Parses command-mode input {{{ /// /// This is the public interface to the parse module /// pub fn parse_command<'a,'b>( _cmd_input: &'a str, state: &mut EditorState,//{{{ _operations: &'b Operations ) -> Result<Command<'a, 'b>, RedError> { // MUST initialize? let mut _address_initial: usize = 1; let mut _address_final: usize = 1; let mut _operation: char = 'p'; let _parameters: &str; let addrs: &str; match state.mode { EditorMode::Insert => { Err( RedError::CriticalError( "parse_command: executing command while in input mode!" .to_string() )) }, EditorMode::Command => { let ( op_indx, _operation ) = match get_opchar_index( _cmd_input ) { Ok( x ) => x, Err( e ) => return Err(e), }; match _cmd_input.split_at( op_indx ) { (x, y) => { addrs = x; _parameters = &y[1..].trim(); }, } let ( _address_initial, _address_final ) = try!( get_address_range( addrs, state ) ); Ok( Command { address_initial: _address_initial, address_final: _address_final, operation: _operation, parameters: _parameters, operations: _operations, } ) } } }// }}} //}}} /// Identify address range {{{ /// /// What do we want to do if string ends in ',' or ';'? /// e.g. :13,25,p /// ? /// Should this print lines 13-25 or ignore 13 and just print 25? /// Probably want to ignore. or error? fn get_address_range( address_string: &str, state: &mut EditorState )// {{{ -> Result<(usize, usize), RedError> { let (left, right) = match address_string.trim() { "%" => ( "1", "$" ), "," => ( "1", "$" ), ";" => ( ".", "$" ), "" => ( "", "" ), _ => parse_address_list( address_string ), }; let result_right = try!(parse_address_field( right, state )).unwrap(); let result_left = match left.len() { 0 => result_right, _ => try!(parse_address_field( left, state )).unwrap(), }; Ok( (result_left, result_right) ) }// }}} //}}} /// Test whether char is an address separator// {{{ fn is_address_separator( ch: char ) -> bool {// {{{ ch == ',' || ch == ';' }// }}} // }}} /// Turn address list into two address expressions// {{{ /// /// Returns the latter-two non-empty elements in a list /// elements are separated according to is_address_separator() /// separators inside /.../ or ?...? are ignored using is_in_regex() fn parse_address_list( address_string: &str ) -> (&str, &str) {// {{{ let mut right: &str = address_string; let mut left: &str = ""; loop { match right.find( is_address_separator ) { Some(indx) => { if !is_in_regex( address_string, indx ) { match right.split_at( indx ) { (x, y) => { if x.len() > 0 { left = x.trim(); } right = &y[ 1 .. ].trim(); } } } } None => { return ( left, right ); }, } } }// }}} // }}} /// Ensure line number is in buffer range// {{{ fn normalize_address( buffer: &Buffer, address: usize ) -> usize {// {{{ if address > buffer.num_lines() { buffer.num_lines() } else if address < 1 { 1 } else { address } // not reached }// }}} // }}} /// Calculates address from arithmetic expression// {{{ fn calc_address_field( address: &str, buffer: &Buffer )// {{{ -> Result<Option<usize>, RedError> { let re_rithmetic: Regex = Regex::new( ADDR_REGEX_RITHMETIC ).unwrap(); let re_addorsubt: Regex = Regex::new( ADDR_REGEX_ADDORSUBT ).unwrap(); let rithmetic_captures = re_rithmetic.captures( address ).unwrap(); let operand_lstr: &str = rithmetic_captures.at( 1 ).unwrap().trim(); let mut operand_adds: usize; let mut operand_subs: usize = 0; let mut operation_str: &str; let mut operand_str: &str; let mut next_step_str: &str; // Parse left operand value if operand_lstr == "." || operand_lstr == "" { operand_adds = buffer.get_current_address(); } else if operand_lstr == "$" { operand_adds = buffer.num_lines(); } else { operand_adds = try!( operand_lstr.parse() .map_err(|_| RedError::AddressSyntax{ address: "calc1:".to_string() + address } )); } next_step_str = rithmetic_captures.at(2).expect( "parse::calc_address_field: regex capture missing" ); let mut next_step_caps = re_addorsubt.captures( next_step_str ).unwrap(); loop { operation_str = next_step_caps.at( 2 ).expect( "parse::calc_address_field: regex capture missing" ); operand_str = next_step_caps.at( 3 ).expect( "parse::calc_address_field: regex capture missing" ); match operation_str { "+" => { operand_adds += match operand_str { "" => 1, _ => try!( operand_str.parse() .map_err(|_| RedError::AddressSyntax{ address: "calc2:".to_string() + address } )), }; }, "-" => { operand_subs += match operand_str { "" => 1, _ => try!( operand_str.parse() .map_err(|_| RedError::AddressSyntax{ address: "calc3:".to_string() + address } )), }; }, _ => { return Err( RedError::AddressSyntax{ address: "calc4:".to_string() + address }); }, } match next_step_caps.at(4) { Some( "" ) => break, Some( x ) => next_step_str = x, None => return Err( RedError::AddressSyntax{ address: "calc5:".to_string() + address }), } next_step_caps = re_addorsubt.captures( next_step_str ).unwrap(); } if operand_subs > operand_adds { Ok( Some( 1 )) } else { Ok( Some( normalize_address( &buffer, operand_adds - operand_subs ) )) } }// }}} // }}} /// Parse address field; convert regex or integer into line number// {{{ pub fn parse_address_field( address: &str, state: &mut EditorState )// {{{ -> Result<Option<usize>, RedError> { let re_fwdsearch: Regex = Regex::new( ADDR_REGEX_FWDSEARCH ).unwrap(); let re_revsearch: Regex = Regex::new( ADDR_REGEX_REVSEARCH ).unwrap(); let re_rithmetic: Regex = Regex::new( ADDR_REGEX_RITHMETIC ).unwrap(); let re_marker: Regex = Regex::new( ADDR_REGEX_MARKER ).unwrap(); if address.len() == 0 { // no address provided - use default Ok( Some( 0 )) // will be interpreted as default by operation } else if address.len() == 1 && address != "+" && address != "-" { match address { "." => { Ok( Some( state.buffer.get_current_address() )) }, "$" => { Ok( Some( state.buffer.num_lines() )) }, _ => { match address.parse() { Ok(x) => Ok( Some( normalize_address( &state.buffer, x ) )), Err(_) => Err( RedError::AddressSyntax { address: "parsefield1:".to_string() + address } ), } }, } } else if re_fwdsearch.is_match( address ) { // forward regex search? let _to_match = re_fwdsearch.captures( address ) .expect("parse_address_field: matched, now not matching...?") .at(1).expect("parse_address_field: missing expected capture"); if _to_match.trim().len() != 0 { state.last_regex = _to_match.to_string(); } Ok( state.buffer.find_match( &state.last_regex )) } else if re_revsearch.is_match( address ) { // backward regex search? let _to_match = re_revsearch.captures( address ) .expect("parse_address_field: matched, now not matching...?") .at(1).expect("parse_address_field: missing expected capture"); if _to_match.trim().len() != 0 { state.last_regex = _to_match.to_string(); } Ok( state.buffer.find_match_reverse( &state.last_regex )) } else { // otherwise, replace any markers and calculate/parse let _address: &str = &re_marker.replace( address, |caps: &Captures| { state.buffer.get_marked_line( caps.at(1).unwrap_or("A").chars() .next().unwrap_or('A') ).to_string() }); if re_rithmetic.is_match( _address ) { // +/- operation(s) calc_address_field( _address, &state.buffer ) } else { // just a (multi-digit) number match _address.parse() { Ok(x) => Ok( Some( normalize_address( &state.buffer, x ) )), Err(_) => Err( RedError::AddressSyntax{ address: "parsefield2:".to_string() + _address } ) } } } }// }}} // }}} /// Parse substitution parameter into separate parts// {{{ pub fn parse_substitution_parameter( sub_parm: &str )// {{{ -> Result<Substitution, RedError> { let re_sub_parm: Regex = Regex::new( SUB_REGEX_PARAMETER ).unwrap(); match re_sub_parm.captures( sub_parm ) { Some( cap ) => { Ok( Substitution { to_match: match cap.at(1) { Some(x) => x.to_string(), None => return Err( RedError::ParameterSyntax{ parameter: sub_parm.to_string() }), }, to_sub: match cap.at(2) { Some(x) => x.to_string(), None => return Err( RedError::ParameterSyntax{ parameter: sub_parm.to_string() }), }, which: match cap.at(3) { Some(x) => { if x == "g" { WhichMatch::Global } else if x == "" { WhichMatch::Number(1) } else { WhichMatch::Number( try!( x.parse().map_err(|_| RedError::ParameterSyntax{ parameter: sub_parm.to_string() }))) } }, None => return Err( RedError::ParameterSyntax{ parameter: sub_parm.to_string() }), } }) }, None => return Err( RedError::ParameterSyntax{ parameter: sub_parm.to_string() }), } }// }}} // }}} /// Replace regex capture references with the captures// {{{ pub fn sub_captures( original: &str, captures: Captures )// {{{ -> String { let mut result: String = String::new(); let re = Regex::new( SUB_REGEX_BACKREF ).unwrap(); let mut last_end: usize = 0; let mut orig_captures = re.captures_iter( original ); for ( start, end ) in re.find_iter( original ) { match orig_captures.next() { Some(cap) => { result += &original[ last_end .. start ]; // unwraps assured by setup - panic is reasonable here // may want to replace with expect match captures.at( cap.at(1).unwrap().parse().unwrap() ) { Some(x) => result += x, // or just leave as-is; already know cap.at(0) is not None None => result += cap.at(0).unwrap(), }; }, None => break, } last_end = end; } result += &original[ last_end .. ]; result }// }}} // }}} /// Find index of operation code in string /// /// Parses full command and finds the index of the operation character; /// The trick here is that the operation character may appear any number /// of times as part of a regular expression used to specify an address /// range that matches; /// What this function does is simply locates the first alphabetic character /// that is not wrapped in either /.../ or ?...? /// /// Trims white space on the left as well - does not count these characters /// /// # Examples /// See tests in tests module below fn get_opchar_index( _cmd_input: &str ) -> Result<(usize, char), RedError> { let mut current_indx: usize = 0; let mut bytes_iter: Bytes = _cmd_input.trim().bytes(); loop { match bytes_iter.next() { Some( x ) => { if _cmd_input.is_char_boundary( current_indx ) { match x { b'a'...b'z' | b'A'...b'Z' => { if !is_in_addr( _cmd_input.trim(), current_indx ) { return Ok( (current_indx, x as char ) ); } }, _ => {}, } } }, None => break, } current_indx += 1; } Result::Err( RedError::OpCharIndex ) } /// Return true if character at indx is part of address// {{{ /// /// first, checks to see if character is preceded by a single-quote, which /// would indicate that it is a marker; /// then, checks to see if character is part of a regular expression via /// the is_in_regex function; fn is_in_addr( text: &str, indx: usize ) -> bool {// {{{ is_marker( text, indx ) || is_in_regex( text, indx ) }// }}} // }}} /// Return true if character at indx is preceded by a single-quote//{{{ fn is_marker( text: &str, indx: usize ) -> bool {// {{{ // set curr_indx to just before char before char at current indx let mut curr_indx: usize = 0; if indx > 0 { curr_indx = indx - 1; } let ( _, right ) = text.split_at( curr_indx ); let mut _chars = right.chars(); if _chars.next().unwrap_or('\0') == '\'' { true } else { false } // unreached }//}}} //}}} /// Return true if index is contained in regex// {{{ /// /// Is regex if wrapped in /.../ or ?...? within larger string /// In some functions, we need to know this so we know how to treat the /// character fn is_in_regex( text: &str, indx: usize ) -> bool {// {{{ let regex: Vec<u8> = vec!(b'/', b'?'); let mut c_regex: Vec<bool> = vec!( false; regex.len() ); let mut c_indx: usize = 0; let mut escaped: bool = false; // let (left, _) = text.split_at( indx ); // for ch in left.bytes() { if left.is_char_boundary( c_indx ) { if ch == b'\\' { escaped = !escaped; c_indx += 1; continue } for i in 0 .. regex.len() { if ch == regex[i] { if !escaped && !is_quoted( text, c_indx ) && c_regex[1-i] == false { // can't have both c_regex[i] = !c_regex[i]; // switch on/off } } } escaped = false; } c_indx += 1; } if c_regex == vec!( false; c_regex.len() ) { false } else { true } }// }}} // }}} /// Parse parameter for g, v operations// {{{ /// /// Confirms that a properly formatted regex leads /// a set of commands, one on each line; possibly one /// on the same line as the regex. /// Returns Result::Err( RedError::ParameterSyntax ) if /// no regex is found; /// Otherwise, returns tuple - pattern, list of commands /// # Panics /// * unable to compile regular expression pattern /// from ADDR_REGEX_FWDSEARCH - should never happen /// * Finds match but somehow there is no capture pub fn parse_global_op<'a>( g_op: &'a str )// {{{ -> Result<(&'a str, &'a str), RedError> { let re_pattern: Regex = Regex::new( ADDR_REGEX_FWDSEARCH ).unwrap(); let pattern: &'a str = match &re_pattern.captures( g_op ) { &Some(ref s) => s.at(1) .expect("already confirmed match; capture expected"), &None => return Err( RedError::ParameterSyntax{ parameter: "parse_global_op: ".to_string() + g_op }), }; let (_, right) = re_pattern.find( g_op ) .expect("parse_global_op: already proved match, now not matching"); let commands: &'a str = &g_op[right ..]; Ok( (pattern, commands) ) }// }}} // }}} // ^^^ Functions ^^^ }}} #[cfg(test)] mod tests { use super::{get_opchar_index, is_in_regex, parse_address_field, parse_address_list, get_address_range, is_address_separator}; use buf::*; use ::EditorState; const COMMAND_CONTENT_LINE: &'static str = "this is a test; number"; const COMMAND_FILE_SUFFIX: &'static str = ".cmd"; const TEST_FILE: &'static str = "red_filetest"; /// Prep and return buffer for use in "command buffer" test functions /// /// uses test_lines function to create file with which buffer /// is initialized pub fn open_command_buffer_test( test_num: u8 ) -> EditorState {// {{{ // let num_lines: usize = 7; // number of lines to have in buffer let command_content_line = COMMAND_CONTENT_LINE; let test_file: String = TEST_FILE.to_string() + COMMAND_FILE_SUFFIX + test_num.to_string().as_str(); let test_command = "echo -e ".to_string() + &test_lines( command_content_line, num_lines ); let mut buffer = Buffer::new( BufferInput::Command( test_command )) .unwrap(); buffer.move_file( &test_file ).unwrap(); buffer.set_current_address( 1 ); EditorState::new(buffer) }// }}} /// deconstruct buffer from "command buffer" test; /// any other necessary closing actions pub fn close_command_buffer_test( state: &mut EditorState ) {// {{{ state.buffer.destruct(); }// }}} // begin prep functions /// Generate and return string containing lines for testing /// /// Takes string to use as base for text on each line /// This string will have the line number appended /// Also takes a single u8 integer, the number of lines to generate fn test_lines( line_str: &str, num_lines: usize ) -> String {// {{{ let mut file_content = "".to_string(); let mut next: String; for i in 1 .. ( num_lines + 1 ) { next = line_str.to_string() + i.to_string().as_str(); next = next + r"\n"; file_content.push_str( &next ); } file_content }// }}} // Tests for parse::get_opchar_index /// No address given #[test] fn get_opchar_index_test_1() { let _in: &str = "e myfile.txt"; assert_eq!( get_opchar_index( _in ).unwrap_or( (9999, '\0') ), (0, 'e') ); } /// No address given, with spaces #[test] fn get_opchar_index_test_2() { let _in: &str = " e myfile.txt"; assert_eq!( get_opchar_index( _in ).unwrap_or( (9999, '\0') ), (0, 'e') ); } /// No address given, with spaces and tabs #[test] fn get_opchar_index_test_3() { let _in: &str = " e myfile.txt"; assert_eq!( get_opchar_index( _in ).unwrap_or( (9999, '\0') ), (0, 'e') ); } /// Most basic address value types #[test] fn get_opchar_index_test_4() { let _in: &str = ".a"; assert_eq!( get_opchar_index( _in ).unwrap_or( (9999, '\0') ), (1, 'a') ); } #[test] fn get_opchar_index_test_5() { let _in: &str = ".,.p"; assert_eq!( get_opchar_index( _in ).unwrap_or( (9999, '\0') ), (3, 'p') ); } /// Slightly more complicated #[test] fn get_opchar_index_test_6() { let _in: &str = ".-2,.+2p"; assert_eq!( get_opchar_index( _in ).unwrap_or( (9999, '\0') ), (7, 'p') ); } /// Regular expression match line search forward #[test] fn get_opchar_index_test_7() { let _in: &str = "/^Beginning with.*$/;/.* at the end$/s_mytest_yourtest_g"; assert_eq!( get_opchar_index( _in ).unwrap_or( (9999, '\0') ), (37, 's') ); } /// Regular expression match line search forward with spaces and tabs #[test] fn get_opchar_index_test_8() { let _in: &str = " /^Beginning with.*$/;/.* at the end$/s_mytest_yourtest_g"; assert_eq!( get_opchar_index( _in ).unwrap_or( (9999, '\0') ), (37, 's') ); } /// Regular expression match line search backward #[test] fn get_opchar_index_test_9() { let _in: &str = "?^Beginning with.*$?,?.* at the end$?s_mytest_yourtest_g"; assert_eq!( get_opchar_index( _in ).unwrap_or( (9999, '\0') ), (37, 's') ); } #[test] fn is_in_regex_test_1() { let haystack = "This is a / abc /string to search"; let indx = haystack.find( "abc" ).unwrap(); assert!( is_in_regex( haystack, indx ), "abc" ); let indx = haystack.find( "is a" ).unwrap(); assert!( !is_in_regex( haystack, indx ), "is a" ); let indx = haystack.find( "search" ).unwrap(); assert!( !is_in_regex( haystack, indx ), "search" ); } #[test] fn is_in_regex_test_2() { let haystack = "This is a ? abc ?string to search"; let indx = haystack.find( "abc" ).unwrap(); assert!( is_in_regex( haystack, indx ) ); let indx = haystack.find( "is a" ).unwrap(); assert!( !is_in_regex( haystack, indx ) ); let indx = haystack.find( "string" ).unwrap(); assert!( !is_in_regex( haystack, indx ) ); } #[test] fn is_in_regex_test_3() { let haystack = r#"?This? "is a / abc /string" to search"#; let indx = haystack.find( "abc" ).unwrap(); assert!( !is_in_regex( haystack, indx ) ); let indx = haystack.find( "is a" ).unwrap(); assert!( !is_in_regex( haystack, indx ) ); let indx = haystack.find( "string" ).unwrap(); assert!( !is_in_regex( haystack, indx ) ); let indx = haystack.find( "This" ).unwrap(); assert!( is_in_regex( haystack, indx ) ); } #[test] fn is_in_regex_test_4() { let haystack: &str = " /^Beginning with.*$/;/.* at the end$/s_mytest_yourtest_g"; let indx = haystack.find( "Beginning" ).unwrap(); assert!( is_in_regex( haystack, indx ) ); let indx = haystack.find( "the end" ).unwrap(); assert!( is_in_regex( haystack, indx ) ); let indx = haystack.find( "with" ).unwrap(); assert!( is_in_regex( haystack, indx ) ); let indx = haystack.find( "mytest" ).unwrap(); assert!( !is_in_regex( haystack, indx ) ); } #[test] fn is_address_separator_test_1() { let ch = ';'; assert!( is_address_separator( ch ) ); } #[test] fn is_address_separator_test_2() { let ch = '.'; assert!( !is_address_separator( ch ) ); } #[test] fn is_address_separator_test_3() { let ch = 'r'; assert!( !is_address_separator( ch ) ); } #[test] fn is_address_separator_test_4() { let ch = ','; assert!( is_address_separator( ch ) ); } #[test] fn get_address_range_test_1() { // set contstants let test_num: u8 = 1; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "1, 3"; let ini_expected: usize = 1; let fin_expected: usize = 3; // let ( ini, fin ) = get_address_range( address_string, &mut buffer ).unwrap(); assert_eq!( ini, ini_expected ); assert_eq!( fin, fin_expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn get_address_range_test_2() { // set contstants let test_num: u8 = 2; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "1, 56"; let ini_expected: usize = 1; let fin_expected: usize = 8; // let ( ini, fin ) = get_address_range( address_string, &mut buffer ).unwrap(); assert_eq!( ini, ini_expected ); assert_eq!( fin, fin_expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn get_address_range_test_3() { // set contstants let test_num: u8 = 3; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "0, 4"; let ini_expected: usize = 1; let fin_expected: usize = 4; // let ( ini, fin ) = get_address_range( address_string, &mut buffer ).unwrap(); assert_eq!( ini, ini_expected ); assert_eq!( fin, fin_expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn get_address_range_test_4() { // set contstants let test_num: u8 = 4; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "/number1/, 5"; let ini_expected: usize = 1; let fin_expected: usize = 5; // let ( ini, fin ) = get_address_range( address_string, &mut buffer ) .unwrap_or( (0_usize, 0_usize) ); assert_eq!( ini, ini_expected ); assert_eq!( fin, fin_expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_list_test_1() { // set contstants let address_string: &str = "1, 3"; let ini_expected: &str = "1"; let fin_expected: &str = "3"; // let ( ini, fin ) = parse_address_list( address_string ); assert_eq!( ini, ini_expected ); assert_eq!( fin, fin_expected ); } #[test] fn parse_address_list_test_2() { // set contstants let address_string: &str = "1, 56"; let ini_expected: &str = "1"; let fin_expected: &str = "56"; // let ( ini, fin ) = parse_address_list( address_string ); assert_eq!( ini, ini_expected ); assert_eq!( fin, fin_expected ); } #[test] fn parse_address_list_test_3() { // set contstants let address_string: &str = "0, 4"; let ini_expected: &str = "0"; let fin_expected: &str = "4"; // let ( ini, fin ) = parse_address_list( address_string ); assert_eq!( ini, ini_expected ); assert_eq!( fin, fin_expected ); } #[test] fn parse_address_list_test_4() { // set contstants let address_string: &str = "/number3/, 5"; let ini_expected: &str = "/number3/"; let fin_expected: &str = "5"; // let ( ini, fin ) = parse_address_list( address_string ); assert_eq!( ini, ini_expected ); assert_eq!( fin, fin_expected ); } #[test] fn parse_address_field_test_1() { // set contstants let test_num: u8 = 1; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "1"; let expected: usize = 1; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_2() { // set contstants let test_num: u8 = 2; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "56"; let expected: usize = 8; // num_lines // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_3() { // set contstants let test_num: u8 = 3; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "0"; let expected: usize = 1; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_4() { // set contstants let test_num: u8 = 4; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "/number3/"; let expected: usize = 3; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_5() { // set contstants let test_num: u8 = 5; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "?number4?"; let expected: usize = 4; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_6() { // set contstants let test_num: u8 = 6; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "/badtestcmd/"; // no match let expected: Option<usize> = None; // let result = parse_address_field( address_string, &mut buffer ) .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_7() { // set contstants let test_num: u8 = 7; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "/test; num/"; let expected: usize = 1; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_8() { // set contstants let test_num: u8 = 8; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = ".-3"; let expected: usize = 1; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_9() { // set contstants let test_num: u8 = 9; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = " + "; let expected: usize = 2; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_10() { // set contstants let test_num: u8 = 10; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "5- 3"; let expected: usize = 2; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_11() { // set contstants let test_num: u8 = 11; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = " . + 1 "; let expected: usize = 2; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_12() { // set contstants let test_num: u8 = 12; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "7 -- 1- 3 "; let expected: usize = 2; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_13() { // set contstants let test_num: u8 = 13; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = " . +1-- -+5"; let expected: usize = 4; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_14() { // set contstants let test_num: u8 = 14; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = "$ - 3"; let expected: usize = 5; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } #[test] fn parse_address_field_test_15() { // set contstants let test_num: u8 = 15; // let mut buffer = open_command_buffer_test( test_num ); let address_string: &str = " -5"; let expected: usize = 1; // let result = parse_address_field( address_string, &mut buffer ) .unwrap() .unwrap(); assert_eq!( result, expected ); // Common test close routine close_command_buffer_test( &mut buffer ); } }
use P80::graph_converters::unlabeled; use P83::*; pub fn main() { let g = unlabeled::from_term_form( &vec!['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], &vec![ ('a', 'b'), ('a', 'd'), ('b', 'c'), ('b', 'e'), ('c', 'e'), ('d', 'e'), ('d', 'f'), ('d', 'g'), ('e', 'h'), ('f', 'g'), ('g', 'h'), ], ); let trees = spanning_trees(&g); for tree in trees { println!("{:?}", unlabeled::to_term_form(&tree)); } }
fn main() { println!("🔓 Challenge 1"); println!("Try running: `cargo test chal1`"); println!("Code in 'encoding/src/lib.rs'"); }
use std::convert::TryFrom; use std::num; pub mod error; use error::Error; pub fn parse_input(input: &str) -> Result<Vec<u8>, num::ParseIntError> { input .trim() .chars() .map(|c| c.to_string().parse::<u8>()) .collect::<Result<Vec<u8>, num::ParseIntError>>() } pub struct SpaceImg { pixels: Vec<u8>, width: usize, height: usize, } struct SpaceImgIter<'a> { layer: usize, space_img: &'a SpaceImg, } impl<'a> Iterator for SpaceImgIter<'a> { type Item = &'a [u8]; fn next(&mut self) -> Option<Self::Item> { let layer_size = self.space_img.width * self.space_img.height; if layer_size * self.layer < self.space_img.pixels.len() { let ret_value = Some( &self.space_img.pixels[self.layer * layer_size..(self.layer + 1) * layer_size], ); self.layer += 1; ret_value } else { None } } } impl SpaceImg { pub fn new(pixels: Vec<u8>, width: usize, height: usize) -> Self { SpaceImg { pixels, width, height, } } fn layers_iter(&self) -> SpaceImgIter { SpaceImgIter { layer: 0, space_img: self, } } fn verification_code(layer: &[u8]) -> Result<u64, Error> { let ones_count = u64::try_from(layer.iter().filter(|&x| *x == 1).count())?; let twos_count = u64::try_from(layer.iter().filter(|&x| *x == 2).count())?; Ok(ones_count * twos_count) } pub fn verify(&self) -> Result<u64, Error> { let (_, verification) = self.layers_iter().try_fold( (None, 0), |(mut min_zeroes_in_layer, mut verification), layer| { let zeroes_count = layer.iter().filter(|&x| *x == 0).count(); if let Some(existing_zeroes_in_layer) = min_zeroes_in_layer { if zeroes_count < existing_zeroes_in_layer { min_zeroes_in_layer = Some(zeroes_count); verification = match Self::verification_code(layer) { Ok(v) => v, Err(e) => return Err(e), }; } } else { min_zeroes_in_layer = Some(zeroes_count); verification = match Self::verification_code(layer) { Ok(v) => v, Err(e) => return Err(e), }; } Ok((min_zeroes_in_layer, verification)) }, )?; Ok(verification) } pub fn compose(&self) -> Result<Vec<u8>, Error> { Ok(self .layers_iter() .fold(vec![2; self.width * self.height], |final_img, layer| { layer .iter() .zip(final_img.into_iter()) .map(|(l, f)| if f == 2 { *l } else { f }) .collect() })) } } pub fn display(pixels: Vec<u8>, width: usize, height: usize) { for row in 0..height { for col in 0..width { let color = pixels[col + row * width]; match color { 0 => print!(" "), 1 => print!("X"), _ => unreachable!(), } } println!(); } } #[cfg(test)] mod tests { use super::*; #[test] fn day8_ex1() { let input = parse_input("123456789012").unwrap(); let img = SpaceImg::new(input, 3, 2); let mut layers = img.layers_iter(); assert_eq!(Some(&vec![1, 2, 3, 4, 5, 6][..]), layers.next()); assert_eq!(Some(&vec![7, 8, 9, 0, 1, 2][..]), layers.next()); assert_eq!(None, layers.next()); } #[test] fn day8_ex2() { let input = parse_input("0222112222120000").unwrap(); let img = SpaceImg::new(input, 2, 2); let composed_img = img.compose().unwrap(); assert_eq!(composed_img[0], 0); assert_eq!(composed_img[1], 1); assert_eq!(composed_img[2], 1); assert_eq!(composed_img[3], 0); assert_eq!(composed_img.len(), 4); } }
use file_reader; const INPUT_FILENAME: &str = "input.txt"; const TREE: char = '#'; fn main() { let input_str = match file_reader::file_to_vec(INPUT_FILENAME) { Err(_) => { println!("Couldn't turn file into vec!"); return; }, Ok(v) => v, }; let result = num_trees_hit(&input_str, (1, 1)) * num_trees_hit(&input_str, (3, 1)) * num_trees_hit(&input_str, (5, 1)) * num_trees_hit(&input_str, (7, 1)) * num_trees_hit(&input_str, (1, 2)); println!("{:?}", result); } fn num_trees_hit(input: &Vec<String>, slope: (usize, usize)) -> usize { let max_len = input[0].len(); let mut x = 0; let mut result = 0; for line in input.into_iter().step_by(slope.1) { if line.chars().nth(x).unwrap() == TREE { result += 1; } x += slope.0; if x >= max_len { x -= max_len; } } result }
use super::*; use std::fmt; use std::string::ToString; #[derive(Debug, Eq, PartialEq, Hash, Clone)] pub enum AgricolaTile { BuildRoom_BuildStables = 1, StartingPlayer_Food = 2, Grain = 3, Plow = 4, BuildStable_BakeBread = 5, DayLaborer = 6, Sow_BakeBread = 7, Wood = 8, Clay = 9, Reed = 10, Fishing = 11, Fences = 12, MajorImprovement = 13, Sheep = 14, FamilyGrowth = 15, Stone_1 = 16, Renovation_MajorImprovement = 17, Vegetable = 18, Boar = 19, Cattle = 20, Stone_2 = 21, Plow_Sow = 22, FamilyGrowth_NoSpace = 23, Renovation_Fences = 24 } impl ToString for AgricolaTile { fn to_string(&self) -> String { match self { &AgricolaTile::BuildRoom_BuildStables => String::from("BuildRoom_BuildStables"), &AgricolaTile::StartingPlayer_Food => String::from("StartingPlayer_Food"), &AgricolaTile::Grain => String::from("Grain"), &AgricolaTile::Plow => String::from("Plow"), &AgricolaTile::BuildStable_BakeBread => String::from("BuildStable_BakeBread"), &AgricolaTile::DayLaborer => String::from("DayLaborer"), &AgricolaTile::Sow_BakeBread => String::from("Sow_BakeBread"), &AgricolaTile::Wood => String::from("Wood"), &AgricolaTile::Clay => String::from("Clay"), &AgricolaTile::Reed => String::from("Reed"), &AgricolaTile::Fishing => String::from("Fishing"), &AgricolaTile::Fences => String::from("Fences"), &AgricolaTile::MajorImprovement => String::from("MajorImprovement"), &AgricolaTile::Sheep => String::from("Sheep"), &AgricolaTile::FamilyGrowth => String::from("FamilyGrowth"), &AgricolaTile::Stone_1 => String::from("Stone_1"), &AgricolaTile::Renovation_MajorImprovement => String::from("Renovation_MajorImprovement"), &AgricolaTile::Vegetable => String::from("Vegetable"), &AgricolaTile::Boar => String::from("Boar"), &AgricolaTile::Cattle => String::from("Cattle"), &AgricolaTile::Stone_2 => String::from("Stone_2"), &AgricolaTile::Plow_Sow => String::from("Plow_Sow"), &AgricolaTile::FamilyGrowth_NoSpace => String::from("FamilyGrowth_NoSpace"), &AgricolaTile::Renovation_Fences => String::from("Renovation_Fences"), } } } #[derive(Debug)] pub enum AgricolaAction { BuildRoom_BuildStables = 1, BuildRoom = 15, BuildStables = 16, StartingPlayer_Food = 2, Grain = 3, Plow = 4, BuildStable_BakeBread = 5, BuildStable = 19, BakeBread_NoStable = 20, DayLaborer_Food_Wood = 6, DayLaborer_Food_Clay = 7, DayLaborer_Food_Reed = 8, DayLaborer_Food_Stone = 9, Sow_BakeBread = 10, Sow = 17, BakeBread_NotSow = 18, Wood = 11, Clay = 12, Reed = 13, Fishing = 14, Fences = 21, MajorImprovement = 22, Sheep = 23, FamilyGrowth = 24, Stone_1 = 25, Renovation_MajorImprovement_Fireplace_2 = 38, Renovation_MajorImprovement_Fireplace_3 = 39, Renovation_MajorImprovement_CookingHearth_4 = 42, Renovation_MajorImprovement_CookingHearth_5 = 43, Vegetable = 27, Boar = 28, Cattle = 29, Stone_2 = 30, Plow_Sow = 31, Plow_NoSow = 34, Sow_NoPlow = 35, FamilyGrowth_NoSpace = 32, Renovation_Fences = 33, MajorImprovement_Fireplace_2 = 36, MajorImprovement_Fireplace_3 = 37, MajorImprovement_CookingHearth_4 = 40, MajorImprovement_CookingHearth_5 = 41, MajorImprovement_ClayOven = 44, Renovation_MajorImprovement_ClayOven = 45, MajorImprovement_StoneOven = 46, Renovation_MajorImprovement_StoneOven = 47, MajorImprovement_Pottery = 48, Renovation_MajorImprovement_Pottery = 49, MajorImprovement_Joinery = 50, Renovation_MajorImprovement_Joinery = 51, MajorImprovement_BasketmakersWorkshop = 52, Renovation_MajorImprovement_BasketmakersWorkshop = 53, MajorImprovement_Well = 54, Renovation_MajorImprovement_Well = 55, } impl AgricolaAction { pub fn from_u32(x: u32) -> Option<AgricolaAction> { match x { 1 => Some(AgricolaAction::BuildRoom_BuildStables), 15 => Some(AgricolaAction::BuildRoom), 16 => Some(AgricolaAction::BuildStables), 2 => Some(AgricolaAction::StartingPlayer_Food), 3 => Some(AgricolaAction::Grain), 4 => Some(AgricolaAction::Plow), 5 => Some(AgricolaAction::BuildStable_BakeBread), 19 => Some(AgricolaAction::BuildStable), 20 => Some(AgricolaAction::BakeBread_NoStable), 6 => Some(AgricolaAction::DayLaborer_Food_Wood), 7 => Some(AgricolaAction::DayLaborer_Food_Clay), 8 => Some(AgricolaAction::DayLaborer_Food_Reed), 9 => Some(AgricolaAction::DayLaborer_Food_Stone), 10 => Some(AgricolaAction::Sow_BakeBread), 17 => Some(AgricolaAction::Sow), 18 => Some(AgricolaAction::BakeBread_NotSow), 11 => Some(AgricolaAction::Wood), 12 => Some(AgricolaAction::Clay), 13 => Some(AgricolaAction::Reed), 14 => Some(AgricolaAction::Fishing), 21 => Some(AgricolaAction::Fences), 22 => Some(AgricolaAction::MajorImprovement), 23 => Some(AgricolaAction::Sheep), 24 => Some(AgricolaAction::FamilyGrowth), 25 => Some(AgricolaAction::Stone_1), // 26 => Some(AgricolaAction::Renovation_MajorImprovement), 27 => Some(AgricolaAction::Vegetable), 28 => Some(AgricolaAction::Boar), 29 => Some(AgricolaAction::Cattle), 30 => Some(AgricolaAction::Stone_2), 31 => Some(AgricolaAction::Plow_Sow), 34 => Some(AgricolaAction::Plow_NoSow), 35 => Some(AgricolaAction::Sow_NoPlow), 32 => Some(AgricolaAction::FamilyGrowth_NoSpace), 33 => Some(AgricolaAction::Renovation_Fences), 36 => Some(AgricolaAction::MajorImprovement_Fireplace_2), 37 => Some(AgricolaAction::MajorImprovement_Fireplace_3), 38 => Some(AgricolaAction::Renovation_MajorImprovement_Fireplace_2), 39 => Some(AgricolaAction::Renovation_MajorImprovement_Fireplace_3), 40 => Some(AgricolaAction::MajorImprovement_CookingHearth_4), 41 => Some(AgricolaAction::MajorImprovement_CookingHearth_5), 42 => Some(AgricolaAction::Renovation_MajorImprovement_CookingHearth_4), 43 => Some(AgricolaAction::Renovation_MajorImprovement_CookingHearth_5), 44 => Some(AgricolaAction::MajorImprovement_ClayOven), 45 => Some(AgricolaAction::Renovation_MajorImprovement_ClayOven), 46 => Some(AgricolaAction::MajorImprovement_StoneOven), 47 => Some(AgricolaAction::Renovation_MajorImprovement_StoneOven), 48 => Some(AgricolaAction::MajorImprovement_Pottery), 49 => Some(AgricolaAction::Renovation_MajorImprovement_Pottery), 50 => Some(AgricolaAction::MajorImprovement_Joinery), 51 => Some(AgricolaAction::Renovation_MajorImprovement_Joinery), 52 => Some(AgricolaAction::MajorImprovement_BasketmakersWorkshop), 53 => Some(AgricolaAction::Renovation_MajorImprovement_BasketmakersWorkshop), 54 => Some(AgricolaAction::MajorImprovement_Well), 55 => Some(AgricolaAction::Renovation_MajorImprovement_Well), _ => None } } }
pub mod client_data; pub mod delta_encoder; pub mod in_message_reader; pub mod network_manager; pub mod protobuf; pub mod service;
// Copyright 2022 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::collections::BTreeMap; use std::fmt::Display; use std::fmt::Formatter; use crate::ast::statements::show::ShowLimit; use crate::ast::write_comma_separated_list; use crate::ast::write_period_separated_list; use crate::ast::write_space_separated_map; use crate::ast::Expr; use crate::ast::Identifier; use crate::ast::Query; use crate::ast::TableReference; use crate::ast::TimeTravelPoint; use crate::ast::TypeName; use crate::ast::UriLocation; #[derive(Debug, Clone, PartialEq)] // Tables pub struct ShowTablesStmt { pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub full: bool, pub limit: Option<ShowLimit>, pub with_history: bool, } impl Display for ShowTablesStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "SHOW")?; if self.full { write!(f, " FULL")?; } write!(f, " TABLES")?; if self.with_history { write!(f, " HISTORY")?; } if let Some(database) = &self.database { write!(f, " FROM ")?; if let Some(catalog) = &self.catalog { write!(f, "{catalog}.",)?; } write!(f, "{database}")?; } if let Some(limit) = &self.limit { write!(f, " {limit}")?; } Ok(()) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ShowCreateTableStmt { pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub table: Identifier, } impl Display for ShowCreateTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "SHOW CREATE TABLE ")?; write_period_separated_list( f, self.catalog .iter() .chain(&self.database) .chain(Some(&self.table)), ) } } #[derive(Debug, Clone, PartialEq)] pub struct ShowTablesStatusStmt { pub database: Option<Identifier>, pub limit: Option<ShowLimit>, } impl Display for ShowTablesStatusStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "SHOW TABLE STATUS")?; if let Some(database) = &self.database { write!(f, " FROM {database}")?; } if let Some(limit) = &self.limit { write!(f, " {limit}")?; } Ok(()) } } #[derive(Debug, Clone, PartialEq)] pub struct CreateTableStmt { pub if_not_exists: bool, pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub table: Identifier, pub source: Option<CreateTableSource>, pub engine: Option<Engine>, pub uri_location: Option<UriLocation>, pub cluster_by: Vec<Expr>, pub table_options: BTreeMap<String, String>, pub as_query: Option<Box<Query>>, pub transient: bool, } impl Display for CreateTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "CREATE ")?; if self.transient { write!(f, "TRANSIENT ")?; } write!(f, "TABLE ")?; if self.if_not_exists { write!(f, "IF NOT EXISTS ")?; } write_period_separated_list( f, self.catalog .iter() .chain(&self.database) .chain(Some(&self.table)), )?; if let Some(source) = &self.source { write!(f, " {source}")?; } if let Some(engine) = &self.engine { write!(f, " ENGINE = {engine}")?; } if !self.cluster_by.is_empty() { write!(f, " CLUSTER BY (")?; write_comma_separated_list(f, &self.cluster_by)?; write!(f, ")")? } // Format table options write_space_separated_map(f, self.table_options.iter())?; if let Some(as_query) = &self.as_query { write!(f, " AS {as_query}")?; } Ok(()) } } #[allow(clippy::large_enum_variant)] #[derive(Debug, Clone, PartialEq)] pub enum CreateTableSource { Columns(Vec<ColumnDefinition>), Like { catalog: Option<Identifier>, database: Option<Identifier>, table: Identifier, }, } impl Display for CreateTableSource { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { CreateTableSource::Columns(columns) => { write!(f, "(")?; write_comma_separated_list(f, columns)?; write!(f, ")") } CreateTableSource::Like { catalog, database, table, } => { write!(f, "LIKE ")?; write_period_separated_list(f, catalog.iter().chain(database).chain(Some(table))) } } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct DescribeTableStmt { pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub table: Identifier, } impl Display for DescribeTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "DESCRIBE ")?; write_period_separated_list( f, self.catalog .iter() .chain(self.database.iter().chain(Some(&self.table))), ) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct DropTableStmt { pub if_exists: bool, pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub table: Identifier, pub all: bool, } impl Display for DropTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "DROP TABLE ")?; if self.if_exists { write!(f, "IF EXISTS ")?; } write_period_separated_list( f, self.catalog .iter() .chain(&self.database) .chain(Some(&self.table)), )?; if self.all { write!(f, " ALL")?; } Ok(()) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct UndropTableStmt { pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub table: Identifier, } impl Display for UndropTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "UNDROP TABLE ")?; write_period_separated_list( f, self.catalog .iter() .chain(&self.database) .chain(Some(&self.table)), ) } } #[derive(Debug, Clone, PartialEq)] pub struct AlterTableStmt { pub if_exists: bool, pub table_reference: TableReference, pub action: AlterTableAction, } impl Display for AlterTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "ALTER TABLE ")?; if self.if_exists { write!(f, "IF EXISTS ")?; } write!(f, "{}", self.table_reference)?; write!(f, " {}", self.action) } } #[derive(Debug, Clone, PartialEq)] pub enum AlterTableAction { RenameTable { new_table: Identifier, }, AddColumn { column: ColumnDefinition, }, DropColumn { column: Identifier, }, AlterTableClusterKey { cluster_by: Vec<Expr>, }, DropTableClusterKey, ReclusterTable { is_final: bool, selection: Option<Expr>, }, RevertTo { point: TimeTravelPoint, }, } impl Display for AlterTableAction { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { AlterTableAction::RenameTable { new_table } => { write!(f, "RENAME TO {new_table}") } AlterTableAction::AddColumn { column } => { write!(f, "ADD COLUMN {column}") } AlterTableAction::DropColumn { column } => { write!(f, "DROP COLUMN {column}") } AlterTableAction::AlterTableClusterKey { cluster_by } => { write!(f, "CLUSTER BY ")?; write_comma_separated_list(f, cluster_by) } AlterTableAction::DropTableClusterKey => { write!(f, "DROP CLUSTER KEY") } AlterTableAction::ReclusterTable { is_final, selection, } => { write!(f, "RECLUSTER")?; if *is_final { write!(f, " FINAL")?; } if let Some(conditions) = selection { write!(f, " WHERE {conditions}")?; } Ok(()) } AlterTableAction::RevertTo { point } => { write!(f, "REVERT TO {}", point)?; Ok(()) } } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct RenameTableStmt { pub if_exists: bool, pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub table: Identifier, pub new_catalog: Option<Identifier>, pub new_database: Option<Identifier>, pub new_table: Identifier, } impl Display for RenameTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "RENAME TABLE ")?; if self.if_exists { write!(f, "IF EXISTS ")?; } write_period_separated_list( f, self.catalog .iter() .chain(&self.database) .chain(Some(&self.table)), )?; write!(f, " TO ")?; write_period_separated_list( f, self.new_catalog .iter() .chain(&self.new_database) .chain(Some(&self.new_table)), ) } } #[derive(Debug, Clone, PartialEq)] pub struct TruncateTableStmt { pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub table: Identifier, pub purge: bool, } impl Display for TruncateTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "TRUNCATE TABLE ")?; write_period_separated_list( f, self.catalog .iter() .chain(&self.database) .chain(Some(&self.table)), )?; if self.purge { write!(f, " PURGE")?; } Ok(()) } } #[derive(Debug, Clone, PartialEq)] pub struct OptimizeTableStmt { pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub table: Identifier, pub action: OptimizeTableAction, } impl Display for OptimizeTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "OPTIMIZE TABLE ")?; write_period_separated_list( f, self.catalog .iter() .chain(&self.database) .chain(Some(&self.table)), )?; write!(f, " {}", &self.action)?; Ok(()) } } #[derive(Debug, Clone, PartialEq)] pub struct AnalyzeTableStmt { pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub table: Identifier, } impl Display for AnalyzeTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "ANALYZE TABLE ")?; write_period_separated_list( f, self.catalog .iter() .chain(&self.database) .chain(Some(&self.table)), )?; Ok(()) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ExistsTableStmt { pub catalog: Option<Identifier>, pub database: Option<Identifier>, pub table: Identifier, } impl Display for ExistsTableStmt { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "EXISTS TABLE ")?; write_period_separated_list( f, self.catalog .iter() .chain(&self.database) .chain(Some(&self.table)), ) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Engine { Null, Memory, Fuse, View, Random, } impl Display for Engine { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { Engine::Null => write!(f, "NULL"), Engine::Memory => write!(f, "MEMORY"), Engine::Fuse => write!(f, "FUSE"), Engine::View => write!(f, "VIEW"), Engine::Random => write!(f, "RANDOM"), } } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum CompactTarget { Block, Segment, } #[derive(Debug, Clone, PartialEq)] pub enum OptimizeTableAction { All, Purge { before: Option<TimeTravelPoint>, }, Compact { target: CompactTarget, limit: Option<Expr>, }, } impl Display for OptimizeTableAction { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { OptimizeTableAction::All => write!(f, "ALL"), OptimizeTableAction::Purge { before } => { write!(f, "PURGE")?; if let Some(point) = before { write!(f, " BEFORE {}", point)?; } Ok(()) } OptimizeTableAction::Compact { target, limit } => { match target { CompactTarget::Block => { write!(f, "COMPACT BLOCK")?; } CompactTarget::Segment => { write!(f, "COMPACT SEGMENT")?; } } if let Some(limit) = limit { write!(f, " LIMIT {limit}")?; } Ok(()) } } } } #[derive(Debug, Clone, PartialEq)] pub struct ColumnDefinition { pub name: Identifier, pub data_type: TypeName, pub default_expr: Option<Box<Expr>>, pub comment: Option<String>, } impl Display for ColumnDefinition { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { write!(f, "{} {}", self.name, self.data_type)?; if !matches!(self.data_type, TypeName::Nullable(_)) { write!(f, " NOT NULL")?; } if let Some(default_expr) = &self.default_expr { write!(f, " DEFAULT {default_expr}")?; } if let Some(comment) = &self.comment { write!(f, " COMMENT '{comment}'")?; } Ok(()) } }
// build-fail // aux-build:main_functions.rs #![feature(imported_main)] extern crate main_functions; pub use main_functions::boilerplate as main; //~ ERROR entry symbol `main` from foreign crate // FIXME: Should be run-pass
use crate::riscv32_core::PrivMode; use crate::riscv32_core::VMMode; use crate::riscv32_core::MemResult; use crate::riscv32_core::AddrT; use crate::riscv32_core::InstT; use crate::riscv64_core::Xlen64T; #[derive(PartialEq, Eq, Copy, Clone)] pub enum TraceType { XRegWrite, XRegRead, // Integer // FRegWrite, // FRegRead, // Single-Precision Float // DRegWrite, // DRegRead, // Double-Precision Float MemRead, MemWrite, // Memory Write // CsrWrite, // CsrRead, None, } pub struct TraceInfo { pub m_trace_type: TraceType, pub m_trace_size: u32, pub m_trace_addr: AddrT, pub m_trace_value: Xlen64T, pub m_trace_memresult: MemResult, /* Memory Access Result */ } impl TraceInfo { pub fn new() -> TraceInfo { TraceInfo { m_trace_type: TraceType::None, m_trace_size: 0, m_trace_addr: 0, m_trace_value: 0, m_trace_memresult: MemResult::NoExcept, /* Memory Access Result */ } } } pub struct Tracer { pub m_priv: PrivMode, pub m_vmmode: VMMode, pub m_executed_pc: AddrT, pub m_executed_phypc: AddrT, pub m_inst_hex: InstT, pub m_step: u32, pub m_trace_info: Vec<TraceInfo>, } impl Tracer { pub fn new() -> Tracer { Tracer { m_priv: PrivMode::Machine, m_vmmode: VMMode::Mbare, m_executed_pc: 0, m_executed_phypc: 0, m_inst_hex: 0, m_step: 0, m_trace_info: vec![], } } } pub trait RiscvTracer { fn clear(&mut self); fn print_trace(&mut self); } impl RiscvTracer for Tracer { fn clear(&mut self) { self.m_priv = PrivMode::Machine; self.m_vmmode = VMMode::Mbare; self.m_executed_pc = 0; self.m_executed_phypc = 0; self.m_inst_hex = 0; self.m_step = 0; self.m_trace_info = vec![]; } fn print_trace(&mut self) { print!("{:10}:", self.m_step); print!( "{}:", match self.m_priv { PrivMode::User => "U", PrivMode::Supervisor => "S", PrivMode::Hypervisor => "H", PrivMode::Machine => "M", } ); print!( "{}:", match self.m_vmmode { VMMode::Mbare => "Bare", VMMode::Sv32 => "Sv32", VMMode::Sv39 => "Sv39", VMMode::Sv48 => "Sv48", VMMode::Sv57 => "Sv57", VMMode::Sv64 => "Sv64", } ); print!("{:08x}:{:08x}:", self.m_executed_pc, self.m_inst_hex,); for trace_idx in 0..self.m_trace_info.len() { match self.m_trace_info[trace_idx].m_trace_type { TraceType::XRegWrite => { print!( "x{:02}<={:016x} ", self.m_trace_info[trace_idx].m_trace_addr, self.m_trace_info[trace_idx].m_trace_value ); } TraceType::XRegRead => { print!( "x{:02}=>{:016x} ", self.m_trace_info[trace_idx].m_trace_addr, self.m_trace_info[trace_idx].m_trace_value ); } TraceType::MemWrite => { print!( "({:08x})<={:08x} ", self.m_trace_info[trace_idx].m_trace_addr, self.m_trace_info[trace_idx].m_trace_value ); } TraceType::MemRead => { print!( "({:08x})=>{:08x} ", self.m_trace_info[trace_idx].m_trace_addr, self.m_trace_info[trace_idx].m_trace_value ); } _ => { print!( "[{:} is not supported] ", self.m_trace_info[trace_idx].m_trace_type as u32 ); } } } println!(" // DASM({:08x})", self.m_inst_hex); } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct CreateProcessMethod(pub i32); pub const CpCreateProcess: CreateProcessMethod = CreateProcessMethod(0i32); pub const CpCreateProcessAsUser: CreateProcessMethod = CreateProcessMethod(1i32); pub const CpAicLaunchAdminProcess: CreateProcessMethod = CreateProcessMethod(2i32); impl ::core::convert::From<i32> for CreateProcessMethod { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for CreateProcessMethod { type Abi = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IDDEInitializer(pub ::windows::core::IUnknown); impl IDDEInitializer { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Shell"))] pub unsafe fn Initialize< 'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::super::UI::Shell::IShellItem>, Param4: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>, Param5: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>, Param6: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>, Param7: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>, Param8: ::windows::core::IntoParam<'a, super::super::super::Foundation::PWSTR>, >( &self, fileextensionorprotocol: Param0, method: CreateProcessMethod, currentdirectory: Param2, exectarget: Param3, site: Param4, application: Param5, targetfile: Param6, arguments: Param7, verb: Param8, ) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)( ::core::mem::transmute_copy(self), fileextensionorprotocol.into_param().abi(), ::core::mem::transmute(method), currentdirectory.into_param().abi(), exectarget.into_param().abi(), site.into_param().abi(), application.into_param().abi(), targetfile.into_param().abi(), arguments.into_param().abi(), verb.into_param().abi(), ) .ok() } } unsafe impl ::windows::core::Interface for IDDEInitializer { type Vtable = IDDEInitializer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x30dc931f_33fc_4ffd_a168_942258cf3ca4); } impl ::core::convert::From<IDDEInitializer> for ::windows::core::IUnknown { fn from(value: IDDEInitializer) -> Self { value.0 } } impl ::core::convert::From<&IDDEInitializer> for ::windows::core::IUnknown { fn from(value: &IDDEInitializer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDDEInitializer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDDEInitializer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IDDEInitializer_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Shell"))] pub unsafe extern "system" fn( this: ::windows::core::RawPtr, fileextensionorprotocol: super::super::super::Foundation::PWSTR, method: CreateProcessMethod, currentdirectory: super::super::super::Foundation::PWSTR, exectarget: ::windows::core::RawPtr, site: ::windows::core::RawPtr, application: super::super::super::Foundation::PWSTR, targetfile: super::super::super::Foundation::PWSTR, arguments: super::super::super::Foundation::PWSTR, verb: super::super::super::Foundation::PWSTR, ) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_UI_Shell")))] usize, );
use quickcheck::{Arbitrary, Gen}; use rand::seq::SliceRandom; use crate::{Code, Code::*, Multihash, MultihashDigest}; const HASHES: [Code; 16] = [ Identity, Sha1, Sha2_256, Sha2_512, Sha3_512, Sha3_384, Sha3_256, Sha3_224, Keccak224, Keccak256, Keccak384, Keccak512, Blake2b256, Blake2b512, Blake2s128, Blake2s256, ]; /// Generates a random hash algorithm. /// /// The more exotic ones will be generated just as frequently as the common ones. impl Arbitrary for Code { fn arbitrary<G: Gen>(g: &mut G) -> Self { *HASHES.choose(g).unwrap() } } /// Generates a random valid multihash. /// /// This is done by encoding a random piece of data. impl Arbitrary for Multihash { fn arbitrary<G: Gen>(g: &mut G) -> Self { let code: Code = Arbitrary::arbitrary(g); let data: Vec<u8> = Arbitrary::arbitrary(g); // encoding an actual random piece of data might be better than just choosing // random numbers of the appropriate size, since some hash algos might produce // a limited set of values Box::<dyn MultihashDigest<Code>>::from(code).digest(&data) } }
// NTRUMLS bindings // Written in 2018 by // Vladislav Markushin // //! # Build script // Coding conventions #![deny(non_upper_case_globals)] #![deny(non_camel_case_types)] #![deny(non_snake_case)] #![deny(unused_mut)] #![warn(missing_docs)] extern crate gcc; fn main() { let mut base_config = gcc::Build::new(); base_config.include("depend/NTRUMLS/src").include("depend/NTRUMLS/").flag("-g"); base_config .file("depend/NTRUMLS/src/crypto_hash_sha512.c") .file("depend/NTRUMLS/src/crypto_stream.c") .file("depend/NTRUMLS/src/fastrandombytes.c") .file("depend/NTRUMLS/src/shred.c") .file("depend/NTRUMLS/src/convert.c") .file("depend/NTRUMLS/src/pack.c") .file("depend/NTRUMLS/src/pol.c") .file("depend/NTRUMLS/src/params.c") .file("depend/NTRUMLS/src/pqntrusign.c"); if cfg!(target_os = "windows") { base_config.file("depend/NTRUMLS/src/randombytes-vs.c"); } else { base_config.file("depend/NTRUMLS/src/randombytes.c"); } if let Err(e) = base_config.try_compile("libntrumls.a") { panic!("Compiler error: {:?}", e); } }
use super::*; use bitflags::bitflags; use zircon_object::vm::*; impl Syscall<'_> { /// creates a new mapping in the virtual address space of the calling process. /// - `addr` - The starting address for the new mapping /// - `len` - specifies the length of the mapping /// - `prot ` - describes the desired memory protection of the mapping /// - `flags` - determines whether updates to the mapping are visible to other processes mapping the same region, /// and whether updates are carried through to the underlying file. /// - `fd` - mapping file descriptor /// - `offset` - offset in the file pub async fn sys_mmap( &self, addr: usize, len: usize, prot: usize, flags: usize, fd: FileDesc, offset: u64, ) -> SysResult { let prot = MmapProt::from_bits_truncate(prot); let flags = MmapFlags::from_bits_truncate(flags); info!( "mmap: addr={:#x}, size={:#x}, prot={:?}, flags={:?}, fd={:?}, offset={:#x}", addr, len, prot, flags, fd, offset ); let proc = self.zircon_process(); let vmar = proc.vmar(); if flags.contains(MmapFlags::FIXED) { // unmap first vmar.unmap(addr, len)?; } let vmar_offset = flags.contains(MmapFlags::FIXED).then(|| addr - vmar.addr()); if flags.contains(MmapFlags::ANONYMOUS) { if flags.contains(MmapFlags::SHARED) { return Err(LxError::EINVAL); } let vmo = VmObject::new_paged(pages(len)); let addr = vmar.map(vmar_offset, vmo.clone(), 0, vmo.len(), prot.to_flags())?; Ok(addr) } else { let file = self.linux_process().get_file(fd)?; let mut buf = vec![0; len]; let len = file.read_at(offset, &mut buf).await?; let vmo = VmObject::new_paged(pages(len)); vmo.write(0, &buf[..len])?; let addr = vmar.map(vmar_offset, vmo.clone(), 0, vmo.len(), prot.to_flags())?; Ok(addr) } } /// changes the access protections for the calling process's memory pages /// containing any part of the address range in the interval [addr, addr+len-1] /// TODO: unimplemented pub fn sys_mprotect(&self, addr: usize, len: usize, prot: usize) -> SysResult { let prot = MmapProt::from_bits_truncate(prot); info!( "mprotect: addr={:#x}, size={:#x}, prot={:?}", addr, len, prot ); warn!("mprotect: unimplemented"); Ok(0) } /// Deletes the mappings for the specified address range, and causes further references to addresses /// within the range to generate invalid memory references. pub fn sys_munmap(&self, addr: usize, len: usize) -> SysResult { info!("munmap: addr={:#x}, size={:#x}", addr, len); let proc = self.thread.proc(); let vmar = proc.vmar(); vmar.unmap(addr, len)?; Ok(0) } } bitflags! { /// for the flag argument in mmap() pub struct MmapFlags: usize { #[allow(clippy::identity_op)] /// Changes are shared. const SHARED = 1 << 0; /// Changes are private. const PRIVATE = 1 << 1; /// Place the mapping at the exact address const FIXED = 1 << 4; /// The mapping is not backed by any file. (non-POSIX) const ANONYMOUS = MMAP_ANONYMOUS; } } /// MmapFlags `MMAP_ANONYMOUS` depends on arch #[cfg(target_arch = "mips")] const MMAP_ANONYMOUS: usize = 0x800; #[cfg(not(target_arch = "mips"))] const MMAP_ANONYMOUS: usize = 1 << 5; bitflags! { /// for the prot argument in mmap() pub struct MmapProt: usize { #[allow(clippy::identity_op)] /// Data can be read const READ = 1 << 0; /// Data can be written const WRITE = 1 << 1; /// Data can be executed const EXEC = 1 << 2; } } impl MmapProt { /// convert MmapProt to MMUFlags fn to_flags(self) -> MMUFlags { let mut flags = MMUFlags::USER; if self.contains(MmapProt::READ) { flags |= MMUFlags::READ; } if self.contains(MmapProt::WRITE) { flags |= MMUFlags::WRITE; } if self.contains(MmapProt::EXEC) { flags |= MMUFlags::EXECUTE; } // FIXME: hack for unimplemented mprotect if self.is_empty() { flags |= MMUFlags::READ | MMUFlags::WRITE; } flags } }
use std::error::Error as StdError; use serde::{Deserialize, Serialize}; pub const INTERNAL_SERVER_ERROR: Fault = Fault::Static(StaticException::InternalServerError); pub const NOT_FOUND: Fault = Fault::Static(StaticException::NotFound); #[derive(Debug, Serialize, Deserialize)] #[serde(tag = "type")] pub enum Fault { /// Static will handle exceptions related to the static server #[serde(rename = "about:blank")] Static(StaticException), /// RateLimit handles exceptions related to filter gated request behind a /// leaky bucket rate limiter #[serde(rename = "/report/rate-limit")] RateLimit(RateLimitException) } impl Fault { pub fn to_status_code(&self) -> warp::http::StatusCode { use warp::http::StatusCode; use Fault::*; match self { Static(StaticException::NotFound) => StatusCode::NOT_FOUND, Static(StaticException::InternalServerError) => { StatusCode::INTERNAL_SERVER_ERROR }, RateLimit(_) => warp::http::StatusCode::TOO_MANY_REQUESTS, } } } impl std::fmt::Display for Fault { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let exception_msg: ExceptionMsg = self.into(); // TODO: improve f.write_str(&format!("{:?}", exception_msg)) } } impl StdError for Fault {} /// Serde serializes an ExceptionMsg with its title field set to None and /// with its problem field to the Fault::Static variant, the title field in the /// generated serialization is taken from the StaticException variant. #[derive(Debug, Serialize, Deserialize)] #[serde(tag = "title")] pub enum StaticException { #[serde(rename = "Not Found")] NotFound, #[serde(rename = "Internal Server Error")] InternalServerError, } #[derive(Debug, Serialize)] pub struct ExceptionMsg<'a> { #[serde(flatten)] pub fault: &'a Fault, #[serde(skip_serializing_if = "Option::is_none")] pub title: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub status: Option<u16>, #[serde(skip_serializing_if = "Option::is_none")] pub detail: Option<String>, } impl<'a> From<&'a Fault> for ExceptionMsg<'a> { fn from(fault: &'a Fault) -> ExceptionMsg<'a> { use Fault::*; let status = Some(fault.to_status_code().as_u16()); let (title, detail) = match fault { Static(_) => { (None, None) } RateLimit(_) => { ( Some("Your request has been rate limited.".to_owned()), None, ) } }; ExceptionMsg { fault, title, status, detail, } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RateLimitException { pub wait_time_millis: u64, }
/*! * 用于监听Redis的写入操作,据此可以实现数据复制,监控等相关的应用。 * * # 原理 * * 此crate实现了[Redis Replication协议],在运行时,程序将以replica的身份连接到Redis,相当于Redis的一个副本。 * * 所以,在程序连接上某个Redis之后,Redis会将它当前的所有数据以RDB的格式dump一份,dump完毕之后便发送过来,这个RDB中的每一条数据就对应一个[`Event`]`::RDB`事件。 * * 在这之后,Redis接收到来自客户端的写入操作(即Redis命令)后,也会将这个写入操作传播给它的replica,每一个写入操作就对应一个[`Event`]`::AOF`事件。 * * # 示例 * * ```no_run * use std::net::{IpAddr, SocketAddr}; * use std::sync::atomic::AtomicBool; * use std::sync::Arc; * use std::str::FromStr; * use std::rc::Rc; * use std::cell::RefCell; * use redis_event::listener; * use redis_event::config::Config; * use redis_event::{NoOpEventHandler, RedisListener}; * * fn main() -> std::io::Result<()> { * let host = String::from("127.0.0.1"); * let port = 6379; * * let conf = Config { * is_discard_rdb: false, // 不跳过RDB * is_aof: false, // 不处理AOF * host, * port, * username: String::new(), // 用户名为空 * password: String::new(), // 密码为空 * repl_id: String::from("?"), // replication id,若无此id,设置为?即可 * repl_offset: -1, // replication offset,若无此offset,设置为-1即可 * read_timeout: None, // None,即读取永不超时 * write_timeout: None, // None,即写入永不超时 * is_tls_enabled: false, // 不启用TLS * is_tls_insecure: false, // 未启用TLS,设置为false即可 * identity: None, // 未启用TLS,设置为None即可 * identity_passwd: None // 未启用TLS,设置为None即可 * }; * let running = Arc::new(AtomicBool::new(true)); * * let mut builder = listener::Builder::new(); * builder.with_config(conf); * // 设置控制变量, 通过此变量在外界中断`redis_event`内部的逻辑 * builder.with_control_flag(running); * // 设置事件处理器 * builder.with_event_handler(Rc::new(RefCell::new(NoOpEventHandler{}))); * * let mut redis_listener = builder.build(); * // 启动程序 * redis_listener.start()?; * Ok(()) * } * ``` * * [Redis Replication协议]: https://redis.io/topics/replication * [`Event`]: enum.Event.html */ use std::io::{Read, Result}; use crate::cmd::Command; use crate::rdb::{Module, Object}; pub mod cmd; pub mod config; mod io; mod iter; pub mod listener; mod lzf; pub mod rdb; pub mod resp; mod tests; /// Redis事件监听器的定义,所有类型的监听器都实现此接口 pub trait RedisListener { /// 开启事件监听 fn start(&mut self) -> Result<()>; } /// Redis RDB 解析器定义 pub trait RDBParser { /// 解析RDB的具体实现 /// /// 方法参数: /// /// * `input`: RDB输入流 /// * `length`: RDB的总长度 /// * `event_handler`: Redis事件处理器 fn parse(&mut self, input: &mut dyn Read, length: i64, event_handler: &mut dyn EventHandler) -> Result<()>; } /// Redis事件 pub enum Event<'a> { /// RDB事件 /// /// 当开启`RedisListener`之后,Redis会将此刻内存中的数据dump出来(以rdb的格式进行dump), /// dump完毕之后的rdb数据便会发送给`RedisListener`,此rdb中的数据即对应此事件 RDB(Object<'a>), /// AOF事件 /// /// 在上面rdb数据处理完毕之后,客户端对Redis的数据写入操作将会发送给`RedisListener`, /// 此写入操作即对应此事件 AOF(Command<'a>), } /// Redis事件处理器的定义,所有类型的处理器都必须实现此接口 pub trait EventHandler { fn handle(&mut self, event: Event); } /// 对于接收到的Redis事件不做任何处理 pub struct NoOpEventHandler {} impl EventHandler for NoOpEventHandler { fn handle(&mut self, _: Event) {} } /// Module Parser pub trait ModuleParser { /// 解析Module的具体实现 /// /// 方法参数: /// /// * `input`: RDB输入流 /// * `module_name`: Module的名字 /// * `module_version`: Module的版本 fn parse(&mut self, input: &mut dyn Read, module_name: &str, module_version: usize) -> Box<dyn Module>; } /// 转换为utf-8字符串,不验证正确性 fn to_string(bytes: Vec<u8>) -> String { return unsafe { String::from_utf8_unchecked(bytes) }; }
extern crate protobuf_iter; extern crate byteorder; extern crate libdeflater; pub mod blob_reader; pub use blob_reader::*; pub mod blob; pub use blob::*; pub mod parse; pub use parse::*; pub mod delta; pub mod delimited;
extern crate dotenv; // extern crate envy; #[macro_use] extern crate serde_derive; use std::env; #[derive(Deserialize, Debug)] struct Environment { lang: String, } #[derive(Deserialize, Debug)] struct MailerConfig { email_backend: String, email_from: String, } fn main() { println!("24 Days of Rust, volume 2 - environment"); match env::var("LANG") { Ok(lang) => println!("Language code: {}", lang), Err(e) => println!("Couldn't read LANG ({})", e), }; // match envy::from_env::<Environment>() { // Ok(environment) => println!("Language code: {}", environment.lang), // Err(e) => println!("Couldn't read LANG ({})", e), // }; dotenv::dotenv().expect("Failed to read .env file"); println!( "Email backend: {}", env::var("EMAIL_BACKEND").expect("EMAIL_BACKEND not found") ); // match envy::from_env::<MailerConfig>() { // Ok(config) => println!("{:?}", config), // Err(e) => println!("Couldn't read mailer config ({})", e), // }; }
// Trim a Binary Search Tree // https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3626/ use std::cell::RefCell; use std::rc::Rc; pub struct Solution; // Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] #[allow(dead_code)] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } } } impl Solution { pub fn trim_bst( root: Option<Rc<RefCell<TreeNode>>>, low: i32, high: i32, ) -> Option<Rc<RefCell<TreeNode>>> { root.and_then(|node| { let val = node.borrow().val; if val < low { Solution::trim_bst(node.borrow().right.clone(), low, high) } else if val > high { Solution::trim_bst(node.borrow().left.clone(), low, high) } else { Some(Rc::new(RefCell::new(TreeNode { val, left: Solution::trim_bst( node.borrow().left.clone(), low, high, ), right: Solution::trim_bst( node.borrow().right.clone(), low, high, ), }))) } }) } } #[cfg(test)] mod tests { use super::*; fn node( val: i32, left: Option<Rc<RefCell<TreeNode>>>, right: Option<Rc<RefCell<TreeNode>>>, ) -> Option<Rc<RefCell<TreeNode>>> { Some(Rc::new(RefCell::new(TreeNode { val, left, right }))) } fn leaf(val: i32) -> Option<Rc<RefCell<TreeNode>>> { node(val, None, None) } #[test] fn example1() { let root = node(1, leaf(0), leaf(2)); let expected = node(1, None, leaf(2)); assert_eq!(Solution::trim_bst(root, 1, 2), expected); } #[test] fn example2() { let root = node(3, node(0, None, node(2, leaf(1), None)), leaf(4)); let expected = node(3, node(2, leaf(1), None), None); assert_eq!(Solution::trim_bst(root, 1, 3), expected); } #[test] fn example3() { let root = leaf(1); let expected = leaf(1); assert_eq!(Solution::trim_bst(root, 1, 2), expected); } #[test] fn example4() { let root = node(1, None, leaf(2)); let expected = node(1, None, leaf(2)); assert_eq!(Solution::trim_bst(root, 1, 3), expected); } #[test] fn example5() { let root = node(1, None, leaf(2)); let expected = leaf(2); assert_eq!(Solution::trim_bst(root, 2, 4), expected); } }
use std::collections::HashMap; #[derive(Debug)] pub struct Config { pub debug: bool, pub render_screen: bool, pub initial_color: u32, pub play_sound: bool, } impl Config { pub fn new(config_name: &str) -> Self { let mut config = config::Config::default(); config.merge(config::File::with_name(config_name)).unwrap(); let config = config.try_into::<HashMap<String, String>>() .unwrap(); let debug = read_value("debug", false, &config) .expect("debug should be one of: true/false"); let render_screen = read_value("render_screen", true, &config) .expect("render_screen should be one of: true/false"); let initial_color = read_value("initial_color", 0xFFFF_FFFF, &config) .expect("initial_color should be a 32bit number"); let play_sound = read_value("play_sound", true, &config) .expect("play_sound should be one of: true/false"); Config { debug, render_screen, initial_color, play_sound } } } fn read_value<T: std::str::FromStr>(name: &str, default: T, config: &HashMap<String, String>) -> Result<T, T::Err> { return config.get(name) .map_or(Ok(default), |v| v.parse::<T>()); }
use crate::impl_pnext; use crate::prelude::*; use std::marker::PhantomData; use std::os::raw::{c_char, c_void}; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkDeviceCreateInfo<'a> { lt: PhantomData<&'a ()>, pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkDeviceCreateFlagBits, pub queueCreateInfoCount: u32, pub pQueueCreateInfos: *const VkDeviceQueueCreateInfo, pub enabledLayerCount: u32, pub ppEnabledLayerNames: *const *const c_char, pub enabledExtensionCount: u32, pub ppEnabledExtensionNames: *const *const c_char, pub pEnabledFeatures: *const VkPhysicalDeviceFeatures, } impl<'a> VkDeviceCreateInfo<'a> { pub fn new<T>( flags: T, queue_create_info: &'a [VkDeviceQueueCreateInfo], enabled_extension_names: &'a VkNames, enabled_features: &'a VkPhysicalDeviceFeatures, ) -> Self where T: Into<VkDeviceCreateFlagBits>, { VkDeviceCreateInfo { lt: PhantomData, sType: VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, pNext: ptr::null(), flags: flags.into(), queueCreateInfoCount: queue_create_info.len() as u32, pQueueCreateInfos: queue_create_info.as_ptr(), enabledLayerCount: 0, ppEnabledLayerNames: ptr::null(), enabledExtensionCount: enabled_extension_names.c_names().len() as u32, ppEnabledExtensionNames: enabled_extension_names.c_names().as_ptr(), pEnabledFeatures: enabled_features as *const _, } } } impl_pnext!( VkDeviceCreateInfo<'_>, VkPhysicalDeviceDescriptorIndexingFeaturesEXT );
#![no_main] #![feature(start)] extern crate olin; use olin::entrypoint; use serde_json::{from_slice, to_string, Value}; entrypoint!(); fn main() -> Result<(), std::io::Error> { let input = include_bytes!("./bigjson.json"); if let Ok(val) = from_slice(input) { let v: Value = val; if let Err(_why) = to_string(&v) { return Err(std::io::Error::new( std::io::ErrorKind::Other, "oh no json encoding failed!", )); } } else { return Err(std::io::Error::new( std::io::ErrorKind::Other, "oh no json parsing failed!", )); } Ok(()) }
// Quiet diesel warnings https://github.com/diesel-rs/diesel/issues/1785 #![allow(proc_macro_derive_resolution_fallback)] // Force these as errors so that they are not lost in all the diesel warnings #![deny(unreachable_patterns)] #![deny(unknown_lints)] #![deny(unused_variables)] #![deny(unused_imports)] // Unused results is more often than not an error #![deny(unused_must_use)] #![deny(unused_extern_crates)] #[macro_use] extern crate diesel_migrations; extern crate bigneon_db; extern crate clap; extern crate diesel; #[allow(unused_imports)] embed_migrations!("./migrations"); use bigneon_db::prelude::*; use clap::ArgMatches; use clap::{App, Arg, SubCommand}; use diesel::connection::SimpleConnection; use diesel::pg::PgConnection; use diesel::Connection; pub fn main() { let matches = App::new("Big Neon DB CLI") .author("Big Neon") .about("Command Line Interface for creating and migrating the Big Neon database") .subcommand( SubCommand::with_name("migrate") .about("Migrates the database to the latest version") .arg( Arg::with_name("connection") .short("c") .takes_value(true) .help("Connection string to the database"), ), ).subcommand( SubCommand::with_name("create") .about("Creates a new instance of the database and inserts the system administrator user") .arg( Arg::with_name("connection") .short("c") .takes_value(true) .help("Connection string to the database"), ) .arg( Arg::with_name("email") .short("e") .takes_value(true) .help("email for system administrator"), ).arg( Arg::with_name("phone") .short("m") .takes_value(true) .help("phone number for system administrator"), ).arg( Arg::with_name("password") .short("p") .takes_value(true) .help("password for system administrator"), ).arg( Arg::with_name("force").short("f").help("Drops the database if it exists. WARNING! This is NOT REVERSIBLE") ), ).subcommand( SubCommand::with_name("drop") .about("Deletes the current database. WARNING! This is NOT REVERSIBLE") .arg( Arg::with_name("connection") .short("c") .takes_value(true) .help("Connection string to the database"), ) ).subcommand( SubCommand::with_name("seed") .about("Populates the database with example data") .arg(Arg::with_name("connection") .short("c") .takes_value(true) .help("Connection string to the database") ) ).get_matches(); match matches.subcommand() { ("create", Some(matches)) => create_db_and_user(matches), ("drop", Some(matches)) => drop_db(matches), ("migrate", Some(matches)) => migrate_db(matches), ("seed", Some(matches)) => seed_db(matches), _ => unreachable!("The cli parser will prevent reaching here"), } } fn change_database(conn_string: &str) -> String { let last_slash = conn_string .rfind('/') .expect("Connection string does not conform to <hostname>/<database>"); format!("{}/postgres", conn_string.get(..last_slash).unwrap()) } fn get_db(conn_string: &str) -> (String, String) { let parts: Vec<&str> = conn_string.split('/').collect(); let db = parts.last().unwrap(); let db = str::replace(db, "'", "''"); let postgres_conn_string = change_database(conn_string); (postgres_conn_string, db) } fn execute_sql(postgres_conn_string: &str, query: &str) -> Result<(), diesel::result::Error> { let connection = PgConnection::establish(&postgres_conn_string).unwrap(); connection.execute(query).map(|_i| ()) } fn create_db(conn_string: &str) -> Result<(), diesel::result::Error> { let (postgres_conn_string, db) = get_db(conn_string); execute_sql( &postgres_conn_string, &format!("CREATE DATABASE \"{}\"", db), ) } fn migrate_db(matches: &ArgMatches) { let conn_string = matches .value_of("connection") .expect("Connection string was not provided"); match create_db(conn_string) { Ok(_o) => println!("Creating database"), Err(_e) => println!("Database already exists"), } println!("Migrating database"); let connection = PgConnection::establish(conn_string).unwrap(); embedded_migrations::run_with_output(&connection, &mut std::io::stdout()) .expect("Migration failed"); } fn create_db_and_user(matches: &ArgMatches) { let conn_string = matches .value_of("connection") .expect("Connection string was not provided"); if matches.is_present("force") { drop_db(matches); } create_db(conn_string) .expect("Can't create database because one with the same name already exists"); { let connection = get_connection(conn_string); embedded_migrations::run_with_output(&connection, &mut std::io::stdout()) .expect("Migration failed"); } let username = matches.value_of("email").expect("Email was not provided"); let phone = matches .value_of("phone") .expect("Phone number was not provided"); let password = matches .value_of("password") .expect("Password was not provided"); println!("Creating user"); let db_connection = get_connection(conn_string); let user = User::create("System", "Administrator", username, phone, password) .commit(&db_connection) .expect("Failed to create system admin"); user.add_role(Roles::Admin, &db_connection) .expect("Could not assign System Administrator role to the user"); } fn seed_db(matches: &ArgMatches) { println!("Seeding database"); let conn_string = matches .value_of("connection") .expect("Connection string was not provided"); let db_connection = get_connection(conn_string); let seed_query = include_str!("seed_data/seed.sql"); println!("Seed {}", seed_query); db_connection .batch_execute(seed_query) .expect("Seeding database failed"); } fn get_connection(connection_string: &str) -> PgConnection { PgConnection::establish(&connection_string).expect("Error connecting to DB") } fn drop_db(matches: &ArgMatches) { let conn_string = matches .value_of("connection") .expect("Connection string was not provided"); let (postgres_conn_string, db) = get_db(conn_string); println!("Dropping {} from {}", db, postgres_conn_string); execute_sql( &postgres_conn_string, &format!("DROP DATABASE IF EXISTS \"{}\"", db), ).expect("Error dropping database"); }
use crate::{ geo::{Geo, HitResult, HitTemp, Texture, TextureRaw}, linalg::{Ray, Transform, Vct}, Deserialize, Serialize, EPS, }; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Plane { pub transform: Transform, pub texture: Texture, } impl Plane { pub fn new(texture: Texture, transform: Transform) -> Self { Self { texture, transform } } } impl Geo for Plane { // calculate t, which means r.origin + r.direct * t is the intersection point fn hit_t(&self, r: &Ray) -> Option<HitTemp> { let n = self.transform.z(); let d = n.dot(r.direct); if d.abs() > EPS { let t = n.dot(self.transform.pos() - r.origin) / d; if t > EPS { return Some((t, None)); } } None } // return the hit result fn hit(&self, r: &Ray, tmp: HitTemp) -> HitResult { let pos = r.origin + r.direct * tmp.0; let n = self.transform.z(); HitResult { pos, norm: if n.dot(r.direct) > 0.0 { n } else { -n }, texture: match self.texture { Texture::Raw(ref raw) => *raw, Texture::Image(ref img) => { let v = pos - self.transform.pos(); let px = self.transform.x().dot(v) * img.width_ratio; let py = self.transform.y().dot(v) * img.height_ratio; let col = img.image.get_repeat(px as isize, py as isize); TextureRaw { emission: Vct::zero(), color: Vct::new(col.0, col.1, col.2), material: img.material, } } }, } } }
//! # quicksilver //! ![Quicksilver Logo](./logo.svg) //! //! [![Build Status](https://travis-ci.org/ryanisaacg/quicksilver.svg)](https://travis-ci.org/ryanisaacg///! //! //! quicksilver) //! [![Crates.io](https://img.shields.io/crates/v/quicksilver.svg)](https://crates.io/crates/quicksilver) //! [![Docs Status](https://docs.rs/quicksilver/badge.svg)](https://docs.rs/quicksilver) //! [![dependency status](https://deps.rs/repo/github/ryanisaacg/quicksilver/status.svg)](https://deps.rs/repo///! github/ryanisaacg/quicksilver) //! [![Gitter chat](https://badges.gitter.im/quicksilver-rs/Lobby.svg)](https://gitter.im/quicksilver-rs/Lobby?//! utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) //! //! A 2D game framework written in pure Rust, for both the Web and Desktop //! //! ## A quick example //! //! Create a rust project and add this line to your `Cargo.toml` file under `[dependencies]`: //! ```text //! quicksilver = "*" //! ``` //! Then replace `src/main.rs` with the following (the contents of quicksilver's examples/draw-geometry.rs): //! //! ```no_run //! // Draw some multi-colored geometry to the screen //! extern crate quicksilver; //! //! use quicksilver::{ //! Result, //! geom::{Circle, Line, Rectangle, Transform, Triangle, Vector}, //! graphics::{Background::Col, Color}, //! lifecycle::{Settings, State, Window, run}, //! }; //! //! struct DrawGeometry; //! //! impl State for DrawGeometry { //! fn new() -> Result<DrawGeometry> { //! Ok(DrawGeometry) //! } //! //! fn draw(&mut self, window: &mut Window) -> Result<()> { //! window.clear(Color::WHITE)?; //! window.draw(&Rectangle::new((100, 100), (32, 32)), Col(Color::BLUE)); //! window.draw_ex(&Rectangle::new((400, 300), (32, 32)), Col(Color::BLUE), Transform::rotate(45), 10); //! window.draw(&Circle::new((400, 300), 100), Col(Color::GREEN)); //! window.draw_ex( //! &Line::new((50, 80),(600, 450)).with_thickness(2.0), //! Col(Color::RED), //! Transform::IDENTITY, //! 5 //! ); //! window.draw_ex( //! &Triangle::new((500, 50), (450, 100), (650, 150)), //! Col(Color::RED), //! Transform::rotate(45) * Transform::scale((0.5, 0.5)), //! 0 //! ); //! Ok(()) //! } //! } //! //! fn main() { //! run::<DrawGeometry>("Draw Geometry", Vector::new(800, 600), Settings::default()); //! } //! ``` //! //! Run this with `cargo run` or, if you have the wasm32 toolchain installed, you can build for the web //! //! //! (instructions below). //! //! ## Learning Quicksilver //! //! A good way to get started with Quicksilver is to [read and run the examples](https://github.com/ryanisaacg///! quicksilver/tree/master/examples) and go through the tutorial modules [on docs.rs](https://docs.rs/quicksilver). If you have any question, feel free to hop onto Gitter or open an issue. //! //! ## Building and Deploying a Quicksilver application //! //! Quicksilver should always compile and run on the latest stable version of Rust, for both web and desktop. //! //! Make sure to put all your assets in a top-level folder of your crate called `static/`. *All* Quicksilver file //! loading-APIs will expect paths that originate in the static folder, so `static/image.png` should be //! //! referenced as `image.png`. //! //! ### Linux dependencies //! //! On Windows and Mac, all you'll need to build Quicksilver is a recent stable version of `rustc` and `cargo`. A //! few of Quicksilver's dependencies require Linux packages to build, namely `libudev`, `zlib`, and `alsa`. To //! install these on Ubuntu or Debian, run the command `sudo apt install libudev-dev zlib1g-dev alsa //! //! //! libasound2-dev`. //! //! ### Deploying for desktop //! //! If you're deploying for desktop platforms, build in release mode (`cargo build --release`) //! and copy the executable file produced (found at "target/release/") and any assets you used (image files //! etc) and create an archive (on Windows a zip file, on Unix a tar file). You should be able to distribute //! this archive with no problems; if there are any, please open an issue. //! //! ### Deploying for the web //! //! If you're deploying for the web, first make sure you've [installed the cargo web tool](https://github.com///! //! koute/cargo-web). Then use the `cargo web deploy` to build your application for distribution (located //! at `target/deploy`). //! //! If you want to test your application locally, use `cargo web start` and open your favorite browser to the //! //! port it provides. //! //! ## Optional Features //! //! Quicksilver by default tries to provide all features a 2D application may need, but not all applications need //! these features. //! The optional features available are //! collision support (via [ncollide2d](https://github.com/sebcrozet/ncollide)), //! font support (via [rusttype](https://github.com/redox-os/rusttype)), //! gamepad support (via [gilrs](https://gitlab.com/gilrs-project/gilrs)), //! saving (via [serde_json](https://github.com/serde-rs/json)), //! complex shape / svg rendering (via [lyon](https://github.com/nical/lyon)), //! immediate-mode GUIs (via [immi](https://github.com/tomaka/immi)), //! and sounds (via [rodio](https://github.com/tomaka/rodio)). //! //! Each are enabled by default, but you can [specify which features](https://doc.rust-lang.org/cargo/reference///! specifying-dependencies.html#choosing-features) you actually want to use. //! //! ## Supported Platforms //! //! The engine is supported on Windows, macOS, Linux, and the web via WebAssembly. //! The web is only supported via the `wasm32-unknown-unknown` Rust target, not through emscripten. //! It might work with emscripten but this is not an ongoing guarantee. //! //! Mobile support would be a future possibility, but likely only through external contributions. #![doc(html_root_url = "https://docs.rs/quicksilver/0.3.12/quicksilver")] #![deny( bare_trait_objects, missing_docs, unused_extern_crates, unused_import_braces, unused_qualifications )] #[macro_use] extern crate serde_derive; #[cfg(target_arch = "wasm32")] #[macro_use] extern crate stdweb; mod backend; mod error; mod file; pub mod geom; pub mod graphics; pub mod input; pub mod lifecycle; pub mod prelude; #[cfg(feature = "saving")] pub mod saving; #[cfg(feature = "sounds")] pub mod sound; pub use crate::error::QuicksilverError as Error; pub use crate::file::load_file; #[cfg(feature = "lyon")] pub use lyon; pub mod tutorials; /// A Result that returns either success or a Quicksilver Error pub type Result<T> = ::std::result::Result<T, Error>; /// Types that represents a "future" computation, used to load assets pub use futures::Future; /// Helpers that allow chaining computations together in a single Future /// /// This allows one Asset object that contains all of the various resources /// an application needs to load. pub use futures::future as combinators;
use graph_map::GraphMMap; use declarative_dataflow::server::Server; use declarative_dataflow::plan::{Plan, Join}; use declarative_dataflow::{q, Binding, AttributeConfig, InputSemantics, Rule, Datom, Value}; use Value::Eid; fn main() { let filename = std::env::args().nth(1).unwrap(); let batching = std::env::args().nth(2).unwrap().parse::<usize>().unwrap(); let inspect = std::env::args().any(|x| x == "inspect"); timely::execute_from_args(std::env::args().skip(2), move |worker| { let mut timer = std::time::Instant::now(); let graph = GraphMMap::new(&filename); let mut server = Server::<u64, u64>::new(Default::default()); // [?a :edge ?b] [?b :edge ?c] [?a :edge ?c] let (a, b, c) = (1, 2, 3); // let plan = q( // vec![a, b, c], // vec![ // Binding::attribute(a, "edge", b), // Binding::attribute(b, "edge", c), // Binding::attribute(a, "edge", c), // ], // ); let plan = q( vec![a, b, c], vec![ Binding::attribute(a, "edge", b), Binding::attribute(a, "edge", c), Binding::attribute(b, "edge", c), ], ); // let plan = q( // vec![a, b, c], // vec![ // Binding::attribute(b, "edge", c), // Binding::attribute(a, "edge", c), // Binding::attribute(a, "edge", b), // ], // ); // ([?a ?b] [?b ?c]) [?a ?c] // let plan = Plan::Join(Join { // variables: vec![a], // left_plan: Box::new(Plan::MatchA(a, "edge".to_string(), c)), // right_plan: Box::new(Plan::Join(Join { // variables: vec![b], // left_plan: Box::new(Plan::MatchA(a, "edge".to_string(), b)), // right_plan: Box::new(Plan::MatchA(b, "edge".to_string(), c)), // })) // }); // ([?a ?b] [?a ?c]) [?b ?c] // let plan = Plan::Join(Join { // variables: vec![b, c], // left_plan: Box::new(Plan::MatchA(b, "edge".to_string(), c)), // right_plan: Box::new(Plan::Join(Join { // variables: vec![a], // left_plan: Box::new(Plan::MatchA(a, "edge".to_string(), b)), // right_plan: Box::new(Plan::MatchA(a, "edge".to_string(), c)), // })) // }); // ([?a ?c] [?b ?c]) [?a ?b] // let plan = Plan::Join(Join { // variables: vec![a, b], // left_plan: Box::new(Plan::MatchA(a, "edge".to_string(), b)), // right_plan: Box::new(Plan::Join(Join { // variables: vec![c], // left_plan: Box::new(Plan::MatchA(a, "edge".to_string(), c)), // right_plan: Box::new(Plan::MatchA(b, "edge".to_string(), c)), // })) // }); let peers = worker.peers(); let index = worker.index(); worker.dataflow::<u64, _, _>(|scope| { server .create_attribute(scope, "edge", AttributeConfig::tx_time(InputSemantics::Raw)) .unwrap(); server .test_single( scope, Rule { name: "triangles".to_string(), plan, }, ) .filter(move |_| inspect) .inspect(|x| println!("\tTriangle: {:?}", x)); server.advance_domain(None, 1).unwrap(); }); let mut index = index; let mut next_tx = 1; while index < graph.nodes() { server .transact( graph .edges(index) .iter() .map(|y| Datom(index as u64, "edge".to_string(), Eid(*y as u64), None, 1)) .collect(), 0, 0, ) .unwrap(); server.advance_domain(None, next_tx).unwrap(); next_tx += 1; index += peers; if (index / peers) % batching == 0 { worker.step_while(|| server.is_any_outdated()); println!("{},{}", index, timer.elapsed().as_millis()); timer = std::time::Instant::now(); } } }) .unwrap(); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IXsltProcessor(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXsltProcessor { type Vtable = IXsltProcessor_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7b64703f_550c_48c6_a90f_93a5b964518f); } #[repr(C)] #[doc(hidden)] pub struct IXsltProcessor_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Data_Xml_Dom")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputnode: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Data_Xml_Dom"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IXsltProcessor2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXsltProcessor2 { type Vtable = IXsltProcessor2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8da45c56_97a5_44cb_a8be_27d86280c70a); } #[repr(C)] #[doc(hidden)] pub struct IXsltProcessor2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Data_Xml_Dom")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, inputnode: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Data_Xml_Dom"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IXsltProcessorFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXsltProcessorFactory { type Vtable = IXsltProcessorFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x274146c0_9a51_4663_bf30_0ef742146f20); } #[repr(C)] #[doc(hidden)] pub struct IXsltProcessorFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Data_Xml_Dom")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, document: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Data_Xml_Dom"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XsltProcessor(pub ::windows::core::IInspectable); impl XsltProcessor { #[cfg(feature = "Data_Xml_Dom")] pub fn TransformToString<'a, Param0: ::windows::core::IntoParam<'a, super::Dom::IXmlNode>>(&self, inputnode: Param0) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), inputnode.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Data_Xml_Dom")] pub fn TransformToDocument<'a, Param0: ::windows::core::IntoParam<'a, super::Dom::IXmlNode>>(&self, inputnode: Param0) -> ::windows::core::Result<super::Dom::XmlDocument> { let this = &::windows::core::Interface::cast::<IXsltProcessor2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), inputnode.into_param().abi(), &mut result__).from_abi::<super::Dom::XmlDocument>(result__) } } #[cfg(feature = "Data_Xml_Dom")] pub fn CreateInstance<'a, Param0: ::windows::core::IntoParam<'a, super::Dom::XmlDocument>>(document: Param0) -> ::windows::core::Result<XsltProcessor> { Self::IXsltProcessorFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), document.into_param().abi(), &mut result__).from_abi::<XsltProcessor>(result__) }) } pub fn IXsltProcessorFactory<R, F: FnOnce(&IXsltProcessorFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<XsltProcessor, IXsltProcessorFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for XsltProcessor { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Data.Xml.Xsl.XsltProcessor;{7b64703f-550c-48c6-a90f-93a5b964518f})"); } unsafe impl ::windows::core::Interface for XsltProcessor { type Vtable = IXsltProcessor_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7b64703f_550c_48c6_a90f_93a5b964518f); } impl ::windows::core::RuntimeName for XsltProcessor { const NAME: &'static str = "Windows.Data.Xml.Xsl.XsltProcessor"; } impl ::core::convert::From<XsltProcessor> for ::windows::core::IUnknown { fn from(value: XsltProcessor) -> Self { value.0 .0 } } impl ::core::convert::From<&XsltProcessor> for ::windows::core::IUnknown { fn from(value: &XsltProcessor) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XsltProcessor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a XsltProcessor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XsltProcessor> for ::windows::core::IInspectable { fn from(value: XsltProcessor) -> Self { value.0 } } impl ::core::convert::From<&XsltProcessor> for ::windows::core::IInspectable { fn from(value: &XsltProcessor) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XsltProcessor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a XsltProcessor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XsltProcessor {} unsafe impl ::core::marker::Sync for XsltProcessor {}
use std::convert::TryInto; //use std::iter::FromIterator; fn main() { let fire = "fire"; println!("Name: {}", fire[0..2].to_string()); let fi_re = "fire"; let s = fi_re.get(0..2); println!("Name: {}", fi_re[0..2].to_string()); let name = "Jürgen"; //println!("Name: {}", name[0..2].to_string()); let smiley = "👌✊👏"; //println!("Name: {}", smiley[0..2].to_string()); let teil: String = name.chars().into_iter().take(2).collect(); println!("Name: {}", teil); let teil: String = name.chars().into_iter().skip(4).take(2).collect(); println!("Name: {}", teil); let teil: String = fi_re.chars().into_iter().take(2).collect(); println!("Name: {}", teil); let teil: String = smiley.chars().into_iter().take(2).collect(); println!("Name: {}", teil); print_lens(fire); print_lens(fi_re); print_lens(name); print_lens(smiley); fn print_lens(text: &str) { println!("Länge von {}, bytes: {}, chars: {}", text, text.len(), text.chars().count()); } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[cfg(feature = "Win32_Storage_Xps_Printing")] pub mod Printing; #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Graphics_Gdi")] pub fn AbortDoc(hdc: super::super::Graphics::Gdi::HDC) -> i32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn DeviceCapabilitiesA(pdevice: super::super::Foundation::PSTR, pport: super::super::Foundation::PSTR, fwcapability: DEVICE_CAPABILITIES, poutput: super::super::Foundation::PSTR, pdevmode: *const super::super::Graphics::Gdi::DEVMODEA) -> i32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn DeviceCapabilitiesW(pdevice: super::super::Foundation::PWSTR, pport: super::super::Foundation::PWSTR, fwcapability: DEVICE_CAPABILITIES, poutput: super::super::Foundation::PWSTR, pdevmode: *const super::super::Graphics::Gdi::DEVMODEW) -> i32; #[cfg(feature = "Win32_Graphics_Gdi")] pub fn EndDoc(hdc: super::super::Graphics::Gdi::HDC) -> i32; #[cfg(feature = "Win32_Graphics_Gdi")] pub fn EndPage(hdc: super::super::Graphics::Gdi::HDC) -> i32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn Escape(hdc: super::super::Graphics::Gdi::HDC, iescape: i32, cjin: i32, pvin: super::super::Foundation::PSTR, pvout: *mut ::core::ffi::c_void) -> i32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn ExtEscape(hdc: super::super::Graphics::Gdi::HDC, iescape: i32, cjinput: i32, lpindata: super::super::Foundation::PSTR, cjoutput: i32, lpoutdata: super::super::Foundation::PSTR) -> i32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn PrintWindow(hwnd: super::super::Foundation::HWND, hdcblt: super::super::Graphics::Gdi::HDC, nflags: PRINT_WINDOW_FLAGS) -> super::super::Foundation::BOOL; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn SetAbortProc(hdc: super::super::Graphics::Gdi::HDC, proc: ABORTPROC) -> i32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn StartDocA(hdc: super::super::Graphics::Gdi::HDC, lpdi: *const DOCINFOA) -> i32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub fn StartDocW(hdc: super::super::Graphics::Gdi::HDC, lpdi: *const DOCINFOW) -> i32; #[cfg(feature = "Win32_Graphics_Gdi")] pub fn StartPage(hdc: super::super::Graphics::Gdi::HDC) -> i32; } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))] pub type ABORTPROC = ::core::option::Option<unsafe extern "system" fn(param0: super::super::Graphics::Gdi::HDC, param1: i32) -> super::super::Foundation::BOOL>; pub type DEVICE_CAPABILITIES = u32; pub const DC_BINNAMES: DEVICE_CAPABILITIES = 12u32; pub const DC_BINS: DEVICE_CAPABILITIES = 6u32; pub const DC_COLLATE: DEVICE_CAPABILITIES = 22u32; pub const DC_COLORDEVICE: DEVICE_CAPABILITIES = 32u32; pub const DC_COPIES: DEVICE_CAPABILITIES = 18u32; pub const DC_DRIVER: DEVICE_CAPABILITIES = 11u32; pub const DC_DUPLEX: DEVICE_CAPABILITIES = 7u32; pub const DC_ENUMRESOLUTIONS: DEVICE_CAPABILITIES = 13u32; pub const DC_EXTRA: DEVICE_CAPABILITIES = 9u32; pub const DC_FIELDS: DEVICE_CAPABILITIES = 1u32; pub const DC_FILEDEPENDENCIES: DEVICE_CAPABILITIES = 14u32; pub const DC_MAXEXTENT: DEVICE_CAPABILITIES = 5u32; pub const DC_MEDIAREADY: DEVICE_CAPABILITIES = 29u32; pub const DC_MEDIATYPENAMES: DEVICE_CAPABILITIES = 34u32; pub const DC_MEDIATYPES: DEVICE_CAPABILITIES = 35u32; pub const DC_MINEXTENT: DEVICE_CAPABILITIES = 4u32; pub const DC_ORIENTATION: DEVICE_CAPABILITIES = 17u32; pub const DC_NUP: DEVICE_CAPABILITIES = 33u32; pub const DC_PAPERNAMES: DEVICE_CAPABILITIES = 16u32; pub const DC_PAPERS: DEVICE_CAPABILITIES = 2u32; pub const DC_PAPERSIZE: DEVICE_CAPABILITIES = 3u32; pub const DC_PERSONALITY: DEVICE_CAPABILITIES = 25u32; pub const DC_PRINTERMEM: DEVICE_CAPABILITIES = 28u32; pub const DC_PRINTRATE: DEVICE_CAPABILITIES = 26u32; pub const DC_PRINTRATEPPM: DEVICE_CAPABILITIES = 31u32; pub const DC_PRINTRATEUNIT: DEVICE_CAPABILITIES = 27u32; pub const DC_SIZE: DEVICE_CAPABILITIES = 8u32; pub const DC_STAPLE: DEVICE_CAPABILITIES = 30u32; pub const DC_TRUETYPE: DEVICE_CAPABILITIES = 15u32; pub const DC_VERSION: DEVICE_CAPABILITIES = 10u32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DOCINFOA { pub cbSize: i32, pub lpszDocName: super::super::Foundation::PSTR, pub lpszOutput: super::super::Foundation::PSTR, pub lpszDatatype: super::super::Foundation::PSTR, pub fwType: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DOCINFOA {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DOCINFOA { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DOCINFOW { pub cbSize: i32, pub lpszDocName: super::super::Foundation::PWSTR, pub lpszOutput: super::super::Foundation::PWSTR, pub lpszDatatype: super::super::Foundation::PWSTR, pub fwType: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DOCINFOW {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DOCINFOW { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DRAWPATRECT { pub ptPosition: super::super::Foundation::POINT, pub ptSize: super::super::Foundation::POINT, pub wStyle: u16, pub wPattern: u16, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DRAWPATRECT {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DRAWPATRECT { fn clone(&self) -> Self { *self } } pub type HPTPROVIDER = isize; pub type IXpsDocumentPackageTarget = *mut ::core::ffi::c_void; pub type IXpsDocumentPackageTarget3D = *mut ::core::ffi::c_void; pub type IXpsOMBrush = *mut ::core::ffi::c_void; pub type IXpsOMCanvas = *mut ::core::ffi::c_void; pub type IXpsOMColorProfileResource = *mut ::core::ffi::c_void; pub type IXpsOMColorProfileResourceCollection = *mut ::core::ffi::c_void; pub type IXpsOMCoreProperties = *mut ::core::ffi::c_void; pub type IXpsOMDashCollection = *mut ::core::ffi::c_void; pub type IXpsOMDictionary = *mut ::core::ffi::c_void; pub type IXpsOMDocument = *mut ::core::ffi::c_void; pub type IXpsOMDocumentCollection = *mut ::core::ffi::c_void; pub type IXpsOMDocumentSequence = *mut ::core::ffi::c_void; pub type IXpsOMDocumentStructureResource = *mut ::core::ffi::c_void; pub type IXpsOMFontResource = *mut ::core::ffi::c_void; pub type IXpsOMFontResourceCollection = *mut ::core::ffi::c_void; pub type IXpsOMGeometry = *mut ::core::ffi::c_void; pub type IXpsOMGeometryFigure = *mut ::core::ffi::c_void; pub type IXpsOMGeometryFigureCollection = *mut ::core::ffi::c_void; pub type IXpsOMGlyphs = *mut ::core::ffi::c_void; pub type IXpsOMGlyphsEditor = *mut ::core::ffi::c_void; pub type IXpsOMGradientBrush = *mut ::core::ffi::c_void; pub type IXpsOMGradientStop = *mut ::core::ffi::c_void; pub type IXpsOMGradientStopCollection = *mut ::core::ffi::c_void; pub type IXpsOMImageBrush = *mut ::core::ffi::c_void; pub type IXpsOMImageResource = *mut ::core::ffi::c_void; pub type IXpsOMImageResourceCollection = *mut ::core::ffi::c_void; pub type IXpsOMLinearGradientBrush = *mut ::core::ffi::c_void; pub type IXpsOMMatrixTransform = *mut ::core::ffi::c_void; pub type IXpsOMNameCollection = *mut ::core::ffi::c_void; pub type IXpsOMObjectFactory = *mut ::core::ffi::c_void; pub type IXpsOMObjectFactory1 = *mut ::core::ffi::c_void; pub type IXpsOMPackage = *mut ::core::ffi::c_void; pub type IXpsOMPackage1 = *mut ::core::ffi::c_void; pub type IXpsOMPackageTarget = *mut ::core::ffi::c_void; pub type IXpsOMPackageWriter = *mut ::core::ffi::c_void; pub type IXpsOMPackageWriter3D = *mut ::core::ffi::c_void; pub type IXpsOMPage = *mut ::core::ffi::c_void; pub type IXpsOMPage1 = *mut ::core::ffi::c_void; pub type IXpsOMPageReference = *mut ::core::ffi::c_void; pub type IXpsOMPageReferenceCollection = *mut ::core::ffi::c_void; pub type IXpsOMPart = *mut ::core::ffi::c_void; pub type IXpsOMPartResources = *mut ::core::ffi::c_void; pub type IXpsOMPartUriCollection = *mut ::core::ffi::c_void; pub type IXpsOMPath = *mut ::core::ffi::c_void; pub type IXpsOMPrintTicketResource = *mut ::core::ffi::c_void; pub type IXpsOMRadialGradientBrush = *mut ::core::ffi::c_void; pub type IXpsOMRemoteDictionaryResource = *mut ::core::ffi::c_void; pub type IXpsOMRemoteDictionaryResource1 = *mut ::core::ffi::c_void; pub type IXpsOMRemoteDictionaryResourceCollection = *mut ::core::ffi::c_void; pub type IXpsOMResource = *mut ::core::ffi::c_void; pub type IXpsOMShareable = *mut ::core::ffi::c_void; pub type IXpsOMSignatureBlockResource = *mut ::core::ffi::c_void; pub type IXpsOMSignatureBlockResourceCollection = *mut ::core::ffi::c_void; pub type IXpsOMSolidColorBrush = *mut ::core::ffi::c_void; pub type IXpsOMStoryFragmentsResource = *mut ::core::ffi::c_void; pub type IXpsOMThumbnailGenerator = *mut ::core::ffi::c_void; pub type IXpsOMTileBrush = *mut ::core::ffi::c_void; pub type IXpsOMVisual = *mut ::core::ffi::c_void; pub type IXpsOMVisualBrush = *mut ::core::ffi::c_void; pub type IXpsOMVisualCollection = *mut ::core::ffi::c_void; pub type IXpsSignature = *mut ::core::ffi::c_void; pub type IXpsSignatureBlock = *mut ::core::ffi::c_void; pub type IXpsSignatureBlockCollection = *mut ::core::ffi::c_void; pub type IXpsSignatureCollection = *mut ::core::ffi::c_void; pub type IXpsSignatureManager = *mut ::core::ffi::c_void; pub type IXpsSignatureRequest = *mut ::core::ffi::c_void; pub type IXpsSignatureRequestCollection = *mut ::core::ffi::c_void; pub type IXpsSigningOptions = *mut ::core::ffi::c_void; pub type PRINT_WINDOW_FLAGS = u32; pub const PW_CLIENTONLY: PRINT_WINDOW_FLAGS = 1u32; #[repr(C)] pub struct PSFEATURE_CUSTPAPER { pub lOrientation: i32, pub lWidth: i32, pub lHeight: i32, pub lWidthOffset: i32, pub lHeightOffset: i32, } impl ::core::marker::Copy for PSFEATURE_CUSTPAPER {} impl ::core::clone::Clone for PSFEATURE_CUSTPAPER { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct PSFEATURE_OUTPUT { pub bPageIndependent: super::super::Foundation::BOOL, pub bSetPageDevice: super::super::Foundation::BOOL, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for PSFEATURE_OUTPUT {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for PSFEATURE_OUTPUT { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct PSINJECTDATA { pub DataBytes: u32, pub InjectionPoint: PSINJECT_POINT, pub PageNumber: u16, } impl ::core::marker::Copy for PSINJECTDATA {} impl ::core::clone::Clone for PSINJECTDATA { fn clone(&self) -> Self { *self } } pub type PSINJECT_POINT = u16; pub const PSINJECT_BEGINSTREAM: PSINJECT_POINT = 1u16; pub const PSINJECT_PSADOBE: PSINJECT_POINT = 2u16; pub const PSINJECT_PAGESATEND: PSINJECT_POINT = 3u16; pub const PSINJECT_PAGES: PSINJECT_POINT = 4u16; pub const PSINJECT_DOCNEEDEDRES: PSINJECT_POINT = 5u16; pub const PSINJECT_DOCSUPPLIEDRES: PSINJECT_POINT = 6u16; pub const PSINJECT_PAGEORDER: PSINJECT_POINT = 7u16; pub const PSINJECT_ORIENTATION: PSINJECT_POINT = 8u16; pub const PSINJECT_BOUNDINGBOX: PSINJECT_POINT = 9u16; pub const PSINJECT_DOCUMENTPROCESSCOLORS: PSINJECT_POINT = 10u16; pub const PSINJECT_COMMENTS: PSINJECT_POINT = 11u16; pub const PSINJECT_BEGINDEFAULTS: PSINJECT_POINT = 12u16; pub const PSINJECT_ENDDEFAULTS: PSINJECT_POINT = 13u16; pub const PSINJECT_BEGINPROLOG: PSINJECT_POINT = 14u16; pub const PSINJECT_ENDPROLOG: PSINJECT_POINT = 15u16; pub const PSINJECT_BEGINSETUP: PSINJECT_POINT = 16u16; pub const PSINJECT_ENDSETUP: PSINJECT_POINT = 17u16; pub const PSINJECT_TRAILER: PSINJECT_POINT = 18u16; pub const PSINJECT_EOF: PSINJECT_POINT = 19u16; pub const PSINJECT_ENDSTREAM: PSINJECT_POINT = 20u16; pub const PSINJECT_DOCUMENTPROCESSCOLORSATEND: PSINJECT_POINT = 21u16; pub const PSINJECT_PAGENUMBER: PSINJECT_POINT = 100u16; pub const PSINJECT_BEGINPAGESETUP: PSINJECT_POINT = 101u16; pub const PSINJECT_ENDPAGESETUP: PSINJECT_POINT = 102u16; pub const PSINJECT_PAGETRAILER: PSINJECT_POINT = 103u16; pub const PSINJECT_PLATECOLOR: PSINJECT_POINT = 104u16; pub const PSINJECT_SHOWPAGE: PSINJECT_POINT = 105u16; pub const PSINJECT_PAGEBBOX: PSINJECT_POINT = 106u16; pub const PSINJECT_ENDPAGECOMMENTS: PSINJECT_POINT = 107u16; pub const PSINJECT_VMSAVE: PSINJECT_POINT = 200u16; pub const PSINJECT_VMRESTORE: PSINJECT_POINT = 201u16; #[repr(C)] pub struct XPS_COLOR { pub colorType: XPS_COLOR_TYPE, pub value: XPS_COLOR_0, } impl ::core::marker::Copy for XPS_COLOR {} impl ::core::clone::Clone for XPS_COLOR { fn clone(&self) -> Self { *self } } #[repr(C)] pub union XPS_COLOR_0 { pub sRGB: XPS_COLOR_0_1, pub scRGB: XPS_COLOR_0_2, pub context: XPS_COLOR_0_0, } impl ::core::marker::Copy for XPS_COLOR_0 {} impl ::core::clone::Clone for XPS_COLOR_0 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct XPS_COLOR_0_0 { pub channelCount: u8, pub channels: [f32; 9], } impl ::core::marker::Copy for XPS_COLOR_0_0 {} impl ::core::clone::Clone for XPS_COLOR_0_0 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct XPS_COLOR_0_1 { pub alpha: u8, pub red: u8, pub green: u8, pub blue: u8, } impl ::core::marker::Copy for XPS_COLOR_0_1 {} impl ::core::clone::Clone for XPS_COLOR_0_1 { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct XPS_COLOR_0_2 { pub alpha: f32, pub red: f32, pub green: f32, pub blue: f32, } impl ::core::marker::Copy for XPS_COLOR_0_2 {} impl ::core::clone::Clone for XPS_COLOR_0_2 { fn clone(&self) -> Self { *self } } pub type XPS_COLOR_INTERPOLATION = i32; pub const XPS_COLOR_INTERPOLATION_SCRGBLINEAR: XPS_COLOR_INTERPOLATION = 1i32; pub const XPS_COLOR_INTERPOLATION_SRGBLINEAR: XPS_COLOR_INTERPOLATION = 2i32; pub type XPS_COLOR_TYPE = i32; pub const XPS_COLOR_TYPE_SRGB: XPS_COLOR_TYPE = 1i32; pub const XPS_COLOR_TYPE_SCRGB: XPS_COLOR_TYPE = 2i32; pub const XPS_COLOR_TYPE_CONTEXT: XPS_COLOR_TYPE = 3i32; #[repr(C)] pub struct XPS_DASH { pub length: f32, pub gap: f32, } impl ::core::marker::Copy for XPS_DASH {} impl ::core::clone::Clone for XPS_DASH { fn clone(&self) -> Self { *self } } pub type XPS_DASH_CAP = i32; pub const XPS_DASH_CAP_FLAT: XPS_DASH_CAP = 1i32; pub const XPS_DASH_CAP_ROUND: XPS_DASH_CAP = 2i32; pub const XPS_DASH_CAP_SQUARE: XPS_DASH_CAP = 3i32; pub const XPS_DASH_CAP_TRIANGLE: XPS_DASH_CAP = 4i32; pub type XPS_DOCUMENT_TYPE = i32; pub const XPS_DOCUMENT_TYPE_UNSPECIFIED: XPS_DOCUMENT_TYPE = 1i32; pub const XPS_DOCUMENT_TYPE_XPS: XPS_DOCUMENT_TYPE = 2i32; pub const XPS_DOCUMENT_TYPE_OPENXPS: XPS_DOCUMENT_TYPE = 3i32; pub const XPS_E_ABSOLUTE_REFERENCE: ::windows_sys::core::HRESULT = -2142108159i32; pub const XPS_E_ALREADY_OWNED: ::windows_sys::core::HRESULT = -2142108413i32; pub const XPS_E_BLEED_BOX_PAGE_DIMENSIONS_NOT_IN_SYNC: ::windows_sys::core::HRESULT = -2142108407i32; pub const XPS_E_BOTH_PATHFIGURE_AND_ABBR_SYNTAX_PRESENT: ::windows_sys::core::HRESULT = -2142108409i32; pub const XPS_E_BOTH_RESOURCE_AND_SOURCEATTR_PRESENT: ::windows_sys::core::HRESULT = -2142108408i32; pub const XPS_E_CARET_OUTSIDE_STRING: ::windows_sys::core::HRESULT = -2142108923i32; pub const XPS_E_CARET_OUT_OF_ORDER: ::windows_sys::core::HRESULT = -2142108922i32; pub const XPS_E_COLOR_COMPONENT_OUT_OF_RANGE: ::windows_sys::core::HRESULT = -2142108410i32; pub const XPS_E_DICTIONARY_ITEM_NAMED: ::windows_sys::core::HRESULT = -2142108671i32; pub const XPS_E_DUPLICATE_NAMES: ::windows_sys::core::HRESULT = -2142109175i32; pub const XPS_E_DUPLICATE_RESOURCE_KEYS: ::windows_sys::core::HRESULT = -2142109184i32; pub const XPS_E_INDEX_OUT_OF_RANGE: ::windows_sys::core::HRESULT = -2142108416i32; pub const XPS_E_INVALID_BLEED_BOX: ::windows_sys::core::HRESULT = -2142109692i32; pub const XPS_E_INVALID_CONTENT_BOX: ::windows_sys::core::HRESULT = -2142109685i32; pub const XPS_E_INVALID_CONTENT_TYPE: ::windows_sys::core::HRESULT = -2142109682i32; pub const XPS_E_INVALID_FLOAT: ::windows_sys::core::HRESULT = -2142109689i32; pub const XPS_E_INVALID_FONT_URI: ::windows_sys::core::HRESULT = -2142109686i32; pub const XPS_E_INVALID_LANGUAGE: ::windows_sys::core::HRESULT = -2142109696i32; pub const XPS_E_INVALID_LOOKUP_TYPE: ::windows_sys::core::HRESULT = -2142109690i32; pub const XPS_E_INVALID_MARKUP: ::windows_sys::core::HRESULT = -2142109684i32; pub const XPS_E_INVALID_NAME: ::windows_sys::core::HRESULT = -2142109695i32; pub const XPS_E_INVALID_NUMBER_OF_COLOR_CHANNELS: ::windows_sys::core::HRESULT = -2142108158i32; pub const XPS_E_INVALID_NUMBER_OF_POINTS_IN_CURVE_SEGMENTS: ::windows_sys::core::HRESULT = -2142108160i32; pub const XPS_E_INVALID_OBFUSCATED_FONT_URI: ::windows_sys::core::HRESULT = -2142109681i32; pub const XPS_E_INVALID_PAGE_SIZE: ::windows_sys::core::HRESULT = -2142109693i32; pub const XPS_E_INVALID_RESOURCE_KEY: ::windows_sys::core::HRESULT = -2142109694i32; pub const XPS_E_INVALID_SIGNATUREBLOCK_MARKUP: ::windows_sys::core::HRESULT = -2142108789i32; pub const XPS_E_INVALID_THUMBNAIL_IMAGE_TYPE: ::windows_sys::core::HRESULT = -2142109691i32; pub const XPS_E_INVALID_XML_ENCODING: ::windows_sys::core::HRESULT = -2142109683i32; pub const XPS_E_MAPPING_OUTSIDE_INDICES: ::windows_sys::core::HRESULT = -2142108924i32; pub const XPS_E_MAPPING_OUTSIDE_STRING: ::windows_sys::core::HRESULT = -2142108925i32; pub const XPS_E_MAPPING_OUT_OF_ORDER: ::windows_sys::core::HRESULT = -2142108926i32; pub const XPS_E_MARKUP_COMPATIBILITY_ELEMENTS: ::windows_sys::core::HRESULT = -2142108791i32; pub const XPS_E_MISSING_COLORPROFILE: ::windows_sys::core::HRESULT = -2142109436i32; pub const XPS_E_MISSING_DISCARDCONTROL: ::windows_sys::core::HRESULT = -2142109422i32; pub const XPS_E_MISSING_DOCUMENT: ::windows_sys::core::HRESULT = -2142109431i32; pub const XPS_E_MISSING_DOCUMENTSEQUENCE_RELATIONSHIP: ::windows_sys::core::HRESULT = -2142109432i32; pub const XPS_E_MISSING_FONTURI: ::windows_sys::core::HRESULT = -2142109433i32; pub const XPS_E_MISSING_GLYPHS: ::windows_sys::core::HRESULT = -2142109438i32; pub const XPS_E_MISSING_IMAGE_IN_IMAGEBRUSH: ::windows_sys::core::HRESULT = -2142109426i32; pub const XPS_E_MISSING_LOOKUP: ::windows_sys::core::HRESULT = -2142109439i32; pub const XPS_E_MISSING_NAME: ::windows_sys::core::HRESULT = -2142109440i32; pub const XPS_E_MISSING_PAGE_IN_DOCUMENT: ::windows_sys::core::HRESULT = -2142109428i32; pub const XPS_E_MISSING_PAGE_IN_PAGEREFERENCE: ::windows_sys::core::HRESULT = -2142109427i32; pub const XPS_E_MISSING_PART_REFERENCE: ::windows_sys::core::HRESULT = -2142109424i32; pub const XPS_E_MISSING_PART_STREAM: ::windows_sys::core::HRESULT = -2142109421i32; pub const XPS_E_MISSING_REFERRED_DOCUMENT: ::windows_sys::core::HRESULT = -2142109430i32; pub const XPS_E_MISSING_REFERRED_PAGE: ::windows_sys::core::HRESULT = -2142109429i32; pub const XPS_E_MISSING_RELATIONSHIP_TARGET: ::windows_sys::core::HRESULT = -2142109435i32; pub const XPS_E_MISSING_RESOURCE_KEY: ::windows_sys::core::HRESULT = -2142109425i32; pub const XPS_E_MISSING_RESOURCE_RELATIONSHIP: ::windows_sys::core::HRESULT = -2142109434i32; pub const XPS_E_MISSING_RESTRICTED_FONT_RELATIONSHIP: ::windows_sys::core::HRESULT = -2142109423i32; pub const XPS_E_MISSING_SEGMENT_DATA: ::windows_sys::core::HRESULT = -2142109437i32; pub const XPS_E_MULTIPLE_DOCUMENTSEQUENCE_RELATIONSHIPS: ::windows_sys::core::HRESULT = -2142109182i32; pub const XPS_E_MULTIPLE_PRINTTICKETS_ON_DOCUMENT: ::windows_sys::core::HRESULT = -2142109178i32; pub const XPS_E_MULTIPLE_PRINTTICKETS_ON_DOCUMENTSEQUENCE: ::windows_sys::core::HRESULT = -2142109177i32; pub const XPS_E_MULTIPLE_PRINTTICKETS_ON_PAGE: ::windows_sys::core::HRESULT = -2142109179i32; pub const XPS_E_MULTIPLE_REFERENCES_TO_PART: ::windows_sys::core::HRESULT = -2142109176i32; pub const XPS_E_MULTIPLE_RESOURCES: ::windows_sys::core::HRESULT = -2142109183i32; pub const XPS_E_MULTIPLE_THUMBNAILS_ON_PACKAGE: ::windows_sys::core::HRESULT = -2142109180i32; pub const XPS_E_MULTIPLE_THUMBNAILS_ON_PAGE: ::windows_sys::core::HRESULT = -2142109181i32; pub const XPS_E_NEGATIVE_FLOAT: ::windows_sys::core::HRESULT = -2142108918i32; pub const XPS_E_NESTED_REMOTE_DICTIONARY: ::windows_sys::core::HRESULT = -2142108670i32; pub const XPS_E_NOT_ENOUGH_GRADIENT_STOPS: ::windows_sys::core::HRESULT = -2142108405i32; pub const XPS_E_NO_CUSTOM_OBJECTS: ::windows_sys::core::HRESULT = -2142108414i32; pub const XPS_E_OBJECT_DETACHED: ::windows_sys::core::HRESULT = -2142108790i32; pub const XPS_E_ODD_BIDILEVEL: ::windows_sys::core::HRESULT = -2142108921i32; pub const XPS_E_ONE_TO_ONE_MAPPING_EXPECTED: ::windows_sys::core::HRESULT = -2142108920i32; pub const XPS_E_PACKAGE_ALREADY_OPENED: ::windows_sys::core::HRESULT = -2142108793i32; pub const XPS_E_PACKAGE_NOT_OPENED: ::windows_sys::core::HRESULT = -2142108794i32; pub const XPS_E_PACKAGE_WRITER_NOT_CLOSED: ::windows_sys::core::HRESULT = -2142108404i32; pub const XPS_E_RELATIONSHIP_EXTERNAL: ::windows_sys::core::HRESULT = -2142108406i32; pub const XPS_E_RESOURCE_NOT_OWNED: ::windows_sys::core::HRESULT = -2142108412i32; pub const XPS_E_RESTRICTED_FONT_NOT_OBFUSCATED: ::windows_sys::core::HRESULT = -2142108919i32; pub const XPS_E_SIGNATUREID_DUP: ::windows_sys::core::HRESULT = -2142108792i32; pub const XPS_E_SIGREQUESTID_DUP: ::windows_sys::core::HRESULT = -2142108795i32; pub const XPS_E_STRING_TOO_LONG: ::windows_sys::core::HRESULT = -2142108928i32; pub const XPS_E_TOO_MANY_INDICES: ::windows_sys::core::HRESULT = -2142108927i32; pub const XPS_E_UNAVAILABLE_PACKAGE: ::windows_sys::core::HRESULT = -2142109420i32; pub const XPS_E_UNEXPECTED_COLORPROFILE: ::windows_sys::core::HRESULT = -2142108411i32; pub const XPS_E_UNEXPECTED_CONTENT_TYPE: ::windows_sys::core::HRESULT = -2142109688i32; pub const XPS_E_UNEXPECTED_RELATIONSHIP_TYPE: ::windows_sys::core::HRESULT = -2142109680i32; pub const XPS_E_UNEXPECTED_RESTRICTED_FONT_RELATIONSHIP: ::windows_sys::core::HRESULT = -2142109679i32; pub const XPS_E_VISUAL_CIRCULAR_REF: ::windows_sys::core::HRESULT = -2142108415i32; pub const XPS_E_XKEY_ATTR_PRESENT_OUTSIDE_RES_DICT: ::windows_sys::core::HRESULT = -2142108672i32; pub type XPS_FILL_RULE = i32; pub const XPS_FILL_RULE_EVENODD: XPS_FILL_RULE = 1i32; pub const XPS_FILL_RULE_NONZERO: XPS_FILL_RULE = 2i32; pub type XPS_FONT_EMBEDDING = i32; pub const XPS_FONT_EMBEDDING_NORMAL: XPS_FONT_EMBEDDING = 1i32; pub const XPS_FONT_EMBEDDING_OBFUSCATED: XPS_FONT_EMBEDDING = 2i32; pub const XPS_FONT_EMBEDDING_RESTRICTED: XPS_FONT_EMBEDDING = 3i32; pub const XPS_FONT_EMBEDDING_RESTRICTED_UNOBFUSCATED: XPS_FONT_EMBEDDING = 4i32; #[repr(C)] pub struct XPS_GLYPH_INDEX { pub index: i32, pub advanceWidth: f32, pub horizontalOffset: f32, pub verticalOffset: f32, } impl ::core::marker::Copy for XPS_GLYPH_INDEX {} impl ::core::clone::Clone for XPS_GLYPH_INDEX { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct XPS_GLYPH_MAPPING { pub unicodeStringStart: u32, pub unicodeStringLength: u16, pub glyphIndicesStart: u32, pub glyphIndicesLength: u16, } impl ::core::marker::Copy for XPS_GLYPH_MAPPING {} impl ::core::clone::Clone for XPS_GLYPH_MAPPING { fn clone(&self) -> Self { *self } } pub type XPS_IMAGE_TYPE = i32; pub const XPS_IMAGE_TYPE_JPEG: XPS_IMAGE_TYPE = 1i32; pub const XPS_IMAGE_TYPE_PNG: XPS_IMAGE_TYPE = 2i32; pub const XPS_IMAGE_TYPE_TIFF: XPS_IMAGE_TYPE = 3i32; pub const XPS_IMAGE_TYPE_WDP: XPS_IMAGE_TYPE = 4i32; pub const XPS_IMAGE_TYPE_JXR: XPS_IMAGE_TYPE = 5i32; pub type XPS_INTERLEAVING = i32; pub const XPS_INTERLEAVING_OFF: XPS_INTERLEAVING = 1i32; pub const XPS_INTERLEAVING_ON: XPS_INTERLEAVING = 2i32; pub type XPS_LINE_CAP = i32; pub const XPS_LINE_CAP_FLAT: XPS_LINE_CAP = 1i32; pub const XPS_LINE_CAP_ROUND: XPS_LINE_CAP = 2i32; pub const XPS_LINE_CAP_SQUARE: XPS_LINE_CAP = 3i32; pub const XPS_LINE_CAP_TRIANGLE: XPS_LINE_CAP = 4i32; pub type XPS_LINE_JOIN = i32; pub const XPS_LINE_JOIN_MITER: XPS_LINE_JOIN = 1i32; pub const XPS_LINE_JOIN_BEVEL: XPS_LINE_JOIN = 2i32; pub const XPS_LINE_JOIN_ROUND: XPS_LINE_JOIN = 3i32; #[repr(C)] pub struct XPS_MATRIX { pub m11: f32, pub m12: f32, pub m21: f32, pub m22: f32, pub m31: f32, pub m32: f32, } impl ::core::marker::Copy for XPS_MATRIX {} impl ::core::clone::Clone for XPS_MATRIX { fn clone(&self) -> Self { *self } } pub type XPS_OBJECT_TYPE = i32; pub const XPS_OBJECT_TYPE_CANVAS: XPS_OBJECT_TYPE = 1i32; pub const XPS_OBJECT_TYPE_GLYPHS: XPS_OBJECT_TYPE = 2i32; pub const XPS_OBJECT_TYPE_PATH: XPS_OBJECT_TYPE = 3i32; pub const XPS_OBJECT_TYPE_MATRIX_TRANSFORM: XPS_OBJECT_TYPE = 4i32; pub const XPS_OBJECT_TYPE_GEOMETRY: XPS_OBJECT_TYPE = 5i32; pub const XPS_OBJECT_TYPE_SOLID_COLOR_BRUSH: XPS_OBJECT_TYPE = 6i32; pub const XPS_OBJECT_TYPE_IMAGE_BRUSH: XPS_OBJECT_TYPE = 7i32; pub const XPS_OBJECT_TYPE_LINEAR_GRADIENT_BRUSH: XPS_OBJECT_TYPE = 8i32; pub const XPS_OBJECT_TYPE_RADIAL_GRADIENT_BRUSH: XPS_OBJECT_TYPE = 9i32; pub const XPS_OBJECT_TYPE_VISUAL_BRUSH: XPS_OBJECT_TYPE = 10i32; #[repr(C)] pub struct XPS_POINT { pub x: f32, pub y: f32, } impl ::core::marker::Copy for XPS_POINT {} impl ::core::clone::Clone for XPS_POINT { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct XPS_RECT { pub x: f32, pub y: f32, pub width: f32, pub height: f32, } impl ::core::marker::Copy for XPS_RECT {} impl ::core::clone::Clone for XPS_RECT { fn clone(&self) -> Self { *self } } pub type XPS_SEGMENT_STROKE_PATTERN = i32; pub const XPS_SEGMENT_STROKE_PATTERN_ALL: XPS_SEGMENT_STROKE_PATTERN = 1i32; pub const XPS_SEGMENT_STROKE_PATTERN_NONE: XPS_SEGMENT_STROKE_PATTERN = 2i32; pub const XPS_SEGMENT_STROKE_PATTERN_MIXED: XPS_SEGMENT_STROKE_PATTERN = 3i32; pub type XPS_SEGMENT_TYPE = i32; pub const XPS_SEGMENT_TYPE_ARC_LARGE_CLOCKWISE: XPS_SEGMENT_TYPE = 1i32; pub const XPS_SEGMENT_TYPE_ARC_LARGE_COUNTERCLOCKWISE: XPS_SEGMENT_TYPE = 2i32; pub const XPS_SEGMENT_TYPE_ARC_SMALL_CLOCKWISE: XPS_SEGMENT_TYPE = 3i32; pub const XPS_SEGMENT_TYPE_ARC_SMALL_COUNTERCLOCKWISE: XPS_SEGMENT_TYPE = 4i32; pub const XPS_SEGMENT_TYPE_BEZIER: XPS_SEGMENT_TYPE = 5i32; pub const XPS_SEGMENT_TYPE_LINE: XPS_SEGMENT_TYPE = 6i32; pub const XPS_SEGMENT_TYPE_QUADRATIC_BEZIER: XPS_SEGMENT_TYPE = 7i32; pub type XPS_SIGNATURE_STATUS = i32; pub const XPS_SIGNATURE_STATUS_INCOMPLIANT: XPS_SIGNATURE_STATUS = 1i32; pub const XPS_SIGNATURE_STATUS_INCOMPLETE: XPS_SIGNATURE_STATUS = 2i32; pub const XPS_SIGNATURE_STATUS_BROKEN: XPS_SIGNATURE_STATUS = 3i32; pub const XPS_SIGNATURE_STATUS_QUESTIONABLE: XPS_SIGNATURE_STATUS = 4i32; pub const XPS_SIGNATURE_STATUS_VALID: XPS_SIGNATURE_STATUS = 5i32; pub type XPS_SIGN_FLAGS = i32; pub const XPS_SIGN_FLAGS_NONE: XPS_SIGN_FLAGS = 0i32; pub const XPS_SIGN_FLAGS_IGNORE_MARKUP_COMPATIBILITY: XPS_SIGN_FLAGS = 1i32; pub type XPS_SIGN_POLICY = i32; pub const XPS_SIGN_POLICY_NONE: XPS_SIGN_POLICY = 0i32; pub const XPS_SIGN_POLICY_CORE_PROPERTIES: XPS_SIGN_POLICY = 1i32; pub const XPS_SIGN_POLICY_SIGNATURE_RELATIONSHIPS: XPS_SIGN_POLICY = 2i32; pub const XPS_SIGN_POLICY_PRINT_TICKET: XPS_SIGN_POLICY = 4i32; pub const XPS_SIGN_POLICY_DISCARD_CONTROL: XPS_SIGN_POLICY = 8i32; pub const XPS_SIGN_POLICY_ALL: XPS_SIGN_POLICY = 15i32; #[repr(C)] pub struct XPS_SIZE { pub width: f32, pub height: f32, } impl ::core::marker::Copy for XPS_SIZE {} impl ::core::clone::Clone for XPS_SIZE { fn clone(&self) -> Self { *self } } pub type XPS_SPREAD_METHOD = i32; pub const XPS_SPREAD_METHOD_PAD: XPS_SPREAD_METHOD = 1i32; pub const XPS_SPREAD_METHOD_REFLECT: XPS_SPREAD_METHOD = 2i32; pub const XPS_SPREAD_METHOD_REPEAT: XPS_SPREAD_METHOD = 3i32; pub type XPS_STYLE_SIMULATION = i32; pub const XPS_STYLE_SIMULATION_NONE: XPS_STYLE_SIMULATION = 1i32; pub const XPS_STYLE_SIMULATION_ITALIC: XPS_STYLE_SIMULATION = 2i32; pub const XPS_STYLE_SIMULATION_BOLD: XPS_STYLE_SIMULATION = 3i32; pub const XPS_STYLE_SIMULATION_BOLDITALIC: XPS_STYLE_SIMULATION = 4i32; pub type XPS_THUMBNAIL_SIZE = i32; pub const XPS_THUMBNAIL_SIZE_VERYSMALL: XPS_THUMBNAIL_SIZE = 1i32; pub const XPS_THUMBNAIL_SIZE_SMALL: XPS_THUMBNAIL_SIZE = 2i32; pub const XPS_THUMBNAIL_SIZE_MEDIUM: XPS_THUMBNAIL_SIZE = 3i32; pub const XPS_THUMBNAIL_SIZE_LARGE: XPS_THUMBNAIL_SIZE = 4i32; pub type XPS_TILE_MODE = i32; pub const XPS_TILE_MODE_NONE: XPS_TILE_MODE = 1i32; pub const XPS_TILE_MODE_TILE: XPS_TILE_MODE = 2i32; pub const XPS_TILE_MODE_FLIPX: XPS_TILE_MODE = 3i32; pub const XPS_TILE_MODE_FLIPY: XPS_TILE_MODE = 4i32; pub const XPS_TILE_MODE_FLIPXY: XPS_TILE_MODE = 5i32; pub const XpsOMObjectFactory: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3916747373, data2: 15771, data3: 19783, data4: [136, 204, 56, 114, 242, 220, 53, 133], }; pub const XpsOMThumbnailGenerator: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2118788066, data2: 47465, data3: 18273, data4: [190, 53, 26, 140, 237, 88, 227, 35] }; pub const XpsSignatureManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2965648160, data2: 8981, data3: 17570, data4: [183, 10, 9, 67, 161, 64, 168, 238] };
use ring::{aead, digest, pbkdf2}; use crate::error::{ErrorKind, Result}; use crate::types::GrinboxAddress; use crate::utils::from_hex; use crate::utils::secp::{PublicKey, Secp256k1, SecretKey}; #[derive(Debug, Serialize, Deserialize)] pub struct GrinboxMessage { #[serde(default)] pub destination: Option<GrinboxAddress>, encrypted_message: String, salt: String, nonce: String, } impl GrinboxMessage { pub fn key(&self, sender_public_key: &PublicKey, secret_key: &SecretKey) -> Result<[u8; 32]> { let salt = from_hex(self.salt.clone()).map_err(|_| ErrorKind::Decryption)?; let secp = Secp256k1::new(); let mut common_secret = sender_public_key.clone(); common_secret .mul_assign(&secp, secret_key) .map_err(|_| ErrorKind::Decryption)?; let common_secret_ser = common_secret.serialize_vec(&secp, true); let common_secret_slice = &common_secret_ser[1..33]; let mut key = [0; 32]; pbkdf2::derive(&digest::SHA512, 10000, &salt, common_secret_slice, &mut key); Ok(key) } pub fn decrypt_with_key(&self, key: &[u8; 32]) -> Result<String> { let mut encrypted_message = from_hex(self.encrypted_message.clone()).map_err(|_| ErrorKind::Decryption)?; let nonce = from_hex(self.nonce.clone()).map_err(|_| ErrorKind::Decryption)?; let opening_key = aead::OpeningKey::new(&aead::CHACHA20_POLY1305, key) .map_err(|_| ErrorKind::Decryption)?; let decrypted_data = aead::open_in_place(&opening_key, &nonce, &[], 0, &mut encrypted_message) .map_err(|_| ErrorKind::Decryption)?; String::from_utf8(decrypted_data.to_vec()).map_err(|_| ErrorKind::Decryption.into()) } }
use solana_program::{ account_info::{next_account_info, AccountInfo}, entrypoint::ProgramResult, program_error::ProgramError, msg, pubkey::Pubkey, program_pack::{Pack, IsInitialized}, sysvar::{rent::Rent, Sysvar}, program::invoke }; use crate::{instruction::StakingInstruction, error::StakingError, state::Staking}; use spl_token::state::Account as TokenAccount; pub struct Processor; impl Processor { pub fn process(program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8]) -> ProgramResult { let instruction = StakingInstruction::unpack(instruction_data)?; match instruction { StakingInstruction::DepositToVault { vesting_period, amount_to_deposit} => { msg!("Instruction: Deposit to Vault"); Self::process_deposit(accounts, vesting_period, amount_to_deposit, program_id) }, StakingInstruction::MintxTokA {amount_to_mint} => { msg!("Instruction: MintxTokA"); Self::process_mint(accounts, amount_to_mint, program_id) }, StakingInstruction::DepositxTokA {amount} => { msg!("Instruction: DepositxTokA"); Self::process_mint(accounts, amount, program_id) }, StakingInstruction::WithdrawFromVault {amount} => { msg!("Instruction: WithdrawFromVault"); Self::process_mint(accounts, amount, program_id) }, StakingInstruction::BurnxTokA {amount} => { msg!("Instruction: BurnxToA"); Self::process_mint(accounts, amount, program_id) }, } } fn process_deposit( accounts: &[AccountInfo], vesting_period: u64, amount: u64, program_id: &Pubkey, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let initializer = next_account_info(account_info_iter)?; if !initializer.is_signer { return Err(ProgramError::MissingRequiredSignature); } let initializer_tokenA_account = next_account_info(account_info_iter)?; let initializer_tokenA_account_info = TokenAccount::unpack(&initializer_tokenA_account.data.borrow())?; if initializer_tokenA_account_info.amount==0 { return Err(StakingError::TokenBalanceZero.into()); } msg!("Initializer_TokenA account owner: {} " ,initializer_tokenA_account_info.owner ); let xtokenA_to_receive_account = next_account_info(account_info_iter)?; if *xtokenA_to_receive_account.owner != spl_token::id() { return Err(ProgramError::IncorrectProgramId); } let staking_account = next_account_info(account_info_iter)?; let tokA_vault = next_account_info(account_info_iter)?; msg!("TokA_Vault.key: {} " ,tokA_vault.key); let tokA_vault_info = TokenAccount::unpack(&tokA_vault.data.borrow())?; msg!(" tokA_Vault.owner {}", tokA_vault_info.owner); msg!("tokA_Vault.mint {}", tokA_vault_info.mint); let rent = &Rent::from_account_info(next_account_info(account_info_iter)?)?; if !rent.is_exempt(staking_account.lamports(), staking_account.data_len()) { return Err(StakingError::NotRentExempt.into()); } let mut staking_info = Staking::unpack_unchecked(&staking_account.data.borrow())?; /**this is how i can enforce that this the right transactions happen after one another*/ if staking_info.is_initialized(){ return Err(ProgramError::AccountAlreadyInitialized); } staking_info.vesting_period = vesting_period; staking_info.amount_currently_locked = staking_info.amount_currently_locked+amount; staking_info.is_initialized = true; staking_info.initializer_token_to_receive_account_pubkey = *xtokenA_to_receive_account.key; Staking::pack(staking_info, &mut staking_account.data.borrow_mut())?; //let (pda, _bump_seed) = Pubkey::find_program_address(&[b"tokenAvault"], program_id); let token_program = next_account_info(account_info_iter)?; msg!("making instruction to transfer {} coins to vault {}", amount,tokA_vault.key,); let transfer_tokA_to_vault_ix = spl_token::instruction::transfer( token_program.key, initializer_tokenA_account.key, tokA_vault.key, initializer.key, &[&initializer.key], amount )?; msg!("Calling the token program transfer TokenA to vault..."); invoke( &transfer_tokA_to_vault_ix, &[ initializer_tokenA_account.clone(), tokA_vault.clone(), initializer.clone(), token_program.clone(), ], )?; Ok(()) } fn process_mint( accounts: &[AccountInfo], amount_to_mint: u64, program_id: &Pubkey, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let xTokA_minting_authority = next_account_info(account_info_iter)?; let xTokA_mint = next_account_info(account_info_iter)?; let initializer= next_account_info(account_info_iter)?; let staking_account = next_account_info(account_info_iter)?; let initializer_xTokA_accnt_to_recieve = next_account_info(account_info_iter)?; let rent = &Rent::from_account_info(next_account_info(account_info_iter)?)?; let token_program = next_account_info(account_info_iter)?; if !rent.is_exempt(staking_account.lamports(), staking_account.data_len()) { return Err(StakingError::NotRentExempt.into()); } let mut staking_info = Staking::unpack_unchecked(&staking_account.data.borrow())?; if *initializer_xTokA_accnt_to_recieve.key!=staking_info.initializer_token_to_receive_account_pubkey{ return Err(StakingError::NotExpectedTokenAccount.into()); } if !staking_info.is_initialized{ return Err(StakingError::NoMatchingDeposit.into()); } if staking_info.amount_currently_locked<amount_to_mint{ return Err(StakingError::MintAmountExceedsLockedValue.into()); } let xTokenA_mint_info = TokenAccount::unpack(&xTokA_mint.data.borrow())?; msg!("TokenA_mint_info.owner: {} ", xTokenA_mint_info.owner); let xtokenA_mint_ix = spl_token::instruction::mint_to( token_program.key, xTokA_mint.key, &initializer_xTokA_accnt_to_recieve.key, &initializer.key, &[&xTokenA_mint_info.owner], amount_to_mint )?; msg!("Calling the token program mint xTokenA to depositer..."); invoke( &xtokenA_mint_ix, &[ xTokA_mint.clone(), initializer_xTokA_accnt_to_recieve.clone(), xTokA_minting_authority.clone(), token_program.clone(), ], )?; Ok(()) } }
#![feature(proc_macro_hygiene, decl_macro)] #![feature(async_closure)] use challenges::chal31; use hyper::{self, Client}; use rocket::{self, get, routes}; use rocket::{ config::{Config, Environment, LoggingLevel}, http::{RawStr, Status}, }; use std::thread; use std::time::{Duration, Instant}; // NOTE: when using HMAC-SHA1, we use the `Mac` trait defined in Hmac crate instead of the simple // MAC trait in this crate use encoding::hex; use hmac::{Hmac, Mac}; use sha1::Sha1; const HMAC_KEY: [u8; 22] = *b"whatever length secret"; // delibrately not 16 in length #[get("/test?<file>&<signature>")] // NOTE: for simplicity the `file` param will be the content of the file, the `signature` will be // just generated on the value of the `file`, not an actual file. // `signature` is hex string fn test(file: &RawStr, signature: &RawStr) -> Status { let mut hmac = Hmac::<Sha1>::new_varkey(&HMAC_KEY.to_vec()).expect("HMAC can take key of any size"); hmac.input(&file.to_string().as_bytes()); let tag = hmac.result().code().to_vec(); let sig_bytes = hex::hexstr_to_bytes(&signature.to_string()).unwrap_or_default(); if chal31::insecure_compare(&tag, &sig_bytes) { Status::Ok } else { Status::InternalServerError } } #[tokio::main] async fn main() { println!("🔓 Challenge 31"); // launch web server let server_config = Config::build(Environment::Development) .port(9000) .log_level(LoggingLevel::Off) .finalize() .unwrap(); thread::spawn(|| { rocket::custom(server_config).mount("/", routes![test]).launch(); }); // launch timing attack at the server thread::sleep(Duration::from_secs(1)); // make sure the server is launched let tag = timing_attack().await; println!("The tag/signature is: {}", tag); } async fn timing_attack() -> String { let file = "foo"; println!("Finding tag of 'foo' via timing attack..."); let mut sig = [0 as u8; 20]; for i in 0..20 { for byte in 0..=255 { sig[i] = byte; let now = Instant::now(); query(&file, &sig).await.unwrap(); if now.elapsed().as_millis() >= 50 * (i as u128 + 1) { println!("the {}th byte is: {:?}", i, byte); break; } } } // make sure the sig discovered is correct let resp = query(&file, &sig).await.unwrap(); assert!(resp); hex::bytes_to_hexstr(&sig) } async fn query(file: &str, sig: &[u8]) -> Result<bool, Box<dyn std::error::Error + Send + Sync>> { let client = Client::new(); let uri = format!( "http://localhost:9000/test?file={}&signature={}", file, hex::bytes_to_hexstr(sig) ); let resp = client.get(uri.parse()?).await?; if resp.status() == 200 { return Ok(true); } Ok(false) }
use PT_FIRSTMACH; pub type c_long = i32; pub type c_ulong = u32; pub type c_char = u8; pub type __cpu_simple_lock_nv_t = ::c_int; pub const PT_STEP: ::c_int = PT_FIRSTMACH + 0; pub const PT_GETREGS: ::c_int = PT_FIRSTMACH + 1; pub const PT_SETREGS: ::c_int = PT_FIRSTMACH + 2;
use std::f64::consts::SQRT_2; use enumset::EnumSetType; use crate::expansion_policy::ExpansionPolicy; use crate::node_pool::NodePool; use crate::{astar_unchecked, Owner}; /// Indicates that the implementing type guarantees the following invariants: /// /// If `Self` is a `NodePool<(i32, i32)>`: /// - All ids from `(0, 0)` inclusive to `(self.width(), self.height())` exclusive are in-bounds. /// /// If `Self` is an `ExpansionPolicy<(i32, i32)>`: /// - All ids from `(0, 0)` inclusive to `(self.width(), self.height())` exclusive are in-bounds. /// - The ids of the destinations of all edges produced by `expand_unchecked` are in-bounds. pub unsafe trait GridDomain { fn width(&self) -> i32; fn height(&self) -> i32; } pub fn grid_search<N, E>( pool: &mut N, owner: &mut Owner, expansion_policy: &mut E, h: impl FnMut((i32, i32)) -> f64, source: (i32, i32), goal: (i32, i32), ) where N: NodePool<(i32, i32)> + GridDomain, E: ExpansionPolicy<(i32, i32)> + GridDomain, { assert!(pool.width() >= expansion_policy.width()); assert!(pool.height() >= expansion_policy.height()); assert!(source.0 >= 0 && source.0 < expansion_policy.width()); assert!(source.1 >= 0 && source.1 < expansion_policy.height()); unsafe { // SAFETY: We check that the pool is large enough for the expansion policy. The expansion // policy guarantees that it never produces edges leading out-of-bounds. We check // that the source vertex is in-bounds. astar_unchecked(pool, owner, expansion_policy, h, source, goal) } } /// Indicates that the implementing type guarantees the following invariants: /// /// If `Self` is a `NodePool<usize>`: /// - All ids from `0` inclusive to `self.len()` exclusive are in-bounds. /// /// If `Self` is an `ExpansionPolicy<usize>`: /// - All ids from `0` inclusive to `self.len()` exclusive are in-bounds. /// - The ids of the destinations of all edges produced by `expand_unchecked` are in-bounds. pub unsafe trait IndexDomain { fn len(&self) -> usize; } pub fn index_search<N, E>( pool: &mut N, owner: &mut Owner, expansion_policy: &mut E, h: impl FnMut(usize) -> f64, source: usize, goal: usize, ) where N: NodePool<usize> + IndexDomain, E: ExpansionPolicy<usize> + IndexDomain, { assert!(pool.len() >= expansion_policy.len()); assert!(source < expansion_policy.len()); unsafe { // SAFETY: We check that the pool is large enough for the expansion policy. The expansion // policy guarantees that it never produces edges leading out-of-bounds. We check // that the source vertex is in-bounds. astar_unchecked(pool, owner, expansion_policy, h, source, goal) } } #[derive(Debug, EnumSetType)] pub enum Direction { NorthWest, North, NorthEast, West, East, SouthWest, South, SouthEast, } #[derive(Copy, Clone, Debug)] pub struct Neighborhood<T> { pub nw: T, pub n: T, pub ne: T, pub w: T, pub c: T, pub e: T, pub sw: T, pub s: T, pub se: T, } impl<T> Neighborhood<T> { /// Rotate clockwise 90 degrees pub fn rotate_cw(self) -> Self { Neighborhood { c: self.c, ne: self.nw, e: self.n, se: self.ne, s: self.e, sw: self.se, w: self.s, nw: self.sw, n: self.w, } } /// Flip across north-south pub fn flip_ortho(self) -> Self { Neighborhood { n: self.n, c: self.c, s: self.s, ne: self.nw, e: self.w, se: self.sw, nw: self.ne, w: self.e, sw: self.se, } } /// Flip across southwest-northeast pub fn flip_diagonal(self) -> Self { Neighborhood { ne: self.ne, c: self.c, sw: self.sw, n: self.e, e: self.n, w: self.s, s: self.w, nw: self.se, se: self.nw, } } } impl<T: Copy> Neighborhood<&T> { pub fn copied(self) -> Neighborhood<T> { Neighborhood { nw: *self.nw, n: *self.n, ne: *self.ne, w: *self.w, c: *self.c, e: *self.e, sw: *self.sw, s: *self.s, se: *self.se, } } } pub trait Cost { fn cost(&self) -> f64; } macro_rules! nz_cost_impls { ($($t:ident),*) => { $( impl Cost for std::num::$t { fn cost(&self) -> f64 { self.get() as f64 } } )* }; } nz_cost_impls!(NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroUsize); macro_rules! prim_cost_impls { ($($t:ty),*) => { $( impl Cost for $t { fn cost(&self) -> f64 { *self as f64 } } )* }; } prim_cost_impls!(u8, u16, u32, u64, usize, f32, f64, i8, i16, i32, i64, isize); pub fn octile_heuristic((tx, ty): (i32, i32), scale: f64) -> impl Fn((i32, i32)) -> f64 { move |(x, y)| { let dx = (tx - x).abs(); let dy = (ty - y).abs(); let diagonal_moves = dx.min(dy); let ortho_moves = dx.max(dy) - dx.min(dy); (ortho_moves as f64 + SQRT_2 * diagonal_moves as f64) * scale } } pub fn manhattan_heuristic((tx, ty): (i32, i32), scale: f64) -> impl Fn((i32, i32)) -> f64 { move |(x, y)| { let dx = (tx - x).abs(); let dy = (ty - y).abs(); (dx + dy) as f64 * scale } } pub fn zero_heuristic<VertexId>() -> impl Fn(VertexId) -> f64 { |_| 0.0 }
// 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. //! Helpers for working with streams. use { futures::{ready, Stream, StreamExt}, std::{ future::Future, pin::Pin, task::{Context, Poll}, }, }; /// Essentially `stream.into_future().map(move |(value, stream) (value, stream, with))` pub(super) struct NextWith<St, With> { opt: Option<(St, With)>, } const USED_AFTER_COMPLETION: &str = "`NextWith` used after completion"; impl<St, With> NextWith<St, With> { /// Create a new `NextWith` future. pub fn new(stream: St, with: With) -> Self { NextWith { opt: Some((stream, with)) } } fn stream(&mut self) -> &mut St { &mut self.opt.as_mut().expect(USED_AFTER_COMPLETION).0 } fn take(&mut self) -> (St, With) { self.opt.take().expect(USED_AFTER_COMPLETION) } } impl<St, With> Unpin for NextWith<St, With> {} impl<St, With> Future for NextWith<St, With> where St: Stream + Unpin, { type Output = Option<(St::Item, St, With)>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let opt = ready!(self.stream().poll_next_unpin(cx)); Poll::Ready(opt.map(|next| { let (st, with) = self.take(); (next, st, with) })) } }
/* * Multiples of 3 and 5 * ==================== * If we list all the natural numbers below 10 that are multiples of 3 or 5, we * get 3, 5, 6 and 9. The sum of these multiples is 23. * * Find the sum of all the multiples of 3 or 5 below 1000. */ trait NumberTheory { fn divides(&self, n: u32) -> bool; } impl NumberTheory for u32 { fn divides(&self, n: u32) -> bool { n % *self == 0 } } fn main() { // Don't include 1000 in this strange Fizz Buzz. let multiples = (1..1000). filter(|n: &u32| 3.divides(*n) || 5.divides(*n)); let answer: u32 = multiples.fold(0, |sum: u32, n: u32| sum + n); println!("{}", answer); }
use crate::graph::JsGraph; use crate::layout::force_simulation::coordinates::JsCoordinates; use js_sys::{Function, Reflect}; use petgraph_layout_force::link_force::LinkArgument; use petgraph_layout_force_simulation::Force; use petgraph_layout_grouped_force::force::group_many_body_force::GroupManyBodyForceArgument; use petgraph_layout_grouped_force::force::group_position_force; use petgraph_layout_grouped_force::force::{ GroupLinkForce, GroupManyBodyForce, GroupPositionForce, }; use wasm_bindgen::prelude::*; #[wasm_bindgen(js_name = GroupLinkForce)] pub struct JsGroupLinkForce { force: GroupLinkForce, } #[wasm_bindgen(js_class = GroupLinkForce)] impl JsGroupLinkForce { #[wasm_bindgen(constructor)] pub fn new( graph: &JsGraph, group_accessor: &Function, inter_link_accessor: &Function, intra_link_accessor: &Function, ) -> Result<JsGroupLinkForce, JsValue> { Ok(JsGroupLinkForce { force: GroupLinkForce::new( graph.graph(), |_, u| { let obj = group_accessor .call1(&JsValue::null(), &JsValue::from_f64(u.index() as f64)) .unwrap(); Reflect::get(&obj, &"group".into()) .unwrap() .as_f64() .unwrap() as usize }, |_, e| { let obj = inter_link_accessor .call1(&JsValue::null(), &JsValue::from_f64(e.index() as f64)) .unwrap(); LinkArgument { distance: Some( Reflect::get(&obj, &"distance".into()) .unwrap() .as_f64() .unwrap() as f32, ), strength: Some( Reflect::get(&obj, &"strength".into()) .unwrap() .as_f64() .unwrap() as f32, ), } }, |_, e| { let obj = intra_link_accessor .call1(&JsValue::null(), &JsValue::from_f64(e.index() as f64)) .unwrap(); LinkArgument { distance: Some( Reflect::get(&obj, &"distance".into()) .unwrap() .as_f64() .unwrap() as f32, ), strength: Some( Reflect::get(&obj, &"strength".into()) .unwrap() .as_f64() .unwrap() as f32, ), } }, ), }) } pub fn apply(&self, coordinates: &mut JsCoordinates, alpha: f32) { self.force.apply(coordinates.points_mut(), alpha); } } #[wasm_bindgen(js_name = GroupManyBodyForce)] pub struct JsGroupManyBodyForce { force: GroupManyBodyForce, } #[wasm_bindgen(js_class = GroupManyBodyForce)] impl JsGroupManyBodyForce { #[wasm_bindgen(constructor)] pub fn new(graph: &JsGraph, node_accessor: &Function) -> Result<JsGroupManyBodyForce, JsValue> { Ok(JsGroupManyBodyForce { force: GroupManyBodyForce::new(graph.graph(), |_, u| { let obj = node_accessor .call1(&JsValue::null(), &JsValue::from_f64(u.index() as f64)) .unwrap(); GroupManyBodyForceArgument { group: Reflect::get(&obj, &"group".into()) .unwrap() .as_f64() .unwrap() as usize, strength: Some( Reflect::get(&obj, &"strength".into()) .unwrap() .as_f64() .unwrap() as f32, ), } }), }) } pub fn apply(&self, coordinates: &mut JsCoordinates, alpha: f32) { self.force.apply(coordinates.points_mut(), alpha); } } #[wasm_bindgen(js_name = GroupPositionForce)] pub struct JsGroupPositionForce { force: GroupPositionForce, } #[wasm_bindgen(js_class=GroupPositionForce)] impl JsGroupPositionForce { #[wasm_bindgen(constructor)] pub fn new( graph: &JsGraph, node_accessor: &Function, group_accessor: &Function, ) -> Result<JsGroupPositionForce, JsValue> { Ok(JsGroupPositionForce { force: GroupPositionForce::new( graph.graph(), |_, u| { let obj = node_accessor .call1(&JsValue::null(), &JsValue::from_f64(u.index() as f64)) .unwrap(); group_position_force::NodeArgument { group: Reflect::get(&obj, &"group".into()) .unwrap() .as_f64() .unwrap() as usize, strength: Reflect::get(&obj, &"strength".into()) .unwrap() .as_f64() .unwrap() as f32, } }, |_, g| { let obj = group_accessor .call1(&JsValue::null(), &JsValue::from_f64(g as f64)) .unwrap(); group_position_force::GroupArgument { x: Reflect::get(&obj, &"x".into()).unwrap().as_f64().unwrap() as f32, y: Reflect::get(&obj, &"y".into()).unwrap().as_f64().unwrap() as f32, } }, ), }) } pub fn apply(&self, coordinates: &mut JsCoordinates, alpha: f32) { self.force.apply(coordinates.points_mut(), alpha); } }
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 //! Algorithm-generic signature traits. /// An error returned by a signature operation. /// /// This type serves as a combination of built-in error types known to /// Manticore, plus a "custom error" component for surfacing /// implementation-specific errors that Manticore can treat as a black box. /// /// This type has the benefit that, unlike a pure associated type, `From` /// implementations for error-handling can be implemented on it. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum Error<E = ()> { /// The "custom" error type, which is treated by Manticore as a black box. Custom(E), } impl<E> Error<E> { /// Erases the custom error type from this `Error`, replacing it with `()`. pub fn erased(self) -> Error { match self { Self::Custom(_) => Error::Custom(()), } } } /// Convenience type for the error returned by [`Verify::verify()`]. pub type VerifyError<V> = Error<<V as Verify>::Error>; /// Convenience type for the error returned by [`Sign::sign()`]. pub type SignError<S> = Error<<S as Sign>::Error>; /// A signature-verification engine, already primed with a key. /// /// There is no way to extract the key back out of an `Engine` value. pub trait Verify { /// The error returned when an operation fails. type Error; /// Uses this engine to verify `signature` against `expected_hash`, by /// performing an encryption operation on `signature`, and comparing the /// result to a hash of `message`. /// /// If the underlying cryptographic operation succeeds, returns `Ok(())`. /// Failures, including signature check failures, are included in the /// `Err` variant. fn verify( &mut self, signature: &[u8], message: &[u8], ) -> Result<(), VerifyError<Self>>; } /// Marker trait for specifying a bound on a [`Verify`] to specify that it can /// verify a specific kind of signature. /// /// For example, you might write `verify: impl VerifyFor<Rsa>` instead of /// `verify: impl Verify` if you only wish to accept verifiers for RSA. This is /// mostly useful in situations where this is the only supported algorithm for /// an operation. pub trait VerifyFor<Algo>: Verify {} /// An signing engine, already primed with a keypair. /// /// There is no way to extract the keypair back out of a `Sign` value. pub trait Sign { /// The error returned when an operation fails. type Error; /// Returns the number of bytes a signature produced by this signer needs. fn sig_bytes(&self) -> usize; /// Uses this signer to create a signature value for `message`. /// /// If the underlying cryptographic operation succeeds, returns `Ok(())`. /// Failures are included in the `Err` variant. fn sign( &mut self, message: &[u8], signature: &mut [u8], ) -> Result<(), SignError<Self>>; } /// Marker trait for specifying a bound on a [`Sign`] to specify that it can /// create a specific kind of signature. /// /// See [`VerifyFor`]. pub trait SignFor<Algo>: Sign {}
use ::{WeakTypeContainer, FieldReference}; #[derive(Debug)] /// Used to reference a specific property of another field. pub struct FieldPropertyReference { pub reference: FieldReference, pub reference_node: Option<WeakTypeContainer>, pub property: String, } impl FieldPropertyReference { }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type Geofence = *mut ::core::ffi::c_void; pub type GeofenceMonitor = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct GeofenceMonitorStatus(pub i32); impl GeofenceMonitorStatus { pub const Ready: Self = Self(0i32); pub const Initializing: Self = Self(1i32); pub const NoData: Self = Self(2i32); pub const Disabled: Self = Self(3i32); pub const NotInitialized: Self = Self(4i32); pub const NotAvailable: Self = Self(5i32); } impl ::core::marker::Copy for GeofenceMonitorStatus {} impl ::core::clone::Clone for GeofenceMonitorStatus { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct GeofenceRemovalReason(pub i32); impl GeofenceRemovalReason { pub const Used: Self = Self(0i32); pub const Expired: Self = Self(1i32); } impl ::core::marker::Copy for GeofenceRemovalReason {} impl ::core::clone::Clone for GeofenceRemovalReason { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct GeofenceState(pub u32); impl GeofenceState { pub const None: Self = Self(0u32); pub const Entered: Self = Self(1u32); pub const Exited: Self = Self(2u32); pub const Removed: Self = Self(4u32); } impl ::core::marker::Copy for GeofenceState {} impl ::core::clone::Clone for GeofenceState { fn clone(&self) -> Self { *self } } pub type GeofenceStateChangeReport = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct MonitoredGeofenceStates(pub u32); impl MonitoredGeofenceStates { pub const None: Self = Self(0u32); pub const Entered: Self = Self(1u32); pub const Exited: Self = Self(2u32); pub const Removed: Self = Self(4u32); } impl ::core::marker::Copy for MonitoredGeofenceStates {} impl ::core::clone::Clone for MonitoredGeofenceStates { fn clone(&self) -> Self { *self } }
use std::fs::{create_dir_all, File}; use std::io; use std::io::prelude::*; use std::path::{Path, PathBuf}; use amethyst::utils::app_root_dir::application_root_dir; pub fn file<S>(path: S) -> String where S: ToString, { use amethyst::utils::app_root_dir::application_dir; let path = if cfg!(target_os = "windows") { path.to_string().replace("/", "\\") } else { path.to_string() }; application_dir(path).unwrap().to_str().unwrap().to_string() } pub fn resource<S>(path: S) -> String where S: ToString, { use amethyst::utils::app_root_dir::application_dir; let path = if cfg!(target_os = "windows") { path.to_string().replace("/", "\\") } else { path.to_string() }; let res_dir = application_dir("resources").expect("Should have resources directory"); let path = res_dir.join(path); path.to_str().unwrap().to_string() } pub fn write_file<P, S>(path: P, data: S) -> Result<(), io::Error> where P: AsRef<Path>, S: ToString, { let mut file = File::create(path)?; write!(&mut file, "{}", data.to_string()) } pub fn data_dir() -> Option<PathBuf> { if let Some(mut path) = dirs::data_local_dir() { path.push(crate::meta::NAME); if !path.is_dir() { create_dir_all(&path).unwrap(); } Some(path) } else { application_root_dir().ok() } }
pub mod qtouchdevice; pub use self::qtouchdevice::QTouchDevice; pub mod qwindow; pub use self::qwindow::QWindow; pub mod qgenericplugin; pub use self::qgenericplugin::QGenericPlugin; pub mod qsyntaxhighlighter; pub use self::qsyntaxhighlighter::QSyntaxHighlighter; pub mod qbrush; pub use self::qbrush::QRadialGradient; pub mod qevent; pub use self::qevent::QWhatsThisClickedEvent; pub mod qopenglcontext; pub use self::qopenglcontext::QOpenGLVersionProfile; pub use self::qevent::QExposeEvent; pub mod qtextformat; pub use self::qtextformat::QTextLength; pub mod qtextoption; pub use self::qtextoption::QTextOption; pub mod qpagelayout; pub use self::qpagelayout::QPageLayout; pub mod qvector2d; pub use self::qvector2d::QVector2D; pub use self::qbrush::QConicalGradient; pub use self::qevent::QInputMethodEvent; pub mod qimagereader; pub use self::qimagereader::QImageReader; pub mod qrawfont; pub use self::qrawfont::QRawFont; pub mod qmatrix4x4; pub use self::qmatrix4x4::QMatrix4x4; pub use self::qtextformat::QTextImageFormat; pub mod qaccessible; pub use self::qaccessible::QAccessible; pub mod qaccessibleobject; pub use self::qaccessibleobject::QAccessibleApplication; pub mod qtexttable; pub use self::qtexttable::QTextTableCell; pub mod qpaintengine; pub use self::qpaintengine::QTextItem; pub use self::qpaintengine::QPaintEngineState; pub mod qimage; pub use self::qimage::QImage; pub mod qimageiohandler; pub use self::qimageiohandler::QImageIOHandler; pub use self::qpaintengine::QPaintEngine; pub mod qpainterpath; pub use self::qpainterpath::QPainterPath; pub mod qvalidator; pub use self::qvalidator::QRegularExpressionValidator; pub mod qfontmetrics; pub use self::qfontmetrics::QFontMetrics; pub use self::qevent::QHelpEvent; pub use self::qevent::QActionEvent; pub mod qpagesize; pub use self::qpagesize::QPageSize; pub mod qtextobject; pub use self::qtextobject::QTextObject; pub mod qmovie; pub use self::qmovie::QMovie; pub mod qstatictext; pub use self::qstatictext::QStaticText; pub mod qpalette; pub use self::qpalette::QPalette; pub use self::qevent::QMouseEvent; pub mod qcolor; pub use self::qcolor::QColor; pub use self::qevent::QFileOpenEvent; pub mod qopenglwindow; pub use self::qopenglwindow::QOpenGLWindow; pub use self::qevent::QToolBarChangeEvent; pub use self::qtextformat::QTextFormat; pub mod qcursor; pub use self::qcursor::QCursor; pub mod qrasterwindow; pub use self::qrasterwindow::QRasterWindow; pub use self::qevent::QTabletEvent; pub mod qkeysequence; pub use self::qkeysequence::QKeySequence; pub use self::qaccessible::QAccessibleTableModelChangeEvent; pub use self::qaccessible::QAccessibleTextInterface; pub mod qsessionmanager; pub use self::qsessionmanager::QSessionManager; pub use self::qpainterpath::QPainterPathStroker; pub use self::qtextobject::QTextBlockUserData; pub mod qguiapplication; pub use self::qguiapplication::QGuiApplication; pub mod qpen; pub use self::qpen::QPen; pub use self::qevent::QTouchEvent; pub mod qdrag; pub use self::qdrag::QDrag; pub mod qdesktopservices; pub use self::qdesktopservices::QDesktopServices; pub mod qopengltimerquery; pub use self::qopengltimerquery::QOpenGLTimerQuery; pub use self::qaccessible::QAccessibleEvent; pub use self::qaccessible::QAccessibleActionInterface; pub use self::qtextobject::QTextFragment; pub use self::qaccessibleobject::QAccessibleObject; pub use self::qvalidator::QDoubleValidator; pub use self::qevent::QScreenOrientationChangeEvent; pub use self::qtextformat::QTextBlockFormat; pub mod qpicture; pub use self::qpicture::QPictureIO; pub mod qtransform; pub use self::qtransform::QTransform; pub mod qabstracttextdocumentlayout; pub use self::qabstracttextdocumentlayout::QTextObjectInterface; pub mod qopenglpaintdevice; pub use self::qopenglpaintdevice::QOpenGLPaintDevice; pub use self::qaccessible::QAccessibleInterface; pub use self::qevent::QIconDragEvent; pub use self::qpicture::QPicture; pub mod qpaintdevicewindow; pub use self::qpaintdevicewindow::QPaintDeviceWindow; pub mod qiconengineplugin; pub use self::qiconengineplugin::QIconEnginePlugin; pub mod qopengltexture; pub use self::qopengltexture::QOpenGLTexture; pub use self::qaccessible::QAccessibleEditableTextInterface; pub use self::qevent::QCloseEvent; pub mod qfontinfo; pub use self::qfontinfo::QFontInfo; pub use self::qvalidator::QIntValidator; pub mod qmatrix; pub use self::qmatrix::QMatrix; pub mod qtextdocument; pub use self::qtextdocument::QTextDocument; pub mod qregion; pub use self::qregion::QRegion; pub use self::qevent::QDragEnterEvent; pub mod qimagewriter; pub use self::qimagewriter::QImageWriter; pub mod qopenglbuffer; pub use self::qopenglbuffer::QOpenGLBuffer; pub mod qaccessibleplugin; pub use self::qaccessibleplugin::QAccessiblePlugin; pub mod qvector3d; pub use self::qvector3d::QVector3D; pub use self::qtextformat::QTextCharFormat; pub mod qpagedpaintdevice; pub use self::qpagedpaintdevice::QPagedPaintDevice; pub use self::qtextdocument::QAbstractUndoItem; pub use self::qevent::QWheelEvent; pub mod qpolygon; pub use self::qpolygon::QPolygon; pub mod qtextlayout; pub use self::qtextlayout::QTextLine; pub mod qopenglpixeltransferoptions; pub use self::qopenglpixeltransferoptions::QOpenGLPixelTransferOptions; pub mod qpainter; pub use self::qpainter::QPainter; pub use self::qtextlayout::QTextLayout; pub use self::qevent::QScrollEvent; pub use self::qevent::QHoverEvent; pub use self::qopenglcontext::QOpenGLContext; pub use self::qaccessible::QAccessibleTableCellInterface; pub mod qaccessiblebridge; pub use self::qaccessiblebridge::QAccessibleBridgePlugin; pub mod qstandarditemmodel; pub use self::qstandarditemmodel::QStandardItemModel; pub use self::qaccessible::QAccessibleTableInterface; pub mod qfontdatabase; pub use self::qfontdatabase::QFontDatabase; pub mod qpaintdevice; pub use self::qpaintdevice::QPaintDevice; pub use self::qevent::QDragMoveEvent; pub use self::qtextformat::QTextTableFormat; pub use self::qbrush::QBrush; pub mod qinputmethod; pub use self::qinputmethod::QInputMethod; pub mod qiconengine; pub use self::qiconengine::QIconEngine; pub mod qopenglshaderprogram; pub use self::qopenglshaderprogram::QOpenGLShader; pub use self::qopenglcontext::QOpenGLContextGroup; pub mod qsurface; pub use self::qsurface::QSurface; pub mod qopengldebug; pub use self::qopengldebug::QOpenGLDebugMessage; pub use self::qevent::QShowEvent; pub use self::qpolygon::QPolygonF; pub mod qbackingstore; pub use self::qbackingstore::QBackingStore; pub mod qopenglvertexarrayobject; pub use self::qopenglvertexarrayobject::QOpenGLVertexArrayObject; pub mod qtextlist; pub use self::qtextlist::QTextList; pub use self::qevent::QPlatformSurfaceEvent; pub use self::qaccessible::QAccessibleTextUpdateEvent; pub use self::qevent::QPaintEvent; pub use self::qaccessible::QAccessibleStateChangeEvent; pub mod qpictureformatplugin; pub use self::qpictureformatplugin::QPictureFormatPlugin; pub use self::qbrush::QGradient; pub use self::qtextlayout::QTextInlineObject; pub mod qopenglversionfunctions; pub use self::qopenglversionfunctions::QOpenGLVersionFunctionsBackend; pub mod qglyphrun; pub use self::qglyphrun::QGlyphRun; pub use self::qevent::QFocusEvent; pub mod qoffscreensurface; pub use self::qoffscreensurface::QOffscreenSurface; pub mod qvector4d; pub use self::qvector4d::QVector4D; pub use self::qevent::QNativeGestureEvent; pub use self::qevent::QResizeEvent; pub use self::qevent::QStatusTipEvent; pub use self::qevent::QEnterEvent; pub use self::qopenglversionfunctions::QAbstractOpenGLFunctions; pub mod qscreen; pub use self::qscreen::QScreen; pub mod qclipboard; pub use self::qclipboard::QClipboard; pub use self::qevent::QMoveEvent; pub use self::qimageiohandler::QImageIOPlugin; pub use self::qaccessible::QAccessibleImageInterface; pub mod qtextcursor; pub use self::qtextcursor::QTextCursor; pub use self::qstandarditemmodel::QStandardItem; pub use self::qaccessible::QAccessibleTextInsertEvent; pub use self::qfontmetrics::QFontMetricsF; pub use self::qevent::QHideEvent; pub mod qpdfwriter; pub use self::qpdfwriter::QPdfWriter; pub use self::qevent::QDragLeaveEvent; pub use self::qopenglversionfunctions::QOpenGLVersionStatus; pub use self::qtextformat::QTextTableCellFormat; pub mod qpixmap; pub use self::qpixmap::QPixmap; pub use self::qaccessible::QAccessibleValueInterface; pub mod qsurfaceformat; pub use self::qsurfaceformat::QSurfaceFormat; pub use self::qaccessible::QAccessibleTextRemoveEvent; pub use self::qtextobject::QTextFrameLayoutData; pub use self::qevent::QDropEvent; pub mod qfont; pub use self::qfont::QFont; pub use self::qopengldebug::QOpenGLDebugLogger; pub mod qtextdocumentfragment; pub use self::qtextdocumentfragment::QTextDocumentFragment; pub use self::qevent::QInputEvent; pub use self::qtextobject::QTextBlock; pub mod qopenglframebufferobject; pub use self::qopenglframebufferobject::QOpenGLFramebufferObjectFormat; pub mod qstylehints; pub use self::qstylehints::QStyleHints; pub mod qopenglfunctions; pub use self::qopenglfunctions::QOpenGLFunctions; pub use self::qopenglshaderprogram::QOpenGLShaderProgram; pub use self::qtextformat::QTextListFormat; pub mod qbitmap; pub use self::qbitmap::QBitmap; pub use self::qaccessible::QAccessibleTextSelectionEvent; pub use self::qevent::QApplicationStateChangeEvent; pub use self::qtextobject::QTextBlockGroup; pub mod qpixmapcache; pub use self::qpixmapcache::QPixmapCache; pub mod qgenericpluginfactory; pub use self::qgenericpluginfactory::QGenericPluginFactory; pub use self::qbrush::QBrushData; pub mod qquaternion; pub use self::qquaternion::QQuaternion; pub use self::qaccessible::QAccessibleTextCursorEvent; pub use self::qabstracttextdocumentlayout::QAbstractTextDocumentLayout; pub use self::qevent::QKeyEvent; pub use self::qevent::QContextMenuEvent; pub use self::qevent::QScrollPrepareEvent; pub use self::qevent::QShortcutEvent; pub mod qicon; pub use self::qicon::QIcon; pub use self::qevent::QWindowStateChangeEvent; pub use self::qaccessiblebridge::QAccessibleBridge; pub use self::qtextobject::QTextFrame; pub use self::qvalidator::QValidator; pub mod qtextdocumentwriter; pub use self::qtextdocumentwriter::QTextDocumentWriter; pub mod qpixelformat; pub use self::qpixelformat::QPixelFormat; pub use self::qbrush::QLinearGradient; pub use self::qvalidator::QRegExpValidator; pub use self::qopenglframebufferobject::QOpenGLFramebufferObject; pub use self::qaccessible::QAccessibleValueChangeEvent; pub use self::qtextformat::QTextFrameFormat; pub use self::qtexttable::QTextTable; pub use self::qopengltimerquery::QOpenGLTimeMonitor; pub use self::qevent::QInputMethodQueryEvent;
/* 为了不让 common 出现在测试输出中,我们将创建 tests/common/mod.rs , 而不是创建 tests/common.rs 。这是一种 Rust 的命名规范, 这样命名告诉 Rust 不要将 common 看作一个集成测试文件。 将 setup 函数代码移动到 tests/common/mod.rs 并删除 tests/common.rs 文件之后, 测试输出中将不会出现这一部分。tests 目录中的子目录不会被作为单独的 crate 编译或作为一个测试结果部分出现在测试输出中。 一旦拥有了 tests/common/mod.rs,就可以将其作为模块以便在任何集成测试文件中使用。 */ pub fn setup() { // 编写特定库测试所需的代码 }
use super::Part; use crate::codec::{Decode, Encode}; use crate::{remote_type, RemoteObject, Vector3}; remote_type!( /// A control surface. Obtained by calling `Part::control_surface().` object SpaceCenter.ControlSurface { properties: { { Part { /// Returns the part object for this control surface. /// /// **Game Scenes**: All get: part -> Part } } { PitchEnabled { /// Returns whether the control surface has pitch control enabled. /// /// **Game Scenes**: All get: is_pitch_enabled -> bool, /// Sets whether the control surface has pitch control enabled. /// /// **Game Scenes**: All set: set_pitch_enabled(bool) } } { YawEnabled { /// Returns whether the control surface has yaw control enabled. /// /// **Game Scenes**: All get: is_yaw_enabled -> bool, /// Sets whether the control surface has yaw control enabled. /// /// **Game Scenes**: All set: set_yaw_enabled(bool) } } { RollEnabled { /// Returns whether the control surface has roll control enabled. /// /// **Game Scenes**: All get: is_roll_enabled -> bool, /// Sets whether the control surface has roll control enabled. /// /// **Game Scenes**: All set: set_roll_enabled(bool) } } { AuthorityLimiter { /// Returns the authority limiter for the control surface, which controls how /// far the control surface will move. /// /// **Game Scenes**: All get: authority_limiter -> f32, /// Sets the authority limiter for the control surface, which controls how /// far the control surface will move. /// /// **Game Scenes**: All set: set_authority_limiter(f32) } } { Inverted { /// Returns whether the control surface movement is inverted. /// /// **Game Scenes**: All get: is_inverted -> bool, /// Sets whether the control surface movement is inverted. /// /// **Game Scenes**: All set: set_inverted(bool) } } { Deployed { /// Returns whether the control surface has been fully deployed. /// /// **Game Scenes**: All get: is_deployed -> bool, /// Sets whether the control surface has been fully deployed.s /// /// **Game Scenes**: All set: set_deployed(bool) } } { SurfaceArea { /// Returns the surface area of the control surface in m<sup>2</sup>. /// /// **Game Scenes**: All get: surface_area -> f32 } } { AvailableTorque { /// Returns the available torque, in Newton meters, that can be produced by this /// control surface, in the positive and negative pitch, roll and yaw axes of the /// vessel. These axes correspond to the coordinate axes of the /// `Vessel::reference_frame()`. /// /// **Game Scenes**: All get: available_torque -> (Vector3, Vector3) } } } });
use { super::{ChunkVec, Vox, VoxType, VoxVec, WorldVec, CHUNK_SIDE, CHUNK_VOX_COUNT}, crate::proto::{ chunk_save::{ChunkSave, ChunkSaveContents}, ReadProto, WriteProto, }, std::{ convert::TryFrom, iter::Iterator, ops::{Index, IndexMut}, }, }; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum ChunkContents { Empty, Heightmap, Structures, } impl ChunkContents { #[inline(always)] pub fn has_heightmap(self) -> bool { self == ChunkContents::Heightmap } #[inline(always)] pub fn has_structures(self) -> bool { self == ChunkContents::Structures } } impl ReadProto<ChunkSaveContents> for ChunkContents { fn read_proto(message: ChunkSaveContents) -> Option<Self> { Some(match message { ChunkSaveContents::EMPTY => ChunkContents::Empty, ChunkSaveContents::HEIGHTMAP => ChunkContents::Heightmap, ChunkSaveContents::STRUCTURES => ChunkContents::Structures, }) } } impl WriteProto<ChunkSaveContents> for ChunkContents { fn write_proto(&self) -> ChunkSaveContents { match self { ChunkContents::Empty => ChunkSaveContents::EMPTY, ChunkContents::Heightmap => ChunkSaveContents::HEIGHTMAP, ChunkContents::Structures => ChunkSaveContents::STRUCTURES, } } } type VoxArray = [Vox; CHUNK_VOX_COUNT]; pub struct Chunk { vec: ChunkVec, modified: bool, contents: ChunkContents, voxels: Box<VoxArray>, } impl Chunk { pub fn new_empty(vec: ChunkVec) -> Self { Self::new_modified( vec, ChunkContents::Empty, Box::new([Default::default(); CHUNK_VOX_COUNT]), ) } pub fn new_unmodified(vec: ChunkVec, contents: ChunkContents, voxels: Box<VoxArray>) -> Self { Self { vec, modified: false, contents, voxels, } } pub fn new_modified(vec: ChunkVec, contents: ChunkContents, voxels: Box<VoxArray>) -> Self { Self { vec, modified: true, contents, voxels, } } pub fn vec(&self) -> ChunkVec { self.vec } pub fn contains(&self, vec: WorldVec) -> bool { let WorldVec(wx, wy, wz) = vec; let ChunkVec(cx, cy, cz) = self.vec; (cx <= wx && cx + CHUNK_SIDE > wx) && (cy <= wy && cy + CHUNK_SIDE > wy) && (cz <= wz && cz + CHUNK_SIDE > wz) } pub fn iter(&self) -> impl Iterator<Item = (VoxVec, &Vox)> { VoxIterator::new(&self) } pub fn set_unmodified(&mut self) { self.modified = false; } pub fn is_modified(&self) -> bool { self.modified } #[inline(always)] pub fn set_contents(&mut self, contents: ChunkContents) { self.contents = contents; } #[inline(always)] pub fn has_heightmap(&self) -> bool { self.contents.has_heightmap() } #[inline(always)] pub fn has_structures(&self) -> bool { self.contents.has_structures() } } impl Index<VoxVec> for Chunk { type Output = Vox; #[inline(always)] fn index(&self, index: VoxVec) -> &Self::Output { let index: usize = index.into(); &self.voxels[index] } } impl IndexMut<VoxVec> for Chunk { #[inline(always)] fn index_mut(&mut self, index: VoxVec) -> &mut Self::Output { self.modified = true; let index: usize = index.into(); &mut self.voxels[index] } } impl Clone for Chunk { fn clone(&self) -> Self { let mut voxels = Box::new([Default::default(); CHUNK_VOX_COUNT]); voxels.copy_from_slice(self.voxels.as_ref()); Self { vec: self.vec, modified: self.modified, contents: self.contents, voxels, } } } impl WriteProto<ChunkSave> for Chunk { fn write_proto(&self) -> ChunkSave { let mut chunk = ChunkSave::new(); chunk.set_contents(self.contents.write_proto()); chunk.set_vec(self.vec.write_proto()); for Vox(val) in self.voxels.iter() { chunk.voxels.push(*val as u32); } chunk } } impl ReadProto<&ChunkSave> for Chunk { fn read_proto(value: &ChunkSave) -> Option<Self> { if value.voxels.len() != CHUNK_VOX_COUNT { // data size does not match return None; } let mut voxels = Box::new([Default::default(); CHUNK_VOX_COUNT]); for (i, val) in value.voxels.iter().enumerate() { if let Ok(vox_type) = VoxType::try_from(*val) { voxels[i] = Vox(vox_type); } else { // invalid data return None; } } Some(Chunk::new_unmodified( ChunkVec::read_proto(value.get_vec())?, ChunkContents::read_proto(value.get_contents())?, voxels, )) } } struct VoxIterator<'a> { chunk: &'a Chunk, index: usize, } impl<'a> VoxIterator<'a> { pub(self) fn new(chunk: &'a Chunk) -> Self { VoxIterator { chunk, index: 0 } } } impl<'a> Iterator for VoxIterator<'a> { type Item = (VoxVec, &'a Vox); fn next(&mut self) -> Option<Self::Item> { if self.index < CHUNK_VOX_COUNT { let vec = VoxVec::from(self.index); let vox = &self.chunk[vec]; self.index += 1; Some((vec, vox)) } else { None } } } #[cfg(test)] mod tests { use {super::*, crate::terrain::consts::CHUNK_SIDE}; #[test] fn get_and_set_voxels_by_vec() { let vec = VoxVec(2, 3, 4); let mut chunk = Chunk::new_empty(ChunkVec::origin()); chunk[vec] = Vox(VoxType::Stone); assert_eq!(chunk[vec], Vox(VoxType::Stone)); } #[test] fn iterate_voxels_by_x_z_y() { let chunk = Chunk::new_empty(ChunkVec::origin()); let mut iterator = chunk.iter(); // x increments first iterator.next(); let (vec, _) = iterator.next().unwrap(); assert_eq!(vec, VoxVec(1, 0, 0)); // x wraps, z increments for _ in 0..CHUNK_SIDE - 2 { iterator.next(); } let (vec, _) = iterator.next().unwrap(); assert_eq!(vec, VoxVec(0, 0, 1)); // z wraps, y increments for _ in 0..CHUNK_SIDE * (CHUNK_SIDE - 1) - 1 { iterator.next(); } let (vec, _) = iterator.next().unwrap(); assert_eq!(vec, VoxVec(0, 1, 0)); } #[test] fn test_chunk_contains() { let chunk = Chunk::new_empty(ChunkVec(-CHUNK_SIDE, 0, 0)); assert!(chunk.contains(WorldVec(-1, 0, 0))); let chunk = Chunk::new_empty(ChunkVec(0, 0, CHUNK_SIDE)); assert!(!chunk.contains(WorldVec(0, 0, 23))); assert!(chunk.contains(WorldVec(0, 0, 33))); } }
extern crate proconio; use proconio::input; fn main() { input! { n: usize, d: i64, pts: [(i64, i64); n], } println!( "{}", pts.iter() .filter(|(x, y)| x * x + y * y <= d * d) .collect::<Vec<_>>() .len() ); }
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - USART Configuration register. Basic USART configuration settings that typically are not changed during operation."] pub cfg: CFG, #[doc = "0x04 - USART Control register. USART control settings that are more likely to change during operation."] pub ctrl: CTRL, #[doc = "0x08 - USART Status register. The complete status value can be read here. Writing 1s clears some bits in the register. Some bits can be cleared by writing a 1 to them."] pub stat: STAT, #[doc = "0x0c - Interrupt Enable read and Set register. Contains an individual interrupt enable bit for each potential USART interrupt. A complete value may be read from this register. Writing a 1 to any implemented bit position causes that bit to be set."] pub intenset: INTENSET, #[doc = "0x10 - Interrupt Enable Clear register. Allows clearing any combination of bits in the INTENSET register. Writing a 1 to any implemented bit position causes the corresponding bit to be cleared."] pub intenclr: INTENCLR, #[doc = "0x14 - Receiver Data register. Contains the last character received."] pub rxdata: RXDATA, #[doc = "0x18 - Receiver Data with Status register. Combines the last character received with the current USART receive status. Allows software to recover incoming data and status together."] pub rxdatastat: RXDATASTAT, #[doc = "0x1c - Transmit Data register. Data to be transmitted is written here."] pub txdata: TXDATA, #[doc = "0x20 - Baud Rate Generator register. 16-bit integer baud rate divisor value."] pub brg: BRG, #[doc = "0x24 - Interrupt status register. Reflects interrupts that are currently enabled."] pub intstat: INTSTAT, } #[doc = "USART Configuration register. Basic USART configuration settings that typically are not changed during operation."] pub struct CFG { register: ::vcell::VolatileCell<u32>, } #[doc = "USART Configuration register. Basic USART configuration settings that typically are not changed during operation."] pub mod cfg; #[doc = "USART Control register. USART control settings that are more likely to change during operation."] pub struct CTRL { register: ::vcell::VolatileCell<u32>, } #[doc = "USART Control register. USART control settings that are more likely to change during operation."] pub mod ctrl; #[doc = "USART Status register. The complete status value can be read here. Writing 1s clears some bits in the register. Some bits can be cleared by writing a 1 to them."] pub struct STAT { register: ::vcell::VolatileCell<u32>, } #[doc = "USART Status register. The complete status value can be read here. Writing 1s clears some bits in the register. Some bits can be cleared by writing a 1 to them."] pub mod stat; #[doc = "Interrupt Enable read and Set register. Contains an individual interrupt enable bit for each potential USART interrupt. A complete value may be read from this register. Writing a 1 to any implemented bit position causes that bit to be set."] pub struct INTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Interrupt Enable read and Set register. Contains an individual interrupt enable bit for each potential USART interrupt. A complete value may be read from this register. Writing a 1 to any implemented bit position causes that bit to be set."] pub mod intenset; #[doc = "Interrupt Enable Clear register. Allows clearing any combination of bits in the INTENSET register. Writing a 1 to any implemented bit position causes the corresponding bit to be cleared."] pub struct INTENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Interrupt Enable Clear register. Allows clearing any combination of bits in the INTENSET register. Writing a 1 to any implemented bit position causes the corresponding bit to be cleared."] pub mod intenclr; #[doc = "Receiver Data register. Contains the last character received."] pub struct RXDATA { register: ::vcell::VolatileCell<u32>, } #[doc = "Receiver Data register. Contains the last character received."] pub mod rxdata; #[doc = "Receiver Data with Status register. Combines the last character received with the current USART receive status. Allows software to recover incoming data and status together."] pub struct RXDATASTAT { register: ::vcell::VolatileCell<u32>, } #[doc = "Receiver Data with Status register. Combines the last character received with the current USART receive status. Allows software to recover incoming data and status together."] pub mod rxdatastat; #[doc = "Transmit Data register. Data to be transmitted is written here."] pub struct TXDATA { register: ::vcell::VolatileCell<u32>, } #[doc = "Transmit Data register. Data to be transmitted is written here."] pub mod txdata; #[doc = "Baud Rate Generator register. 16-bit integer baud rate divisor value."] pub struct BRG { register: ::vcell::VolatileCell<u32>, } #[doc = "Baud Rate Generator register. 16-bit integer baud rate divisor value."] pub mod brg; #[doc = "Interrupt status register. Reflects interrupts that are currently enabled."] pub struct INTSTAT { register: ::vcell::VolatileCell<u32>, } #[doc = "Interrupt status register. Reflects interrupts that are currently enabled."] pub mod intstat;
#![deny(warnings)] use std::task::{Context, Poll}; use futures_util::future; use hyper::service::Service; use hyper::{Body, Request, Response, Server}; const ROOT: &str = "/"; #[derive(Debug)] pub struct Svc; impl Service<Request<Body>> for Svc { type Response = Response<Body>; type Error = hyper::Error; type Future = future::Ready<Result<Self::Response, Self::Error>>; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Ok(()).into() } fn call(&mut self, req: Request<Body>) -> Self::Future { let rsp = Response::builder(); let uri = req.uri(); if uri.path() != ROOT { let body = Body::from(Vec::new()); let rsp = rsp.status(404).body(body).unwrap(); return future::ok(rsp); } let body = Body::from(Vec::from(&b"heyo!"[..])); let rsp = rsp.status(200).body(body).unwrap(); future::ok(rsp) } } pub struct MakeSvc; impl<T> Service<T> for MakeSvc { type Response = Svc; type Error = std::io::Error; type Future = future::Ready<Result<Self::Response, Self::Error>>; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Ok(()).into() } fn call(&mut self, _: T) -> Self::Future { future::ok(Svc) } } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { pretty_env_logger::init(); let addr = "127.0.0.1:1337".parse().unwrap(); let server = Server::bind(&addr).serve(MakeSvc); println!("Listening on http://{}", addr); server.await?; Ok(()) }
use crate::world::space::*; #[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)] pub enum Size { Tiny, Small, Medium, Large, Huge, Gargantuan, } impl Size { pub fn space(self) -> Squares { use Size::*; Squares(match self { Tiny => 0, Small | Medium => 1, Large => 2, Huge => 3, Gargantuan => 4, // XXX "or more" }) } }
//! Serial port implementation for Unix operating systems. extern crate serial_core as core; extern crate libc; extern crate termios; extern crate ioctl_rs as ioctl; pub use tty::*; mod error; mod poll; mod tty;
use std::io::Read; fn main() { let mut buf = String::new(); // 標準入力から全部bufに読み込む std::io::stdin().read_to_string(&mut buf).unwrap(); // 行ごとのiterが取れる let mut iter = buf.split_whitespace(); let y: usize = iter.next().unwrap().parse().unwrap(); let x: usize = iter.next().unwrap().parse().unwrap(); let squares: Vec<Vec<char>> = (0..y) .map(|_| { let str: String = iter.next().unwrap().parse().unwrap(); str.chars().collect::<Vec<char>>() }) .collect(); let mut can_paint = true; 'outer: for (i, line) in squares.iter().enumerate() { for (j, &square) in line.iter().enumerate() { if square == '#' { // before line if i != 0 { if squares[i - 1][j] == '#' { continue; } } // same line if j != 0 { if squares[i][j - 1] == '#' { continue; } } if j < x - 1 { if squares[i][j + 1] == '#' { continue; } } // next line if i < y - 1 { if squares[i + 1][j] == '#' { continue; } } // when the proces reaches here, this squres can't fill. can_paint = false; break 'outer; } } } println!("{}", if can_paint { "Yes" } else { "No" }); }
use color_eyre::eyre::{Result, WrapErr}; use git_conventional::{Commit, FEAT, FIX}; use crate::changelog::{Changelog, Version}; use crate::git::get_commit_messages_after_last_tag; use crate::semver::{bump_version, get_version, Rule}; #[derive(Debug)] struct ConventionalCommits { rule: Rule, features: Vec<String>, fixes: Vec<String>, breaking_changes: Vec<String>, } impl ConventionalCommits { fn from_commits(commits: Vec<Commit>) -> Self { let mut rule = Rule::Patch; let mut features = Vec::new(); let mut fixes = Vec::new(); let mut breaking_changes = Vec::new(); for commit in commits { if commit.breaking() { rule = Rule::Major; breaking_changes.push(commit.description().to_string()); } else if commit.type_() == FEAT { features.push(commit.description().to_string()); if !matches!(rule, Rule::Major) { rule = Rule::Minor; } } else if commit.type_() == FIX { fixes.push(commit.description().to_string()); } } ConventionalCommits { rule, features, fixes, breaking_changes, } } } fn get_conventional_commits_after_last_tag() -> Result<ConventionalCommits> { let commit_messages = get_commit_messages_after_last_tag() .wrap_err("Could not get commit messages after last tag.")?; let commits = commit_messages .iter() .filter_map(|message| Commit::parse(message.trim()).ok()) .collect(); Ok(ConventionalCommits::from_commits(commits)) } pub(crate) fn update_project_from_conventional_commits( state: crate::State, changelog_path: &str, ) -> Result<crate::State> { let ConventionalCommits { rule, features, fixes, breaking_changes, } = get_conventional_commits_after_last_tag()?; let state = bump_version(state, &rule).wrap_err("While bumping version")?; let new_version = get_version().wrap_err("While getting new version")?; let changelog_text = std::fs::read_to_string(changelog_path).wrap_err("While reading CHANGELOG.md")?; let changelog = Changelog::from_markdown(&changelog_text); let changelog_version = Version { title: new_version.to_string(), fixes, features, breaking_changes, }; let changelog = changelog.add_version(changelog_version); std::fs::write(changelog_path, changelog.into_markdown()) .wrap_err_with(|| format!("While writing to {}", changelog_path))?; Ok(state) }
use std::collections::VecDeque; use proconio::input; fn mpow(a: u64, x: u64, m: u64) -> u64 { if x == 0 { 1 % m } else if x == 1 { a % m } else if x % 2 == 0 { mpow(a * a % m, x / 2, m) } else { a * mpow(a, x - 1, m) % m } } fn main() { input! { q: usize, }; const M: u64 = 998244353; let mut s = VecDeque::new(); s.push_back(1); let mut ans = 1; for _ in 0..q { input! { op: u8, }; if op == 1 { input! { x: u64, }; s.push_back(x); ans = (ans * 10 + x) % M; } else if op == 2 { let l = s.len() as u64; let y = s.pop_front().unwrap(); ans = (M + ans - y * mpow(10, l - 1, M) % M) % M; } else { println!("{}", ans); } } }
use serde::{Deserialize, Serialize}; use std::collections::BTreeSet; use std::io; use std::path::Path; use walkdir::WalkDir; type Listing = BTreeSet<String>; #[derive(Deserialize, Serialize)] pub struct Listings { pub d: Listing, pub g: Listing, } fn listdir(base_path: &Path, sub: &str) -> Result<Listing, std::io::Error> { let mut ret = Listing::new(); for entry in WalkDir::new(base_path.join(sub)) { let entry = entry?; if entry.depth() != 1 { continue; } ret.insert( entry .path() .to_str() .ok_or_else(|| { io::Error::new( io::ErrorKind::InvalidData, format!( "invalid directory entry found: '{}'", entry.path().display() ), ) })? .to_string(), ); } Ok(ret) } pub fn update_listings(base_path: &Path) -> Result<(), serde_cbor::Error> { let listings = Listings { d: listdir(base_path, "d")?, g: listdir(base_path, "g")?, }; let p = base_path.join("idx.dat"); let lf = std::fs::File::create(p)?; let mut zstde = zstd::stream::Encoder::new(lf, 10)?; serde_cbor::to_writer(&mut zstde, &listings)?; use std::io::Write; let mut w = zstde.finish()?; w.flush()?; w.sync_all()?; Ok(()) } pub fn parse_listings<R: std::io::Read>(lst: R) -> Result<Listings, serde_cbor::Error> { let zstdd = zstd::stream::Decoder::new(lst)?; let cbord: Listings = serde_cbor::from_reader(zstdd)?; Ok(cbord) }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - power control register"] pub cr1: CR1, #[doc = "0x04 - power control/status register"] pub csr1: CSR1, #[doc = "0x08 - power control register"] pub cr2: CR2, #[doc = "0x0c - power control/status register"] pub csr2: CSR2, } #[doc = "power control 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 [cr1](cr1) module"] pub type CR1 = crate::Reg<u32, _CR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CR1; #[doc = "`read()` method returns [cr1::R](cr1::R) reader structure"] impl crate::Readable for CR1 {} #[doc = "`write(|w| ..)` method takes [cr1::W](cr1::W) writer structure"] impl crate::Writable for CR1 {} #[doc = "power control register"] pub mod cr1; #[doc = "power control/status 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 [csr1](csr1) module"] pub type CSR1 = crate::Reg<u32, _CSR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CSR1; #[doc = "`read()` method returns [csr1::R](csr1::R) reader structure"] impl crate::Readable for CSR1 {} #[doc = "`write(|w| ..)` method takes [csr1::W](csr1::W) writer structure"] impl crate::Writable for CSR1 {} #[doc = "power control/status register"] pub mod csr1; #[doc = "power control 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 [cr2](cr2) module"] pub type CR2 = crate::Reg<u32, _CR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CR2; #[doc = "`read()` method returns [cr2::R](cr2::R) reader structure"] impl crate::Readable for CR2 {} #[doc = "`write(|w| ..)` method takes [cr2::W](cr2::W) writer structure"] impl crate::Writable for CR2 {} #[doc = "power control register"] pub mod cr2; #[doc = "power control/status 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 [csr2](csr2) module"] pub type CSR2 = crate::Reg<u32, _CSR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CSR2; #[doc = "`read()` method returns [csr2::R](csr2::R) reader structure"] impl crate::Readable for CSR2 {} #[doc = "`write(|w| ..)` method takes [csr2::W](csr2::W) writer structure"] impl crate::Writable for CSR2 {} #[doc = "power control/status register"] pub mod csr2;
use serenity::model::prelude::{Activity, OnlineStatus, Ready}; use serenity::model::Permissions; use serenity::prelude::Context; pub struct ReadyEvent; impl ReadyEvent { pub async fn run(ctx: &Context, ready: &Ready) { let perms = Permissions::from_bits(0).unwrap(); let user = &ready.user; ctx.set_presence( Some(Activity::listening("new launch announcements")), OnlineStatus::Online, ) .await; println!( " Ready as {} * Serving {} guilds * Invite URL: {}", user.tag(), ready.guilds.len(), user.invite_url(ctx.clone(), perms).await.unwrap(), ); } }
use failure::Fail; use typed_igo::conjugation::*; #[derive(Debug, Fail, Clone, PartialEq, Eq, Hash)] pub enum ConjugationTransformError { #[fail( display = "This conjugation has no possible suffixes: {:?}", conjugation )] Unsupported { conjugation: Conjugation }, #[fail( display = "If `{}` truely have the specified conjugation {:?}, the suffix of the word should be one of {:?}.", word, conjugation, suffixes_possible )] SuffixNotFound { word: String, conjugation: Conjugation, suffixes_possible: &'static [&'static str], }, } pub fn get_suffixes( kind: ConjugationKind, form: ConjugationForm, ) -> Result<&'static [&'static str], ConjugationTransformError> { use typed_igo::conjugation::ConjugationForm::*; use typed_igo::conjugation::ConjugationKind::*; match (kind, form) { (KahenKuru, ImperativeI) => Ok(&["こい"]), (KahenKuru, Basic) => Ok(&["くる"]), (KahenKuru, NegativeU) => Ok(&["こよ"]), (KahenKuru, Continuous) => Ok(&["き"]), (KahenKuru, ConditionalContraction1) => Ok(&["くりゃ"]), (KahenKuru, SpecialAttributive) => Ok(&["くん"]), (KahenKuru, SpecialAttributive2) => Ok(&["く"]), (KahenKuru, Conditional) => Ok(&["くれ"]), (KahenKuru, Negative) => Ok(&["こ"]), (KahenKuru, ImperativeYo) => Ok(&["こよ"]), (KahenKuruKanji, SpecialAttributive) => Ok(&["来ん"]), (KahenKuruKanji, NegativeU) => Ok(&["来よ"]), (KahenKuruKanji, Negative) => Ok(&["来"]), (KahenKuruKanji, Conditional) => Ok(&["来れ"]), (KahenKuruKanji, ImperativeYo) => Ok(&["来よ"]), (KahenKuruKanji, Basic) => Ok(&["来る"]), (KahenKuruKanji, ConditionalContraction1) => Ok(&["来りゃ"]), (KahenKuruKanji, SpecialAttributive2) => Ok(&["来"]), (KahenKuruKanji, ImperativeI) => Ok(&["来い"]), (KahenKuruKanji, Continuous) => Ok(&["来"]), (SahenSuru, ConditionalContraction1) => Ok(&["すりゃ"]), (SahenSuru, SpecialAttributive) => Ok(&["すん"]), (SahenSuru, SpecialAttributive2) => Ok(&["す"]), (SahenSuru, NegativeNu) => Ok(&["せ"]), (SahenSuru, NegativeU) => Ok(&["しよ", "しょ"]), (SahenSuru, OldBasic) => Ok(&["す"]), (SahenSuru, Negative) => Ok(&["し"]), (SahenSuru, Conditional) => Ok(&["すれ"]), (SahenSuru, ImperativeYo) => Ok(&["せよ"]), (SahenSuru, NegativeReru) => Ok(&["さ"]), (SahenSuru, ImperativeRo) => Ok(&["しろ"]), (SahenSuru, Continuous) => Ok(&["し"]), (SahenSuru, Basic) => Ok(&["する"]), (SahenSuru, ImperativeI) => Ok(&["せい"]), (SahenSuruConnected, Negative) => Ok(&["し"]), (SahenSuruConnected, ConditionalContraction1) => Ok(&["すりゃ"]), (SahenSuruConnected, Conditional) => Ok(&["すれ"]), (SahenSuruConnected, Basic) => Ok(&["する"]), (SahenSuruConnected, OldBasic) => Ok(&["す"]), (SahenSuruConnected, NegativeU) => Ok(&["しよ", "しょ"]), (SahenSuruConnected, ImperativeYo) => Ok(&["せよ"]), (SahenSuruConnected, ImperativeRo) => Ok(&["しろ"]), (SahenSuruConnected, NegativeReru) => Ok(&["せ"]), (SahenZuruConnected, Conditional) => Ok(&["ずれ"]), (SahenZuruConnected, NegativeU) => Ok(&["ぜよ"]), (SahenZuruConnected, OldBasic) => Ok(&["ず"]), (SahenZuruConnected, ConditionalContraction1) => Ok(&["ずりゃ"]), (SahenZuruConnected, ImperativeYo) => Ok(&["ぜよ"]), (SahenZuruConnected, Basic) => Ok(&["ずる"]), (SahenZuruConnected, Negative) => Ok(&["ぜ"]), (Ichidan, Negative) => Ok(&[""]), (Ichidan, Continuous) => Ok(&[""]), (Ichidan, NegativeU) => Ok(&["よ"]), (Ichidan, ConditionalContraction1) => Ok(&["りゃ"]), (Ichidan, SpecialAttributive) => Ok(&["ん"]), (Ichidan, ImperativeYo) => Ok(&["よ"]), (Ichidan, Basic) => Ok(&["る"]), (Ichidan, Conditional) => Ok(&["れ"]), (Ichidan, ImperativeRo) => Ok(&["ろ"]), (IchidanYameru, Basic) => Ok(&["る"]), (GodanKaIonbin, Conditional) => Ok(&["け"]), (GodanKaIonbin, Negative) => Ok(&["か"]), (GodanKaIonbin, ConditionalContraction1) => Ok(&["きゃ"]), (GodanKaIonbin, NegativeU) => Ok(&["こ"]), (GodanKaIonbin, ContinuousTa) => Ok(&["い"]), (GodanKaIonbin, Continuous) => Ok(&["き"]), (GodanKaIonbin, ImperativeE) => Ok(&["け"]), (GodanKaIonbin, Basic) => Ok(&["く"]), (GodanKaSokuonbin, ImperativeE) => Ok(&["け"]), (GodanKaSokuonbin, Negative) => Ok(&["か"]), (GodanKaSokuonbin, NegativeU) => Ok(&["こ"]), (GodanKaSokuonbin, Conditional) => Ok(&["け"]), (GodanKaSokuonbin, Continuous) => Ok(&["き"]), (GodanKaSokuonbin, ContinuousTa) => Ok(&["っ"]), (GodanKaSokuonbin, ConditionalContraction1) => Ok(&["きゃ"]), (GodanKaSokuonbin, Basic) => Ok(&["く"]), (GodanKaSokuonbinYuku, Conditional) => Ok(&["け"]), (GodanKaSokuonbinYuku, ImperativeE) => Ok(&["け"]), (GodanKaSokuonbinYuku, ConditionalContraction1) => Ok(&["きゃ"]), (GodanKaSokuonbinYuku, Basic) => Ok(&["く"]), (GodanKaSokuonbinYuku, Negative) => Ok(&["か"]), (GodanKaSokuonbinYuku, NegativeU) => Ok(&["こ"]), (GodanKaSokuonbinYuku, Continuous) => Ok(&["き"]), (GodanGa, Basic) => Ok(&["ぐ"]), (GodanGa, NegativeU) => Ok(&["ご"]), (GodanGa, ContinuousTa) => Ok(&["い"]), (GodanGa, Conditional) => Ok(&["げ"]), (GodanGa, Continuous) => Ok(&["ぎ"]), (GodanGa, ImperativeE) => Ok(&["げ"]), (GodanGa, ConditionalContraction1) => Ok(&["ぎゃ"]), (GodanGa, Negative) => Ok(&["が"]), (GodanSa, ImperativeE) => Ok(&["せ"]), (GodanSa, Negative) => Ok(&["さ"]), (GodanSa, NegativeU) => Ok(&["そ"]), (GodanSa, Basic) => Ok(&["す"]), (GodanSa, Conditional) => Ok(&["せ"]), (GodanSa, ConditionalContraction1) => Ok(&["しゃ"]), (GodanSa, Continuous) => Ok(&["し"]), (GodanTa, ConditionalContraction1) => Ok(&["ちゃ"]), (GodanTa, Continuous) => Ok(&["ち"]), (GodanTa, NegativeU) => Ok(&["と"]), (GodanTa, Negative) => Ok(&["た"]), (GodanTa, Basic) => Ok(&["つ"]), (GodanTa, ContinuousTa) => Ok(&["っ"]), (GodanTa, Conditional) => Ok(&["て"]), (GodanTa, ImperativeE) => Ok(&["て"]), (GodanNa, Continuous) => Ok(&["に"]), (GodanNa, ConditionalContraction1) => Ok(&["にゃ"]), (GodanNa, NegativeU) => Ok(&["の"]), (GodanNa, ImperativeE) => Ok(&["ね"]), (GodanNa, ContinuousTa) => Ok(&["ん"]), (GodanNa, Conditional) => Ok(&["ね"]), (GodanNa, Basic) => Ok(&["ぬ"]), (GodanNa, Negative) => Ok(&["な"]), (GodanBa, Basic) => Ok(&["ぶ"]), (GodanBa, NegativeU) => Ok(&["ぼ"]), (GodanBa, ConditionalContraction1) => Ok(&["びゃ"]), (GodanBa, ImperativeE) => Ok(&["べ"]), (GodanBa, Negative) => Ok(&["ば"]), (GodanBa, Conditional) => Ok(&["べ"]), (GodanBa, ContinuousTa) => Ok(&["ん"]), (GodanBa, Continuous) => Ok(&["び"]), (GodanMa, Conditional) => Ok(&["め"]), (GodanMa, Basic) => Ok(&["む"]), (GodanMa, NegativeU) => Ok(&["も"]), (GodanMa, Continuous) => Ok(&["み"]), (GodanMa, ContinuousTa) => Ok(&["ん"]), (GodanMa, Negative) => Ok(&["ま"]), (GodanMa, ImperativeE) => Ok(&["め"]), (GodanMa, ConditionalContraction1) => Ok(&["みゃ"]), (GodanRa, SpecialAttributive2) => Ok(&[""]), (GodanRa, NegativeU) => Ok(&["ろ"]), (GodanRa, ImperativeE) => Ok(&["れ"]), (GodanRa, ConditionalContraction1) => Ok(&["りゃ"]), (GodanRa, Negative) => Ok(&["ら"]), (GodanRa, Conditional) => Ok(&["れ"]), (GodanRa, Continuous) => Ok(&["り"]), (GodanRa, SpecialAttributive) => Ok(&["ん"]), (GodanRa, Basic) => Ok(&["る"]), (GodanRa, NegativeSpecial) => Ok(&["ん"]), (GodanRa, ContinuousTa) => Ok(&["っ"]), (GodanRaAru, Continuous) => Ok(&["り"]), (GodanRaAru, Negative) => Ok(&["ら"]), (GodanRaAru, ContinuousTa) => Ok(&["っ"]), (GodanRaAru, ConditionalContraction1) => Ok(&["りゃ"]), (GodanRaAru, Conditional) => Ok(&["れ"]), (GodanRaAru, SpecialAttributive) => Ok(&["ん"]), (GodanRaAru, ImperativeE) => Ok(&["れ"]), (GodanRaAru, NegativeU) => Ok(&["ろ"]), (GodanRaAru, Basic) => Ok(&["る"]), (GodanRaSpecial, Negative) => Ok(&["ら"]), (GodanRaSpecial, Basic) => Ok(&["る"]), (GodanRaSpecial, NegativeSpecial) => Ok(&["ん"]), (GodanRaSpecial, Conditional) => Ok(&["れ"]), (GodanRaSpecial, Continuous) => Ok(&["い"]), (GodanRaSpecial, ImperativeI) => Ok(&["い"]), (GodanRaSpecial, ConditionalContraction1) => Ok(&["りゃ"]), (GodanRaSpecial, ContinuousTa) => Ok(&["っ"]), (GodanRaSpecial, ImperativeE) => Ok(&["れ"]), (GodanRaSpecial, NegativeU) => Ok(&["ろ"]), (GodanWaUonbin, Basic) => Ok(&["う"]), (GodanWaUonbin, ContinuousTa) => Ok(&["う"]), (GodanWaUonbin, Continuous) => Ok(&["い"]), (GodanWaUonbin, Conditional) => Ok(&["え"]), (GodanWaUonbin, ImperativeE) => Ok(&["え"]), (GodanWaUonbin, Negative) => Ok(&["わ"]), (GodanWaUonbin, NegativeU) => Ok(&["お"]), (GodanWaSokuonbin, NegativeU) => Ok(&["お"]), (GodanWaSokuonbin, Continuous) => Ok(&["い"]), (GodanWaSokuonbin, Conditional) => Ok(&["え"]), (GodanWaSokuonbin, ImperativeE) => Ok(&["え"]), (GodanWaSokuonbin, Basic) => Ok(&["う"]), (GodanWaSokuonbin, ContinuousTa) => Ok(&["っ"]), (GodanWaSokuonbin, Negative) => Ok(&["わ"]), (YodanKa, ImperativeE) => Ok(&["け"]), (YodanKa, Negative) => Ok(&["か"]), (YodanKa, Continuous) => Ok(&["き"]), (YodanKa, Basic) => Ok(&["く"]), (YodanKa, Conditional) => Ok(&["け"]), (YodanGa, ImperativeE) => Ok(&["げ"]), (YodanGa, Conditional) => Ok(&["げ"]), (YodanGa, Negative) => Ok(&["が"]), (YodanGa, Basic) => Ok(&["ぐ"]), (YodanGa, Continuous) => Ok(&["ぎ"]), (YodanSa, Continuous) => Ok(&["し"]), (YodanSa, Negative) => Ok(&["さ"]), (YodanSa, Basic) => Ok(&["す"]), (YodanSa, ImperativeE) => Ok(&["せ"]), (YodanSa, Conditional) => Ok(&["せ"]), (YodanTa, Negative) => Ok(&["た"]), (YodanTa, ImperativeE) => Ok(&["て"]), (YodanTa, Basic) => Ok(&["つ"]), (YodanTa, Continuous) => Ok(&["ち"]), (YodanTa, Conditional) => Ok(&["て"]), (YodanBa, Continuous) => Ok(&["び"]), (YodanBa, Negative) => Ok(&["ば"]), (YodanBa, Conditional) => Ok(&["べ"]), (YodanBa, Basic) => Ok(&["ぶ"]), (YodanBa, ImperativeE) => Ok(&["べ"]), (YodanMa, ImperativeE) => Ok(&["め"]), (YodanMa, Continuous) => Ok(&["み"]), (YodanMa, Basic) => Ok(&["む"]), (YodanMa, Negative) => Ok(&["ま"]), (YodanMa, Conditional) => Ok(&["め"]), (YodanRa, Continuous) => Ok(&["り"]), (YodanRa, ImperativeE) => Ok(&["れ"]), (YodanRa, Negative) => Ok(&["ら"]), (YodanRa, Basic) => Ok(&["る"]), (YodanRa, Conditional) => Ok(&["れ"]), (YodanHa, ImperativeE) => Ok(&["へ"]), (YodanHa, Negative) => Ok(&["は"]), (YodanHa, Continuous) => Ok(&["ひ"]), (YodanHa, Conditional) => Ok(&["へ"]), (YodanHa, Basic) => Ok(&["ふ"]), (Rahen, Continuous) => Ok(&["り"]), (Rahen, AttributiveConjunction) => Ok(&["る"]), (Rahen, Basic) => Ok(&["り"]), (Rahen, Conditional) => Ok(&["れ"]), (Rahen, Negative) => Ok(&["ら"]), (Rahen, ImperativeE) => Ok(&["れ"]), (KaminiDa, ModernBasic) => Ok(&["ず"]), (KaminiDa, Basic) => Ok(&["づ"]), (KaminiDa, Negative) => Ok(&["ぢ"]), (KaminiDa, Continuous) => Ok(&["ぢ"]), (KaminiDa, AttributiveConjunction) => Ok(&["づる", "ずる"]), (KaminiDa, Conditional) => Ok(&["づれ", "ずれ"]), (KaminiDa, ImperativeYo) => Ok(&["ぢよ"]), (KaminiHa, AttributiveConjunction) => Ok(&["ふる"]), (KaminiHa, Conditional) => Ok(&["ふれ"]), (KaminiHa, ImperativeYo) => Ok(&["ひよ"]), (KaminiHa, Negative) => Ok(&["ひ"]), (KaminiHa, Basic) => Ok(&["ふ"]), (KaminiHa, Continuous) => Ok(&["ひ"]), (ShimoniA, Continuous) => Ok(&["え"]), (ShimoniA, Conditional) => Ok(&["うれ"]), (ShimoniA, Negative) => Ok(&["え"]), (ShimoniA, ImperativeYo) => Ok(&["えよ"]), (ShimoniA, Basic) => Ok(&["う"]), (ShimoniA, AttributiveConjunction) => Ok(&["うる"]), (ShimoniKa, AttributiveConjunction) => Ok(&["くる"]), (ShimoniKa, Conditional) => Ok(&["くれ"]), (ShimoniKa, ImperativeYo) => Ok(&["けよ"]), (ShimoniKa, Continuous) => Ok(&["け"]), (ShimoniKa, Negative) => Ok(&["け"]), (ShimoniKa, Basic) => Ok(&["く"]), (ShimoniGa, Conditional) => Ok(&["ぐれ"]), (ShimoniGa, Negative) => Ok(&["げ"]), (ShimoniGa, Basic) => Ok(&["ぐ"]), (ShimoniGa, AttributiveConjunction) => Ok(&["ぐる"]), (ShimoniGa, ImperativeYo) => Ok(&["げよ"]), (ShimoniGa, Continuous) => Ok(&["げ"]), (ShimoniSa, Negative) => Ok(&["せ"]), (ShimoniSa, Basic) => Ok(&["す"]), (ShimoniSa, Conditional) => Ok(&["すれ"]), (ShimoniSa, Continuous) => Ok(&["せ"]), (ShimoniSa, AttributiveConjunction) => Ok(&["する"]), (ShimoniSa, ImperativeYo) => Ok(&["せよ"]), (ShimoniZa, ImperativeYo) => Ok(&["ぜよ"]), (ShimoniZa, Basic) => Ok(&["ず"]), (ShimoniZa, Negative) => Ok(&["ぜ"]), (ShimoniZa, Continuous) => Ok(&["ぜ"]), (ShimoniZa, AttributiveConjunction) => Ok(&["ずる"]), (ShimoniZa, Conditional) => Ok(&["ずれ"]), (ShimoniTa, Basic) => Ok(&["つ"]), (ShimoniTa, Negative) => Ok(&["て"]), (ShimoniTa, ImperativeYo) => Ok(&["てよ"]), (ShimoniTa, AttributiveConjunction) => Ok(&["つる"]), (ShimoniTa, Conditional) => Ok(&["つれ"]), (ShimoniTa, Continuous) => Ok(&["て"]), (ShimoniDa, Negative) => Ok(&["で"]), (ShimoniDa, Conditional) => Ok(&["づれ"]), (ShimoniDa, AttributiveConjunction) => Ok(&["づる"]), (ShimoniDa, Continuous) => Ok(&["で"]), (ShimoniDa, ImperativeYo) => Ok(&["でよ"]), (ShimoniDa, Basic) => Ok(&["づ"]), (ShimoniNa, Basic) => Ok(&["ぬ"]), (ShimoniNa, ImperativeYo) => Ok(&["ねよ"]), (ShimoniNa, AttributiveConjunction) => Ok(&["ぬる"]), (ShimoniNa, Conditional) => Ok(&["ぬれ"]), (ShimoniNa, Continuous) => Ok(&["ね"]), (ShimoniNa, Negative) => Ok(&["ね"]), (ShimoniHa, AttributiveConjunction) => Ok(&["ふる"]), (ShimoniHa, Negative) => Ok(&["へ"]), (ShimoniHa, ImperativeYo) => Ok(&["へよ"]), (ShimoniHa, Conditional) => Ok(&["ふれ"]), (ShimoniHa, Basic) => Ok(&["ふ"]), (ShimoniHa, Continuous) => Ok(&["へ"]), (ShimoniBa, AttributiveConjunction) => Ok(&["ぶる"]), (ShimoniBa, Negative) => Ok(&["べ"]), (ShimoniBa, Continuous) => Ok(&["べ"]), (ShimoniBa, Conditional) => Ok(&["ぶれ"]), (ShimoniBa, ImperativeYo) => Ok(&["べよ"]), (ShimoniBa, Basic) => Ok(&["ぶ"]), (ShimoniMa, Continuous) => Ok(&["め"]), (ShimoniMa, ImperativeYo) => Ok(&["めよ"]), (ShimoniMa, Negative) => Ok(&["め"]), (ShimoniMa, Basic) => Ok(&["む"]), (ShimoniMa, AttributiveConjunction) => Ok(&["むる"]), (ShimoniMa, Conditional) => Ok(&["むれ"]), (ShimoniYa, Conditional) => Ok(&["ゆれ"]), (ShimoniYa, AttributiveConjunction) => Ok(&["ゆる"]), (ShimoniYa, Continuous) => Ok(&["え"]), (ShimoniYa, Negative) => Ok(&["え"]), (ShimoniYa, ImperativeYo) => Ok(&["えよ"]), (ShimoniYa, Basic) => Ok(&["ゆ"]), (ShimoniRa, Conditional) => Ok(&["るれ"]), (ShimoniRa, ImperativeYo) => Ok(&["れよ"]), (ShimoniRa, Negative) => Ok(&["れ"]), (ShimoniRa, AttributiveConjunction) => Ok(&["るる"]), (ShimoniRa, Basic) => Ok(&["る"]), (ShimoniRa, Continuous) => Ok(&["れ"]), (ShimoniWa, AttributiveConjunction) => Ok(&["うる"]), (ShimoniWa, Negative) => Ok(&["ゑ"]), (ShimoniWa, Conditional) => Ok(&["うれ"]), (ShimoniWa, Continuous) => Ok(&["ゑ"]), (ShimoniWa, ImperativeYo) => Ok(&["ゑよ"]), (ShimoniWa, Basic) => Ok(&["う"]), (ShimoniU, Conditional) => Ok(&["得れ"]), (ShimoniU, Basic) => Ok(&["得"]), (ShimoniU, Continuous) => Ok(&["得"]), (ShimoniU, AttributiveConjunction) => Ok(&["得る"]), (ShimoniU, ImperativeYo) => Ok(&["得よ"]), (ShimoniU, Negative) => Ok(&["得"]), (ShimoniU, NegativeU) => Ok(&["得よ"]), (IchidanKureru, ImperativeE) => Ok(&["れ"]), (IchidanKureru, ConditionalContraction1) => Ok(&["れりゃ"]), (IchidanKureru, ImperativeYo) => Ok(&["れよ"]), (IchidanKureru, Continuous) => Ok(&["れ"]), (IchidanKureru, NegativeU) => Ok(&["れよ"]), (IchidanKureru, Basic) => Ok(&["れる"]), (IchidanKureru, Conditional) => Ok(&["れれ"]), (IchidanKureru, ImperativeRo) => Ok(&["れろ"]), (IchidanKureru, NegativeSpecial) => Ok(&["ん"]), (IchidanKureru, Negative) => Ok(&["れ"]), (IchidanRu, Conditional) => Ok(&["れ"]), (IchidanRu, Basic) => Ok(&["る"]), (IchidanRu, ImperativeRo) => Ok(&["ろ"]), (IchidanRu, ConditionalContraction1) => Ok(&["りゃ"]), (AdjectiveAUO, Conditional) => Ok(&["けれ"]), (AdjectiveAUO, NegativeNu) => Ok(&["から"]), (AdjectiveAUO, Basic) => Ok(&["い"]), (AdjectiveAUO, ImperativeE) => Ok(&["かれ"]), (AdjectiveAUO, OldBasic) => Ok(&["し"]), (AdjectiveAUO, ConditionalContraction1) => Ok(&["けりゃ"]), (AdjectiveAUO, ContinuousTa) => Ok(&["かっ"]), (AdjectiveAUO, NegativeU) => Ok(&["かろ"]), (AdjectiveAUO, AttributiveConjunction) => Ok(&["き"]), (AdjectiveAUO, ConditionalContraction2) => Ok(&["きゃ"]), (AdjectiveAUO, Garu) => Ok(&[""]), (AdjectiveAUO, ContinuousTe) => Ok(&["く", "くっ"]), (AdjectiveAUO, ContinuousGozai) => Ok(&["う", "ぅ"]), (AdjectiveI, ConditionalContraction1) => Ok(&["けりゃ"]), (AdjectiveI, ConditionalContraction2) => Ok(&["きゃ"]), (AdjectiveI, ContinuousTa) => Ok(&["かっ"]), (AdjectiveI, OldBasic) => Ok(&[""]), (AdjectiveI, Garu) => Ok(&[""]), (AdjectiveI, NegativeNu) => Ok(&["から"]), (AdjectiveI, ContinuousTe) => Ok(&["く", "くっ"]), (AdjectiveI, Conditional) => Ok(&["けれ"]), (AdjectiveI, Basic) => Ok(&["い"]), (AdjectiveI, ContinuousGozai) => Ok(&["ゅう", "ゅぅ"]), (AdjectiveI, AttributiveConjunction) => Ok(&["き"]), (AdjectiveI, NegativeU) => Ok(&["かろ"]), (AdjectiveI, ImperativeE) => Ok(&["かれ"]), (SpecialNai, ConditionalContraction1) => Ok(&["なけりゃ"]), (SpecialNai, Conditional) => Ok(&["なけれ"]), (SpecialNai, OldBasic) => Ok(&["なし"]), (SpecialNai, ContinuousTa) => Ok(&["なかっ", "なかつ"]), (SpecialNai, ContinuousGozai) => Ok(&["のう"]), (SpecialNai, NegativeU) => Ok(&["なかろ"]), (SpecialNai, ContinuousDe) => Ok(&["ない"]), (SpecialNai, Garu) => Ok(&["な"]), (SpecialNai, ContinuousTe) => Ok(&["なく", "なくっ"]), (SpecialNai, NegativeNu) => Ok(&["なから"]), (SpecialNai, ConditionalContraction2) => Ok(&["なきゃ"]), (SpecialNai, OnbinBasic) => Ok(&["ねえ", "ねぇ"]), (SpecialNai, Basic) => Ok(&["ない"]), (SpecialNai, ImperativeE) => Ok(&["なかれ"]), (SpecialNai, AttributiveConjunction) => Ok(&["なき"]), (SpecialTai, OnbinBasic) => Ok(&["てえ", "てぇ"]), (SpecialTai, OldBasic) => Ok(&["たし"]), (SpecialTai, NegativeNu) => Ok(&["たから"]), (SpecialTai, NegativeU) => Ok(&["たかろ"]), (SpecialTai, Conditional) => Ok(&["たけれ"]), (SpecialTai, AttributiveConjunction) => Ok(&["たき"]), (SpecialTai, ConditionalContraction2) => Ok(&["たきゃ"]), (SpecialTai, ConditionalContraction1) => Ok(&["たけりゃ"]), (SpecialTai, Garu) => Ok(&["た"]), (SpecialTai, Basic) => Ok(&["たい"]), (SpecialTai, ContinuousTa) => Ok(&["たかっ", "たかつ"]), (SpecialTai, ContinuousTe) => Ok(&["たく", "たくっ"]), (SpecialTai, ContinuousGozai) => Ok(&["とう"]), (SpecialTa, Conditional) => Ok(&["ら"]), (SpecialTa, Basic) => Ok(&[""]), (SpecialTa, Negative) => Ok(&["ろ"]), (SpecialDa, ContinuousTa) => Ok(&["だっ"]), (SpecialDa, ImperativeE) => Ok(&["なれ"]), (SpecialDa, Continuous) => Ok(&["で"]), (SpecialDa, Conditional) => Ok(&["なら"]), (SpecialDa, AttributiveConjunction) => Ok(&["な"]), (SpecialDa, Negative) => Ok(&["だろ", "だら"]), (SpecialDa, Basic) => Ok(&["だ"]), (SpecialDesu, Continuous) => Ok(&["し"]), (SpecialDesu, Basic) => Ok(&["す"]), (SpecialDesu, Negative) => Ok(&["しょ"]), (SpecialJa, Continuous) => Ok(&["っ"]), (SpecialJa, Basic) => Ok(&[""]), (SpecialJa, Negative) => Ok(&["ろ"]), (SpecialMasu, Negative) => Ok(&["せ"]), (SpecialMasu, NegativeU) => Ok(&["しょ"]), (SpecialMasu, Conditional) => Ok(&["すれ"]), (SpecialMasu, ImperativeE) => Ok(&["せ"]), (SpecialMasu, Continuous) => Ok(&["し"]), (SpecialMasu, Basic) => Ok(&["す"]), (SpecialMasu, ImperativeI) => Ok(&["し"]), (SpecialNu, ContinuousNi) => Ok(&["ず"]), (SpecialNu, Conditional) => Ok(&["ね", "ざれ", "ずん"]), (SpecialNu, Basic) => Ok(&["ぬ"]), (SpecialNu, Continuous) => Ok(&["ざり"]), (SpecialNu, AttributiveConjunction) => Ok(&["ざる"]), (SpecialNu, OldBasic) => Ok(&["ず"]), (OldBeshi, Negative) => Ok(&["から"]), (OldBeshi, AttributiveConjunction) => Ok(&["き"]), (OldBeshi, Conditional) => Ok(&["けれ"]), (OldBeshi, Basic) => Ok(&["し"]), (OldBeshi, Continuous) => Ok(&["く"]), (OldGotoshi, Continuous) => Ok(&["く"]), (OldGotoshi, Basic) => Ok(&["し"]), (OldGotoshi, AttributiveConjunction) => Ok(&["き"]), (OldNari, Negative) => Ok(&["ら"]), (OldNari, Conditional) => Ok(&["れ"]), (OldNari, ImperativeE) => Ok(&["れ"]), (OldNari, Basic) => Ok(&["り"]), (OldNari, AttributiveConjunction) => Ok(&["る"]), (OldMaji, Conditional) => Ok(&["けれ"]), (OldMaji, Continuous) => Ok(&["く"]), (OldMaji, Basic) => Ok(&[""]), (OldMaji, AttributiveConjunction) => Ok(&["き"]), (OldShimu, ImperativeYo) => Ok(&["めよ"]), (OldShimu, Basic) => Ok(&["む"]), (OldShimu, Continuous) => Ok(&["め"]), (OldShimu, Negative) => Ok(&["め"]), (OldShimu, AttributiveConjunction) => Ok(&["むる"]), (OldShimu, Conditional) => Ok(&["むれ"]), (OldShimu, ImperativeE) => Ok(&["むれ"]), (OldKi, ImperativeE) => Ok(&["しか"]), (OldKi, Basic) => Ok(&["き"]), (OldKi, AttributiveConjunction) => Ok(&["し"]), (OldKeri, Basic) => Ok(&["り"]), (OldKeri, AttributiveConjunction) => Ok(&["る"]), (OldRi, AttributiveConjunction) => Ok(&["る"]), (OldRi, Basic) => Ok(&["り"]), (OldRu, ImperativeYo) => Ok(&["れよ"]), (OldRu, Basic) => Ok(&["る"]), (OldRu, Negative) => Ok(&["れ"]), (OldRu, Conditional) => Ok(&["るれ"]), (OldRu, ImperativeE) => Ok(&["るれ"]), (OldRu, AttributiveConjunction) => Ok(&["るる"]), (OldRu, Continuous) => Ok(&["れ"]), (NoConjugation, Basic) => Ok(&[""]), (AdjectiveII, BasicSokuonbin) => Ok(&["いっ", "いいっ"]), (AdjectiveII, Basic) => Ok(&["い"]), (SpecialDosu, Basic) => Ok(&["す"]), (IchidanEru, Conditional) => Ok(&["れ"]), (IchidanEru, Basic) => Ok(&["る"]), (SpecialYa, Continuous) => Ok(&["っ"]), (SpecialYa, Negative) => Ok(&["ろ"]), (SpecialYa, Basic) => Ok(&[""]), _ => Err(ConjugationTransformError::Unsupported { conjugation: Conjugation { kind, form }, }), } } pub fn convert( orig: &str, kind: ConjugationKind, from: ConjugationForm, to: ConjugationForm, ) -> Result<String, ConjugationTransformError> { let from_suffixes = get_suffixes(kind, from)?; let from_suffix = from_suffixes .iter() .find(|&suffix| orig.ends_with(suffix)) .ok_or_else(|| ConjugationTransformError::SuffixNotFound { word: orig.into(), conjugation: Conjugation { kind, form: from }, suffixes_possible: from_suffixes, })?; let orig_base = &orig[0..orig.len() - from_suffix.len()]; // TODO: make a good way to select appropriate candidate? // currently use first one in any ways. let to_suffix = get_suffixes(kind, to)? .get(0) .expect("cannot get conjugation suffix."); Ok(format!("{}{}", orig_base, to_suffix)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_convert() { assert_eq!( convert( "こ", ConjugationKind::KahenKuru, ConjugationForm::Negative, ConjugationForm::Basic, ), Ok("くる".into()) ); assert_eq!( convert( "する", ConjugationKind::SahenSuru, ConjugationForm::Basic, ConjugationForm::Continuous, ), Ok("し".into()) ); assert_eq!( convert( "する", ConjugationKind::SahenSuru, ConjugationForm::Basic, ConjugationForm::Continuous, ), Ok("し".into()) ); } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::_3_GENB { #[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() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = "Possible values of the field `PWM_3_GENB_ACTZERO`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTZEROR { #[doc = "Do nothing"] PWM_3_GENB_ACTZERO_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTZERO_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTZERO_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTZERO_ONE, } impl PWM_3_GENB_ACTZEROR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_NONE => 0, PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_INV => 1, PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_ZERO => 2, PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENB_ACTZEROR { match value { 0 => PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_NONE, 1 => PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_INV, 2 => PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_ZERO, 3 => PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTZERO_NONE`"] #[inline(always)] pub fn is_pwm_3_genb_actzero_none(&self) -> bool { *self == PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTZERO_INV`"] #[inline(always)] pub fn is_pwm_3_genb_actzero_inv(&self) -> bool { *self == PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_INV } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTZERO_ZERO`"] #[inline(always)] pub fn is_pwm_3_genb_actzero_zero(&self) -> bool { *self == PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTZERO_ONE`"] #[inline(always)] pub fn is_pwm_3_genb_actzero_one(&self) -> bool { *self == PWM_3_GENB_ACTZEROR::PWM_3_GENB_ACTZERO_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENB_ACTZERO`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTZEROW { #[doc = "Do nothing"] PWM_3_GENB_ACTZERO_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTZERO_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTZERO_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTZERO_ONE, } impl PWM_3_GENB_ACTZEROW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENB_ACTZEROW::PWM_3_GENB_ACTZERO_NONE => 0, PWM_3_GENB_ACTZEROW::PWM_3_GENB_ACTZERO_INV => 1, PWM_3_GENB_ACTZEROW::PWM_3_GENB_ACTZERO_ZERO => 2, PWM_3_GENB_ACTZEROW::PWM_3_GENB_ACTZERO_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENB_ACTZEROW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENB_ACTZEROW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENB_ACTZEROW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_genb_actzero_none(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTZEROW::PWM_3_GENB_ACTZERO_NONE) } #[doc = "Invert pwmB"] #[inline(always)] pub fn pwm_3_genb_actzero_inv(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTZEROW::PWM_3_GENB_ACTZERO_INV) } #[doc = "Drive pwmB Low"] #[inline(always)] pub fn pwm_3_genb_actzero_zero(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTZEROW::PWM_3_GENB_ACTZERO_ZERO) } #[doc = "Drive pwmB High"] #[inline(always)] pub fn pwm_3_genb_actzero_one(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTZEROW::PWM_3_GENB_ACTZERO_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 0); self.w.bits |= ((value as u32) & 3) << 0; self.w } } #[doc = "Possible values of the field `PWM_3_GENB_ACTLOAD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTLOADR { #[doc = "Do nothing"] PWM_3_GENB_ACTLOAD_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTLOAD_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTLOAD_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTLOAD_ONE, } impl PWM_3_GENB_ACTLOADR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_NONE => 0, PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_INV => 1, PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_ZERO => 2, PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENB_ACTLOADR { match value { 0 => PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_NONE, 1 => PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_INV, 2 => PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_ZERO, 3 => PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTLOAD_NONE`"] #[inline(always)] pub fn is_pwm_3_genb_actload_none(&self) -> bool { *self == PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTLOAD_INV`"] #[inline(always)] pub fn is_pwm_3_genb_actload_inv(&self) -> bool { *self == PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_INV } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTLOAD_ZERO`"] #[inline(always)] pub fn is_pwm_3_genb_actload_zero(&self) -> bool { *self == PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTLOAD_ONE`"] #[inline(always)] pub fn is_pwm_3_genb_actload_one(&self) -> bool { *self == PWM_3_GENB_ACTLOADR::PWM_3_GENB_ACTLOAD_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENB_ACTLOAD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTLOADW { #[doc = "Do nothing"] PWM_3_GENB_ACTLOAD_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTLOAD_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTLOAD_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTLOAD_ONE, } impl PWM_3_GENB_ACTLOADW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENB_ACTLOADW::PWM_3_GENB_ACTLOAD_NONE => 0, PWM_3_GENB_ACTLOADW::PWM_3_GENB_ACTLOAD_INV => 1, PWM_3_GENB_ACTLOADW::PWM_3_GENB_ACTLOAD_ZERO => 2, PWM_3_GENB_ACTLOADW::PWM_3_GENB_ACTLOAD_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENB_ACTLOADW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENB_ACTLOADW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENB_ACTLOADW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_genb_actload_none(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTLOADW::PWM_3_GENB_ACTLOAD_NONE) } #[doc = "Invert pwmB"] #[inline(always)] pub fn pwm_3_genb_actload_inv(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTLOADW::PWM_3_GENB_ACTLOAD_INV) } #[doc = "Drive pwmB Low"] #[inline(always)] pub fn pwm_3_genb_actload_zero(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTLOADW::PWM_3_GENB_ACTLOAD_ZERO) } #[doc = "Drive pwmB High"] #[inline(always)] pub fn pwm_3_genb_actload_one(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTLOADW::PWM_3_GENB_ACTLOAD_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 2); self.w.bits |= ((value as u32) & 3) << 2; self.w } } #[doc = "Possible values of the field `PWM_3_GENB_ACTCMPAU`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTCMPAUR { #[doc = "Do nothing"] PWM_3_GENB_ACTCMPAU_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTCMPAU_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTCMPAU_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTCMPAU_ONE, } impl PWM_3_GENB_ACTCMPAUR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_NONE => 0, PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_INV => 1, PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_ZERO => 2, PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENB_ACTCMPAUR { match value { 0 => PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_NONE, 1 => PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_INV, 2 => PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_ZERO, 3 => PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPAU_NONE`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpau_none(&self) -> bool { *self == PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPAU_INV`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpau_inv(&self) -> bool { *self == PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_INV } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPAU_ZERO`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpau_zero(&self) -> bool { *self == PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPAU_ONE`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpau_one(&self) -> bool { *self == PWM_3_GENB_ACTCMPAUR::PWM_3_GENB_ACTCMPAU_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENB_ACTCMPAU`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTCMPAUW { #[doc = "Do nothing"] PWM_3_GENB_ACTCMPAU_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTCMPAU_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTCMPAU_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTCMPAU_ONE, } impl PWM_3_GENB_ACTCMPAUW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENB_ACTCMPAUW::PWM_3_GENB_ACTCMPAU_NONE => 0, PWM_3_GENB_ACTCMPAUW::PWM_3_GENB_ACTCMPAU_INV => 1, PWM_3_GENB_ACTCMPAUW::PWM_3_GENB_ACTCMPAU_ZERO => 2, PWM_3_GENB_ACTCMPAUW::PWM_3_GENB_ACTCMPAU_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENB_ACTCMPAUW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENB_ACTCMPAUW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENB_ACTCMPAUW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_genb_actcmpau_none(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPAUW::PWM_3_GENB_ACTCMPAU_NONE) } #[doc = "Invert pwmB"] #[inline(always)] pub fn pwm_3_genb_actcmpau_inv(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPAUW::PWM_3_GENB_ACTCMPAU_INV) } #[doc = "Drive pwmB Low"] #[inline(always)] pub fn pwm_3_genb_actcmpau_zero(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPAUW::PWM_3_GENB_ACTCMPAU_ZERO) } #[doc = "Drive pwmB High"] #[inline(always)] pub fn pwm_3_genb_actcmpau_one(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPAUW::PWM_3_GENB_ACTCMPAU_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 4); self.w.bits |= ((value as u32) & 3) << 4; self.w } } #[doc = "Possible values of the field `PWM_3_GENB_ACTCMPAD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTCMPADR { #[doc = "Do nothing"] PWM_3_GENB_ACTCMPAD_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTCMPAD_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTCMPAD_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTCMPAD_ONE, } impl PWM_3_GENB_ACTCMPADR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_NONE => 0, PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_INV => 1, PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_ZERO => 2, PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENB_ACTCMPADR { match value { 0 => PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_NONE, 1 => PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_INV, 2 => PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_ZERO, 3 => PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPAD_NONE`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpad_none(&self) -> bool { *self == PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPAD_INV`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpad_inv(&self) -> bool { *self == PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_INV } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPAD_ZERO`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpad_zero(&self) -> bool { *self == PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPAD_ONE`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpad_one(&self) -> bool { *self == PWM_3_GENB_ACTCMPADR::PWM_3_GENB_ACTCMPAD_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENB_ACTCMPAD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTCMPADW { #[doc = "Do nothing"] PWM_3_GENB_ACTCMPAD_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTCMPAD_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTCMPAD_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTCMPAD_ONE, } impl PWM_3_GENB_ACTCMPADW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENB_ACTCMPADW::PWM_3_GENB_ACTCMPAD_NONE => 0, PWM_3_GENB_ACTCMPADW::PWM_3_GENB_ACTCMPAD_INV => 1, PWM_3_GENB_ACTCMPADW::PWM_3_GENB_ACTCMPAD_ZERO => 2, PWM_3_GENB_ACTCMPADW::PWM_3_GENB_ACTCMPAD_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENB_ACTCMPADW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENB_ACTCMPADW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENB_ACTCMPADW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_genb_actcmpad_none(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPADW::PWM_3_GENB_ACTCMPAD_NONE) } #[doc = "Invert pwmB"] #[inline(always)] pub fn pwm_3_genb_actcmpad_inv(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPADW::PWM_3_GENB_ACTCMPAD_INV) } #[doc = "Drive pwmB Low"] #[inline(always)] pub fn pwm_3_genb_actcmpad_zero(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPADW::PWM_3_GENB_ACTCMPAD_ZERO) } #[doc = "Drive pwmB High"] #[inline(always)] pub fn pwm_3_genb_actcmpad_one(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPADW::PWM_3_GENB_ACTCMPAD_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 6); self.w.bits |= ((value as u32) & 3) << 6; self.w } } #[doc = "Possible values of the field `PWM_3_GENB_ACTCMPBU`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTCMPBUR { #[doc = "Do nothing"] PWM_3_GENB_ACTCMPBU_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTCMPBU_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTCMPBU_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTCMPBU_ONE, } impl PWM_3_GENB_ACTCMPBUR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_NONE => 0, PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_INV => 1, PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_ZERO => 2, PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENB_ACTCMPBUR { match value { 0 => PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_NONE, 1 => PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_INV, 2 => PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_ZERO, 3 => PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPBU_NONE`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpbu_none(&self) -> bool { *self == PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPBU_INV`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpbu_inv(&self) -> bool { *self == PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_INV } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPBU_ZERO`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpbu_zero(&self) -> bool { *self == PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPBU_ONE`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpbu_one(&self) -> bool { *self == PWM_3_GENB_ACTCMPBUR::PWM_3_GENB_ACTCMPBU_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENB_ACTCMPBU`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTCMPBUW { #[doc = "Do nothing"] PWM_3_GENB_ACTCMPBU_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTCMPBU_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTCMPBU_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTCMPBU_ONE, } impl PWM_3_GENB_ACTCMPBUW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENB_ACTCMPBUW::PWM_3_GENB_ACTCMPBU_NONE => 0, PWM_3_GENB_ACTCMPBUW::PWM_3_GENB_ACTCMPBU_INV => 1, PWM_3_GENB_ACTCMPBUW::PWM_3_GENB_ACTCMPBU_ZERO => 2, PWM_3_GENB_ACTCMPBUW::PWM_3_GENB_ACTCMPBU_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENB_ACTCMPBUW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENB_ACTCMPBUW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENB_ACTCMPBUW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_genb_actcmpbu_none(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPBUW::PWM_3_GENB_ACTCMPBU_NONE) } #[doc = "Invert pwmB"] #[inline(always)] pub fn pwm_3_genb_actcmpbu_inv(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPBUW::PWM_3_GENB_ACTCMPBU_INV) } #[doc = "Drive pwmB Low"] #[inline(always)] pub fn pwm_3_genb_actcmpbu_zero(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPBUW::PWM_3_GENB_ACTCMPBU_ZERO) } #[doc = "Drive pwmB High"] #[inline(always)] pub fn pwm_3_genb_actcmpbu_one(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPBUW::PWM_3_GENB_ACTCMPBU_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 8); self.w.bits |= ((value as u32) & 3) << 8; self.w } } #[doc = "Possible values of the field `PWM_3_GENB_ACTCMPBD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTCMPBDR { #[doc = "Do nothing"] PWM_3_GENB_ACTCMPBD_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTCMPBD_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTCMPBD_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTCMPBD_ONE, } impl PWM_3_GENB_ACTCMPBDR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_NONE => 0, PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_INV => 1, PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_ZERO => 2, PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENB_ACTCMPBDR { match value { 0 => PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_NONE, 1 => PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_INV, 2 => PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_ZERO, 3 => PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPBD_NONE`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpbd_none(&self) -> bool { *self == PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPBD_INV`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpbd_inv(&self) -> bool { *self == PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_INV } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPBD_ZERO`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpbd_zero(&self) -> bool { *self == PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENB_ACTCMPBD_ONE`"] #[inline(always)] pub fn is_pwm_3_genb_actcmpbd_one(&self) -> bool { *self == PWM_3_GENB_ACTCMPBDR::PWM_3_GENB_ACTCMPBD_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENB_ACTCMPBD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENB_ACTCMPBDW { #[doc = "Do nothing"] PWM_3_GENB_ACTCMPBD_NONE, #[doc = "Invert pwmB"] PWM_3_GENB_ACTCMPBD_INV, #[doc = "Drive pwmB Low"] PWM_3_GENB_ACTCMPBD_ZERO, #[doc = "Drive pwmB High"] PWM_3_GENB_ACTCMPBD_ONE, } impl PWM_3_GENB_ACTCMPBDW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENB_ACTCMPBDW::PWM_3_GENB_ACTCMPBD_NONE => 0, PWM_3_GENB_ACTCMPBDW::PWM_3_GENB_ACTCMPBD_INV => 1, PWM_3_GENB_ACTCMPBDW::PWM_3_GENB_ACTCMPBD_ZERO => 2, PWM_3_GENB_ACTCMPBDW::PWM_3_GENB_ACTCMPBD_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENB_ACTCMPBDW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENB_ACTCMPBDW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENB_ACTCMPBDW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_genb_actcmpbd_none(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPBDW::PWM_3_GENB_ACTCMPBD_NONE) } #[doc = "Invert pwmB"] #[inline(always)] pub fn pwm_3_genb_actcmpbd_inv(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPBDW::PWM_3_GENB_ACTCMPBD_INV) } #[doc = "Drive pwmB Low"] #[inline(always)] pub fn pwm_3_genb_actcmpbd_zero(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPBDW::PWM_3_GENB_ACTCMPBD_ZERO) } #[doc = "Drive pwmB High"] #[inline(always)] pub fn pwm_3_genb_actcmpbd_one(self) -> &'a mut W { self.variant(PWM_3_GENB_ACTCMPBDW::PWM_3_GENB_ACTCMPBD_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 10); self.w.bits |= ((value as u32) & 3) << 10; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:1 - Action for Counter=0"] #[inline(always)] pub fn pwm_3_genb_actzero(&self) -> PWM_3_GENB_ACTZEROR { PWM_3_GENB_ACTZEROR::_from(((self.bits >> 0) & 3) as u8) } #[doc = "Bits 2:3 - Action for Counter=LOAD"] #[inline(always)] pub fn pwm_3_genb_actload(&self) -> PWM_3_GENB_ACTLOADR { PWM_3_GENB_ACTLOADR::_from(((self.bits >> 2) & 3) as u8) } #[doc = "Bits 4:5 - Action for Comparator A Up"] #[inline(always)] pub fn pwm_3_genb_actcmpau(&self) -> PWM_3_GENB_ACTCMPAUR { PWM_3_GENB_ACTCMPAUR::_from(((self.bits >> 4) & 3) as u8) } #[doc = "Bits 6:7 - Action for Comparator A Down"] #[inline(always)] pub fn pwm_3_genb_actcmpad(&self) -> PWM_3_GENB_ACTCMPADR { PWM_3_GENB_ACTCMPADR::_from(((self.bits >> 6) & 3) as u8) } #[doc = "Bits 8:9 - Action for Comparator B Up"] #[inline(always)] pub fn pwm_3_genb_actcmpbu(&self) -> PWM_3_GENB_ACTCMPBUR { PWM_3_GENB_ACTCMPBUR::_from(((self.bits >> 8) & 3) as u8) } #[doc = "Bits 10:11 - Action for Comparator B Down"] #[inline(always)] pub fn pwm_3_genb_actcmpbd(&self) -> PWM_3_GENB_ACTCMPBDR { PWM_3_GENB_ACTCMPBDR::_from(((self.bits >> 10) & 3) as u8) } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:1 - Action for Counter=0"] #[inline(always)] pub fn pwm_3_genb_actzero(&mut self) -> _PWM_3_GENB_ACTZEROW { _PWM_3_GENB_ACTZEROW { w: self } } #[doc = "Bits 2:3 - Action for Counter=LOAD"] #[inline(always)] pub fn pwm_3_genb_actload(&mut self) -> _PWM_3_GENB_ACTLOADW { _PWM_3_GENB_ACTLOADW { w: self } } #[doc = "Bits 4:5 - Action for Comparator A Up"] #[inline(always)] pub fn pwm_3_genb_actcmpau(&mut self) -> _PWM_3_GENB_ACTCMPAUW { _PWM_3_GENB_ACTCMPAUW { w: self } } #[doc = "Bits 6:7 - Action for Comparator A Down"] #[inline(always)] pub fn pwm_3_genb_actcmpad(&mut self) -> _PWM_3_GENB_ACTCMPADW { _PWM_3_GENB_ACTCMPADW { w: self } } #[doc = "Bits 8:9 - Action for Comparator B Up"] #[inline(always)] pub fn pwm_3_genb_actcmpbu(&mut self) -> _PWM_3_GENB_ACTCMPBUW { _PWM_3_GENB_ACTCMPBUW { w: self } } #[doc = "Bits 10:11 - Action for Comparator B Down"] #[inline(always)] pub fn pwm_3_genb_actcmpbd(&mut self) -> _PWM_3_GENB_ACTCMPBDW { _PWM_3_GENB_ACTCMPBDW { w: self } } }
//! Mii data. //! //! This module contains the structs that represent all the data of a Mii. //! //! Have a look at the [`MiiSelector`](crate::applets::mii_selector::MiiSelector) applet to learn how to ask the user for a specific Mii. /// Region lock of the Mii. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum RegionLock { /// No region-lock. None, /// Japan region-lock. Japan, /// USA region-lock. USA, /// Europe region-lock. Europe, } /// Charset of the Mii. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Charset { /// Japan-USA-Europe unified charset. JapanUSAEurope, /// China charset. China, /// Korea charset. Korea, /// Taiwan charset. Taiwan, } /// Generic options of the Mii. #[derive(Copy, Clone, Debug)] pub struct Options { /// Whether it is allowed to copy the Mii. pub is_copying_allowed: bool, /// Whether the profanity flag is active. pub is_profanity_flag_enabled: bool, /// The Mii's active region-lock. pub region_lock: RegionLock, /// The Mii's used charset. pub charset: Charset, } /// Positional Index that the Mii has on the [`MiiSelector`](crate::applets::mii_selector::MiiSelector) window. #[derive(Copy, Clone, Debug)] pub struct SelectorPosition { /// Index of the page where the Mii is found. pub page_index: u8, /// Index of the slot (relative to the page) where the Mii is found. pub slot_index: u8, } /// Console model from which the Mii originated. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum OriginConsole { /// Nintendo Wii. Wii, /// Nintendo DSi. DSi, /// Nintendo 3DS. /// /// This includes all consoles of the 3DS family (3DS, 2DS, and their respective "New" or "XL" variants). N3DS, /// Nintendo Wii U/Switch. WiiUSwitch, } /// Identity of the origin console. #[derive(Copy, Clone, Debug)] pub struct ConsoleIdentity { /// From which console the Mii originated from. pub origin_console: OriginConsole, } /// Sex of the Mii. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Sex { /// Male sex. Male, /// Female sex. Female, } /// Generic details of the Mii. #[derive(Copy, Clone, Debug)] pub struct Details { /// Sex of the Mii. pub sex: Sex, /// Birthday month. pub birthday_month: u8, /// Birthday day. pub birthday_day: u8, /// Color of the Mii's shirt. pub shirt_color: u8, /// Whether the Mii is a favorite. pub is_favorite: bool, /// Whether the Mii can be shared. pub is_sharing_enabled: bool, } /// Face style of the Mii. #[derive(Copy, Clone, Debug)] pub struct FaceStyle { /// Face shape. pub shape: u8, /// Skin color. pub skin_color: u8, } /// Face details of the Mii. #[derive(Copy, Clone, Debug)] pub struct FaceDetails { /// Face style. pub style: FaceStyle, /// Wrinkles. pub wrinkles: u8, /// Makeup. pub makeup: u8, } /// Hair details of the Mii. #[derive(Copy, Clone, Debug)] pub struct HairDetails { /// Hair style. pub style: u8, /// Hair color. pub color: u8, /// Whether the Mii's hair is flipped. pub is_flipped: bool, } /// Eye details of the Mii. #[derive(Copy, Clone, Debug)] pub struct EyeDetails { /// Eye style. pub style: u8, /// Eye color. pub color: u8, /// Eye scale. pub scale: u8, /// Eye scale (y-axis). pub y_scale: u8, /// Eye rotation. pub rotation: u8, /// Spacing between the eyes. pub x_spacing: u8, /// Eye height. pub y_position: u8, } /// Eyebrow details of the Mii. #[derive(Copy, Clone, Debug)] pub struct EyebrowDetails { /// Eyebrow style. pub style: u8, /// Eyebrow color. pub color: u8, /// Eyebrow scale. pub scale: u8, /// Eyebrow scale (y-axis). pub y_scale: u8, /// Eyebrow rotation. pub rotation: u8, /// Spacing between the eyebrows pub x_spacing: u8, /// Eyebrow height. pub y_position: u8, } /// Nose details of the Mii. #[derive(Copy, Clone, Debug)] pub struct NoseDetails { /// Nose style. pub style: u8, /// Nose scale. pub scale: u8, /// Nose height. pub y_position: u8, } /// Mouth details of the Mii. #[derive(Copy, Clone, Debug)] pub struct MouthDetails { /// Mouth style. pub style: u8, /// Mouth color. pub color: u8, /// Mouth scale. pub scale: u8, /// Mouth scale (y-axis). pub y_scale: u8, /// Mouth height. pub y_position: u8, } /// Mustache details of the Mii. #[derive(Copy, Clone, Debug)] pub struct MustacheDetails { /// Mustache style. pub mustache_style: u8, } /// Beard details of the Mii. #[derive(Copy, Clone, Debug)] pub struct BeardDetails { /// Beard style pub style: u8, /// Beard color. pub color: u8, /// Beard scale. pub scale: u8, /// Beard height. pub y_position: u8, } /// Glasses details of the Mii. #[derive(Copy, Clone, Debug)] pub struct GlassesDetails { /// Glasses style. pub style: u8, /// Glasses color. pub color: u8, /// Glasses scale. pub scale: u8, /// Glasses height. pub y_position: u8, } /// Mole details of the Mii. #[derive(Copy, Clone, Debug)] pub struct MoleDetails { /// Whether the Mii has a mole. pub is_enabled: bool, /// Mole scale. pub scale: u8, /// Mole position (x-axis). pub x_position: u8, /// Mole position (y-axis). pub y_position: u8, } /// Full Mii data representation. /// /// Some values are not ordered *like* the Mii Editor UI. The mapped values can be seen [here](https://www.3dbrew.org/wiki/Mii#Mapped_Editor_.3C-.3E_Hex_values). /// /// This struct can be retrieved by [`MiiSelector::launch()`](crate::applets::mii_selector::MiiSelector::launch). #[derive(Clone, Debug)] pub struct Mii { /// Mii options. pub options: Options, /// Position taken by the Mii on the Mii Selector screen. pub selector_position: SelectorPosition, /// Console the Mii was created on. pub console_identity: ConsoleIdentity, /// Unique system ID, not dependant on the MAC address pub system_id: [u8; 8], /// Console's MAC address. pub mac_address: [u8; 6], /// General information about the Mii. pub details: Details, /// Mii name. pub name: String, /// Mii height. pub height: u8, /// Mii width. pub width: u8, /// Face details. pub face_details: FaceDetails, /// Hair details. pub hair_details: HairDetails, /// Eyes details. pub eye_details: EyeDetails, /// Eyebrow details. pub eyebrow_details: EyebrowDetails, /// Nose details. pub nose_details: NoseDetails, /// Mouth details. pub mouth_details: MouthDetails, /// Mustache details. pub mustache_details: MustacheDetails, /// Beard details. pub beard_details: BeardDetails, /// Glasses details. pub glass_details: GlassesDetails, /// Mole details. pub mole_details: MoleDetails, /// Name of the Mii's original author. pub author_name: String, } impl From<ctru_sys::MiiData> for Mii { fn from(mii_data: ctru_sys::MiiData) -> Self { let raw_mii_data = mii_data._bindgen_opaque_blob; // Source for the representation and what each thing means: https://www.3dbrew.org/wiki/Mii let raw_options = vec_bit(raw_mii_data[0x1]); let raw_position = vec_bit(raw_mii_data[0x2]); let raw_device = vec_bit(raw_mii_data[0x3]); let system_id = [ raw_mii_data[0x4], raw_mii_data[0x5], raw_mii_data[0x6], raw_mii_data[0x7], raw_mii_data[0x8], raw_mii_data[0x9], raw_mii_data[0xA], raw_mii_data[0xB], ]; let mac_address = [ raw_mii_data[0x10], raw_mii_data[0x11], raw_mii_data[0x12], raw_mii_data[0x13], raw_mii_data[0x14], raw_mii_data[0x15], ]; let raw_details: [bool; 16] = get_and_concat_vec_bit(&raw_mii_data, &[0x18, 0x19]) .try_into() .unwrap(); let raw_utf16_name = &raw_mii_data[0x1A..0x2D]; let height = raw_mii_data[0x2E]; let width = raw_mii_data[0x2F]; let raw_face_style = vec_bit(raw_mii_data[0x30]); let raw_face_details = vec_bit(raw_mii_data[0x31]); let raw_hair_details = vec_bit(raw_mii_data[0x33]); let raw_eye_details: [bool; 32] = get_and_concat_vec_bit(&raw_mii_data, &[0x34, 0x35, 0x36, 0x37]) .try_into() .unwrap(); let raw_eyebrow_details: [bool; 32] = get_and_concat_vec_bit(&raw_mii_data, &[0x38, 0x39, 0x3A, 0x3B]) .try_into() .unwrap(); let raw_nose_details: [bool; 16] = get_and_concat_vec_bit(&raw_mii_data, &[0x3C, 0x3D]) .try_into() .unwrap(); let raw_mouth_details: [bool; 16] = get_and_concat_vec_bit(&raw_mii_data, &[0x3E, 0x3F]) .try_into() .unwrap(); let raw_mustache_details: [bool; 16] = get_and_concat_vec_bit(&raw_mii_data, &[0x40, 0x41]) .try_into() .unwrap(); let raw_beard_details: [bool; 16] = get_and_concat_vec_bit(&raw_mii_data, &[0x42, 0x42]) .try_into() .unwrap(); let raw_glass_details: [bool; 16] = get_and_concat_vec_bit(&raw_mii_data, &[0x44, 0x45]) .try_into() .unwrap(); let raw_mole_details: [bool; 16] = get_and_concat_vec_bit(&raw_mii_data, &[0x46, 0x47]) .try_into() .unwrap(); let raw_utf16_author = &raw_mii_data[0x48..0x5C]; let name = utf16_byte_pairs_to_string(raw_utf16_name); let author_name = utf16_byte_pairs_to_string(raw_utf16_author); let options = Options { is_copying_allowed: raw_options[0], is_profanity_flag_enabled: raw_options[1], region_lock: { match (raw_options[3], raw_options[2]) { (false, false) => RegionLock::None, (false, true) => RegionLock::Japan, (true, false) => RegionLock::USA, (true, true) => RegionLock::Europe, } }, charset: { match (raw_options[5], raw_options[4]) { (false, false) => Charset::JapanUSAEurope, (false, true) => Charset::China, (true, false) => Charset::Korea, (true, true) => Charset::Taiwan, } }, }; let selector_position = SelectorPosition { page_index: partial_u8_bits_to_u8(&raw_position[0..=3]), slot_index: partial_u8_bits_to_u8(&raw_position[4..=7]), }; let console_identity = ConsoleIdentity { origin_console: { match (raw_device[6], raw_device[5], raw_device[4]) { (false, false, true) => OriginConsole::Wii, (false, true, false) => OriginConsole::DSi, (false, true, true) => OriginConsole::N3DS, _ => OriginConsole::WiiUSwitch, } }, }; let details = Details { sex: { match raw_details[0] { true => Sex::Female, false => Sex::Male, } }, birthday_month: partial_u8_bits_to_u8(&raw_details[1..=4]), birthday_day: partial_u8_bits_to_u8(&raw_details[5..=9]), shirt_color: partial_u8_bits_to_u8(&raw_details[10..=13]), is_favorite: raw_details[14], is_sharing_enabled: !raw_face_style[0], }; let face_details = FaceDetails { style: FaceStyle { shape: partial_u8_bits_to_u8(&raw_face_style[1..=4]), skin_color: partial_u8_bits_to_u8(&raw_face_style[5..=7]), }, wrinkles: partial_u8_bits_to_u8(&raw_face_details[0..=3]), makeup: partial_u8_bits_to_u8(&raw_face_details[4..=7]), }; let hair_details = HairDetails { style: raw_mii_data[0x32], color: partial_u8_bits_to_u8(&raw_hair_details[0..=2]), is_flipped: raw_hair_details[3], }; let eye_details = EyeDetails { style: partial_u8_bits_to_u8(&raw_eye_details[0..=5]), color: partial_u8_bits_to_u8(&raw_eye_details[6..=8]), scale: partial_u8_bits_to_u8(&raw_eye_details[9..=12]), y_scale: partial_u8_bits_to_u8(&raw_eye_details[13..=15]), rotation: partial_u8_bits_to_u8(&raw_eye_details[16..=20]), x_spacing: partial_u8_bits_to_u8(&raw_eye_details[21..=24]), y_position: partial_u8_bits_to_u8(&raw_eye_details[25..=29]), }; let eyebrow_details = EyebrowDetails { style: partial_u8_bits_to_u8(&raw_eyebrow_details[0..=4]), color: partial_u8_bits_to_u8(&raw_eyebrow_details[5..=7]), scale: partial_u8_bits_to_u8(&raw_eyebrow_details[8..=11]), // Bits are skipped here, following the 3dbrew wiki: // https://www.3dbrew.org/wiki/Mii#Mii_format offset 0x38 y_scale: partial_u8_bits_to_u8(&raw_eyebrow_details[12..=14]), rotation: partial_u8_bits_to_u8(&raw_eyebrow_details[16..=19]), x_spacing: partial_u8_bits_to_u8(&raw_eyebrow_details[21..=24]), y_position: partial_u8_bits_to_u8(&raw_eyebrow_details[25..=29]), }; let nose_details = NoseDetails { style: partial_u8_bits_to_u8(&raw_nose_details[0..=4]), scale: partial_u8_bits_to_u8(&raw_nose_details[5..=8]), y_position: partial_u8_bits_to_u8(&raw_nose_details[9..=13]), }; let mouth_details = MouthDetails { style: partial_u8_bits_to_u8(&raw_mouth_details[0..=5]), color: partial_u8_bits_to_u8(&raw_mouth_details[6..=8]), scale: partial_u8_bits_to_u8(&raw_mouth_details[9..=12]), y_scale: partial_u8_bits_to_u8(&raw_mouth_details[13..=15]), y_position: partial_u8_bits_to_u8(&raw_mustache_details[0..=4]), }; let mustache_details = MustacheDetails { mustache_style: partial_u8_bits_to_u8(&raw_mustache_details[5..=7]), }; let beard_details = BeardDetails { style: partial_u8_bits_to_u8(&raw_beard_details[0..=2]), color: partial_u8_bits_to_u8(&raw_beard_details[3..=5]), scale: partial_u8_bits_to_u8(&raw_beard_details[6..=9]), y_position: partial_u8_bits_to_u8(&raw_beard_details[10..=14]), }; let glass_details = GlassesDetails { style: partial_u8_bits_to_u8(&raw_glass_details[0..=3]), color: partial_u8_bits_to_u8(&raw_glass_details[4..=6]), scale: partial_u8_bits_to_u8(&raw_glass_details[7..=10]), y_position: partial_u8_bits_to_u8(&raw_glass_details[11..=15]), }; let mole_details = MoleDetails { is_enabled: raw_mole_details[0], scale: partial_u8_bits_to_u8(&raw_mole_details[1..=4]), x_position: partial_u8_bits_to_u8(&raw_mole_details[5..=9]), y_position: partial_u8_bits_to_u8(&raw_mole_details[10..=14]), }; Mii { options, selector_position, console_identity, system_id, mac_address, details, name, height, width, face_details, hair_details, eye_details, eyebrow_details, nose_details, mouth_details, mustache_details, beard_details, glass_details, mole_details, author_name, } } } // Methods to handle "_bits_", ``bitvec`` cannot compile to 32-bit targets, so I had to create a few // helper methods /// Transforms a u8 into a [bool; 8] fn vec_bit(data: u8) -> [bool; 8] { (0..8) .map(|i| (data & (1 << i)) != 0) .collect::<Vec<bool>>() .try_into() .unwrap() } /// Transforms a [bool; 8] into an u8 fn vec_bit_to_u8(data: [bool; 8]) -> u8 { data.into_iter() .fold(0, |result, bit| (result << 1) ^ u8::from(bit)) } /// Given a series of LE bits, they are filled until a full LE u8 is reached fn partial_u8_bits_to_u8(data: &[bool]) -> u8 { let leading_zeroes_to_add = 8 - data.len(); let leading_zeroes = vec![false; leading_zeroes_to_add]; vec_bit_to_u8([data, &leading_zeroes].concat().try_into().unwrap()) } /// UTF-16 Strings are give in pairs of bytes (u8), this converts them into an _actual_ string fn utf16_byte_pairs_to_string(data: &[u8]) -> String { let raw_utf16_composed = data .chunks_exact(2) .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]])) .collect::<Vec<u16>>(); String::from_utf16_lossy(raw_utf16_composed.as_slice()).replace('\0', "") } /// Gets the values from the slice and concatenates them fn get_and_concat_vec_bit(data: &[u8], get_values: &[usize]) -> Vec<bool> { get_values.iter().flat_map(|v| vec_bit(data[*v])).collect() }
pub struct App {} pub enum Msg {} impl yew::Component for App { type Message = Msg; type Properties = (); fn create(_: &yew::Context<Self>) -> Self { App {} } fn update(&mut self, _: &yew::Context<Self>, _: Self::Message) -> bool { true } fn view(&self, _: &yew::Context<Self>) -> yew::Html { use yew::html; html! { <> <p>{ "Hello world!" }</p> </> } } }
mod server; use domain::DomainError; pub use server::*; use warp::reject::Reject; #[derive(Debug)] struct ApiError(DomainError); impl From<DomainError> for ApiError { fn from(err: DomainError) -> Self { Self(err) } } impl Reject for ApiError {}
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 #![allow(dead_code)] #[macro_use] extern crate async_trait; extern crate serde_derive; #[macro_use] extern crate log; #[macro_use] extern crate trace_time; #[macro_use] extern crate prometheus; extern crate transaction_pool as tx_pool; pub use crate::pool::TxStatus; use crate::tx_pool_service_impl::{ ChainNewBlock, GetPendingTxns, ImportTxns, RemoveTxn, SubscribeTxns, TxPoolActor, }; use actix::prelude::*; use anyhow::Result; use common_crypto::hash::HashValue; use futures_channel::mpsc; use starcoin_bus::BusActor; use starcoin_config::TxPoolConfig; use starcoin_txpool_api::TxPoolAsyncService; use std::{fmt::Debug, sync::Arc}; use storage::Storage; use storage::{BlockStore, Store}; #[cfg(test)] use types::block::BlockHeader; use types::{block::Block, transaction, transaction::SignedUserTransaction}; mod counters; mod pool; mod pool_client; #[cfg(test)] mod test; mod tx_pool_service_impl; trait BlockReader { fn get_block_by_hash(&self, block_hash: HashValue) -> Result<Option<Block>>; } #[derive(Clone, Debug)] pub struct TxPoolRef { addr: actix::Addr<TxPoolActor>, } impl TxPoolRef { pub fn start( pool_config: TxPoolConfig, storage: Arc<dyn Store>, best_block_hash: HashValue, bus: actix::Addr<BusActor>, ) -> TxPoolRef { let best_block = match storage.get_block_by_hash(best_block_hash) { Err(e) => panic!("fail to read storage, {}", e), Ok(None) => panic!( "best block id {} should exists in storage", &best_block_hash ), Ok(Some(block)) => block, }; let best_block_header = best_block.into_inner().0; let pool = TxPoolActor::new(pool_config, storage, best_block_header, bus); let pool_addr = pool.start(); TxPoolRef { addr: pool_addr } } #[cfg(test)] pub fn start_with_best_block_header( storage: Arc<Storage>, best_block_header: BlockHeader, bus: actix::Addr<BusActor>, ) -> TxPoolRef { let pool = TxPoolActor::new(TxPoolConfig::default(), storage, best_block_header, bus); let pool_addr = pool.start(); TxPoolRef { addr: pool_addr } } } #[async_trait] impl TxPoolAsyncService for TxPoolRef { async fn add(self, txn: SignedUserTransaction) -> Result<bool> { let mut result = self.add_txns(vec![txn]).await?; Ok(result.pop().unwrap().is_ok()) } async fn add_txns( self, txns: Vec<SignedUserTransaction>, ) -> Result<Vec<Result<(), transaction::TransactionError>>> { let request = self.addr.send(ImportTxns { txns }); match request.await { Err(e) => Err(e.into()), Ok(r) => Ok(r), } } async fn remove_txn( self, txn_hash: HashValue, is_invalid: bool, ) -> Result<Option<SignedUserTransaction>> { match self .addr .send(RemoveTxn { txn_hash, is_invalid, }) .await { Err(e) => Err(e.into()), Ok(r) => Ok(r.map(|v| v.signed().clone())), } } async fn get_pending_txns(self, max_len: Option<u64>) -> Result<Vec<SignedUserTransaction>> { match self .addr .send(GetPendingTxns { max_len: max_len.unwrap_or_else(|| u64::max_value()), }) .await { Ok(r) => Ok(r.into_iter().map(|t| t.signed().clone()).collect()), Err(e) => Err(e.into()), } } async fn subscribe_txns( self, ) -> Result<mpsc::UnboundedReceiver<Arc<Vec<(HashValue, TxStatus)>>>> { match self.addr.send(SubscribeTxns).await { Err(e) => Err(e.into()), Ok(r) => Ok(r), } } /// when new block happened in chain, use this to notify txn pool /// the `HashValue` of `enacted`/`retracted` is the hash of blocks. /// enacted: the blocks which enter into main chain. /// retracted: the blocks which is rollbacked. async fn chain_new_blocks( self, _enacted: Vec<HashValue>, _retracted: Vec<HashValue>, ) -> Result<()> { todo!() } async fn rollback( self, enacted: Vec<SignedUserTransaction>, retracted: Vec<SignedUserTransaction>, ) -> Result<()> { match self.addr.send(ChainNewBlock { enacted, retracted }).await { Err(e) => Err(e.into()), Ok(r) => Ok(r?), } } } #[derive(Debug, Clone)] struct NoneBlockReader; impl BlockReader for NoneBlockReader { fn get_block_by_hash(&self, _block_hash: HashValue) -> Result<Option<Block>> { Ok(None) } } struct StorageBlockReader { storage: Arc<Storage>, } /// TODO: enhance me when storage impl Debug impl Debug for StorageBlockReader { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "storage block reader") } } impl Clone for StorageBlockReader { fn clone(&self) -> Self { StorageBlockReader { storage: self.storage.clone(), } } } impl BlockReader for StorageBlockReader { fn get_block_by_hash(&self, block_hash: HashValue) -> Result<Option<Block>> { self.storage.get_block_by_hash(block_hash) } }
use serde::{Deserialize, Serialize}; use crate::hook::Hook; #[derive(Debug, Serialize, Deserialize)] pub struct StreamSquareHook { pub (crate) ask_stream_start: Hook, pub (crate) tell_stream_started: Hook, }
use nalgebra::geometry::{Isometry3, Point3, Rotation3, Translation, UnitQuaternion}; use nalgebra::{ allocator::Allocator, storage::{Owned, Storage}, DefaultAllocator, RealField, }; use nalgebra::{convert, Dim, OMatrix, SMatrix, Unit, Vector3, U3}; #[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use crate::{ coordinate_system::{CameraFrame, WorldFrame}, Bundle, Points, RayBundle, }; /// Defines the pose of a camera in the world coordinate system. #[derive(Clone, PartialEq)] #[cfg_attr(feature = "serde-serialize", derive(Serialize))] pub struct ExtrinsicParameters<R: RealField> { pub(crate) rquat: UnitQuaternion<R>, pub(crate) camcenter: Point3<R>, #[cfg_attr(feature = "serde-serialize", serde(skip))] pub(crate) cache: ExtrinsicsCache<R>, } impl<R: RealField> std::fmt::Debug for ExtrinsicParameters<R> { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // This should match the auto derived Debug implementation but not print // the cache field. fmt.debug_struct("ExtrinsicParameters") .field("rquat", &self.rquat) .field("camcenter", &self.camcenter) .finish() } } #[derive(Clone, PartialEq)] pub(crate) struct ExtrinsicsCache<R: RealField> { pub(crate) q: Rotation3<R>, pub(crate) translation: Point3<R>, pub(crate) qt: SMatrix<R, 3, 4>, pub(crate) q_inv: Rotation3<R>, pub(crate) camcenter_z0: Point3<R>, pub(crate) pose: Isometry3<R>, pub(crate) pose_inv: Isometry3<R>, } impl<R: RealField> std::fmt::Debug for ExtrinsicsCache<R> { fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // do not show cache Ok(()) } } impl<R: RealField> ExtrinsicParameters<R> { /// Create a new instance from a rotation and a camera center. pub fn from_rotation_and_camcenter(rotation: UnitQuaternion<R>, camcenter: Point3<R>) -> Self { let q = rotation.clone().to_rotation_matrix(); let translation = -(q.clone() * camcenter.clone()); #[rustfmt::skip] let qt = { let q = q.matrix(); SMatrix::<R,3,4>::new( q[(0,0)].clone(), q[(0,1)].clone(), q[(0,2)].clone(), translation[0].clone(), q[(1,0)].clone(), q[(1,1)].clone(), q[(1,2)].clone(), translation[1].clone(), q[(2,0)].clone(), q[(2,1)].clone(), q[(2,2)].clone(), translation[2].clone(), ) }; let q_inv = q.inverse(); let camcenter_z0 = Point3::from(Vector3::new( camcenter[0].clone(), camcenter[1].clone(), convert::<_, R>(0.0), )); let pose = Isometry3::from_parts( Translation { vector: translation.clone().coords, }, rotation.clone(), ); let pose_inv = pose.inverse(); let cache = ExtrinsicsCache { q, translation, qt, q_inv, camcenter_z0, pose, pose_inv, }; // TODO: ensure that our rotation is right handed. The commented out // code below is not robust enough. For example, the following code // would cause it to panic: // // let camcenter = Vector3::new(10.0, 0.0, 10.0); // let lookat = Vector3::new(0.0, 0.0, 0.0); // let up = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0)); // ExtrinsicParameters::from_view(&camcenter, &lookat, &up); // if !crate::camera::is_right_handed_rotation_quat(&rotation) { // panic!("rotation is not right handed."); // } Self { rquat: rotation, camcenter, cache, } } /// Create a new instance from an [`nalgebra::Isometry3`](https://docs.rs/nalgebra/latest/nalgebra/geometry/type.Isometry3.html). pub fn from_pose(pose: &Isometry3<R>) -> Self { let rquat = pose.clone().rotation; let translation = pose.clone().translation.vector; let q = rquat.inverse().to_rotation_matrix(); let camcenter = -(q * translation); let cc = Point3 { coords: camcenter }; Self::from_rotation_and_camcenter(rquat, cc) } /// Create a new instance from a camera center, a lookat vector, and an up vector. pub fn from_view(camcenter: &Vector3<R>, lookat: &Vector3<R>, up: &Unit<Vector3<R>>) -> Self { let dir = lookat - camcenter; let dir_unit = nalgebra::Unit::new_normalize(dir); let q = UnitQuaternion::look_at_lh(dir_unit.as_ref(), up.as_ref()); let pi: R = convert(std::f64::consts::PI); let q2 = UnitQuaternion::from_axis_angle(&dir_unit, pi); let q3 = q * q2; Self::from_rotation_and_camcenter( q3, Point3 { coords: camcenter.clone(), }, ) } /// Return the camera center #[inline] pub fn camcenter(&self) -> &Point3<R> { &self.camcenter } /// Return the camera pose #[inline] pub fn pose(&self) -> &Isometry3<R> { &self.cache.pose } /// Return the pose as a 3x4 matrix #[inline] pub fn matrix(&self) -> &SMatrix<R, 3, 4> { &self.cache.qt } /// Return the rotation part of the pose #[inline] pub fn rotation(&self) -> &Rotation3<R> { &self.cache.q } /// Return the translation part of the pose #[inline] pub fn translation(&self) -> &Point3<R> { &self.cache.translation } /// Return a unit vector aligned along our look (+Z) direction. pub fn forward(&self) -> Unit<Vector3<R>> { let pt_cam = Point3::new(R::zero(), R::zero(), R::one()); self.lookdir(&pt_cam) } /// Return a unit vector aligned along our up (-Y) direction. pub fn up(&self) -> Unit<Vector3<R>> { let pt_cam = Point3::new(R::zero(), -R::one(), R::zero()); self.lookdir(&pt_cam) } /// Return a unit vector aligned along our right (+X) direction. pub fn right(&self) -> Unit<Vector3<R>> { let pt_cam = Point3::new(R::one(), R::zero(), R::zero()); self.lookdir(&pt_cam) } /// Return a world coords unit vector aligned along the given direction /// /// `pt_cam` is specified in camera coords. fn lookdir(&self, pt_cam: &Point3<R>) -> Unit<Vector3<R>> { let cc = self.camcenter(); let pt = self.cache.pose_inv.transform_point(pt_cam) - cc; nalgebra::Unit::new_normalize(pt) } /// Convert points in camera coordinates to world coordinates. pub fn camera_to_world<NPTS, InStorage>( &self, cam_coords: &Points<CameraFrame, R, NPTS, InStorage>, ) -> Points<WorldFrame, R, NPTS, Owned<R, NPTS, U3>> where NPTS: Dim, InStorage: Storage<R, NPTS, U3>, DefaultAllocator: Allocator<R, NPTS, U3>, { let mut world = Points::new(OMatrix::zeros_generic( NPTS::from_usize(cam_coords.data.nrows()), U3::from_usize(3), )); // Potential optimization: remove for loops let in_mult = &cam_coords.data; let out_mult = &mut world.data; for i in 0..in_mult.nrows() { let tmp = self.cache.pose_inv.transform_point(&Point3::new( in_mult[(i, 0)].clone(), in_mult[(i, 1)].clone(), in_mult[(i, 2)].clone(), )); for j in 0..3 { out_mult[(i, j)] = tmp[j].clone(); } } world } /// Convert rays in camera coordinates to world coordinates. #[inline] pub fn ray_camera_to_world<BType, NPTS, StorageCamera>( &self, camera: &RayBundle<CameraFrame, BType, R, NPTS, StorageCamera>, ) -> RayBundle<WorldFrame, BType, R, NPTS, Owned<R, NPTS, U3>> where BType: Bundle<R>, NPTS: Dim, StorageCamera: Storage<R, NPTS, U3>, DefaultAllocator: Allocator<R, NPTS, U3>, { camera.to_pose(self.cache.pose_inv.clone()) } /// Convert points in world coordinates to camera coordinates. pub fn world_to_camera<NPTS, InStorage>( &self, world: &Points<WorldFrame, R, NPTS, InStorage>, ) -> Points<CameraFrame, R, NPTS, Owned<R, NPTS, U3>> where NPTS: Dim, InStorage: Storage<R, NPTS, U3>, DefaultAllocator: Allocator<R, NPTS, U3>, { let mut cam_coords = Points::new(OMatrix::zeros_generic( NPTS::from_usize(world.data.nrows()), U3::from_usize(3), )); // Potential optimization: remove for loops let in_mult = &world.data; let out_mult = &mut cam_coords.data; for i in 0..in_mult.nrows() { let tmp = self.cache.pose.transform_point(&Point3::new( in_mult[(i, 0)].clone(), in_mult[(i, 1)].clone(), in_mult[(i, 2)].clone(), )); for j in 0..3 { out_mult[(i, j)] = tmp[j].clone(); } } cam_coords } } // So far, I could not figure out how to get serde derive to construct a cache // only after rquat and camcenter are created. Instead serde derive wants the // struct to be deserialized to implement the Default trait. #[cfg(feature = "serde-serialize")] impl<'de, R: RealField + serde::Deserialize<'de>> serde::Deserialize<'de> for ExtrinsicParameters<R> { fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> where D: serde::Deserializer<'de>, { use serde::de; use std::fmt; #[derive(Deserialize)] #[serde(field_identifier, rename_all = "lowercase")] enum Field { RQuat, CamCenter, }; struct ExtrinsicParametersVisitor<'de, R2: RealField + serde::Deserialize<'de>>( std::marker::PhantomData<&'de R2>, ); impl<'de, R2: RealField + serde::Deserialize<'de>> serde::de::Visitor<'de> for ExtrinsicParametersVisitor<'de, R2> { type Value = ExtrinsicParameters<R2>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("struct ExtrinsicParameters") } fn visit_seq<V>( self, mut seq: V, ) -> std::result::Result<ExtrinsicParameters<R2>, V::Error> where V: serde::de::SeqAccess<'de>, { let rquat = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let camcenter = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; Ok(ExtrinsicParameters::from_rotation_and_camcenter( rquat, camcenter, )) } fn visit_map<V>( self, mut map: V, ) -> std::result::Result<ExtrinsicParameters<R2>, V::Error> where V: serde::de::MapAccess<'de>, { let mut rquat = None; let mut camcenter = None; while let Some(key) = map.next_key()? { match key { Field::RQuat => { if rquat.is_some() { return Err(de::Error::duplicate_field("rquat")); } rquat = Some(map.next_value()?); } Field::CamCenter => { if camcenter.is_some() { return Err(de::Error::duplicate_field("camcenter")); } camcenter = Some(map.next_value()?); } } } let rquat = rquat.ok_or_else(|| de::Error::missing_field("rquat"))?; let camcenter = camcenter.ok_or_else(|| de::Error::missing_field("camcenter"))?; Ok(ExtrinsicParameters::from_rotation_and_camcenter( rquat, camcenter, )) } } const FIELDS: &'static [&'static str] = &["rquat", "camcenter"]; deserializer.deserialize_struct( "ExtrinsicParameters", FIELDS, ExtrinsicParametersVisitor(std::marker::PhantomData), ) } } #[cfg(feature = "serde-serialize")] fn _test_extrinsics_is_serialize() { // Compile-time test to ensure ExtrinsicParameters implements Serialize trait. fn implements<T: serde::Serialize>() {} implements::<ExtrinsicParameters<f64>>(); } #[cfg(feature = "serde-serialize")] fn _test_extrinsics_is_deserialize() { // Compile-time test to ensure ExtrinsicParameters implements Deserialize trait. fn implements<'de, T: serde::Deserialize<'de>>() {} implements::<ExtrinsicParameters<f64>>(); } #[cfg(test)] mod tests { use super::*; use nalgebra::convert as c; #[test] fn roundtrip_f64() { roundtrip_generic::<f64>(1e-10) } #[test] fn roundtrip_f32() { roundtrip_generic::<f32>(1e-5) } fn roundtrip_generic<R: RealField>(epsilon: R) { let zero: R = convert(0.0); let one: R = convert(1.0); let e1 = ExtrinsicParameters::<R>::from_view( &Vector3::new(c(1.2), c(3.4), c(5.6)), // camcenter &Vector3::new(c(2.2), c(3.4), c(5.6)), // lookat &nalgebra::Unit::new_normalize(Vector3::new(zero.clone(), zero.clone(), one.clone())), // up ); #[rustfmt::skip] let cam_coords = Points { coords: std::marker::PhantomData, data: SMatrix::<R, 4, 3>::new( zero.clone(), zero.clone(), zero.clone(), // at camera center zero.clone(), zero.clone(), one.clone(), // one unit in +Z - exactly in camera direction one.clone(), zero.clone(), zero.clone(), // one unit in +X - right of camera axis zero.clone(), one, zero, // one unit in +Y - down from camera axis ), }; #[rustfmt::skip] let world_expected = SMatrix::<R, 4, 3>::new( c(1.2), c(3.4), c(5.6), c(2.2), c(3.4), c(5.6), c(1.2), c(2.4), c(5.6), c(1.2), c(3.4), c(4.6), ); let world_actual = e1.camera_to_world(&cam_coords); approx::assert_abs_diff_eq!(world_expected, world_actual.data, epsilon = epsilon.clone()); // test roundtrip let camera_actual = e1.world_to_camera(&world_actual); approx::assert_abs_diff_eq!( cam_coords.data, camera_actual.data, epsilon = epsilon ); } #[test] #[cfg(feature = "serde-serialize")] fn test_serde() { let expected = ExtrinsicParameters::<f64>::from_view( &Vector3::new(1.2, 3.4, 5.6), // camcenter &Vector3::new(2.2, 3.4, 5.6), // lookat &nalgebra::Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0)), // up ); let buf = serde_json::to_string(&expected).unwrap(); let actual: crate::ExtrinsicParameters<f64> = serde_json::from_str(&buf).unwrap(); assert!(expected == actual); } }
use std::{cell::RefCell, rc::Rc}; use crate::binding::http::builder::Builder; use crate::binding::{ http::{header_prefix, SPEC_VERSION_HEADER}, CLOUDEVENTS_JSON_HEADER, }; use crate::event::SpecVersion; use crate::message::{BinarySerializer, MessageAttributeValue, Result, StructuredSerializer}; macro_rules! str_to_header_value { ($header_value:expr) => { http::header::HeaderValue::from_str(&$header_value.to_string()).map_err(|e| { crate::message::Error::Other { source: Box::new(e), } }) }; } pub struct Serializer<T> { builder: Rc<RefCell<dyn Builder<T>>>, } impl<T> Serializer<T> { pub fn new<B: Builder<T> + 'static>(delegate: B) -> Serializer<T> { let builder = Rc::new(RefCell::new(delegate)); Serializer { builder } } } impl<T> BinarySerializer<T> for Serializer<T> { fn set_spec_version(self, spec_version: SpecVersion) -> Result<Self> { self.builder .borrow_mut() .header(SPEC_VERSION_HEADER, str_to_header_value!(spec_version)?); Ok(self) } fn set_attribute(self, name: &str, value: MessageAttributeValue) -> Result<Self> { self.builder .borrow_mut() .header(&header_prefix(name), str_to_header_value!(value)?); Ok(self) } fn set_extension(self, name: &str, value: MessageAttributeValue) -> Result<Self> { self.builder .borrow_mut() .header(&header_prefix(name), str_to_header_value!(value)?); Ok(self) } fn end_with_data(self, bytes: Vec<u8>) -> Result<T> { self.builder.borrow_mut().body(bytes) } fn end(self) -> Result<T> { self.builder.borrow_mut().finish() } } impl<T> StructuredSerializer<T> for Serializer<T> { fn set_structured_event(self, bytes: Vec<u8>) -> Result<T> { let mut builder = self.builder.borrow_mut(); builder.header( http::header::CONTENT_TYPE.as_str(), http::HeaderValue::from_static(CLOUDEVENTS_JSON_HEADER), ); builder.body(bytes) } }
use core::fmt; #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Debug)] pub enum Abi { Rust, C { unwind: bool }, // Single platform ABIs Cdecl { unwind: bool }, Stdcall { unwind: bool }, Fastcall { unwind: bool }, Vectorcall { unwind: bool }, Thiscall { unwind: bool }, Aapcs { unwind: bool }, Win64 { unwind: bool }, SysV64 { unwind: bool }, PtxKernel, Msp430Interrupt, X86Interrupt, AmdGpuKernel, EfiApi, AvrInterrupt, AvrNonBlockingInterrupt, CCmseNonSecureCall, Wasm, // Multiplatform / generic ABIs System { unwind: bool }, RustIntrinsic, RustCall, PlatformIntrinsic, Unadjusted, Erlang, } #[derive(Copy, Clone)] pub struct AbiData { abi: Abi, /// Name of this ABI as we like it called. name: &'static str, } #[allow(non_upper_case_globals)] const AbiDatas: &[AbiData] = &[ AbiData { abi: Abi::Erlang, name: "Erlang", }, AbiData { abi: Abi::Rust, name: "Rust", }, AbiData { abi: Abi::C { unwind: false }, name: "C", }, AbiData { abi: Abi::C { unwind: true }, name: "C-unwind", }, AbiData { abi: Abi::Cdecl { unwind: false }, name: "cdecl", }, AbiData { abi: Abi::Cdecl { unwind: true }, name: "cdecl-unwind", }, AbiData { abi: Abi::Stdcall { unwind: false }, name: "stdcall", }, AbiData { abi: Abi::Stdcall { unwind: true }, name: "stdcall-unwind", }, AbiData { abi: Abi::Fastcall { unwind: false }, name: "fastcall", }, AbiData { abi: Abi::Fastcall { unwind: true }, name: "fastcall-unwind", }, AbiData { abi: Abi::Vectorcall { unwind: false }, name: "vectorcall", }, AbiData { abi: Abi::Vectorcall { unwind: true }, name: "vectorcall-unwind", }, AbiData { abi: Abi::Thiscall { unwind: false }, name: "thiscall", }, AbiData { abi: Abi::Thiscall { unwind: true }, name: "thiscall-unwind", }, AbiData { abi: Abi::Aapcs { unwind: false }, name: "aapcs", }, AbiData { abi: Abi::Aapcs { unwind: true }, name: "aapcs-unwind", }, AbiData { abi: Abi::Win64 { unwind: false }, name: "win64", }, AbiData { abi: Abi::Win64 { unwind: true }, name: "win64-unwind", }, AbiData { abi: Abi::SysV64 { unwind: false }, name: "sysv64", }, AbiData { abi: Abi::SysV64 { unwind: true }, name: "sysv64-unwind", }, AbiData { abi: Abi::PtxKernel, name: "ptx-kernel", }, AbiData { abi: Abi::Msp430Interrupt, name: "msp430-interrupt", }, AbiData { abi: Abi::X86Interrupt, name: "x86-interrupt", }, AbiData { abi: Abi::AmdGpuKernel, name: "amdgpu-kernel", }, AbiData { abi: Abi::EfiApi, name: "efiapi", }, AbiData { abi: Abi::AvrInterrupt, name: "avr-interrupt", }, AbiData { abi: Abi::AvrNonBlockingInterrupt, name: "avr-non-blocking-interrupt", }, AbiData { abi: Abi::CCmseNonSecureCall, name: "C-cmse-nonsecure-call", }, AbiData { abi: Abi::Wasm, name: "wasm", }, AbiData { abi: Abi::System { unwind: false }, name: "system", }, AbiData { abi: Abi::System { unwind: true }, name: "system-unwind", }, AbiData { abi: Abi::RustIntrinsic, name: "rust-intrinsic", }, AbiData { abi: Abi::RustCall, name: "rust-call", }, AbiData { abi: Abi::PlatformIntrinsic, name: "platform-intrinsic", }, AbiData { abi: Abi::Unadjusted, name: "unadjusted", }, ]; /// Returns the ABI with the given name (if any). pub fn lookup(name: &str) -> Option<Abi> { AbiDatas .iter() .find(|abi_data| name == abi_data.name) .map(|&x| x.abi) } pub fn all_names() -> Vec<&'static str> { AbiDatas.iter().map(|d| d.name).collect() } impl Abi { /// Default ABI chosen for `extern fn` declarations without an explicit ABI. pub const FALLBACK: Abi = Abi::C { unwind: false }; #[inline] pub fn index(self) -> usize { // N.B., this ordering MUST match the AbiDatas array above. // (This is ensured by the test indices_are_correct().) use Abi::*; let i = match self { // Cross-platform ABIs Rust => 0, C { unwind: false } => 1, C { unwind: true } => 2, // Platform-specific ABIs Cdecl { unwind: false } => 3, Cdecl { unwind: true } => 4, Stdcall { unwind: false } => 5, Stdcall { unwind: true } => 6, Fastcall { unwind: false } => 7, Fastcall { unwind: true } => 8, Vectorcall { unwind: false } => 9, Vectorcall { unwind: true } => 10, Thiscall { unwind: false } => 11, Thiscall { unwind: true } => 12, Aapcs { unwind: false } => 13, Aapcs { unwind: true } => 14, Win64 { unwind: false } => 15, Win64 { unwind: true } => 16, SysV64 { unwind: false } => 17, SysV64 { unwind: true } => 18, PtxKernel => 19, Msp430Interrupt => 20, X86Interrupt => 21, AmdGpuKernel => 22, EfiApi => 23, AvrInterrupt => 24, AvrNonBlockingInterrupt => 25, CCmseNonSecureCall => 26, Wasm => 27, // Cross-platform ABIs System { unwind: false } => 28, System { unwind: true } => 29, RustIntrinsic => 30, RustCall => 31, PlatformIntrinsic => 32, Unadjusted => 33, Erlang => 34, }; debug_assert!( AbiDatas .iter() .enumerate() .find(|(_, AbiData { abi, .. })| *abi == self) .map(|(index, _)| index) .expect("abi variant has associated data") == i, "Abi index did not match `AbiDatas` ordering" ); i } #[inline] pub fn data(self) -> &'static AbiData { &AbiDatas[self.index()] } pub fn name(self) -> &'static str { self.data().name } } impl fmt::Display for Abi { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "\"{}\"", self.name()) } } #[cfg(test)] mod tests { use super::*; #[test] fn lookup_erlang() { let abi = lookup("Erlang"); assert!(abi.is_some() && abi.unwrap().data().name == "Erlang"); } #[test] fn lookup_cdecl() { let abi = lookup("cdecl"); assert!(abi.is_some() && abi.unwrap().data().name == "cdecl"); } #[test] fn lookup_baz() { let abi = lookup("baz"); assert!(abi.is_none()); } #[test] fn indices_are_correct() { for (i, abi_data) in AbiDatas.iter().enumerate() { assert_eq!(i, abi_data.abi.index()); } } }
use futures::{ future::{self, Either, FutureResult}, prelude::*, stream::{self, Chain, IterOk, Once} }; use futures::compat::Compat; use get_if_addrs::{IfAddr, get_if_addrs}; use ipnet::{IpNet, Ipv4Net, Ipv6Net}; use libp2p_core::{ Transport, multiaddr::{Protocol, Multiaddr}, transport::{ListenerEvent, TransportError} }; use log::{debug, trace}; use std::{ collections::VecDeque, io::{self, Read, Write}, iter::{self, FromIterator}, net::{IpAddr, SocketAddr}, time::{Duration, Instant}, vec::IntoIter }; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_timer::Delay; /// Represents the configuration for a TCP/IP transport capability for libp2p. #[derive(Debug, Clone, Default)] pub struct TcpConfig { } impl TcpConfig { /// Creates a new configuration object for TCP/IP. pub fn new() -> TcpConfig { TcpConfig { } } } impl Transport for TcpConfig { type Output = TcpTransStream; type Error = io::Error; type Listener = TcpListener; type ListenerUpgrade = FutureResult<Self::Output, Self::Error>; type Dial = TcpDialFut; fn listen_on(self, addr: Multiaddr) -> Result<Self::Listener, TransportError<Self::Error>> { unimplemented!() } fn dial(self, addr: Multiaddr) -> Result<Self::Dial, TransportError<Self::Error>> { let socket_addr = if let Ok(socket_addr) = multiaddr_to_socketaddr(&addr) { if socket_addr.port() == 0 || socket_addr.ip().is_unspecified() { debug!("Instantly refusing dialing {}, as it is invalid", addr); return Err(TransportError::Other(io::ErrorKind::ConnectionRefused.into())) } socket_addr } else { return Err(TransportError::MultiaddrNotSupported(addr)) }; debug!("Dialing {}", addr); let future = TcpDialFut { inner: Box::pin(TcpStream::connect(&socket_addr)), }; Ok(future) } } // This type of logic should probably be moved into the multiaddr package fn multiaddr_to_socketaddr(addr: &Multiaddr) -> Result<SocketAddr, ()> { let mut iter = addr.iter(); let proto1 = iter.next().ok_or(())?; let proto2 = iter.next().ok_or(())?; if iter.next().is_some() { return Err(()); } match (proto1, proto2) { (Protocol::Ip4(ip), Protocol::Tcp(port)) => Ok(SocketAddr::new(ip.into(), port)), (Protocol::Ip6(ip), Protocol::Tcp(port)) => Ok(SocketAddr::new(ip.into(), port)), _ => Err(()), } } /// Future that dials a TCP/IP address. #[derive(Debug)] #[must_use = "futures do nothing unless polled"] pub struct TcpDialFut { inner: Pin<Box<dyn Future<Output = tcp::TcpStream>>>, } impl Future for TcpDialFut { type Item = TcpTransStream; type Error = io::Error; fn poll(&mut self) -> Poll<TcpTransStream, io::Error> { match self.inner.poll() { Ok(Async::Ready(stream)) => { Ok(Async::Ready(TcpTransStream { inner: stream })) } Ok(Async::NotReady) => Ok(Async::NotReady), Err(err) => { debug!("Error while dialing => {:?}", err); Err(err) } } } } /// Wraps around a `TcpStream` and adds logging for important events. #[derive(Debug)] pub struct TcpTransStream { inner: TcpStream, } impl Read for TcpTransStream { fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> { self.inner.read(buf) } } impl AsyncRead for TcpTransStream { unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { self.inner.prepare_uninitialized_buffer(buf) } fn read_buf<B: bytes::BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { self.inner.read_buf(buf) } } impl Write for TcpTransStream { fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> { self.inner.write(buf) } fn flush(&mut self) -> Result<(), io::Error> { self.inner.flush() } } impl AsyncWrite for TcpTransStream { fn shutdown(&mut self) -> Poll<(), io::Error> { AsyncWrite::shutdown(&mut self.inner) } } impl Drop for TcpTransStream { fn drop(&mut self) { if let Ok(addr) = self.inner.peer_addr() { debug!("Dropped TCP connection to {:?}", addr); } else { debug!("Dropped TCP connection to undeterminate peer"); } } }
// 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. use std; use std::fmt::{self, Debug, Display, Formatter}; use std::hash::Hash; use byteorder::{ByteOrder, NetworkEndian}; use packet::{PacketBuilder, ParsablePacket}; use zerocopy::{AsBytes, ByteSlice, ByteSliceMut, FromBytes, Unaligned}; use crate::error::ParseError; use crate::wire::ipv4::{Ipv4Packet, Ipv4PacketBuilder}; use crate::wire::ipv6::{Ipv6Packet, Ipv6PacketBuilder}; /// An IP protocol version. #[allow(missing_docs)] #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum IpVersion { V4, V6, } /// An IP address. #[allow(missing_docs)] #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum IpAddress { V4(Ipv4Addr), V6(Ipv6Addr), } impl<A: IpAddr> From<A> for IpAddress { fn from(addr: A) -> IpAddress { addr.into_ip_address() } } impl IpVersion { /// The number for this IP protocol version. /// /// 4 for `V4` and 6 for `V6`. pub fn version_number(&self) -> u8 { match self { IpVersion::V4 => 4, IpVersion::V6 => 6, } } /// Is this IPv4? pub fn is_v4(&self) -> bool { *self == IpVersion::V4 } /// Is this IPv6? pub fn is_v6(&self) -> bool { *self == IpVersion::V6 } } mod sealed { // Ensure that only Ipv4 and Ipv6 can implement IpVersion and that only // Ipv4Addr and Ipv6Addr can implement IpAddr. pub trait Sealed {} impl Sealed for super::Ipv4 {} impl Sealed for super::Ipv6 {} impl Sealed for super::Ipv4Addr {} impl Sealed for super::Ipv6Addr {} } /// A trait for IP protocol versions. /// /// `Ip` encapsulates the details of a version of the IP protocol. It includes /// the `IpVersion` enum (`VERSION`) and address type (`Addr`). It is /// implemented by `Ipv4` and `Ipv6`. pub trait Ip: Sized + self::sealed::Sealed { /// The IP version. /// /// `V4` for IPv4 and `V6` for IPv6. const VERSION: IpVersion; /// The default loopback address. /// /// When sending packets to a loopback interface, this address is used as /// the source address. It is an address in the loopback subnet. const LOOPBACK_ADDRESS: Self::Addr; /// The subnet of loopback addresses. /// /// Addresses in this subnet must not appear outside a host, and may only be /// used for loopback interfaces. const LOOPBACK_SUBNET: Subnet<Self::Addr>; /// The address type for this IP version. /// /// `Ipv4Addr` for IPv4 and `Ipv6Addr` for IPv6. type Addr: IpAddr<Version = Self>; } /// IPv4. /// /// `Ipv4` implements `Ip` for IPv4. #[derive(Debug, Default)] pub struct Ipv4; impl Ip for Ipv4 { const VERSION: IpVersion = IpVersion::V4; // https://tools.ietf.org/html/rfc5735#section-3 const LOOPBACK_ADDRESS: Ipv4Addr = Ipv4Addr::new([127, 0, 0, 1]); const LOOPBACK_SUBNET: Subnet<Ipv4Addr> = Subnet { network: Ipv4Addr::new([127, 0, 0, 0]), prefix: 8 }; type Addr = Ipv4Addr; } impl Ipv4 { /// The global broadcast address. /// /// This address is considered to be a broadcast address on all networks /// regardless of subnet address. This is distinct from the subnet-specific /// broadcast address (e.g., 192.168.255.255 on the subnet 192.168.0.0/16). pub const BROADCAST_ADDRESS: Ipv4Addr = Ipv4Addr::new([255, 255, 255, 255]); } /// IPv6. /// /// `Ipv6` implements `Ip` for IPv6. #[derive(Debug, Default)] pub struct Ipv6; impl Ip for Ipv6 { const VERSION: IpVersion = IpVersion::V6; const LOOPBACK_ADDRESS: Ipv6Addr = Ipv6Addr::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); const LOOPBACK_SUBNET: Subnet<Ipv6Addr> = Subnet { network: Ipv6Addr::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]), prefix: 128, }; type Addr = Ipv6Addr; } /// An IPv4 or IPv6 address. pub trait IpAddr where Self: Sized + Eq + PartialEq + Hash + Copy + Display + Debug + self::sealed::Sealed, { /// The number of bytes in an address of this type. /// /// 4 for IPv4 and 16 for IPv6. const BYTES: u8; /// The IP version type of this address. /// /// `Ipv4` for `Ipv4Addr` and `Ipv6` for `Ipv6Addr`. type Version: Ip<Addr = Self>; /// Get the underlying bytes of the address. fn bytes(&self) -> &[u8]; /// Mask off the top bits of the address. /// /// Return a copy of `self` where all but the top `bits` bits are set to 0. fn mask(&self, bits: u8) -> Self; /// Convert a statically-typed IP address into a dynamically-typed one. fn into_ip_address(self) -> IpAddress; } /// An IPv4 address. #[derive(Copy, Clone, Default, PartialEq, Eq, Hash, FromBytes, AsBytes, Unaligned)] #[repr(transparent)] pub struct Ipv4Addr([u8; 4]); impl Ipv4Addr { /// Create a new IPv4 address. pub const fn new(bytes: [u8; 4]) -> Self { Ipv4Addr(bytes) } /// Get the bytes of the IPv4 address. pub const fn ipv4_bytes(&self) -> [u8; 4] { self.0 } } impl IpAddr for Ipv4Addr { const BYTES: u8 = 4; type Version = Ipv4; fn mask(&self, bits: u8) -> Self { assert!(bits <= 32); if bits == 0 { // shifting left by the size of the value is undefined Ipv4Addr([0; 4]) } else { let mask = <u32>::max_value() << (32 - bits); let masked = NetworkEndian::read_u32(&self.0) & mask; let mut ret = Ipv4Addr::default(); NetworkEndian::write_u32(&mut ret.0, masked); ret } } fn bytes(&self) -> &[u8] { &self.0 } fn into_ip_address(self) -> IpAddress { IpAddress::V4(self) } } impl From<std::net::Ipv4Addr> for Ipv4Addr { fn from(ip: std::net::Ipv4Addr) -> Self { Ipv4Addr::new(ip.octets()) } } impl Display for Ipv4Addr { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{}.{}.{}.{}", self.0[0], self.0[1], self.0[2], self.0[3]) } } impl Debug for Ipv4Addr { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { Display::fmt(self, f) } } /// An IPv6 address. #[derive(Copy, Clone, Default, PartialEq, Eq, Hash, FromBytes, AsBytes, Unaligned)] #[repr(transparent)] pub struct Ipv6Addr([u8; 16]); impl Ipv6Addr { /// Create a new IPv6 address. pub const fn new(bytes: [u8; 16]) -> Self { Ipv6Addr(bytes) } /// Get the bytes of the IPv6 address. pub const fn ipv6_bytes(&self) -> [u8; 16] { self.0 } } impl IpAddr for Ipv6Addr { const BYTES: u8 = 16; type Version = Ipv6; fn mask(&self, bits: u8) -> Self { assert!(bits <= 128); if bits == 0 { // shifting left by the size of the value is undefined Ipv6Addr([0; 16]) } else { let mask = <u128>::max_value() << (128 - bits); let masked = NetworkEndian::read_u128(&self.0) & mask; let mut ret = Ipv6Addr::default(); NetworkEndian::write_u128(&mut ret.0, masked); ret } } fn bytes(&self) -> &[u8] { &self.0 } fn into_ip_address(self) -> IpAddress { IpAddress::V6(self) } } impl From<std::net::Ipv6Addr> for Ipv6Addr { fn from(ip: std::net::Ipv6Addr) -> Self { Ipv6Addr::new(ip.octets()) } } impl Display for Ipv6Addr { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { let to_u16 = |idx| NetworkEndian::read_u16(&self.0[idx..idx + 2]); Display::fmt( &std::net::Ipv6Addr::new( to_u16(0), to_u16(2), to_u16(4), to_u16(6), to_u16(8), to_u16(10), to_u16(12), to_u16(14), ), f, ) } } impl Debug for Ipv6Addr { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { Display::fmt(self, f) } } /// An IP subnet. #[allow(missing_docs)] #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum IpSubnet { V4(Subnet<Ipv4Addr>), V6(Subnet<Ipv6Addr>), } impl<A: IpAddr> From<Subnet<A>> for IpSubnet { default fn from(_addr: Subnet<A>) -> IpSubnet { unreachable!() } } impl From<Subnet<Ipv4Addr>> for IpSubnet { fn from(subnet: Subnet<Ipv4Addr>) -> IpSubnet { IpSubnet::V4(subnet) } } impl From<Subnet<Ipv6Addr>> for IpSubnet { fn from(subnet: Subnet<Ipv6Addr>) -> IpSubnet { IpSubnet::V6(subnet) } } /// An IP subnet. /// /// `Subnet` is a combination of an IP network address and a prefix length. #[derive(Copy, Clone, Eq, PartialEq)] pub struct Subnet<A> { // invariant: normalized to contain only prefix bits network: A, prefix: u8, } // TODO(joshlf): Currently, we need a separate new_unchecked because trait // bounds other than Sized are not supported in const fns. Once that restriction // is lifted, we can make new a const fn. impl<A> Subnet<A> { /// Create a new subnet without enforcing correctness. /// /// Unlike `new`, `new_unchecked` does not validate that `prefix` is in the /// proper range, and does not mask `network`. It is up to the caller to /// guarantee that `prefix` is in the proper range, and that none of the /// bits of `network` beyond the prefix are set. pub const unsafe fn new_unchecked(network: A, prefix: u8) -> Subnet<A> { Subnet { network, prefix } } } impl<A: IpAddr> Subnet<A> { /// Create a new subnet. /// /// Create a new subnet with the given network address and prefix length. /// /// # Panics /// /// `new` panics if `prefix` is longer than the number of bits in this type /// of IP address (32 for IPv4 and 128 for IPv6). pub fn new(network: A, prefix: u8) -> Subnet<A> { assert!(prefix <= A::BYTES * 8); let network = network.mask(prefix); Subnet { network, prefix } } /// Get the network address component of this subnet. /// /// `network` returns the network address component of this subnet. Any bits /// beyond the prefix will be zero. pub fn network(&self) -> A { self.network } /// Get the prefix length component of this subnet. pub fn prefix(&self) -> u8 { self.prefix } /// Test whether an address is in this subnet. /// /// Test whether `address` is in this subnet by testing whether the prefix /// bits match the prefix bits of the subnet's network address. This is /// equivalent to `subnet.network() == address.mask(subnet.prefix())`. pub fn contains(&self, address: A) -> bool { self.network == address.mask(self.prefix) } } impl Subnet<Ipv4Addr> { /// Get the broadcast address in this subnet. pub fn broadcast(&self) -> Ipv4Addr { if self.prefix == 32 { // shifting right by the size of the value is undefined self.network } else { let mask = <u32>::max_value() >> self.prefix; let masked = NetworkEndian::read_u32(&self.network.0) | mask; let mut ret = Ipv4Addr::default(); NetworkEndian::write_u32(&mut ret.0, masked); ret } } } impl<A: IpAddr> Display for Subnet<A> { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{}/{}", self.network, self.prefix) } } impl<A: IpAddr> Debug for Subnet<A> { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{}/{}", self.network, self.prefix) } } /// An IP protocol or next header number. /// /// For IPv4, this is the protocol number. For IPv6, this is the next header /// number. #[allow(missing_docs)] #[derive(Copy, Clone, Hash, Eq, PartialEq)] pub enum IpProto { Icmp, Igmp, Tcp, Udp, Icmpv6, Other(u8), } impl IpProto { const ICMP: u8 = 1; const IGMP: u8 = 2; const TCP: u8 = 6; const UDP: u8 = 17; const ICMPV6: u8 = 58; } impl From<u8> for IpProto { fn from(u: u8) -> IpProto { match u { Self::ICMP => IpProto::Icmp, Self::IGMP => IpProto::Igmp, Self::TCP => IpProto::Tcp, Self::UDP => IpProto::Udp, Self::ICMPV6 => IpProto::Icmpv6, u => IpProto::Other(u), } } } impl Into<u8> for IpProto { fn into(self) -> u8 { match self { IpProto::Icmp => Self::ICMP, IpProto::Igmp => Self::IGMP, IpProto::Tcp => Self::TCP, IpProto::Udp => Self::UDP, IpProto::Icmpv6 => Self::ICMPV6, IpProto::Other(u) => u, } } } impl Display for IpProto { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!( f, "{}", match self { IpProto::Icmp => "ICMP", IpProto::Igmp => "IGMP", IpProto::Tcp => "TCP", IpProto::Udp => "UDP", IpProto::Icmpv6 => "ICMPv6", IpProto::Other(u) => return write!(f, "IP protocol {}", u), } ) } } impl Debug for IpProto { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { Display::fmt(self, f) } } /// An extension trait to the `Ip` trait adding an associated `Packet` type. /// /// `IpExt` extends the `Ip` trait, adding an associated `Packet` type. It /// cannot be part of the `Ip` trait because it requires a `B: ByteSlice` /// parameter (due to the requirements of `packet::ParsablePacket`). pub trait IpExt<B: ByteSlice>: Ip { type Packet: IpPacket<B, Self, Builder = Self::PacketBuilder>; type PacketBuilder: IpPacketBuilder<Self>; } // NOTE(joshlf): We know that this is safe because we seal the Ip trait to only // be implemented by Ipv4 and Ipv6. impl<B: ByteSlice, I: Ip> IpExt<B> for I { default type Packet = !; default type PacketBuilder = !; } impl<B: ByteSlice> IpExt<B> for Ipv4 { type Packet = Ipv4Packet<B>; type PacketBuilder = Ipv4PacketBuilder; } impl<B: ByteSlice> IpExt<B> for Ipv6 { type Packet = Ipv6Packet<B>; type PacketBuilder = Ipv6PacketBuilder; } /// An IPv4 or IPv6 packet. /// /// `IpPacket` is implemented by `Ipv4Packet` and `Ipv6Packet`. pub trait IpPacket<B: ByteSlice, I: Ip>: Sized + Debug + ParsablePacket<B, (), Error = ParseError> { /// A builder for this packet type. type Builder: IpPacketBuilder<I>; /// The source IP address. fn src_ip(&self) -> I::Addr; /// The destination IP address. fn dst_ip(&self) -> I::Addr; /// The protocol (IPv4) or next header (IPv6) field. fn proto(&self) -> IpProto; /// The Time to Live (TTL). fn ttl(&self) -> u8; /// Set the Time to Live (TTL). /// /// `set_ttl` updates the packet's TTL in place. fn set_ttl(&mut self, ttl: u8) where B: ByteSliceMut; } impl<B: ByteSlice> IpPacket<B, Ipv4> for Ipv4Packet<B> { type Builder = Ipv4PacketBuilder; fn src_ip(&self) -> Ipv4Addr { Ipv4Packet::src_ip(self) } fn dst_ip(&self) -> Ipv4Addr { Ipv4Packet::dst_ip(self) } fn proto(&self) -> IpProto { Ipv4Packet::proto(self) } fn ttl(&self) -> u8 { Ipv4Packet::ttl(self) } fn set_ttl(&mut self, ttl: u8) where B: ByteSliceMut, { Ipv4Packet::set_ttl(self, ttl) } } impl<B: ByteSlice> IpPacket<B, Ipv6> for Ipv6Packet<B> { type Builder = Ipv6PacketBuilder; fn src_ip(&self) -> Ipv6Addr { Ipv6Packet::src_ip(self) } fn dst_ip(&self) -> Ipv6Addr { Ipv6Packet::dst_ip(self) } fn proto(&self) -> IpProto { Ipv6Packet::next_header(self) } fn ttl(&self) -> u8 { Ipv6Packet::hop_limit(self) } fn set_ttl(&mut self, ttl: u8) where B: ByteSliceMut, { Ipv6Packet::set_hop_limit(self, ttl) } } /// A builder for IP packets. /// /// `IpPacketBuilder` is implemented by `Ipv4PacketBuilder` and /// `Ipv6PacketBuilder`. pub trait IpPacketBuilder<I: Ip>: PacketBuilder { fn new(src_ip: I::Addr, dst_ip: I::Addr, ttl: u8, proto: IpProto) -> Self; } impl IpPacketBuilder<Ipv4> for Ipv4PacketBuilder { fn new(src_ip: Ipv4Addr, dst_ip: Ipv4Addr, ttl: u8, proto: IpProto) -> Ipv4PacketBuilder { Ipv4PacketBuilder::new(src_ip, dst_ip, ttl, proto) } } impl IpPacketBuilder<Ipv6> for Ipv6PacketBuilder { fn new(src_ip: Ipv6Addr, dst_ip: Ipv6Addr, ttl: u8, proto: IpProto) -> Ipv6PacketBuilder { Ipv6PacketBuilder::new(src_ip, dst_ip, ttl, proto) } } /// An IPv4 header option. /// /// An IPv4 header option comprises metadata about the option (which is stored /// in the kind byte) and the option itself. Note that all kind-byte-only /// options are handled by the utilities in `wire::util::options`, so this type /// only supports options with variable-length data. /// /// See [Wikipedia] or [RFC 791] for more details. /// /// [Wikipedia]: https://en.wikipedia.org/wiki/IPv4#Options /// [RFC 791]: https://tools.ietf.org/html/rfc791#page-15 pub struct Ipv4Option<'a> { /// Whether this option needs to be copied into all fragments of a fragmented packet. pub copied: bool, // TODO(joshlf): include "Option Class"? /// The variable-length option data. pub data: Ipv4OptionData<'a>, } /// The data associated with an IPv4 header option. /// /// `Ipv4OptionData` represents the variable-length data field of an IPv4 header /// option. #[allow(missing_docs)] pub enum Ipv4OptionData<'a> { // The maximum header length is 60 bytes, and the fixed-length header is 20 // bytes, so there are 40 bytes for the options. That leaves a maximum // options size of 1 kind byte + 1 length byte + 38 data bytes. /// Data for an unrecognized option kind. /// /// Any unrecognized option kind will have its data parsed using this /// variant. This allows code to copy unrecognized options into packets when /// forwarding. /// /// `data`'s length is in the range [0, 38]. Unrecognized { kind: u8, len: u8, data: &'a [u8] }, } #[cfg(test)] mod tests { use super::*; macro_rules! add_mask_test { ($name:ident, $addr:ident, $from_ip:expr => { $($mask:expr => $to_ip:expr),* }) => { #[test] fn $name() { let from = $addr::new($from_ip); $( assert_eq!(from.mask($mask), $addr::new($to_ip), "(`{}`.mask({}))", from, $mask); )* } }; ($name:ident, $addr:ident, $from_ip:expr => { $($mask:expr => $to_ip:expr),*, }) => ( add_mask_test!($name, $addr, $from_ip => { $($mask => $to_ip),* }); ) } add_mask_test!(v4_full_mask, Ipv4Addr, [255, 254, 253, 252] => { 32 => [255, 254, 253, 252], 28 => [255, 254, 253, 240], 24 => [255, 254, 253, 0], 20 => [255, 254, 240, 0], 16 => [255, 254, 0, 0], 12 => [255, 240, 0, 0], 8 => [255, 0, 0, 0], 4 => [240, 0, 0, 0], 0 => [0, 0, 0, 0], }); add_mask_test!(v6_full_mask, Ipv6Addr, [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1, 0xF0] => { 128 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1, 0xF0], 112 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0x00, 0x00], 96 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0x00, 0x00, 0x00, 0x00], 80 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 64 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 48 => [0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 32 => [0xFF, 0xFE, 0xFD, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 16 => [0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 8 => [0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 0 => [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], } ); }
// Copyright 2022 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 anyerror::AnyError; use common_meta_stoerr::MetaStorageError; use crate::raft_types::InitializeError; use crate::MetaNetworkError; use crate::RaftError; /// Error raised when meta-server startup. #[derive(thiserror::Error, serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] pub enum MetaStartupError { #[error(transparent)] InitializeError(#[from] InitializeError), #[error("fail to add node to cluster: {source}")] AddNodeError { source: AnyError }, #[error("{0}")] InvalidConfig(String), #[error("fail to open store: {0}")] StoreOpenError(#[from] MetaStorageError), #[error(transparent)] ServiceStartupError(#[from] MetaNetworkError), #[error("raft state present id={0}, can not create")] MetaStoreAlreadyExists(u64), #[error("raft state absent, can not open")] MetaStoreNotFound, #[error("{0}")] MetaServiceError(String), } impl From<RaftError<InitializeError>> for MetaStartupError { fn from(value: RaftError<InitializeError>) -> Self { match value { RaftError::APIError(e) => e.into(), RaftError::Fatal(f) => Self::MetaServiceError(f.to_string()), } } }