text
stringlengths
8
4.13M
// 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. use std::sync::Arc; use common_base::base::GlobalInstance; use common_exception::Result; use common_grpc::RpcClientConf; use common_management::FileFormatApi; use common_management::FileFormatMgr; use common_management::QuotaApi; use common_management::QuotaMgr; use common_management::RoleApi; use common_management::RoleMgr; use common_management::SettingApi; use common_management::SettingMgr; use common_management::StageApi; use common_management::StageMgr; use common_management::UdfApi; use common_management::UdfMgr; use common_management::UserApi; use common_management::UserMgr; use common_meta_app::principal::AuthInfo; use common_meta_app::tenant::TenantQuota; use common_meta_kvapi::kvapi; use common_meta_store::MetaStore; use common_meta_store::MetaStoreProvider; use common_meta_types::MatchSeq; use common_meta_types::MetaError; use tracing::warn; use crate::idm_config::IDMConfig; pub struct UserApiProvider { meta: MetaStore, client: Arc<dyn kvapi::KVApi<Error = MetaError>>, idm_config: IDMConfig, } impl UserApiProvider { pub async fn init( conf: RpcClientConf, idm_config: IDMConfig, tenant: &str, quota: Option<TenantQuota>, ) -> Result<()> { GlobalInstance::set(Self::try_create(conf, idm_config).await?); if let Some(q) = quota { let i = UserApiProvider::instance().get_tenant_quota_api_client(tenant)?; let res = i.get_quota(MatchSeq::GE(0)).await?; i.set_quota(&q, MatchSeq::Exact(res.seq)).await?; } Ok(()) } pub async fn try_create( conf: RpcClientConf, idm_config: IDMConfig, ) -> Result<Arc<UserApiProvider>> { let client = MetaStoreProvider::new(conf).create_meta_store().await?; for user in idm_config.users.keys() { match user.as_str() { "root" | "default" => { warn!("Reserved built-in user `{}` will be ignored", user); } _ => {} } } Ok(Arc::new(UserApiProvider { meta: client.clone(), client: client.arc(), idm_config, })) } pub async fn try_create_simple(conf: RpcClientConf) -> Result<Arc<UserApiProvider>> { Self::try_create(conf, IDMConfig::default()).await } pub fn instance() -> Arc<UserApiProvider> { GlobalInstance::get() } pub fn get_user_api_client(&self, tenant: &str) -> Result<Arc<impl UserApi>> { Ok(Arc::new(UserMgr::create(self.client.clone(), tenant)?)) } pub fn get_role_api_client(&self, tenant: &str) -> Result<Arc<impl RoleApi>> { Ok(Arc::new(RoleMgr::create(self.client.clone(), tenant)?)) } pub fn get_stage_api_client(&self, tenant: &str) -> Result<Arc<dyn StageApi>> { Ok(Arc::new(StageMgr::create(self.client.clone(), tenant)?)) } pub fn get_file_format_api_client(&self, tenant: &str) -> Result<Arc<dyn FileFormatApi>> { Ok(Arc::new(FileFormatMgr::create( self.client.clone(), tenant, )?)) } pub fn get_udf_api_client(&self, tenant: &str) -> Result<Arc<dyn UdfApi>> { Ok(Arc::new(UdfMgr::create(self.client.clone(), tenant)?)) } pub fn get_tenant_quota_api_client(&self, tenant: &str) -> Result<Arc<dyn QuotaApi>> { Ok(Arc::new(QuotaMgr::create(self.client.clone(), tenant)?)) } pub fn get_setting_api_client(&self, tenant: &str) -> Result<Arc<dyn SettingApi>> { Ok(Arc::new(SettingMgr::create(self.client.clone(), tenant)?)) } pub fn get_meta_store_client(&self) -> Arc<MetaStore> { Arc::new(self.meta.clone()) } pub fn get_configured_user(&self, user_name: &str) -> Option<&AuthInfo> { self.idm_config.users.get(user_name) } }
use entropy::probabilities::IntoStatistics; use io::statistics::Bytes; use std::io::Write; /// An arbitrary buffer size for Brotli compression. /// /// This should not impact file size, only compression speed. const BROTLI_BUFFER_SIZE: usize = 32768; /// Highest Brotli compression level. /// /// Higher values provide better file size but slower compression. // FIXME: Should probably become a compression parameter. const BROTLI_QUALITY: u32 = 11; /// An arbitrary window size for Brotli compression. /// /// Higher values provide better file size but slower compression. // FIXME: SHould probably become a compression parameter. const BROTLI_LG_WINDOW_SIZE: u32 = 20; /// A segment of data, initialized lazily. Also supports writing /// all data to an external file, for /// forensics purposes. /// Lazy initialization ensures that we do not create empty /// sections in a compressed (rather, we skip the section /// entirely) or empty files. pub struct LazyStream { /// A brotli-compressed buffer with the data. /// /// Initialize in the first call to `write()`. lazy_brotli: Option<brotli::CompressorWriter<Vec<u8>>>, /// An optional path to which to write an uncompressed copy /// of the data. dump_path: Option<std::path::PathBuf>, /// The file to the data must be written. Initialized /// in the first call to `write()` if `dump_path` is /// provided. lazy_dump_file: Option<std::fs::File>, /// Number of calls to `increment()` so far. instances: usize, /// Number of bytes received during calls to `write()`. Used /// for debugging and statistics. bytes_written: usize, } impl LazyStream { /// Create a new LazyStream. /// /// If `dump_path.is_some()`, all data written to this stream /// will also be dumped in the file at `dump_path`. pub fn new(dump_path: Option<std::path::PathBuf>) -> Self { LazyStream { dump_path, lazy_brotli: None, lazy_dump_file: None, instances: 0, bytes_written: 0, } } /// Count one more instance. pub fn increment(&mut self) { self.instances += 1; } /// Return the number of calls to `increment()` so far. pub fn instances(&self) -> usize { self.instances } /// Return the number of bytes written so far. pub fn bytes_written(&self) -> usize { self.bytes_written } /// Get the file for writing, initializing it if necessary. /// /// Always returns Ok(None) if `dump_path` was specified as `None`. fn get_file(&mut self) -> Result<Option<&mut std::fs::File>, std::io::Error> { if let Some(ref mut writer) = self.lazy_dump_file { return Ok(Some(writer)); } if let Some(ref path) = self.dump_path { let dir = path.parent().unwrap(); std::fs::DirBuilder::new().recursive(true).create(dir)?; let file = std::fs::File::create(path)?; self.lazy_dump_file = Some(file); return Ok(Some(self.lazy_dump_file.as_mut().unwrap())); } Ok(None) } /// Get the data that needs to be actually written to disk. pub fn data(&self) -> Option<&[u8]> { match self.lazy_brotli { Some(ref writer) => Some(writer.get_ref().as_slice()), None => None, } } } impl std::io::Write for LazyStream { /// Compress the data to the Brotli stream, initializing it if necessary. /// Also dump the data to `dump_path` if `dump_path` was specified. fn write(&mut self, data: &[u8]) -> Result<usize, std::io::Error> { // 1. Write to Brotli. { let brotli = self.lazy_brotli.get_or_insert_with(|| { brotli::CompressorWriter::new( Vec::with_capacity(BROTLI_BUFFER_SIZE), BROTLI_BUFFER_SIZE, BROTLI_QUALITY, BROTLI_LG_WINDOW_SIZE, ) }); brotli.write_all(data)?; } // 2. Write to file if necessary. if let Some(writer) = self.get_file()? { writer.write_all(data)?; } // 3. Done. self.bytes_written += data.len(); Ok(data.len()) } /// Flush all output streams. fn flush(&mut self) -> Result<(), std::io::Error> { if let Some(ref mut writer) = self.lazy_brotli { writer.flush()?; } if let Some(ref mut writer) = self.lazy_dump_file { writer.flush()?; } Ok(()) } } impl IntoStatistics for LazyStream { type AsStatistics = Bytes; fn into_statistics(mut self, _description: &str) -> Bytes { match self.lazy_brotli { None => 0.into(), Some(ref mut writer) => { writer.flush().unwrap(); // Writing to a `Vec<u8>` cannot fail. writer.get_ref().len().into() } } } }
use std::any::Any; use std::fmt; use std::fmt::Formatter; use std::hash::{Hash, Hasher}; use std::marker::PhantomData as marker; use std::ptr::NonNull; use std::sync::atomic::AtomicUsize; use std::sync::Arc; pub type Var = Arc<dyn Any + Send + Sync>; #[derive(Clone)] pub enum Version { Read(Var), Write(Var), } impl Version { pub fn extract(&self) -> &Var { match self { Version::Read(x) => x, Version::Write(x) => x, } } pub fn read(&self) -> Var { return match &*self { &Version::Read(ref v) | &Version::Write(ref v) => v.clone(), }; } pub fn write(&mut self, w: Var) { *self = match self.clone() { Version::Write(_) => Version::Write(w), // TODO: Not sure _ => Version::Write(w), }; } } impl fmt::Debug for Version { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("Version").field("var", &self).finish() } } impl Hash for Version { fn hash<H: Hasher>(&self, state: &mut H) { let x: ArcLayout<dyn Any + Send + Sync> = unsafe { std::mem::transmute_copy(&self.read()) }; x.ptr.as_ptr().hash(state); } } impl PartialEq for Version { fn eq(&self, other: &Self) -> bool { match (self, other) { (Version::Read(left), Version::Read(right)) => Arc::ptr_eq(&left, &right), (Version::Write(left), Version::Write(right)) => Arc::ptr_eq(&left, &right), _ => false, } } } impl Eq for Version {} #[repr(C)] struct ArcInnerLayout<T: ?Sized> { strong: AtomicUsize, weak: AtomicUsize, data: T, } struct ArcLayout<T: ?Sized> { ptr: NonNull<ArcInnerLayout<T>>, phantom: marker<ArcInnerLayout<T>>, }
fn main() { println!("Hello, world!"); let a = [1, 2, 3]; let b = &a; println!("{:p}", b); let mut c = vec![1, 2, 3, 4]; c.push(5); println!("{:?}", c); println!("{:?}", c.pop()); let e = &42; assert_eq!(42, *e); assert_eq!(fizz_buzz(15), "fizz_buzz".to_string()); assert_eq!(fizz_buzz(3), "fizz".to_string()); assert_eq!(fizz_buzz(5), "buzz".to_string()); assert_eq!(fizz_buzz(13), "13".to_string()); assert_eq!(math(sum, 1, 2), 3); assert_eq!(math(sub, 1, 2), -1); let mut arr = [0; init_len()]; for x in 0..5 { arr[x] = x; } println!("{:?}", arr); let close_anntated = |i: i32, j: i32| -> i32 { i + j }; let close_inferred = |i, j| i + j; let i = 1; let j = 6; assert_eq!(close_anntated(i, j), 7); assert_eq!(close_inferred(i, j), 7); let x = 5; let y = 7; assert_eq!(close_math(|| x + y), 12); assert_eq!(close_math(|| x * y), 35); let result = two_times_impl(); assert_eq!(result(2), 4); let isBool = if 1 > 2 { true } else { false }; println!("{}", isBool); } pub fn fizz_buzz(num: i32) -> String { if num % 15 == 0 { return "fizz_buzz".to_string(); } else if num % 3 == 0 { return "fizz".to_string(); } else if num % 5 == 0 { return "buzz".to_string(); } else { return num.to_string(); } } pub fn math(op: fn(i32, i32) -> i32, a: i32, b: i32) -> i32 { op(a, b) } fn sum(a: i32, b: i32) -> i32 { a + b } fn sub(a: i32, b: i32) -> i32 { a - b } const fn init_len() -> usize { return 5; } fn close_math<F: Fn() -> i32>(op: F) -> i32 { op() } fn two_times_impl() -> impl Fn(i32) -> i32 { let i = 2; move |j| j * i }
//! Serialise and deserialise common types in packets use crate::caputre_packets::StreamIdentifier; use byteorder::{ByteOrder, NetworkEndian}; use std::convert::identity; use std::fmt; #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum Direction { ToGameserver, FromGameserver, ToLoginserver, FromLoginserver, } impl From<StreamIdentifier> for Direction { fn from(item: StreamIdentifier) -> Self { if item.dest_port == 6112 { return Direction::ToGameserver; } if item.source_port == 6112 { return Direction::FromGameserver; } if item.dest_port == 20481 { return Direction::ToLoginserver; } if item.source_port == 20481 { return Direction::FromLoginserver; } log::warn!( "Could not convert StreamIdentifier: {:?} to Direction, defaulting to FromLoginserver", item ); Direction::FromLoginserver } } impl From<u8> for Direction { fn from(item: u8) -> Self { match item { 0 => Direction::ToGameserver, 1 => Direction::FromGameserver, 2 => Direction::ToLoginserver, _ => Direction::FromLoginserver, } } } impl From<Direction> for u8 { fn from(item: Direction) -> Self { match item { Direction::ToGameserver => 0, Direction::FromGameserver => 1, Direction::ToLoginserver => 2, Direction::FromLoginserver => 3, } } } impl fmt::Display for Direction { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match self { Direction::ToGameserver => "C -> GS", Direction::FromGameserver => "C <- GS", Direction::ToLoginserver => "C -> LS", Direction::FromLoginserver => "C <- LS", } ) } } #[derive(Clone, Eq, PartialEq)] pub struct PoePacket { pub identifier: StreamIdentifier, pub payload: Vec<u8>, } impl fmt::Display for PoePacket { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{} id: {:02x?}, size: {}", self.identifier, &self.payload[..2], self.payload.len() ) } } impl PoePacket { pub fn new(payload_slice: &[u8], identifier: StreamIdentifier) -> Self { let mut payload = Vec::with_capacity(payload_slice.len()); payload.extend_from_slice(&payload_slice[..]); PoePacket { identifier, payload, } } pub fn stream_id(&self) -> u16 { let direction: Direction = self.identifier.into(); match direction { Direction::ToLoginserver | Direction::ToGameserver => self.identifier.source_port, Direction::FromLoginserver | Direction::FromGameserver => self.identifier.dest_port, } } // pub fn to_buf(&self) -> Vec<u8> { // let mut buf = vec![0u8; 9 + self.payload.len()]; // buf[0] = self.direction.into(); // NetworkEndian::write_u16(&mut buf[1..3], self.stream_id); // NetworkEndian::write_u32(&mut buf[3..7], self.ip.into()); // NetworkEndian::write_u16(&mut buf[7..9], self.payload.len() as u16); // buf.extend_from_slice(&self.payload[..]); // // buf // } // // pub fn from_buf(buf: &[u8]) -> Result<Self, crate::Error> { // if buf.len() < 9 { // return Err(crate::Error::CanNotDeserialize); // } // let direction = buf[0].into(); // let port = NetworkEndian::read_u16(&buf[1..3]); // let ip = NetworkEndian::read_u32(&buf[3..7]).into(); // let size = NetworkEndian::read_u16(&buf[7..9]) as usize; // // if buf.len() < 9 + size { // return Err(crate::Error::CanNotDeserialize); // } // // // TODO: payload begins from index 11 or 15, instead of expected 9 // let mut payload = Vec::with_capacity(size); // payload.extend_from_slice(&buf[buf.len() - size..]); // // let packet = PoePacket { // direction, // payload, // ip, // stream_id: port, // }; // // Ok(packet) // } }
// use std::collections::VecDeque; // trait Event; pub enum Change { Insertion, } // some fact has changed pub enum Fact { Delete, }
use super::*; use crate::parser::ast::*; use anyhow::Result; pub fn write_class(w: &mut Writer, types: &Types, cls: &Class) -> Result<()> { let mut symbols = Symbols::class(&types, cls); cls.subroutines .iter() .map(|sub| function::write_function(w, &mut symbols, cls, sub)) .collect::<Result<()>>() }
use std::{process}; use std::collections::HashMap; use std::error::Error; use std::io; use element::Element; mod element; fn main() { set_icon(); let mut elements: Vec<Element> = Vec::new(); build_list(&mut elements); let element_map = build_map(&mut elements); show_prompts(&element_map); } fn read_element_file() -> String { let raw_data = include_str!("D:\\Rust-General\\periodic_table\\resources\\elements.csv"); raw_data.parse().unwrap() } fn turn_to_struct(list: &mut Vec<Element>) -> Result<(), Box<dyn Error>> { let raw_data = read_element_file(); let mut reader = csv::Reader::from_reader(raw_data.as_bytes()); for result in reader.deserialize() { let element: Element = result?; list.push(element); } Ok(()) } fn build_list(list: &mut Vec<Element>) -> () { if let Err(err) = turn_to_struct(list) { println!("{}", err); process::exit(1); } } fn build_map(list: &mut Vec<Element>) -> HashMap<String, &Element> { let mut map: HashMap<String, &Element> = HashMap::new(); for element in list { map.insert(element.name.to_string().to_ascii_lowercase(), element); map.insert(element.symbol.to_string().to_ascii_lowercase(), element); map.insert(element.atomic_num.to_string(), element); } map } fn show_prompts(elements: &HashMap<String, &Element>) { let quit_tag_1: String = String::from("quit"); let quit_tag_2: char = 'q'; loop { println!("------------Periodic Table------------"); println!("Enter an element's symbol, name, or atomic number to receive it's information.\n(q)uit to exit."); let mut search = String::new(); io::stdin().read_line(&mut search).expect("Error reading input"); let search: String = match search.trim().to_ascii_lowercase().parse() { Ok(search_input) => search_input, Err(_) => continue, }; match search { search if search.eq(&quit_tag_1) || search.eq(&quit_tag_2.to_string()) => process::exit(0), search if search.len() < 1 => continue, _ => () } if elements.get(&search) != None { let element: &Element = elements.get(&search).unwrap(); show_info(element); } } } fn show_info(element: &Element) { println!("Name: {}", element.name); println!("Symbol: {}", element.symbol); println!("Atomic Number: {}", element.atomic_num); println!("Molar mass: {} g/mol", element.mass_per_mole); println!("Number of Protons: {}", element.number_protons); println!("Number of Neutrons: {}", element.number_neutrons); println!("Number of Electrons: {}", element.number_electrons); println!("Category: {}", element.elem_type); if element.group != None { println!("Column: {}", element.group.unwrap()); } if element.number_isotopes != None { println!("Number of Isotopes: {}", element.number_isotopes.unwrap()); } if element.number_valence != None { println!("Number of Valence: {}", element.number_valence.unwrap()); } } fn set_icon() { if cfg!(target_os = "windows") { let mut res = winres::WindowsResource::new(); res.set_icon("test.ico"); res.compile().unwrap(); } }
#[doc = "Reader of register CR4"] pub type R = crate::R<u32, super::CR4>; #[doc = "Writer for register CR4"] pub type W = crate::W<u32, super::CR4>; #[doc = "Register CR4 `reset()`'s with value 0"] impl crate::ResetValue for super::CR4 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `SMPSLPEN`"] pub type SMPSLPEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SMPSLPEN`"] pub struct SMPSLPEN_W<'a> { w: &'a mut W, } impl<'a> SMPSLPEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `SMPSFSTEN`"] pub type SMPSFSTEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SMPSFSTEN`"] pub struct SMPSFSTEN_W<'a> { w: &'a mut W, } impl<'a> SMPSFSTEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `EXTSMPSEN`"] pub type EXTSMPSEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EXTSMPSEN`"] pub struct EXTSMPSEN_W<'a> { w: &'a mut W, } impl<'a> EXTSMPSEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `SMPSBYP`"] pub type SMPSBYP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SMPSBYP`"] pub struct SMPSBYP_W<'a> { w: &'a mut W, } impl<'a> SMPSBYP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `VBRS`"] pub type VBRS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VBRS`"] pub struct VBRS_W<'a> { w: &'a mut W, } impl<'a> VBRS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `VBE`"] pub type VBE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VBE`"] pub struct VBE_W<'a> { w: &'a mut W, } impl<'a> VBE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `WUPP5`"] pub type WUPP5_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WUPP5`"] pub struct WUPP5_W<'a> { w: &'a mut W, } impl<'a> WUPP5_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `WUPP4`"] pub type WUPP4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WUPP4`"] pub struct WUPP4_W<'a> { w: &'a mut W, } impl<'a> WUPP4_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `WUPP3`"] pub type WUPP3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WUPP3`"] pub struct WUPP3_W<'a> { w: &'a mut W, } impl<'a> WUPP3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `WUPP2`"] pub type WUPP2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WUPP2`"] pub struct WUPP2_W<'a> { w: &'a mut W, } impl<'a> WUPP2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `WUPP1`"] pub type WUPP1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WUPP1`"] pub struct WUPP1_W<'a> { w: &'a mut W, } impl<'a> WUPP1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 15 - SMPSLPEN"] #[inline(always)] pub fn smpslpen(&self) -> SMPSLPEN_R { SMPSLPEN_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 14 - SMPSFSTEN"] #[inline(always)] pub fn smpsfsten(&self) -> SMPSFSTEN_R { SMPSFSTEN_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 13 - EXTSMPSEN"] #[inline(always)] pub fn extsmpsen(&self) -> EXTSMPSEN_R { EXTSMPSEN_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 12 - SMPSBYP"] #[inline(always)] pub fn smpsbyp(&self) -> SMPSBYP_R { SMPSBYP_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 9 - VBAT battery charging resistor selection"] #[inline(always)] pub fn vbrs(&self) -> VBRS_R { VBRS_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - VBAT battery charging enable"] #[inline(always)] pub fn vbe(&self) -> VBE_R { VBE_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 4 - Wakeup pin WKUP5 polarity"] #[inline(always)] pub fn wupp5(&self) -> WUPP5_R { WUPP5_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - Wakeup pin WKUP4 polarity"] #[inline(always)] pub fn wupp4(&self) -> WUPP4_R { WUPP4_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - Wakeup pin WKUP3 polarity"] #[inline(always)] pub fn wupp3(&self) -> WUPP3_R { WUPP3_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - Wakeup pin WKUP2 polarity"] #[inline(always)] pub fn wupp2(&self) -> WUPP2_R { WUPP2_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Wakeup pin WKUP1 polarity"] #[inline(always)] pub fn wupp1(&self) -> WUPP1_R { WUPP1_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 15 - SMPSLPEN"] #[inline(always)] pub fn smpslpen(&mut self) -> SMPSLPEN_W { SMPSLPEN_W { w: self } } #[doc = "Bit 14 - SMPSFSTEN"] #[inline(always)] pub fn smpsfsten(&mut self) -> SMPSFSTEN_W { SMPSFSTEN_W { w: self } } #[doc = "Bit 13 - EXTSMPSEN"] #[inline(always)] pub fn extsmpsen(&mut self) -> EXTSMPSEN_W { EXTSMPSEN_W { w: self } } #[doc = "Bit 12 - SMPSBYP"] #[inline(always)] pub fn smpsbyp(&mut self) -> SMPSBYP_W { SMPSBYP_W { w: self } } #[doc = "Bit 9 - VBAT battery charging resistor selection"] #[inline(always)] pub fn vbrs(&mut self) -> VBRS_W { VBRS_W { w: self } } #[doc = "Bit 8 - VBAT battery charging enable"] #[inline(always)] pub fn vbe(&mut self) -> VBE_W { VBE_W { w: self } } #[doc = "Bit 4 - Wakeup pin WKUP5 polarity"] #[inline(always)] pub fn wupp5(&mut self) -> WUPP5_W { WUPP5_W { w: self } } #[doc = "Bit 3 - Wakeup pin WKUP4 polarity"] #[inline(always)] pub fn wupp4(&mut self) -> WUPP4_W { WUPP4_W { w: self } } #[doc = "Bit 2 - Wakeup pin WKUP3 polarity"] #[inline(always)] pub fn wupp3(&mut self) -> WUPP3_W { WUPP3_W { w: self } } #[doc = "Bit 1 - Wakeup pin WKUP2 polarity"] #[inline(always)] pub fn wupp2(&mut self) -> WUPP2_W { WUPP2_W { w: self } } #[doc = "Bit 0 - Wakeup pin WKUP1 polarity"] #[inline(always)] pub fn wupp1(&mut self) -> WUPP1_W { WUPP1_W { w: self } } }
fn main() { let input: Vec<i64> = include_str!("../input") .replace("\n", "") .split(",") .map(|num| num.parse().unwrap()) .collect(); println!("Part 1: {}", part1(&input)); println!("Part 2: {}", part2(&input)); } fn part1(input: &Vec<i64>) -> i64 { procreate(input, 80) } fn part2(input: &Vec<i64>) -> i64 { procreate(input, 256) } fn procreate(input: &Vec<i64>, days: i32) -> i64 { let mut fish = vec![0; 9]; for i in input { fish[*i as usize] += 1; } for _ in 0..days { fish.rotate_left(1); fish[6] += fish[8]; } fish.iter().sum() }
use std::io; // Rng 是一个 trait,它定义了随机数生成器应实现的方法 use rand::Rng; // 同 Result 一样,Ordering 也是一个枚举,它的成员是 Less, Greater, Equal use std::cmp::Ordering; fn main() { println!("Guess the number!"); println!("Please input your guess."); // rand::thread_rng 函数提供实际使用的随机数生成器 // 它位于当前执行线程的本地环境中,并从操作系统取 seed // gen_range 产生一个[)区间的随机数 // 如何知道依赖的 trait 的API文档?在项目目录构建依赖包文档:cargo doc --open // 自动类型推断,u32 let secret_number = rand::thread_rng().gen_range(1, 101); // println!("The secret number is: {}", secret_number); loop { // let 用来创建并绑定变量 // 在 Rust 中,变量默认是不可变的,在变量名前使用 mut 来使一个变量可变: // String::new() 是标准款提供的字符串类型,是 UTF-8 编码的可增长文本快 // ::new 表示 new 是 String 类型的一个 关联函数(associated function) // 关联函数是针对类型实现的,在这个例子中是 String,而不是 String 的某个特定实例 // 关联函数相当于 Java/C++ 中的静态方法(static method), // 而针对特定实例的方法在 Ruby 中出现过 // 另外此处的 类型String,相比之 类String(Class String), // 和 Mysql 中的表(table)切换到 ES 的 index 转换有点类似 // Rust 有一个静态强类型系统,同时也有类型推断 let mut guess = String::new(); // read_line 的工作是将用户的输入存入一个字符串,所以此处的 guess 需要是可变的 // & 表示这个参数是一个 引用(reference),它允许多处代码访问同一处数据,即指针 // 引用是一个复杂的特性,Rust 的一个主要优势就是安全而简单的操纵引用 io::stdin() // read_line 返回一个值 io::Result,在 Rust 中叫做 Result 类型 // Result 类型是 枚举(enumerations),即 enum,这里的枚举成员值有 Ok, Err // Ok 表示操作成功,内部包含成功时产生的值 // Err 意味着操作失败,并且包含失败的前因后果 .read_line(&mut guess) // expect 是 Result 类型实例的方法 // 如果 Result 的值是 Err,expect 会导致程序奔溃 // 如果 Result 的值是 Ok,expect 会获取 Ok 的值并原样返回 .expect("Failed to read line"); // 这里创建了一个叫做 guess 的变量,不过 Rust 允许用一个新值来 隐藏(shadow)之前的值 // 这个功能常用在需要转换值类型的场景,它允许我们复用 guess 变量的名字而不是被迫创建2个不同的变量 //let guess: u32 = guess // trim() 方法取出首尾的空白字符,用户输入5并按下enter键时,guess看起来像 5\n,trim()会移除\n //.trim() // 字符串的 parse 方法将字符串解析成数字,因为可以解析多种数据类型所以需要显示指定数字类型,此处是 let guess: u32 //.parse() //.expect("Please type a number!"); // 忽略非数字输入并继续 let guess: u32 = match guess.trim().parse() { Ok(num) => num, // _ 是一个通配符,本例用来匹配所有 Err 值,continue 是进行下一次 loop Err(_) => continue, }; // println!("Your guessed: {}", guess); // cmp 方法用来比较两个值并可以在任何可比较的值上调用,它获取一个被比较值的引用 // 一个 match 表达式由 分支(arms)构成 // 一个分支包含一个 模式(pattern)和表达式开头的值与分支模式相匹配时应执行的代码 // match 结果和模式是 Rust 中强大的功能,它体现了代码可能遇到的多种清晰, // 并帮助你确保没有遗漏处理 // match guess.cmp(&secret_number) { // Ordering::Less => println!("Too small!"), // 分支1,分支如果没有匹配就继续向下走 // Ordering::Greater => println!("Too big!"), // 分支2,分支匹配后执行完代码就会自动退出match // Ordering::Equal => { // println!("You win!"); // break; // 退出 loop 循环 // } // } // 有效范围检查 // if guess < 1 || guess > 100 { // println!("The secret number will be between 1 and 100."); // continue; // } // 使用自定义类型来确保范围有效 let g = Guess::new(guess); match g.value().cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } } pub struct Guess { value: u32, } impl Guess { pub fn new(value: u32) -> Guess { if value < 1 || value > 100 { panic!("Guess value must be between 1 and 100, got {}", value); } Guess { value } } // 熟悉的 getter pub fn value(&self) -> u32 { self.value } }
use crate::rtrs::objects::Aabb; use crate::HitRecord; use crate::Hitable; use crate::Point; use crate::Ray; use std::f64::consts::PI; use std::sync::Arc; #[derive(Debug)] pub struct Rotation { pub obj: Arc<dyn Hitable>, pub angle_x: f64, pub angle_y: f64, pub angle_z: f64, } impl Rotation { pub fn new_rad(obj: Arc<dyn Hitable>, angle_x: f64, angle_y: f64, angle_z: f64) -> Rotation { Rotation { obj: obj, angle_x: angle_x, angle_y: angle_y, angle_z: angle_z, } } pub fn new_deg(obj: Arc<dyn Hitable>, angle_x: f64, angle_y: f64, angle_z: f64) -> Rotation { Rotation::new_rad( obj, PI * angle_x / 180.0, PI * angle_y / 180.0, PI * angle_z / 180.0, ) } } impl Hitable for Rotation { fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, record: &mut HitRecord) -> bool { let mut origin = ray.origin; let mut direction = ray.direction; // x axis rotation origin.y = origin.y * self.angle_x.cos() - origin.z * self.angle_x.sin(); origin.z = origin.y * self.angle_x.sin() + origin.z * self.angle_x.cos(); direction.y = direction.y * self.angle_x.cos() - direction.z * self.angle_x.sin(); direction.z = direction.y * self.angle_x.sin() + direction.z * self.angle_x.cos(); // y axis rotation origin.x = origin.x * self.angle_y.cos() + origin.z * self.angle_y.sin(); origin.z = -origin.x * self.angle_y.sin() + origin.z * self.angle_y.cos(); direction.x = direction.x * self.angle_y.cos() + direction.z * self.angle_y.sin(); direction.z = -direction.x * self.angle_y.sin() + direction.z * self.angle_y.cos(); // z axis rotation origin.x = origin.x * self.angle_z.cos() - origin.y * self.angle_z.sin(); origin.y = origin.x * self.angle_z.sin() + origin.y * self.angle_z.cos(); direction.x = direction.x * self.angle_z.cos() - direction.y * self.angle_z.sin(); direction.y = direction.x * self.angle_z.sin() + direction.y * self.angle_z.cos(); let rotated = Ray::new(origin, direction, ray.time); if !self.obj.hit(&rotated, t_min, t_max, record) { return false; } let mut p = record.p; let mut normal = record.normal; // x axis rotation p.y = p.y * self.angle_x.cos() + p.z * self.angle_x.sin(); p.z = -p.y * self.angle_x.sin() + p.z * self.angle_x.cos(); normal.y = normal.y * self.angle_x.cos() + normal.z * self.angle_x.sin(); normal.z = -normal.y * self.angle_x.sin() + normal.z * self.angle_x.cos(); // y axis rotation p.x = p.x * self.angle_y.cos() + p.z * self.angle_y.sin(); p.z = -p.x * self.angle_y.sin() + p.z * self.angle_y.cos(); normal.x = normal.x * self.angle_y.cos() + normal.z * self.angle_y.sin(); normal.z = -normal.x * self.angle_y.sin() + normal.z * self.angle_y.cos(); // z axis rotation p.x = p.x * self.angle_z.cos() + p.y * self.angle_z.sin(); p.y = -p.x * self.angle_z.sin() + p.y * self.angle_z.cos(); normal.x = normal.x * self.angle_z.cos() + normal.y * self.angle_z.sin(); normal.y = -normal.x * self.angle_z.sin() + normal.y * self.angle_z.cos(); record.p = p; record.normal = normal; true } fn bounding_box(&self, _time0: f64, _time1: f64, output_box: &mut Aabb) -> bool { // TODO let min = Point::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); let max = Point::new(-f64::INFINITY, -f64::INFINITY, -f64::INFINITY); output_box.min = min; output_box.max = max; true } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::sync::Arc; use alloc::vec::Vec; use super::super::threadmgr::thread::*; use super::super::threadmgr::threads::*; #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub enum TaskStopType { GROUPSTOP, PTRACESTOP, EXECSTOP, VFORKSTOP, OTHER, //DUMMY } pub trait TaskStop: Sync + Send { fn Type(&self) -> TaskStopType; fn Killable(&self) -> bool; } impl ThreadInternal { pub fn beginInternalStop<T: TaskStop + 'static>(&mut self, s: &Arc<T>) { let pidns = self.tg.PIDNamespace(); let owner = pidns.lock().owner.clone(); let _r = owner.read(); let lock = self.tg.lock().signalLock.clone(); let _s = lock.lock(); self.beginInternalStopLocked(s); return } pub fn beginInternalStopLocked<T: TaskStop + 'static>(&mut self, s: &Arc<T>) { if self.stop.is_some() { panic!("Attempting to enter internal stop when already in internal stop"); } self.stop = Some(s.clone()); self.beginStopLocked(); } // endInternalStopLocked indicates the end of an internal stop that applies to // t. endInternalStopLocked does not wait for the task to resume. // // The caller is responsible for ensuring that the internal stop they expect // actually applies to t; this requires holding the signal mutex which protects // t.stop, which is why there is no endInternalStop that locks the signal mutex // for you. // // Preconditions: The signal mutex must be locked. The task must be in an // internal stop (i.e. t.stop != nil). pub fn endInternalStopLocked(&mut self) { if self.stop.is_none() { panic!("Attempting to leave non-existent internal stop") } self.stop = None; self.endStopLocked(); } // beginStopLocked increments t.stopCount to indicate that a new internal or // external stop applies to t. // // Preconditions: The signal mutex must be locked. pub fn beginStopLocked(&mut self) { self.stopCount.Add(1); } // endStopLocked decerements t.stopCount to indicate that an existing internal // or external stop no longer applies to t. // // Preconditions: The signal mutex must be locked. pub fn endStopLocked(&mut self) { self.stopCount.Done(); } } impl Thread { // BeginExternalStop indicates the start of an external stop that applies to t. // BeginExternalStop does not wait for t's task goroutine to stop. pub fn BeginExternalStop(&self) { let mut t = self.lock(); let pidns = t.tg.PIDNamespace(); let owner = pidns.lock().owner.clone(); let _r = owner.read(); let tg = t.tg.clone(); let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); t.beginStopLocked(); t.interrupt(); } // EndExternalStop indicates the end of an external stop started by a previous // call to Task.BeginExternalStop. EndExternalStop does not wait for t's task // goroutine to resume. pub fn EndExternalStop(&self) { let mut t = self.lock(); let pidns = t.tg.PIDNamespace(); let owner = pidns.lock().owner.clone(); let _r = owner.read(); let tg = t.tg.clone(); let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); t.endStopLocked(); } } impl TaskSet { // BeginExternalStop indicates the start of an external stop that applies to // all current and future tasks in ts. BeginExternalStop does not wait for // task goroutines to stop. pub fn BeginExternalStop(&self) { let _l = self.WriteLock(); let mut ts = self.write(); ts.stopCount += 1; if ts.stopCount <= 0 { panic!("BeginExternalStop: Invalid stopCount: {}", ts.stopCount) } if ts.root.is_none() { return } let pidns = ts.root.clone().unwrap(); let threads : Vec<_> = pidns.lock().tids.keys().cloned().collect(); for t in &threads { { let tg = t.lock().tg.clone(); let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); t.lock().beginStopLocked(); } t.lock().interrupt(); } } // EndExternalStop indicates the end of an external stop started by a previous // call to TaskSet.BeginExternalStop. EndExternalStop does not wait for task // goroutines to resume. pub fn EndExternalStop(&self) { let _l = self.WriteLock(); let mut ts = self.write(); ts.stopCount -= 1; if ts.stopCount < 0 { panic!("EndExternalStop: Invalid stopCount: {}", ts.stopCount) } if ts.root.is_none() { return } let pidns = ts.root.clone().unwrap(); let threads : Vec<_> = pidns.lock().tids.keys().cloned().collect(); for t in &threads { let tg = t.lock().tg.clone(); let lock = tg.lock().signalLock.clone(); let _s = lock.lock(); t.lock().endStopLocked(); } } }
//! A small CLI utility to generate dates for my google docs Life Journal use chrono::offset::TimeZone; use chrono::Datelike; use chrono::{Date, Utc, Weekday}; use structopt::clap::arg_enum; use structopt::StructOpt; use time::Duration as Time_Duration; const YEAR: i32 = 2020; const BEGINNING_OF_LAST_WEEK: u64 = (60 * 60 * 24 * 6); #[derive(Debug, StructOpt)] #[structopt( name = "date generator", about = "small CLI utility to generate dates for my google docs" )] struct Opt { #[structopt(possible_values = &Month::variants(), case_insensitive = true)] month: Month, start: u32, end: u32, } arg_enum! { #[derive(Debug, Copy, Clone)] enum Month { January = 1, February, March, April, May, June, July, August, September, October, November, December, } } impl Month { fn from_num(num: u32) -> Self { match num { 1 => Month::January, 2 => Month::February, 3 => Month::March, 4 => Month::April, 5 => Month::May, 6 => Month::June, 7 => Month::July, 8 => Month::August, 9 => Month::September, 10 => Month::October, 11 => Month::November, 12 => Month::December, otherwise => panic!("bad number for Month: {}", otherwise), } } } fn main() { let opt = Opt::from_args(); print_dates(opt); } /// Prints date separators for Alex's Google Docs Life Journal /// # Examples /// ``` /// // $> cargo run March 3 4 /// // calls /// print_dates(opt); /// // which prints: /// // ** Wed Mar 4 ** /// // /// // /// // ** Tue Mar 3 ** /// ``` fn print_dates(opt: Opt) { let month_num = opt.month as u32; for i in (opt.start..opt.end + 1).rev() { let dt = Utc.ymd(YEAR, month_num, i); if dt.weekday() == Weekday::Sun { // Sundays are special because I want to use Sunday to revisit the week's events // and write a recap of that week. print_recap_line(dt); } println!("** {:?} {:?} {} **\n\n", dt.weekday(), opt.month, i); } } /// Prints the Recap line every Sunday fn print_recap_line(dt: Date<Utc>) { // figure out which week range this recap should cover let one_week = Time_Duration::from_std(std::time::Duration::new(BEGINNING_OF_LAST_WEEK, 0)).unwrap(); let one_week_ago = dt.checked_sub_signed(one_week).unwrap(); let month_one_week_ago = Month::from_num(one_week_ago.month()); // Example: Mar 5 let begin = format!("{} {}", month_one_week_ago, one_week_ago.day()); let this_month = Month::from_num(dt.month()); // Example: Mar 12 let end = format!("{} {}", this_month, dt.day()); // Example: Mar 5 - Mar 12 let range = format!("{} - {}", begin, end); println!( "******************** Recap: {} **************************\n\n", range ); }
use serde::Serialize; use crate::error::Error; use super::{Channel, UserID}; use deadpool_postgres::{Pool, PoolError}; pub type GroupID = i32; /// Create a new group. /// /// Returns Ok(None) if the name is not unique. /// Returns Err if a database error occurred. pub async fn create_group(pool: Pool, name: String, picture: String) -> Result<Option<GroupID>, Error> { let conn = pool.get().await?; let stmt = conn.prepare(" INSERT INTO Groop (name, picture) SELECT $1, $2 WHERE NOT EXISTS ( SELECT * FROM Groop WHERE name = $1 ) RETURNING group_id ").await?; Ok(conn.query_opt(&stmt, &[&name, &picture]).await?.map(|row| row.get(0))) } /// Get the channels in a group /// /// Returns an empty vector if the group is invalid. pub async fn group_channels(pool: Pool, group_id: GroupID) -> Result<Vec<Channel>, Error> { let conn = pool.get().await?; let stmt = conn.prepare(" SELECT channel_id, name FROM Channel WHERE group_id = $1 ORDER BY channel_id ").await?; Ok(conn.query(&stmt, &[&group_id]) .await? .iter() .map(|row| Channel { channel_id: row.get(0), name: row.get(1), }) .collect()) } #[derive(Serialize)] pub struct Group { pub group_id: GroupID, pub name: String, pub picture: String, } /// Get the list of groups that a user is a member of. pub async fn user_groups(pool: Pool, user_id: UserID) -> Result<Vec<Group>, Error> { let conn = pool.get().await?; let stmt = conn.prepare(" SELECT Groop.group_id, name, picture FROM Groop JOIN Membership ON Membership.group_id = Groop.group_id WHERE Membership.user_id = $1 ORDER BY Groop.group_id ").await?; Ok(conn.query(&stmt, &[&user_id]).await?.iter().map(|row| Group { group_id: row.get(0), name: row.get(1), picture: row.get(2), }).collect()) } /// Get the list of group IDs that a user is a member of. pub async fn user_group_ids(pool: Pool, user_id: UserID) -> Result<Vec<GroupID>, Error> { let conn = pool.get().await?; let stmt = conn.prepare(" SELECT Groop.group_id FROM Groop JOIN Membership ON Membership.group_id = Groop.group_id WHERE Membership.user_id = $1 ORDER BY Groop.group_id ").await?; Ok(conn.query(&stmt, &[&user_id]).await?.iter().map(|row| row.get(0)).collect()) } /// Determine whether a user is a member of a group pub async fn group_member(pool: Pool, user_id: UserID, group_id: GroupID) -> Result<bool, Error> { let conn = pool.get().await?; let stmt = conn.prepare(" SELECT 1 FROM Membership WHERE user_id = $1 AND group_id = $2 ").await?; Ok(conn.query_opt(&stmt, &[&user_id, &group_id]).await?.is_some()) } pub async fn rename_group(pool: Pool, group_id: GroupID, name: &String, picture: &String) -> Result<bool, PoolError> { let conn = pool.get().await?; let stmt = conn.prepare(" UPDATE Groop SET name = $2, picture = $3 WHERE group_id = $1 AND NOT EXISTS ( SELECT 1 FROM Groop WHERE name = $2 AND group_id != $1 ) ").await?; Ok(conn.execute(&stmt, &[&group_id, name, picture]).await? > 0) } pub async fn delete_group(pool: Pool, group_id: GroupID) -> Result<bool, Error> { let conn = pool.get().await?; let stmt = conn.prepare(" DELETE FROM Groop WHERE group_id = $1 ").await?; Ok(conn.execute(&stmt, &[&group_id]).await? > 0) }
#[macro_use] extern crate criterion; extern crate rand; extern crate sealpir; extern crate serde; #[macro_use] extern crate serde_derive; use criterion::Criterion; use rand::{thread_rng, RngCore}; use sealpir::client::PirClient; use sealpir::server::PirServer; use std::time::Duration; const SIZE: usize = 288; const DIM: u32 = 2; const LOGT: u32 = 23; const POLY_DEGREE: u32 = 2048; const NUMS: [u32; 3] = [1 << 16, 1 << 18, 1 << 20]; #[derive(Serialize, Clone)] struct Element { #[serde(serialize_with = "<[_]>::serialize")] e: [u8; SIZE], } fn setup(c: &mut Criterion) { c.bench_function_over_inputs( &format!("setup_d{}", DIM), |b, &&num| { // setup let mut rng = thread_rng(); let mut collection = vec![]; for _ in 0..num { let mut x = [0u8; SIZE]; rng.fill_bytes(&mut x); collection.push(x); } // measurement b.iter(|| { let mut server = PirServer::new(num, SIZE as u32, POLY_DEGREE, LOGT, DIM); server.setup(&collection); }) }, &NUMS, ); } fn query(c: &mut Criterion) { c.bench_function_over_inputs( &format!("query_d{}", DIM), |b, &&num| { // setup let client = PirClient::new(num, SIZE as u32, POLY_DEGREE, LOGT, DIM); // measurement b.iter_with_setup(|| rand::random::<u32>() % num, |idx| client.gen_query(idx)); }, &NUMS, ); } fn expand(c: &mut Criterion) { c.bench_function_over_inputs( &format!("expand_d{}", DIM), |b, &&num| { // setup let mut rng = thread_rng(); let mut collection = vec![]; for _ in 0..num { let mut x = [0u8; SIZE]; rng.fill_bytes(&mut x); collection.push(x); } let mut server = PirServer::new(num, SIZE as u32, POLY_DEGREE, LOGT, DIM); let client = PirClient::new(num, SIZE as u32, POLY_DEGREE, LOGT, DIM); let key = client.get_key(); server.setup(&collection); server.set_galois_key(key, 0); // measurement b.iter_with_setup( || client.gen_query(rand::random::<u32>() % num), |query| server.expand(&query, 0), ); }, &NUMS, ); } fn reply(c: &mut Criterion) { c.bench_function_over_inputs( &format!("reply_d{}", DIM), |b, &&num| { // setup let mut rng = thread_rng(); let mut collection = vec![]; for _ in 0..num { let mut x = [0u8; SIZE]; rng.fill_bytes(&mut x); collection.push(x); } let mut server = PirServer::new(num, SIZE as u32, POLY_DEGREE, LOGT, DIM); let client = PirClient::new(num, SIZE as u32, POLY_DEGREE, LOGT, DIM); let key = client.get_key(); server.setup(&collection); server.set_galois_key(key, 0); // measurement b.iter_with_setup( || client.gen_query(rand::random::<u32>() % num), |query| server.gen_reply(&query, 0), ); }, &NUMS, ); } fn decode(c: &mut Criterion) { c.bench_function_over_inputs( &format!("decode_d{}", DIM), |b, &&num| { // setup let mut rng = thread_rng(); let mut collection = vec![]; for _ in 0..num { let mut x = [0u8; SIZE]; rng.fill_bytes(&mut x); collection.push(x); } let mut server = PirServer::new(num, SIZE as u32, POLY_DEGREE, LOGT, DIM); let client = PirClient::new(num, SIZE as u32, POLY_DEGREE, LOGT, DIM); let key = client.get_key(); server.setup(&collection); server.set_galois_key(key, 0); let idx = rand::random::<u32>() % num; let query = client.gen_query(idx); let reply = server.gen_reply(&query, 0); // measurement b.iter(|| client.decode_reply::<Element>(idx, &reply)); }, &NUMS, ); } criterion_group! { name = benches; config = Criterion::default() .sample_size(10) .measurement_time(Duration::new(5, 0)) .without_plots(); targets = setup, query, expand, reply, decode } criterion_main!(benches);
mod canvas; mod color; mod drawing; mod event; mod event_ctx; mod input; mod runner; mod screen_geom; mod text; mod widgets; pub mod world; pub use crate::canvas::{Canvas, HorizontalAlignment, VerticalAlignment, BOTTOM_LEFT, CENTERED}; pub use crate::color::Color; pub use crate::drawing::{Drawable, GeomBatch, GfxCtx, Prerender}; pub use crate::event::{hotkey, lctrl, Event, Key, MultiKey}; pub use crate::event_ctx::EventCtx; pub use crate::input::UserInput; pub use crate::runner::{run, EventLoopMode, GUI}; pub use crate::screen_geom::{ScreenDims, ScreenPt}; pub use crate::text::{Line, Text, TextSpan, HOTKEY_COLOR}; pub use crate::widgets::{ Autocomplete, Choice, ItemSlider, ModalMenu, Scroller, Slider, SliderWithTextBox, Warper, WarpingItemSlider, Wizard, WrappedWizard, }; pub enum InputResult<T: Clone> { Canceled, StillActive, Done(String, T), } // At the default text size. Exposed for convenience outside, but ideally, this shouldn't be // needed... pub const LINE_HEIGHT: f64 = 30.0;
use petgraph::graph::{Graph, IndexType, NodeIndex}; use petgraph::unionfind::UnionFind; use petgraph::EdgeType; use std::collections::HashMap; pub fn connected_components<N, E, Ty: EdgeType, Ix: IndexType>( graph: &Graph<N, E, Ty, Ix>, ) -> HashMap<NodeIndex<Ix>, usize> { let mut components = UnionFind::new(graph.node_count()); let indices = graph .node_indices() .enumerate() .map(|(i, u)| (u, i)) .collect::<HashMap<NodeIndex<Ix>, usize>>(); for e in graph.edge_indices() { let (u, v) = graph.edge_endpoints(e).unwrap(); components.union(indices[&u], indices[&v]); } let mut result = HashMap::new(); for u in graph.node_indices() { result.insert(u, components.find(indices[&u])); } result } #[cfg(test)] mod test { use super::*; #[test] fn test_connected_components() { let mut graph = Graph::new_undirected(); let u1 = graph.add_node(()); let u2 = graph.add_node(()); let u3 = graph.add_node(()); let u4 = graph.add_node(()); let u5 = graph.add_node(()); graph.add_edge(u1, u2, ()); graph.add_edge(u1, u3, ()); graph.add_edge(u2, u3, ()); graph.add_edge(u4, u5, ()); let components = connected_components(&graph); assert_eq!(components[&u1], components[&u2]); assert_eq!(components[&u1], components[&u3]); assert_ne!(components[&u3], components[&u4]); assert_eq!(components[&u4], components[&u5]); } }
use proconio::input; use std::cmp::Reverse; use std::collections::BinaryHeap; fn main() { input! { n: usize, l: u64, a: [u64; n], }; let sum = a.iter().sum::<u64>(); let mut heap = BinaryHeap::new(); for a in a { heap.push(Reverse(a)); } if sum < l { heap.push(Reverse(l - sum)); } let mut ans = 0; while heap.len() >= 2 { let Reverse(min) = heap.pop().unwrap(); let Reverse(second_min) = heap.pop().unwrap(); ans += min + second_min; heap.push(Reverse(min + second_min)); } let Reverse(last) = heap.pop().unwrap(); assert_eq!(l, last); println!("{}", ans); }
mod performance_profiler; pub use performance_profiler::*; mod performance_timer; pub use performance_timer::*;
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} #[repr(transparent)] pub struct BitmapAlphaMode(pub i32); impl BitmapAlphaMode { pub const Premultiplied: Self = Self(0i32); pub const Straight: Self = Self(1i32); pub const Ignore: Self = Self(2i32); } impl ::core::marker::Copy for BitmapAlphaMode {} impl ::core::clone::Clone for BitmapAlphaMode { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct BitmapBounds { pub X: u32, pub Y: u32, pub Width: u32, pub Height: u32, } impl ::core::marker::Copy for BitmapBounds {} impl ::core::clone::Clone for BitmapBounds { fn clone(&self) -> Self { *self } } pub type BitmapBuffer = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct BitmapBufferAccessMode(pub i32); impl BitmapBufferAccessMode { pub const Read: Self = Self(0i32); pub const ReadWrite: Self = Self(1i32); pub const Write: Self = Self(2i32); } impl ::core::marker::Copy for BitmapBufferAccessMode {} impl ::core::clone::Clone for BitmapBufferAccessMode { fn clone(&self) -> Self { *self } } pub type BitmapCodecInformation = *mut ::core::ffi::c_void; pub type BitmapDecoder = *mut ::core::ffi::c_void; pub type BitmapEncoder = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct BitmapFlip(pub i32); impl BitmapFlip { pub const None: Self = Self(0i32); pub const Horizontal: Self = Self(1i32); pub const Vertical: Self = Self(2i32); } impl ::core::marker::Copy for BitmapFlip {} impl ::core::clone::Clone for BitmapFlip { fn clone(&self) -> Self { *self } } pub type BitmapFrame = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct BitmapInterpolationMode(pub i32); impl BitmapInterpolationMode { pub const NearestNeighbor: Self = Self(0i32); pub const Linear: Self = Self(1i32); pub const Cubic: Self = Self(2i32); pub const Fant: Self = Self(3i32); } impl ::core::marker::Copy for BitmapInterpolationMode {} impl ::core::clone::Clone for BitmapInterpolationMode { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct BitmapPixelFormat(pub i32); impl BitmapPixelFormat { pub const Unknown: Self = Self(0i32); pub const Rgba16: Self = Self(12i32); pub const Rgba8: Self = Self(30i32); pub const Gray16: Self = Self(57i32); pub const Gray8: Self = Self(62i32); pub const Bgra8: Self = Self(87i32); pub const Nv12: Self = Self(103i32); pub const P010: Self = Self(104i32); pub const Yuy2: Self = Self(107i32); } impl ::core::marker::Copy for BitmapPixelFormat {} impl ::core::clone::Clone for BitmapPixelFormat { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct BitmapPlaneDescription { pub StartIndex: i32, pub Width: i32, pub Height: i32, pub Stride: i32, } impl ::core::marker::Copy for BitmapPlaneDescription {} impl ::core::clone::Clone for BitmapPlaneDescription { fn clone(&self) -> Self { *self } } pub type BitmapProperties = *mut ::core::ffi::c_void; pub type BitmapPropertiesView = *mut ::core::ffi::c_void; pub type BitmapPropertySet = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct BitmapRotation(pub i32); impl BitmapRotation { pub const None: Self = Self(0i32); pub const Clockwise90Degrees: Self = Self(1i32); pub const Clockwise180Degrees: Self = Self(2i32); pub const Clockwise270Degrees: Self = Self(3i32); } impl ::core::marker::Copy for BitmapRotation {} impl ::core::clone::Clone for BitmapRotation { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct BitmapSize { pub Width: u32, pub Height: u32, } impl ::core::marker::Copy for BitmapSize {} impl ::core::clone::Clone for BitmapSize { fn clone(&self) -> Self { *self } } pub type BitmapTransform = *mut ::core::ffi::c_void; pub type BitmapTypedValue = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ColorManagementMode(pub i32); impl ColorManagementMode { pub const DoNotColorManage: Self = Self(0i32); pub const ColorManageToSRgb: Self = Self(1i32); } impl ::core::marker::Copy for ColorManagementMode {} impl ::core::clone::Clone for ColorManagementMode { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ExifOrientationMode(pub i32); impl ExifOrientationMode { pub const IgnoreExifOrientation: Self = Self(0i32); pub const RespectExifOrientation: Self = Self(1i32); } impl ::core::marker::Copy for ExifOrientationMode {} impl ::core::clone::Clone for ExifOrientationMode { fn clone(&self) -> Self { *self } } pub type IBitmapFrame = *mut ::core::ffi::c_void; pub type IBitmapFrameWithSoftwareBitmap = *mut ::core::ffi::c_void; pub type IBitmapPropertiesView = *mut ::core::ffi::c_void; pub type ImageStream = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct JpegSubsamplingMode(pub i32); impl JpegSubsamplingMode { pub const Default: Self = Self(0i32); pub const Y4Cb2Cr0: Self = Self(1i32); pub const Y4Cb2Cr2: Self = Self(2i32); pub const Y4Cb4Cr4: Self = Self(3i32); } impl ::core::marker::Copy for JpegSubsamplingMode {} impl ::core::clone::Clone for JpegSubsamplingMode { fn clone(&self) -> Self { *self } } pub type PixelDataProvider = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct PngFilterMode(pub i32); impl PngFilterMode { pub const Automatic: Self = Self(0i32); pub const None: Self = Self(1i32); pub const Sub: Self = Self(2i32); pub const Up: Self = Self(3i32); pub const Average: Self = Self(4i32); pub const Paeth: Self = Self(5i32); pub const Adaptive: Self = Self(6i32); } impl ::core::marker::Copy for PngFilterMode {} impl ::core::clone::Clone for PngFilterMode { fn clone(&self) -> Self { *self } } pub type SoftwareBitmap = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct TiffCompressionMode(pub i32); impl TiffCompressionMode { pub const Automatic: Self = Self(0i32); pub const None: Self = Self(1i32); pub const Ccitt3: Self = Self(2i32); pub const Ccitt4: Self = Self(3i32); pub const Lzw: Self = Self(4i32); pub const Rle: Self = Self(5i32); pub const Zip: Self = Self(6i32); pub const LzwhDifferencing: Self = Self(7i32); } impl ::core::marker::Copy for TiffCompressionMode {} impl ::core::clone::Clone for TiffCompressionMode { fn clone(&self) -> Self { *self } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qtemporaryfile.h // dst-file: /src/core/qtemporaryfile.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::qfile::*; // 773 use std::ops::Deref; use super::qstring::*; // 773 use super::qobject::*; // 773 use super::qobjectdefs::*; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QTemporaryFile_Class_Size() -> c_int; // proto: bool QTemporaryFile::autoRemove(); fn C_ZNK14QTemporaryFile10autoRemoveEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: static QTemporaryFile * QTemporaryFile::createLocalFile(QFile & file); fn C_ZN14QTemporaryFile15createLocalFileER5QFile(arg0: *mut c_void) -> *mut c_void; // proto: void QTemporaryFile::QTemporaryFile(const QString & templateName); fn C_ZN14QTemporaryFileC2ERK7QString(arg0: *mut c_void) -> u64; // proto: void QTemporaryFile::QTemporaryFile(); fn C_ZN14QTemporaryFileC2Ev() -> u64; // proto: void QTemporaryFile::QTemporaryFile(QObject * parent); fn C_ZN14QTemporaryFileC2EP7QObject(arg0: *mut c_void) -> u64; // proto: void QTemporaryFile::~QTemporaryFile(); fn C_ZN14QTemporaryFileD2Ev(qthis: u64 /* *mut c_void*/); // proto: const QMetaObject * QTemporaryFile::metaObject(); fn C_ZNK14QTemporaryFile10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QTemporaryFile::setAutoRemove(bool b); fn C_ZN14QTemporaryFile13setAutoRemoveEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: QString QTemporaryFile::fileName(); fn C_ZNK14QTemporaryFile8fileNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QString QTemporaryFile::fileTemplate(); fn C_ZNK14QTemporaryFile12fileTemplateEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: static QTemporaryFile * QTemporaryFile::createNativeFile(const QString & fileName); fn C_ZN14QTemporaryFile16createNativeFileERK7QString(arg0: *mut c_void) -> *mut c_void; // proto: bool QTemporaryFile::open(); fn C_ZN14QTemporaryFile4openEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: static QTemporaryFile * QTemporaryFile::createLocalFile(const QString & fileName); fn C_ZN14QTemporaryFile15createLocalFileERK7QString(arg0: *mut c_void) -> *mut c_void; // proto: static QTemporaryFile * QTemporaryFile::createNativeFile(QFile & file); fn C_ZN14QTemporaryFile16createNativeFileER5QFile(arg0: *mut c_void) -> *mut c_void; // proto: void QTemporaryFile::setFileTemplate(const QString & name); fn C_ZN14QTemporaryFile15setFileTemplateERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QTemporaryFile::QTemporaryFile(const QString & templateName, QObject * parent); fn C_ZN14QTemporaryFileC2ERK7QStringP7QObject(arg0: *mut c_void, arg1: *mut c_void) -> u64; } // <= ext block end // body block begin => // class sizeof(QTemporaryFile)=1 #[derive(Default)] pub struct QTemporaryFile { qbase: QFile, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QTemporaryFile { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QTemporaryFile { return QTemporaryFile{qbase: QFile::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QTemporaryFile { type Target = QFile; fn deref(&self) -> &QFile { return & self.qbase; } } impl AsRef<QFile> for QTemporaryFile { fn as_ref(& self) -> & QFile { return & self.qbase; } } // proto: bool QTemporaryFile::autoRemove(); impl /*struct*/ QTemporaryFile { pub fn autoRemove<RetType, T: QTemporaryFile_autoRemove<RetType>>(& self, overload_args: T) -> RetType { return overload_args.autoRemove(self); // return 1; } } pub trait QTemporaryFile_autoRemove<RetType> { fn autoRemove(self , rsthis: & QTemporaryFile) -> RetType; } // proto: bool QTemporaryFile::autoRemove(); impl<'a> /*trait*/ QTemporaryFile_autoRemove<i8> for () { fn autoRemove(self , rsthis: & QTemporaryFile) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QTemporaryFile10autoRemoveEv()}; let mut ret = unsafe {C_ZNK14QTemporaryFile10autoRemoveEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: static QTemporaryFile * QTemporaryFile::createLocalFile(QFile & file); impl /*struct*/ QTemporaryFile { pub fn createLocalFile_s<RetType, T: QTemporaryFile_createLocalFile_s<RetType>>( overload_args: T) -> RetType { return overload_args.createLocalFile_s(); // return 1; } } pub trait QTemporaryFile_createLocalFile_s<RetType> { fn createLocalFile_s(self ) -> RetType; } // proto: static QTemporaryFile * QTemporaryFile::createLocalFile(QFile & file); impl<'a> /*trait*/ QTemporaryFile_createLocalFile_s<QTemporaryFile> for (&'a QFile) { fn createLocalFile_s(self ) -> QTemporaryFile { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFile15createLocalFileER5QFile()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN14QTemporaryFile15createLocalFileER5QFile(arg0)}; let mut ret1 = QTemporaryFile::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QTemporaryFile::QTemporaryFile(const QString & templateName); impl /*struct*/ QTemporaryFile { pub fn new<T: QTemporaryFile_new>(value: T) -> QTemporaryFile { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QTemporaryFile_new { fn new(self) -> QTemporaryFile; } // proto: void QTemporaryFile::QTemporaryFile(const QString & templateName); impl<'a> /*trait*/ QTemporaryFile_new for (&'a QString) { fn new(self) -> QTemporaryFile { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFileC2ERK7QString()}; let ctysz: c_int = unsafe{QTemporaryFile_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_ZN14QTemporaryFileC2ERK7QString(arg0)}; let rsthis = QTemporaryFile{qbase: QFile::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QTemporaryFile::QTemporaryFile(); impl<'a> /*trait*/ QTemporaryFile_new for () { fn new(self) -> QTemporaryFile { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFileC2Ev()}; let ctysz: c_int = unsafe{QTemporaryFile_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN14QTemporaryFileC2Ev()}; let rsthis = QTemporaryFile{qbase: QFile::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QTemporaryFile::QTemporaryFile(QObject * parent); impl<'a> /*trait*/ QTemporaryFile_new for (&'a QObject) { fn new(self) -> QTemporaryFile { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFileC2EP7QObject()}; let ctysz: c_int = unsafe{QTemporaryFile_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_ZN14QTemporaryFileC2EP7QObject(arg0)}; let rsthis = QTemporaryFile{qbase: QFile::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QTemporaryFile::~QTemporaryFile(); impl /*struct*/ QTemporaryFile { pub fn free<RetType, T: QTemporaryFile_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QTemporaryFile_free<RetType> { fn free(self , rsthis: & QTemporaryFile) -> RetType; } // proto: void QTemporaryFile::~QTemporaryFile(); impl<'a> /*trait*/ QTemporaryFile_free<()> for () { fn free(self , rsthis: & QTemporaryFile) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFileD2Ev()}; unsafe {C_ZN14QTemporaryFileD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: const QMetaObject * QTemporaryFile::metaObject(); impl /*struct*/ QTemporaryFile { pub fn metaObject<RetType, T: QTemporaryFile_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QTemporaryFile_metaObject<RetType> { fn metaObject(self , rsthis: & QTemporaryFile) -> RetType; } // proto: const QMetaObject * QTemporaryFile::metaObject(); impl<'a> /*trait*/ QTemporaryFile_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QTemporaryFile) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QTemporaryFile10metaObjectEv()}; let mut ret = unsafe {C_ZNK14QTemporaryFile10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QTemporaryFile::setAutoRemove(bool b); impl /*struct*/ QTemporaryFile { pub fn setAutoRemove<RetType, T: QTemporaryFile_setAutoRemove<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setAutoRemove(self); // return 1; } } pub trait QTemporaryFile_setAutoRemove<RetType> { fn setAutoRemove(self , rsthis: & QTemporaryFile) -> RetType; } // proto: void QTemporaryFile::setAutoRemove(bool b); impl<'a> /*trait*/ QTemporaryFile_setAutoRemove<()> for (i8) { fn setAutoRemove(self , rsthis: & QTemporaryFile) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFile13setAutoRemoveEb()}; let arg0 = self as c_char; unsafe {C_ZN14QTemporaryFile13setAutoRemoveEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QString QTemporaryFile::fileName(); impl /*struct*/ QTemporaryFile { pub fn fileName<RetType, T: QTemporaryFile_fileName<RetType>>(& self, overload_args: T) -> RetType { return overload_args.fileName(self); // return 1; } } pub trait QTemporaryFile_fileName<RetType> { fn fileName(self , rsthis: & QTemporaryFile) -> RetType; } // proto: QString QTemporaryFile::fileName(); impl<'a> /*trait*/ QTemporaryFile_fileName<QString> for () { fn fileName(self , rsthis: & QTemporaryFile) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QTemporaryFile8fileNameEv()}; let mut ret = unsafe {C_ZNK14QTemporaryFile8fileNameEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QString QTemporaryFile::fileTemplate(); impl /*struct*/ QTemporaryFile { pub fn fileTemplate<RetType, T: QTemporaryFile_fileTemplate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.fileTemplate(self); // return 1; } } pub trait QTemporaryFile_fileTemplate<RetType> { fn fileTemplate(self , rsthis: & QTemporaryFile) -> RetType; } // proto: QString QTemporaryFile::fileTemplate(); impl<'a> /*trait*/ QTemporaryFile_fileTemplate<QString> for () { fn fileTemplate(self , rsthis: & QTemporaryFile) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK14QTemporaryFile12fileTemplateEv()}; let mut ret = unsafe {C_ZNK14QTemporaryFile12fileTemplateEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: static QTemporaryFile * QTemporaryFile::createNativeFile(const QString & fileName); impl /*struct*/ QTemporaryFile { pub fn createNativeFile_s<RetType, T: QTemporaryFile_createNativeFile_s<RetType>>( overload_args: T) -> RetType { return overload_args.createNativeFile_s(); // return 1; } } pub trait QTemporaryFile_createNativeFile_s<RetType> { fn createNativeFile_s(self ) -> RetType; } // proto: static QTemporaryFile * QTemporaryFile::createNativeFile(const QString & fileName); impl<'a> /*trait*/ QTemporaryFile_createNativeFile_s<QTemporaryFile> for (&'a QString) { fn createNativeFile_s(self ) -> QTemporaryFile { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFile16createNativeFileERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN14QTemporaryFile16createNativeFileERK7QString(arg0)}; let mut ret1 = QTemporaryFile::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QTemporaryFile::open(); impl /*struct*/ QTemporaryFile { pub fn open<RetType, T: QTemporaryFile_open<RetType>>(& self, overload_args: T) -> RetType { return overload_args.open(self); // return 1; } } pub trait QTemporaryFile_open<RetType> { fn open(self , rsthis: & QTemporaryFile) -> RetType; } // proto: bool QTemporaryFile::open(); impl<'a> /*trait*/ QTemporaryFile_open<i8> for () { fn open(self , rsthis: & QTemporaryFile) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFile4openEv()}; let mut ret = unsafe {C_ZN14QTemporaryFile4openEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: static QTemporaryFile * QTemporaryFile::createLocalFile(const QString & fileName); impl<'a> /*trait*/ QTemporaryFile_createLocalFile_s<QTemporaryFile> for (&'a QString) { fn createLocalFile_s(self ) -> QTemporaryFile { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFile15createLocalFileERK7QString()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN14QTemporaryFile15createLocalFileERK7QString(arg0)}; let mut ret1 = QTemporaryFile::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: static QTemporaryFile * QTemporaryFile::createNativeFile(QFile & file); impl<'a> /*trait*/ QTemporaryFile_createNativeFile_s<QTemporaryFile> for (&'a QFile) { fn createNativeFile_s(self ) -> QTemporaryFile { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFile16createNativeFileER5QFile()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZN14QTemporaryFile16createNativeFileER5QFile(arg0)}; let mut ret1 = QTemporaryFile::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QTemporaryFile::setFileTemplate(const QString & name); impl /*struct*/ QTemporaryFile { pub fn setFileTemplate<RetType, T: QTemporaryFile_setFileTemplate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setFileTemplate(self); // return 1; } } pub trait QTemporaryFile_setFileTemplate<RetType> { fn setFileTemplate(self , rsthis: & QTemporaryFile) -> RetType; } // proto: void QTemporaryFile::setFileTemplate(const QString & name); impl<'a> /*trait*/ QTemporaryFile_setFileTemplate<()> for (&'a QString) { fn setFileTemplate(self , rsthis: & QTemporaryFile) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFile15setFileTemplateERK7QString()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN14QTemporaryFile15setFileTemplateERK7QString(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QTemporaryFile::QTemporaryFile(const QString & templateName, QObject * parent); impl<'a> /*trait*/ QTemporaryFile_new for (&'a QString, &'a QObject) { fn new(self) -> QTemporaryFile { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN14QTemporaryFileC2ERK7QStringP7QObject()}; let ctysz: c_int = unsafe{QTemporaryFile_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN14QTemporaryFileC2ERK7QStringP7QObject(arg0, arg1)}; let rsthis = QTemporaryFile{qbase: QFile::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // <= body block end
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::any::Any; use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::marker::PhantomData; use std::mem::take; use std::sync::Arc; use common_exception::ErrorCode; use common_exception::Result; use common_expression::BlockMetaInfoDowncast; use common_expression::DataBlock; use common_hashtable::hash2bucket; use common_hashtable::HashtableLike; use common_pipeline_core::pipe::Pipe; use common_pipeline_core::pipe::PipeItem; use common_pipeline_core::processors::port::InputPort; use common_pipeline_core::processors::port::OutputPort; use common_pipeline_core::processors::processor::Event; use common_pipeline_core::processors::processor::ProcessorPtr; use common_pipeline_core::processors::Processor; use common_pipeline_core::Pipeline; use common_storage::DataOperator; use crate::pipelines::processors::transforms::aggregator::aggregate_meta::AggregateMeta; use crate::pipelines::processors::transforms::aggregator::aggregate_meta::HashTablePayload; use crate::pipelines::processors::transforms::aggregator::aggregate_meta::SerializedPayload; use crate::pipelines::processors::transforms::aggregator::TransformFinalGroupBy; use crate::pipelines::processors::transforms::group_by::HashMethodBounds; use crate::pipelines::processors::transforms::group_by::KeysColumnIter; use crate::pipelines::processors::transforms::group_by::PartitionedHashMethod; use crate::pipelines::processors::transforms::PartitionedHashTableDropper; use crate::pipelines::processors::transforms::TransformAggregateSpillReader; use crate::pipelines::processors::transforms::TransformFinalAggregate; use crate::pipelines::processors::transforms::TransformGroupBySpillReader; use crate::pipelines::processors::AggregatorParams; static SINGLE_LEVEL_BUCKET_NUM: isize = -1; struct InputPortState { port: Arc<InputPort>, bucket: isize, } pub struct TransformPartitionBucket<Method: HashMethodBounds, V: Copy + Send + Sync + 'static> { output: Arc<OutputPort>, inputs: Vec<InputPortState>, method: Method, working_bucket: isize, pushing_bucket: isize, initialized_all_inputs: bool, buckets_blocks: BTreeMap<isize, Vec<DataBlock>>, unsplitted_blocks: Vec<DataBlock>, _phantom: PhantomData<V>, } impl<Method: HashMethodBounds, V: Copy + Send + Sync + 'static> TransformPartitionBucket<Method, V> { pub fn create(method: Method, input_nums: usize) -> Result<Self> { let mut inputs = Vec::with_capacity(input_nums); for _index in 0..input_nums { inputs.push(InputPortState { bucket: -1, port: InputPort::create(), }); } Ok(TransformPartitionBucket { method, // params, inputs, working_bucket: 0, pushing_bucket: 0, output: OutputPort::create(), buckets_blocks: BTreeMap::new(), unsplitted_blocks: vec![], initialized_all_inputs: false, _phantom: Default::default(), }) } pub fn get_inputs(&self) -> Vec<Arc<InputPort>> { let mut inputs = Vec::with_capacity(self.inputs.len()); for input_state in &self.inputs { inputs.push(input_state.port.clone()); } inputs } pub fn get_output(&self) -> Arc<OutputPort> { self.output.clone() } fn initialize_all_inputs(&mut self) -> Result<bool> { self.initialized_all_inputs = true; for index in 0..self.inputs.len() { if self.inputs[index].port.is_finished() { continue; } // We pull the first unsplitted data block if self.inputs[index].bucket > SINGLE_LEVEL_BUCKET_NUM { continue; } if !self.inputs[index].port.has_data() { self.inputs[index].port.set_need_data(); self.initialized_all_inputs = false; continue; } let data_block = self.inputs[index].port.pull_data().unwrap()?; self.inputs[index].bucket = self.add_bucket(data_block); if self.inputs[index].bucket <= SINGLE_LEVEL_BUCKET_NUM { self.inputs[index].port.set_need_data(); self.initialized_all_inputs = false; } } Ok(self.initialized_all_inputs) } fn add_bucket(&mut self, data_block: DataBlock) -> isize { if let Some(block_meta) = data_block.get_meta() { if let Some(block_meta) = AggregateMeta::<Method, V>::downcast_ref_from(block_meta) { let (bucket, res) = match block_meta { AggregateMeta::Spilling(_) => unreachable!(), AggregateMeta::Partitioned { .. } => unreachable!(), AggregateMeta::Spilled(payload) => (payload.bucket, SINGLE_LEVEL_BUCKET_NUM), AggregateMeta::Serialized(payload) => (payload.bucket, payload.bucket), AggregateMeta::HashTable(payload) => (payload.bucket, payload.bucket), }; if bucket > SINGLE_LEVEL_BUCKET_NUM { match self.buckets_blocks.entry(bucket) { Entry::Vacant(v) => { v.insert(vec![data_block]); } Entry::Occupied(mut v) => { v.get_mut().push(data_block); } }; return res; } } } self.unsplitted_blocks.push(data_block); SINGLE_LEVEL_BUCKET_NUM } fn try_push_data_block(&mut self) -> bool { match self.buckets_blocks.is_empty() { true => self.try_push_single_level(), false => self.try_push_two_level(), } } fn try_push_two_level(&mut self) -> bool { while self.pushing_bucket < self.working_bucket { if let Some(bucket_blocks) = self.buckets_blocks.remove(&self.pushing_bucket) { let data_block = Self::convert_blocks(self.pushing_bucket, bucket_blocks); self.output.push_data(Ok(data_block)); self.pushing_bucket += 1; return true; } self.pushing_bucket += 1; } false } fn try_push_single_level(&mut self) -> bool { if !self.unsplitted_blocks.is_empty() { let data_blocks = take(&mut self.unsplitted_blocks); self.output.push_data(Ok(Self::convert_blocks( SINGLE_LEVEL_BUCKET_NUM, data_blocks, ))); return true; } false } fn convert_blocks(bucket: isize, data_blocks: Vec<DataBlock>) -> DataBlock { let mut data = Vec::with_capacity(data_blocks.len()); for mut data_block in data_blocks.into_iter() { if let Some(block_meta) = data_block.take_meta() { if let Some(block_meta) = AggregateMeta::<Method, V>::downcast_from(block_meta) { data.push(block_meta); } } } DataBlock::empty_with_meta(AggregateMeta::<Method, V>::create_partitioned(bucket, data)) } fn partition_block(&self, payload: SerializedPayload) -> Result<Vec<Option<DataBlock>>> { let column = payload.get_group_by_column(); let keys_iter = self.method.keys_iter_from_column(column)?; let mut indices = Vec::with_capacity(payload.data_block.num_rows()); for key_item in keys_iter.iter() { let hash = self.method.get_hash(key_item); indices.push(hash2bucket::<8, true>(hash as usize) as u16); } let scatter_blocks = DataBlock::scatter(&payload.data_block, &indices, 1 << 8)?; let mut blocks = Vec::with_capacity(scatter_blocks.len()); for (bucket, data_block) in scatter_blocks.into_iter().enumerate() { blocks.push(match data_block.is_empty() { true => None, false => Some(DataBlock::empty_with_meta( AggregateMeta::<Method, V>::create_serialized(bucket as isize, data_block), )), }); } Ok(blocks) } fn partition_hashtable( &self, payload: HashTablePayload<Method, V>, ) -> Result<Vec<Option<DataBlock>>> { let temp = PartitionedHashMethod::convert_hashtable(&self.method, payload.cell)?; let cells = PartitionedHashTableDropper::split_cell(temp); let mut data_blocks = Vec::with_capacity(cells.len()); for (bucket, cell) in cells.into_iter().enumerate() { data_blocks.push(match cell.hashtable.len() == 0 { true => None, false => Some(DataBlock::empty_with_meta( AggregateMeta::<Method, V>::create_hashtable(bucket as isize, cell), )), }) } Ok(data_blocks) } } #[async_trait::async_trait] impl<Method: HashMethodBounds, V: Copy + Send + Sync + 'static> Processor for TransformPartitionBucket<Method, V> { fn name(&self) -> String { String::from("TransformPartitionBucket") } fn as_any(&mut self) -> &mut dyn Any { self } fn event(&mut self) -> Result<Event> { if self.output.is_finished() { for input_state in &self.inputs { input_state.port.finish(); } self.buckets_blocks.clear(); return Ok(Event::Finished); } // We pull the first unsplitted data block if !self.initialized_all_inputs && !self.initialize_all_inputs()? { return Ok(Event::NeedData); } if !self.buckets_blocks.is_empty() && !self.unsplitted_blocks.is_empty() { // Split data blocks if it's unsplitted. return Ok(Event::Sync); } if !self.output.can_push() { for input_state in &self.inputs { input_state.port.set_not_need_data(); } return Ok(Event::NeedConsume); } let pushed_data_block = self.try_push_data_block(); loop { // Try to pull the next data or until the port is closed let mut all_inputs_is_finished = true; let mut all_port_prepared_data = true; for index in 0..self.inputs.len() { if self.inputs[index].port.is_finished() { continue; } all_inputs_is_finished = false; if self.inputs[index].bucket > self.working_bucket { continue; } if !self.inputs[index].port.has_data() { all_port_prepared_data = false; self.inputs[index].port.set_need_data(); continue; } let data_block = self.inputs[index].port.pull_data().unwrap()?; self.inputs[index].bucket = self.add_bucket(data_block); debug_assert!(self.unsplitted_blocks.is_empty()); if self.inputs[index].bucket <= self.working_bucket { all_port_prepared_data = false; self.inputs[index].port.set_need_data(); } } if all_inputs_is_finished { break; } if !all_port_prepared_data { return Ok(Event::NeedData); } self.working_bucket += 1; } if pushed_data_block || self.try_push_data_block() { return Ok(Event::NeedConsume); } if let Some((bucket, bucket_blocks)) = self.buckets_blocks.pop_first() { let data_block = Self::convert_blocks(bucket, bucket_blocks); self.output.push_data(Ok(data_block)); return Ok(Event::NeedConsume); } self.output.finish(); Ok(Event::Finished) } fn process(&mut self) -> Result<()> { let block_meta = self .unsplitted_blocks .pop() .and_then(|mut block| block.take_meta()) .and_then(AggregateMeta::<Method, V>::downcast_from); match block_meta { None => Err(ErrorCode::Internal( "Internal error, TransformPartitionBucket only recv AggregateMeta.", )), Some(agg_block_meta) => { let data_blocks = match agg_block_meta { AggregateMeta::Spilled(_) => unreachable!(), AggregateMeta::Spilling(_) => unreachable!(), AggregateMeta::Partitioned { .. } => unreachable!(), AggregateMeta::Serialized(payload) => self.partition_block(payload)?, AggregateMeta::HashTable(payload) => self.partition_hashtable(payload)?, }; for (bucket, block) in data_blocks.into_iter().enumerate() { if let Some(data_block) = block { match self.buckets_blocks.entry(bucket as isize) { Entry::Vacant(v) => { v.insert(vec![data_block]); } Entry::Occupied(mut v) => { v.get_mut().push(data_block); } }; } } Ok(()) } } } } pub fn build_partition_bucket<Method: HashMethodBounds, V: Copy + Send + Sync + 'static>( method: Method, pipeline: &mut Pipeline, params: Arc<AggregatorParams>, ) -> Result<()> { let input_nums = pipeline.output_len(); let transform = TransformPartitionBucket::<Method, V>::create(method.clone(), input_nums)?; let output = transform.get_output(); let inputs_port = transform.get_inputs(); pipeline.add_pipe(Pipe::create(inputs_port.len(), 1, vec![PipeItem::create( ProcessorPtr::create(Box::new(transform)), inputs_port, vec![output], )])); pipeline.resize(input_nums)?; let operator = DataOperator::instance().operator(); pipeline.add_transform(|input, output| { let operator = operator.clone(); match params.aggregate_functions.is_empty() { true => TransformGroupBySpillReader::<Method>::create(input, output, operator), false => TransformAggregateSpillReader::<Method>::create(input, output, operator), } })?; pipeline.add_transform( |input, output| match params.aggregate_functions.is_empty() { true => { TransformFinalGroupBy::try_create(input, output, method.clone(), params.clone()) } false => { TransformFinalAggregate::try_create(input, output, method.clone(), params.clone()) } }, ) }
// 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 { failure::Error, fidl::endpoints::create_proxy, fidl_fuchsia_bluetooth_host::BondingData, fidl_fuchsia_stash::{ GetIteratorMarker, StoreAccessorMarker, StoreAccessorProxy, StoreMarker, Value, }, fuchsia_bluetooth::error::Error as BtError, fuchsia_syslog::{fx_log_info, fx_log_err}, serde_json, std::collections::HashMap, }; use crate::store::{ keys::{BONDING_DATA_PREFIX, bonding_data_key}, serde::{ BondingDataDeserializer, BondingDataSerializer}, }; /// Stash manages persistent data that is stored in bt-gap's component-specific storage. #[derive(Debug)] pub struct Stash { // The proxy to the Fuchsia stash service. This is assumed to have been initialized as a // read/write capable accessor with the identity of the current component. proxy: StoreAccessorProxy, // In-memory state of the bonding data stash. Each entry is hierarchically indexed by a // local Bluetooth adapter identity and a peer device identifier. bonding_data: HashMap<String, HashMap<String, BondingData>>, } impl Stash { /// Updates the bonding data for a given device. Creates a new entry if one matching this /// device does not exist. pub fn store_bond(&mut self, data: BondingData) -> Result<(), Error> { fx_log_info!("store_bond (id: {})", data.identifier); // Persist the serialized blob. let serialized = serde_json::to_string(&BondingDataSerializer(&data))?; self.proxy.set_value( &bonding_data_key(&data.identifier), &mut Value::Stringval(serialized), )?; self.proxy.commit()?; // Update the in memory cache. let local_map = self .bonding_data .entry(data.local_address.clone()) .or_insert(HashMap::new()); local_map.insert(data.identifier.clone(), data); Ok(()) } /// Returns an iterator over the bonding data entries for the local adapter with the given /// `address`. Returns None if no such data exists. pub fn list_bonds(&self, local_address: &str) -> Option<impl Iterator<Item = &BondingData>> { Some(self.bonding_data.get(local_address)?.values().into_iter()) } // Initializes the stash using the given `accessor`. This asynchronously loads existing // stash data. Returns an error in case of failure. async fn new(accessor: StoreAccessorProxy) -> Result<Stash, Error> { // Obtain a list iterator for all cached bonding data. let (iter, server_end) = create_proxy::<GetIteratorMarker>()?; accessor.get_prefix(BONDING_DATA_PREFIX, server_end)?; let mut bonding_map = HashMap::new(); loop { let next = await!(iter.get_next())?; if next.is_empty() { break; } for key_value in next { if let Value::Stringval(json) = key_value.val { let bonding_data: BondingDataDeserializer = serde_json::from_str(&json)?; let bonding_data = bonding_data.contents(); let local_address_entries = bonding_map .entry(bonding_data.local_address.clone()) .or_insert(HashMap::new()); local_address_entries.insert(bonding_data.identifier.clone(), bonding_data); } else { fx_log_err!("stash malformed: bonding data should be a string"); return Err(BtError::new("failed to initialize stash").into()); } } } Ok(Stash { proxy: accessor, bonding_data: bonding_map, }) } } /// Connects to the stash service and initializes a Stash object. This function obtains /// read/write capability to the component-specific storage identified by `component_id`. pub async fn init_stash(component_id: &str) -> Result<Stash, Error> { let stash_svc = fuchsia_app::client::connect_to_service::<StoreMarker>()?; stash_svc.identify(component_id)?; let (proxy, server_end) = create_proxy::<StoreAccessorMarker>()?; stash_svc.create_accessor(false, server_end)?; await!(Stash::new(proxy)) } // These tests access stash in a hermetic envionment and thus it's ok for state to leak between // test runs, regardless of test failure. Each test clears out the state in stash before performing // its test logic. #[cfg(test)] mod tests { use super::*; use {fuchsia_app::client::connect_to_service, fuchsia_async as fasync, pin_utils::pin_mut}; // create_stash_accessor will create a new accessor to stash scoped under the given test name. // All preexisting data in stash under this identity is deleted before the accessor is // returned. fn create_stash_accessor(test_name: &str) -> Result<StoreAccessorProxy, Error> { let stashserver = connect_to_service::<StoreMarker>()?; // Identify stashserver.identify(&(BONDING_DATA_PREFIX.to_owned() + test_name))?; // Create an accessor let (acc, server_end) = create_proxy()?; stashserver.create_accessor(false, server_end)?; // Clear all data in stash under our identity acc.delete_prefix("")?; acc.commit()?; Ok(acc) } #[test] fn new_stash_succeeds_with_empty_values() { let mut exec = fasync::Executor::new().expect("failed to create an executor"); // Create a Stash service interface. let accessor_proxy = create_stash_accessor("new_stash_succeeds_with_empty_values") .expect("failed to create StashAccessor"); let stash_new_future = Stash::new(accessor_proxy); pin_mut!(stash_new_future); // The stash should be initialized with no data. assert!(exec.run_singlethreaded(stash_new_future) .expect("expected Stash to initialize") .bonding_data.is_empty()); } #[test] fn new_stash_fails_with_malformed_key_value_entry() { let mut exec = fasync::Executor::new().expect("failed to create an executor"); // Create a Stash service interface. let accessor_proxy = create_stash_accessor("new_stash_fails_with_malformed_key_value_entry") .expect("failed to create StashAccessor"); // Set a key/value that contains a non-string value. accessor_proxy.set_value("bonding-data:test1234", &mut Value::Intval(5)) .expect("failed to set a bonding data value"); accessor_proxy.commit() .expect("failed to commit a bonding data value"); // The stash should fail to initialize. let stash_new_future = Stash::new(accessor_proxy); assert!(exec.run_singlethreaded(stash_new_future).is_err()); } #[test] fn new_stash_fails_with_malformed_json() { let mut exec = fasync::Executor::new().expect("failed to create an executor"); // Create a mock Stash service interface. let accessor_proxy = create_stash_accessor("new_stash_fails_with_malformed_json") .expect("failed to create StashAccessor"); // Set a vector that contains a malformed JSON value accessor_proxy.set_value("bonding-data:test1234", &mut Value::Stringval("{0}".to_string())) .expect("failed to set a bonding data value"); accessor_proxy.commit() .expect("failed to commit a bonding data value"); // The stash should fail to initialize. let stash_new_future = Stash::new(accessor_proxy); assert!(exec.run_singlethreaded(stash_new_future).is_err()); } #[test] fn new_stash_succeeds_with_values() { let mut exec = fasync::Executor::new().expect("failed to create an executor"); // Create a Stash service interface. let accessor_proxy = create_stash_accessor("new_stash_succeeds_with_values") .expect("failed to create StashAccessor"); // Insert values into stash that contain bonding data for several devices. accessor_proxy.set_value("bonding-data:id-1", &mut Value::Stringval( r#" { "identifier": "id-1", "localAddress": "00:00:00:00:00:01", "name": "Test Device 1", "le": null, "bredr": null }"# .to_string(), )).expect("failed to set value"); accessor_proxy.set_value("bonding-data:id-2", &mut Value::Stringval( r#" { "identifier": "id-2", "localAddress": "00:00:00:00:00:01", "name": "Test Device 2", "le": null, "bredr": null }"# .to_string(), )).expect("failed to set value"); accessor_proxy.set_value("bonding-data:id-3", &mut Value::Stringval( r#" { "identifier": "id-3", "localAddress": "00:00:00:00:00:02", "name": null, "le": null, "bredr": null }"# .to_string(), )).expect("failed to set value"); accessor_proxy.commit() .expect("failed to commit bonding data values"); // The stash should initialize with bonding data stored in stash let stash_new_future = Stash::new(accessor_proxy); let stash = exec.run_singlethreaded(stash_new_future).expect("stash failed to initialize"); // There should be devices registered for two local addresses. assert_eq!(2, stash.bonding_data.len()); // The first local address should have two devices associated with it. let local = stash .bonding_data .get("00:00:00:00:00:01") .expect("could not find local address entries"); assert_eq!(2, local.len()); assert_eq!( &BondingData { identifier: "id-1".to_string(), local_address: "00:00:00:00:00:01".to_string(), name: Some("Test Device 1".to_string()), le: None, bredr: None, }, local.get("id-1").expect("could not find device") ); assert_eq!( &BondingData { identifier: "id-2".to_string(), local_address: "00:00:00:00:00:01".to_string(), name: Some("Test Device 2".to_string()), le: None, bredr: None, }, local.get("id-2").expect("could not find device") ); // The second local address should have one device associated with it. let local = stash .bonding_data .get("00:00:00:00:00:02") .expect("could not find local address entries"); assert_eq!(1, local.len()); assert_eq!( &BondingData { identifier: "id-3".to_string(), local_address: "00:00:00:00:00:02".to_string(), name: None, le: None, bredr: None, }, local.get("id-3").expect("could not find device") ); } #[test] fn store_bond_commits_entry() { let mut exec = fasync::Executor::new().expect("failed to create an executor"); let accessor_proxy = create_stash_accessor("store_bond_commits_entry") .expect("failed to create StashAccessor"); let mut stash = exec.run_singlethreaded(Stash::new(accessor_proxy.clone())) .expect("stash failed to initialize"); let bonding_data = BondingData { identifier: "id-1".to_string(), local_address: "00:00:00:00:00:01".to_string(), name: None, le: None, bredr: None, }; assert!(stash.store_bond(bonding_data).is_ok()); // Make sure that the in-memory cache has been updated. assert_eq!(1, stash.bonding_data.len()); assert_eq!( &BondingData { identifier: "id-1".to_string(), local_address: "00:00:00:00:00:01".to_string(), name: None, le: None, bredr: None, }, stash .bonding_data .get("00:00:00:00:00:01") .unwrap() .get("id-1") .unwrap() ); // The new data should be accessible over FIDL. assert_eq!(exec.run_singlethreaded(accessor_proxy.get_value("bonding-data:id-1")) .expect("failed to get value") .map(|x| *x), Some(Value::Stringval( "{\"identifier\":\"id-1\",\"localAddress\":\"00:00:00:00:00:01\",\"name\":null,\ \"le\":null,\"bredr\":null}" .to_string() ))); } #[test] fn list_bonds() { let mut exec = fasync::Executor::new().expect("failed to create an executor"); let accessor_proxy = create_stash_accessor("list_bonds") .expect("failed to create StashAccessor"); // Insert values into stash that contain bonding data for several devices. accessor_proxy.set_value("bonding-data:id-1", &mut Value::Stringval( r#" { "identifier": "id-1", "localAddress": "00:00:00:00:00:01", "name": null, "le": null, "bredr": null }"# .to_string(), )).expect("failed to set value"); accessor_proxy.set_value("bonding-data:id-2", &mut Value::Stringval( r#" { "identifier": "id-2", "localAddress": "00:00:00:00:00:01", "name": null, "le": null, "bredr": null }"# .to_string(), )).expect("failed to set value"); accessor_proxy.commit() .expect("failed to commit bonding data values"); let stash = exec.run_singlethreaded(Stash::new(accessor_proxy)) .expect("stash failed to initialize"); // Should return None for unknown address. assert!(stash.list_bonds("00:00:00:00:00:00").is_none()); let mut iter = stash .list_bonds("00:00:00:00:00:01") .expect("expected to find address"); let next_id = &iter.next().unwrap().identifier; assert!("id-1" == next_id.as_str() || "id-2" == next_id.as_str()); let next_id = &iter.next().unwrap().identifier; assert!("id-1" == next_id.as_str() || "id-2" == next_id.as_str()); assert_eq!(None, iter.next()); } }
/* originally generated by rust-bindgen */ //! Bindings for GNU LibC localization functions. //! //! This was generated by rust-bindgen from `<locale.h>`, `<langinfo.h>` and `<iconv.h>`. Iconv is //! included for converting output from nl_langinfo_l to utf-8 in case the user-selected locale is //! not utf-8. Thankfully in Linux all these functions are part of the libc itself, so they are //! already available and we don't need to do any additional linking and so there is no need to put //! this in separate crate either. #![allow(non_camel_case_types)] // Note: rust-bindgen does not generate defines, so these had to be cone manually. Fortunately the // parameters for nl_langinfo are in anonymous enum and were generated. pub const LC_CTYPE: ::libc::c_int = 0; pub const LC_NUMERIC: ::libc::c_int = 1; pub const LC_TIME: ::libc::c_int = 2; pub const LC_COLLATE: ::libc::c_int = 3; pub const LC_MONETARY: ::libc::c_int = 4; pub const LC_MESSAGES: ::libc::c_int = 5; pub const LC_ALL: ::libc::c_int = 6; pub const LC_PAPER: ::libc::c_int = 7; pub const LC_NAME: ::libc::c_int = 8; pub const LC_ADDRESS: ::libc::c_int = 9; pub const LC_TELEPHONE: ::libc::c_int = 10; pub const LC_MEASUREMENT: ::libc::c_int = 11; pub const LC_IDENTIFICATION: ::libc::c_int = 12; pub const LC_CTYPE_MASK: ::libc::c_int = 1 << LC_CTYPE; pub const LC_NUMERIC_MASK: ::libc::c_int = 1 << LC_NUMERIC; pub const LC_TIME_MASK: ::libc::c_int = 1 << LC_TIME; pub const LC_COLLATE_MASK: ::libc::c_int = 1 << LC_COLLATE; pub const LC_MONETARY_MASK: ::libc::c_int = 1 << LC_MONETARY; pub const LC_MESSAGES_MASK: ::libc::c_int = 1 << LC_MESSAGES; pub const LC_PAPER_MASK: ::libc::c_int = 1 << LC_PAPER; pub const LC_NAME_MASK: ::libc::c_int = 1 << LC_NAME; pub const LC_ADDRESS_MASK: ::libc::c_int = 1 << LC_ADDRESS; pub const LC_TELEPHONE_MASK: ::libc::c_int = 1 << LC_TELEPHONE; pub const LC_MEASUREMENT_MASK: ::libc::c_int = 1 << LC_MEASUREMENT; pub const LC_IDENTIFICATION_MASK: ::libc::c_int = 1 << LC_IDENTIFICATION; pub const LC_ALL_MASK: ::libc::c_int = LC_CTYPE_MASK | LC_NUMERIC_MASK | LC_TIME_MASK | LC_COLLATE_MASK | LC_MONETARY_MASK | LC_MESSAGES_MASK | LC_PAPER_MASK | LC_NAME_MASK | LC_ADDRESS_MASK | LC_TELEPHONE_MASK | LC_MEASUREMENT_MASK | LC_IDENTIFICATION_MASK; #[repr(C)] #[derive(Copy, Clone)] pub struct Struct_lconv { pub decimal_point: *mut ::libc::c_char, pub thousands_sep: *mut ::libc::c_char, pub grouping: *mut ::libc::c_char, pub int_curr_symbol: *mut ::libc::c_char, pub currency_symbol: *mut ::libc::c_char, pub mon_decimal_point: *mut ::libc::c_char, pub mon_thousands_sep: *mut ::libc::c_char, pub mon_grouping: *mut ::libc::c_char, pub positive_sign: *mut ::libc::c_char, pub negative_sign: *mut ::libc::c_char, pub int_frac_digits: ::libc::c_char, pub frac_digits: ::libc::c_char, pub p_cs_precedes: ::libc::c_char, pub p_sep_by_space: ::libc::c_char, pub n_cs_precedes: ::libc::c_char, pub n_sep_by_space: ::libc::c_char, pub p_sign_posn: ::libc::c_char, pub n_sign_posn: ::libc::c_char, pub int_p_cs_precedes: ::libc::c_char, pub int_p_sep_by_space: ::libc::c_char, pub int_n_cs_precedes: ::libc::c_char, pub int_n_sep_by_space: ::libc::c_char, pub int_p_sign_posn: ::libc::c_char, pub int_n_sign_posn: ::libc::c_char, } impl ::std::default::Default for Struct_lconv { fn default() -> Struct_lconv { unsafe { ::std::mem::zeroed() } } } pub enum Struct___locale_data { } #[repr(C)] #[derive(Copy, Clone)] pub struct Struct___locale_struct { pub __locales: [*mut Struct___locale_data; 13usize], pub __ctype_b: *const ::libc::c_ushort, pub __ctype_tolower: *const ::libc::c_int, pub __ctype_toupper: *const ::libc::c_int, pub __names: [*const ::libc::c_char; 13usize], } impl ::std::default::Default for Struct___locale_struct { fn default() -> Struct___locale_struct { unsafe { ::std::mem::zeroed() } } } pub type __locale_t = *mut Struct___locale_struct; pub type locale_t = __locale_t; pub type nl_catd = *mut ::libc::c_void; pub type nl_item = ::libc::c_uint; pub type Enum_Unnamed1 = ::libc::c_uint; pub const ABDAY_1: ::libc::c_uint = 131072; pub const ABDAY_2: ::libc::c_uint = 131073; pub const ABDAY_3: ::libc::c_uint = 131074; pub const ABDAY_4: ::libc::c_uint = 131075; pub const ABDAY_5: ::libc::c_uint = 131076; pub const ABDAY_6: ::libc::c_uint = 131077; pub const ABDAY_7: ::libc::c_uint = 131078; pub const DAY_1: ::libc::c_uint = 131079; pub const DAY_2: ::libc::c_uint = 131080; pub const DAY_3: ::libc::c_uint = 131081; pub const DAY_4: ::libc::c_uint = 131082; pub const DAY_5: ::libc::c_uint = 131083; pub const DAY_6: ::libc::c_uint = 131084; pub const DAY_7: ::libc::c_uint = 131085; pub const ABMON_1: ::libc::c_uint = 131086; pub const ABMON_2: ::libc::c_uint = 131087; pub const ABMON_3: ::libc::c_uint = 131088; pub const ABMON_4: ::libc::c_uint = 131089; pub const ABMON_5: ::libc::c_uint = 131090; pub const ABMON_6: ::libc::c_uint = 131091; pub const ABMON_7: ::libc::c_uint = 131092; pub const ABMON_8: ::libc::c_uint = 131093; pub const ABMON_9: ::libc::c_uint = 131094; pub const ABMON_10: ::libc::c_uint = 131095; pub const ABMON_11: ::libc::c_uint = 131096; pub const ABMON_12: ::libc::c_uint = 131097; pub const MON_1: ::libc::c_uint = 131098; pub const MON_2: ::libc::c_uint = 131099; pub const MON_3: ::libc::c_uint = 131100; pub const MON_4: ::libc::c_uint = 131101; pub const MON_5: ::libc::c_uint = 131102; pub const MON_6: ::libc::c_uint = 131103; pub const MON_7: ::libc::c_uint = 131104; pub const MON_8: ::libc::c_uint = 131105; pub const MON_9: ::libc::c_uint = 131106; pub const MON_10: ::libc::c_uint = 131107; pub const MON_11: ::libc::c_uint = 131108; pub const MON_12: ::libc::c_uint = 131109; pub const AM_STR: ::libc::c_uint = 131110; pub const PM_STR: ::libc::c_uint = 131111; pub const D_T_FMT: ::libc::c_uint = 131112; pub const D_FMT: ::libc::c_uint = 131113; pub const T_FMT: ::libc::c_uint = 131114; pub const T_FMT_AMPM: ::libc::c_uint = 131115; pub const ERA: ::libc::c_uint = 131116; pub const __ERA_YEAR: ::libc::c_uint = 131117; pub const ERA_D_FMT: ::libc::c_uint = 131118; pub const ALT_DIGITS: ::libc::c_uint = 131119; pub const ERA_D_T_FMT: ::libc::c_uint = 131120; pub const ERA_T_FMT: ::libc::c_uint = 131121; pub const _NL_TIME_ERA_NUM_ENTRIES: ::libc::c_uint = 131122; pub const _NL_TIME_ERA_ENTRIES: ::libc::c_uint = 131123; pub const _NL_WABDAY_1: ::libc::c_uint = 131124; pub const _NL_WABDAY_2: ::libc::c_uint = 131125; pub const _NL_WABDAY_3: ::libc::c_uint = 131126; pub const _NL_WABDAY_4: ::libc::c_uint = 131127; pub const _NL_WABDAY_5: ::libc::c_uint = 131128; pub const _NL_WABDAY_6: ::libc::c_uint = 131129; pub const _NL_WABDAY_7: ::libc::c_uint = 131130; pub const _NL_WDAY_1: ::libc::c_uint = 131131; pub const _NL_WDAY_2: ::libc::c_uint = 131132; pub const _NL_WDAY_3: ::libc::c_uint = 131133; pub const _NL_WDAY_4: ::libc::c_uint = 131134; pub const _NL_WDAY_5: ::libc::c_uint = 131135; pub const _NL_WDAY_6: ::libc::c_uint = 131136; pub const _NL_WDAY_7: ::libc::c_uint = 131137; pub const _NL_WABMON_1: ::libc::c_uint = 131138; pub const _NL_WABMON_2: ::libc::c_uint = 131139; pub const _NL_WABMON_3: ::libc::c_uint = 131140; pub const _NL_WABMON_4: ::libc::c_uint = 131141; pub const _NL_WABMON_5: ::libc::c_uint = 131142; pub const _NL_WABMON_6: ::libc::c_uint = 131143; pub const _NL_WABMON_7: ::libc::c_uint = 131144; pub const _NL_WABMON_8: ::libc::c_uint = 131145; pub const _NL_WABMON_9: ::libc::c_uint = 131146; pub const _NL_WABMON_10: ::libc::c_uint = 131147; pub const _NL_WABMON_11: ::libc::c_uint = 131148; pub const _NL_WABMON_12: ::libc::c_uint = 131149; pub const _NL_WMON_1: ::libc::c_uint = 131150; pub const _NL_WMON_2: ::libc::c_uint = 131151; pub const _NL_WMON_3: ::libc::c_uint = 131152; pub const _NL_WMON_4: ::libc::c_uint = 131153; pub const _NL_WMON_5: ::libc::c_uint = 131154; pub const _NL_WMON_6: ::libc::c_uint = 131155; pub const _NL_WMON_7: ::libc::c_uint = 131156; pub const _NL_WMON_8: ::libc::c_uint = 131157; pub const _NL_WMON_9: ::libc::c_uint = 131158; pub const _NL_WMON_10: ::libc::c_uint = 131159; pub const _NL_WMON_11: ::libc::c_uint = 131160; pub const _NL_WMON_12: ::libc::c_uint = 131161; pub const _NL_WAM_STR: ::libc::c_uint = 131162; pub const _NL_WPM_STR: ::libc::c_uint = 131163; pub const _NL_WD_T_FMT: ::libc::c_uint = 131164; pub const _NL_WD_FMT: ::libc::c_uint = 131165; pub const _NL_WT_FMT: ::libc::c_uint = 131166; pub const _NL_WT_FMT_AMPM: ::libc::c_uint = 131167; pub const _NL_WERA_YEAR: ::libc::c_uint = 131168; pub const _NL_WERA_D_FMT: ::libc::c_uint = 131169; pub const _NL_WALT_DIGITS: ::libc::c_uint = 131170; pub const _NL_WERA_D_T_FMT: ::libc::c_uint = 131171; pub const _NL_WERA_T_FMT: ::libc::c_uint = 131172; pub const _NL_TIME_WEEK_NDAYS: ::libc::c_uint = 131173; pub const _NL_TIME_WEEK_1STDAY: ::libc::c_uint = 131174; pub const _NL_TIME_WEEK_1STWEEK: ::libc::c_uint = 131175; pub const _NL_TIME_FIRST_WEEKDAY: ::libc::c_uint = 131176; pub const _NL_TIME_FIRST_WORKDAY: ::libc::c_uint = 131177; pub const _NL_TIME_CAL_DIRECTION: ::libc::c_uint = 131178; pub const _NL_TIME_TIMEZONE: ::libc::c_uint = 131179; pub const _DATE_FMT: ::libc::c_uint = 131180; pub const _NL_W_DATE_FMT: ::libc::c_uint = 131181; pub const _NL_TIME_CODESET: ::libc::c_uint = 131182; pub const _NL_NUM_LC_TIME: ::libc::c_uint = 131183; pub const _NL_COLLATE_NRULES: ::libc::c_uint = 196608; pub const _NL_COLLATE_RULESETS: ::libc::c_uint = 196609; pub const _NL_COLLATE_TABLEMB: ::libc::c_uint = 196610; pub const _NL_COLLATE_WEIGHTMB: ::libc::c_uint = 196611; pub const _NL_COLLATE_EXTRAMB: ::libc::c_uint = 196612; pub const _NL_COLLATE_INDIRECTMB: ::libc::c_uint = 196613; pub const _NL_COLLATE_GAP1: ::libc::c_uint = 196614; pub const _NL_COLLATE_GAP2: ::libc::c_uint = 196615; pub const _NL_COLLATE_GAP3: ::libc::c_uint = 196616; pub const _NL_COLLATE_TABLEWC: ::libc::c_uint = 196617; pub const _NL_COLLATE_WEIGHTWC: ::libc::c_uint = 196618; pub const _NL_COLLATE_EXTRAWC: ::libc::c_uint = 196619; pub const _NL_COLLATE_INDIRECTWC: ::libc::c_uint = 196620; pub const _NL_COLLATE_SYMB_HASH_SIZEMB: ::libc::c_uint = 196621; pub const _NL_COLLATE_SYMB_TABLEMB: ::libc::c_uint = 196622; pub const _NL_COLLATE_SYMB_EXTRAMB: ::libc::c_uint = 196623; pub const _NL_COLLATE_COLLSEQMB: ::libc::c_uint = 196624; pub const _NL_COLLATE_COLLSEQWC: ::libc::c_uint = 196625; pub const _NL_COLLATE_CODESET: ::libc::c_uint = 196626; pub const _NL_NUM_LC_COLLATE: ::libc::c_uint = 196627; pub const _NL_CTYPE_CLASS: ::libc::c_uint = 0; pub const _NL_CTYPE_TOUPPER: ::libc::c_uint = 1; pub const _NL_CTYPE_GAP1: ::libc::c_uint = 2; pub const _NL_CTYPE_TOLOWER: ::libc::c_uint = 3; pub const _NL_CTYPE_GAP2: ::libc::c_uint = 4; pub const _NL_CTYPE_CLASS32: ::libc::c_uint = 5; pub const _NL_CTYPE_GAP3: ::libc::c_uint = 6; pub const _NL_CTYPE_GAP4: ::libc::c_uint = 7; pub const _NL_CTYPE_GAP5: ::libc::c_uint = 8; pub const _NL_CTYPE_GAP6: ::libc::c_uint = 9; pub const _NL_CTYPE_CLASS_NAMES: ::libc::c_uint = 10; pub const _NL_CTYPE_MAP_NAMES: ::libc::c_uint = 11; pub const _NL_CTYPE_WIDTH: ::libc::c_uint = 12; pub const _NL_CTYPE_MB_CUR_MAX: ::libc::c_uint = 13; pub const _NL_CTYPE_CODESET_NAME: ::libc::c_uint = 14; pub const CODESET: ::libc::c_uint = 14; pub const _NL_CTYPE_TOUPPER32: ::libc::c_uint = 15; pub const _NL_CTYPE_TOLOWER32: ::libc::c_uint = 16; pub const _NL_CTYPE_CLASS_OFFSET: ::libc::c_uint = 17; pub const _NL_CTYPE_MAP_OFFSET: ::libc::c_uint = 18; pub const _NL_CTYPE_INDIGITS_MB_LEN: ::libc::c_uint = 19; pub const _NL_CTYPE_INDIGITS0_MB: ::libc::c_uint = 20; pub const _NL_CTYPE_INDIGITS1_MB: ::libc::c_uint = 21; pub const _NL_CTYPE_INDIGITS2_MB: ::libc::c_uint = 22; pub const _NL_CTYPE_INDIGITS3_MB: ::libc::c_uint = 23; pub const _NL_CTYPE_INDIGITS4_MB: ::libc::c_uint = 24; pub const _NL_CTYPE_INDIGITS5_MB: ::libc::c_uint = 25; pub const _NL_CTYPE_INDIGITS6_MB: ::libc::c_uint = 26; pub const _NL_CTYPE_INDIGITS7_MB: ::libc::c_uint = 27; pub const _NL_CTYPE_INDIGITS8_MB: ::libc::c_uint = 28; pub const _NL_CTYPE_INDIGITS9_MB: ::libc::c_uint = 29; pub const _NL_CTYPE_INDIGITS_WC_LEN: ::libc::c_uint = 30; pub const _NL_CTYPE_INDIGITS0_WC: ::libc::c_uint = 31; pub const _NL_CTYPE_INDIGITS1_WC: ::libc::c_uint = 32; pub const _NL_CTYPE_INDIGITS2_WC: ::libc::c_uint = 33; pub const _NL_CTYPE_INDIGITS3_WC: ::libc::c_uint = 34; pub const _NL_CTYPE_INDIGITS4_WC: ::libc::c_uint = 35; pub const _NL_CTYPE_INDIGITS5_WC: ::libc::c_uint = 36; pub const _NL_CTYPE_INDIGITS6_WC: ::libc::c_uint = 37; pub const _NL_CTYPE_INDIGITS7_WC: ::libc::c_uint = 38; pub const _NL_CTYPE_INDIGITS8_WC: ::libc::c_uint = 39; pub const _NL_CTYPE_INDIGITS9_WC: ::libc::c_uint = 40; pub const _NL_CTYPE_OUTDIGIT0_MB: ::libc::c_uint = 41; pub const _NL_CTYPE_OUTDIGIT1_MB: ::libc::c_uint = 42; pub const _NL_CTYPE_OUTDIGIT2_MB: ::libc::c_uint = 43; pub const _NL_CTYPE_OUTDIGIT3_MB: ::libc::c_uint = 44; pub const _NL_CTYPE_OUTDIGIT4_MB: ::libc::c_uint = 45; pub const _NL_CTYPE_OUTDIGIT5_MB: ::libc::c_uint = 46; pub const _NL_CTYPE_OUTDIGIT6_MB: ::libc::c_uint = 47; pub const _NL_CTYPE_OUTDIGIT7_MB: ::libc::c_uint = 48; pub const _NL_CTYPE_OUTDIGIT8_MB: ::libc::c_uint = 49; pub const _NL_CTYPE_OUTDIGIT9_MB: ::libc::c_uint = 50; pub const _NL_CTYPE_OUTDIGIT0_WC: ::libc::c_uint = 51; pub const _NL_CTYPE_OUTDIGIT1_WC: ::libc::c_uint = 52; pub const _NL_CTYPE_OUTDIGIT2_WC: ::libc::c_uint = 53; pub const _NL_CTYPE_OUTDIGIT3_WC: ::libc::c_uint = 54; pub const _NL_CTYPE_OUTDIGIT4_WC: ::libc::c_uint = 55; pub const _NL_CTYPE_OUTDIGIT5_WC: ::libc::c_uint = 56; pub const _NL_CTYPE_OUTDIGIT6_WC: ::libc::c_uint = 57; pub const _NL_CTYPE_OUTDIGIT7_WC: ::libc::c_uint = 58; pub const _NL_CTYPE_OUTDIGIT8_WC: ::libc::c_uint = 59; pub const _NL_CTYPE_OUTDIGIT9_WC: ::libc::c_uint = 60; pub const _NL_CTYPE_TRANSLIT_TAB_SIZE: ::libc::c_uint = 61; pub const _NL_CTYPE_TRANSLIT_FROM_IDX: ::libc::c_uint = 62; pub const _NL_CTYPE_TRANSLIT_FROM_TBL: ::libc::c_uint = 63; pub const _NL_CTYPE_TRANSLIT_TO_IDX: ::libc::c_uint = 64; pub const _NL_CTYPE_TRANSLIT_TO_TBL: ::libc::c_uint = 65; pub const _NL_CTYPE_TRANSLIT_DEFAULT_MISSING_LEN: ::libc::c_uint = 66; pub const _NL_CTYPE_TRANSLIT_DEFAULT_MISSING: ::libc::c_uint = 67; pub const _NL_CTYPE_TRANSLIT_IGNORE_LEN: ::libc::c_uint = 68; pub const _NL_CTYPE_TRANSLIT_IGNORE: ::libc::c_uint = 69; pub const _NL_CTYPE_MAP_TO_NONASCII: ::libc::c_uint = 70; pub const _NL_CTYPE_NONASCII_CASE: ::libc::c_uint = 71; pub const _NL_CTYPE_EXTRA_MAP_1: ::libc::c_uint = 72; pub const _NL_CTYPE_EXTRA_MAP_2: ::libc::c_uint = 73; pub const _NL_CTYPE_EXTRA_MAP_3: ::libc::c_uint = 74; pub const _NL_CTYPE_EXTRA_MAP_4: ::libc::c_uint = 75; pub const _NL_CTYPE_EXTRA_MAP_5: ::libc::c_uint = 76; pub const _NL_CTYPE_EXTRA_MAP_6: ::libc::c_uint = 77; pub const _NL_CTYPE_EXTRA_MAP_7: ::libc::c_uint = 78; pub const _NL_CTYPE_EXTRA_MAP_8: ::libc::c_uint = 79; pub const _NL_CTYPE_EXTRA_MAP_9: ::libc::c_uint = 80; pub const _NL_CTYPE_EXTRA_MAP_10: ::libc::c_uint = 81; pub const _NL_CTYPE_EXTRA_MAP_11: ::libc::c_uint = 82; pub const _NL_CTYPE_EXTRA_MAP_12: ::libc::c_uint = 83; pub const _NL_CTYPE_EXTRA_MAP_13: ::libc::c_uint = 84; pub const _NL_CTYPE_EXTRA_MAP_14: ::libc::c_uint = 85; pub const _NL_NUM_LC_CTYPE: ::libc::c_uint = 86; pub const __INT_CURR_SYMBOL: ::libc::c_uint = 262144; pub const __CURRENCY_SYMBOL: ::libc::c_uint = 262145; pub const __MON_DECIMAL_POINT: ::libc::c_uint = 262146; pub const __MON_THOUSANDS_SEP: ::libc::c_uint = 262147; pub const __MON_GROUPING: ::libc::c_uint = 262148; pub const __POSITIVE_SIGN: ::libc::c_uint = 262149; pub const __NEGATIVE_SIGN: ::libc::c_uint = 262150; pub const __INT_FRAC_DIGITS: ::libc::c_uint = 262151; pub const __FRAC_DIGITS: ::libc::c_uint = 262152; pub const __P_CS_PRECEDES: ::libc::c_uint = 262153; pub const __P_SEP_BY_SPACE: ::libc::c_uint = 262154; pub const __N_CS_PRECEDES: ::libc::c_uint = 262155; pub const __N_SEP_BY_SPACE: ::libc::c_uint = 262156; pub const __P_SIGN_POSN: ::libc::c_uint = 262157; pub const __N_SIGN_POSN: ::libc::c_uint = 262158; pub const _NL_MONETARY_CRNCYSTR: ::libc::c_uint = 262159; pub const __INT_P_CS_PRECEDES: ::libc::c_uint = 262160; pub const __INT_P_SEP_BY_SPACE: ::libc::c_uint = 262161; pub const __INT_N_CS_PRECEDES: ::libc::c_uint = 262162; pub const __INT_N_SEP_BY_SPACE: ::libc::c_uint = 262163; pub const __INT_P_SIGN_POSN: ::libc::c_uint = 262164; pub const __INT_N_SIGN_POSN: ::libc::c_uint = 262165; pub const _NL_MONETARY_DUO_INT_CURR_SYMBOL: ::libc::c_uint = 262166; pub const _NL_MONETARY_DUO_CURRENCY_SYMBOL: ::libc::c_uint = 262167; pub const _NL_MONETARY_DUO_INT_FRAC_DIGITS: ::libc::c_uint = 262168; pub const _NL_MONETARY_DUO_FRAC_DIGITS: ::libc::c_uint = 262169; pub const _NL_MONETARY_DUO_P_CS_PRECEDES: ::libc::c_uint = 262170; pub const _NL_MONETARY_DUO_P_SEP_BY_SPACE: ::libc::c_uint = 262171; pub const _NL_MONETARY_DUO_N_CS_PRECEDES: ::libc::c_uint = 262172; pub const _NL_MONETARY_DUO_N_SEP_BY_SPACE: ::libc::c_uint = 262173; pub const _NL_MONETARY_DUO_INT_P_CS_PRECEDES: ::libc::c_uint = 262174; pub const _NL_MONETARY_DUO_INT_P_SEP_BY_SPACE: ::libc::c_uint = 262175; pub const _NL_MONETARY_DUO_INT_N_CS_PRECEDES: ::libc::c_uint = 262176; pub const _NL_MONETARY_DUO_INT_N_SEP_BY_SPACE: ::libc::c_uint = 262177; pub const _NL_MONETARY_DUO_P_SIGN_POSN: ::libc::c_uint = 262178; pub const _NL_MONETARY_DUO_N_SIGN_POSN: ::libc::c_uint = 262179; pub const _NL_MONETARY_DUO_INT_P_SIGN_POSN: ::libc::c_uint = 262180; pub const _NL_MONETARY_DUO_INT_N_SIGN_POSN: ::libc::c_uint = 262181; pub const _NL_MONETARY_UNO_VALID_FROM: ::libc::c_uint = 262182; pub const _NL_MONETARY_UNO_VALID_TO: ::libc::c_uint = 262183; pub const _NL_MONETARY_DUO_VALID_FROM: ::libc::c_uint = 262184; pub const _NL_MONETARY_DUO_VALID_TO: ::libc::c_uint = 262185; pub const _NL_MONETARY_CONVERSION_RATE: ::libc::c_uint = 262186; pub const _NL_MONETARY_DECIMAL_POINT_WC: ::libc::c_uint = 262187; pub const _NL_MONETARY_THOUSANDS_SEP_WC: ::libc::c_uint = 262188; pub const _NL_MONETARY_CODESET: ::libc::c_uint = 262189; pub const _NL_NUM_LC_MONETARY: ::libc::c_uint = 262190; pub const __DECIMAL_POINT: ::libc::c_uint = 65536; pub const RADIXCHAR: ::libc::c_uint = 65536; pub const __THOUSANDS_SEP: ::libc::c_uint = 65537; pub const THOUSEP: ::libc::c_uint = 65537; pub const __GROUPING: ::libc::c_uint = 65538; pub const _NL_NUMERIC_DECIMAL_POINT_WC: ::libc::c_uint = 65539; pub const _NL_NUMERIC_THOUSANDS_SEP_WC: ::libc::c_uint = 65540; pub const _NL_NUMERIC_CODESET: ::libc::c_uint = 65541; pub const _NL_NUM_LC_NUMERIC: ::libc::c_uint = 65542; pub const __YESEXPR: ::libc::c_uint = 327680; pub const __NOEXPR: ::libc::c_uint = 327681; pub const __YESSTR: ::libc::c_uint = 327682; pub const __NOSTR: ::libc::c_uint = 327683; pub const _NL_MESSAGES_CODESET: ::libc::c_uint = 327684; pub const _NL_NUM_LC_MESSAGES: ::libc::c_uint = 327685; pub const _NL_PAPER_HEIGHT: ::libc::c_uint = 458752; pub const _NL_PAPER_WIDTH: ::libc::c_uint = 458753; pub const _NL_PAPER_CODESET: ::libc::c_uint = 458754; pub const _NL_NUM_LC_PAPER: ::libc::c_uint = 458755; pub const _NL_NAME_NAME_FMT: ::libc::c_uint = 524288; pub const _NL_NAME_NAME_GEN: ::libc::c_uint = 524289; pub const _NL_NAME_NAME_MR: ::libc::c_uint = 524290; pub const _NL_NAME_NAME_MRS: ::libc::c_uint = 524291; pub const _NL_NAME_NAME_MISS: ::libc::c_uint = 524292; pub const _NL_NAME_NAME_MS: ::libc::c_uint = 524293; pub const _NL_NAME_CODESET: ::libc::c_uint = 524294; pub const _NL_NUM_LC_NAME: ::libc::c_uint = 524295; pub const _NL_ADDRESS_POSTAL_FMT: ::libc::c_uint = 589824; pub const _NL_ADDRESS_COUNTRY_NAME: ::libc::c_uint = 589825; pub const _NL_ADDRESS_COUNTRY_POST: ::libc::c_uint = 589826; pub const _NL_ADDRESS_COUNTRY_AB2: ::libc::c_uint = 589827; pub const _NL_ADDRESS_COUNTRY_AB3: ::libc::c_uint = 589828; pub const _NL_ADDRESS_COUNTRY_CAR: ::libc::c_uint = 589829; pub const _NL_ADDRESS_COUNTRY_NUM: ::libc::c_uint = 589830; pub const _NL_ADDRESS_COUNTRY_ISBN: ::libc::c_uint = 589831; pub const _NL_ADDRESS_LANG_NAME: ::libc::c_uint = 589832; pub const _NL_ADDRESS_LANG_AB: ::libc::c_uint = 589833; pub const _NL_ADDRESS_LANG_TERM: ::libc::c_uint = 589834; pub const _NL_ADDRESS_LANG_LIB: ::libc::c_uint = 589835; pub const _NL_ADDRESS_CODESET: ::libc::c_uint = 589836; pub const _NL_NUM_LC_ADDRESS: ::libc::c_uint = 589837; pub const _NL_TELEPHONE_TEL_INT_FMT: ::libc::c_uint = 655360; pub const _NL_TELEPHONE_TEL_DOM_FMT: ::libc::c_uint = 655361; pub const _NL_TELEPHONE_INT_SELECT: ::libc::c_uint = 655362; pub const _NL_TELEPHONE_INT_PREFIX: ::libc::c_uint = 655363; pub const _NL_TELEPHONE_CODESET: ::libc::c_uint = 655364; pub const _NL_NUM_LC_TELEPHONE: ::libc::c_uint = 655365; pub const _NL_MEASUREMENT_MEASUREMENT: ::libc::c_uint = 720896; pub const _NL_MEASUREMENT_CODESET: ::libc::c_uint = 720897; pub const _NL_NUM_LC_MEASUREMENT: ::libc::c_uint = 720898; pub const _NL_IDENTIFICATION_TITLE: ::libc::c_uint = 786432; pub const _NL_IDENTIFICATION_SOURCE: ::libc::c_uint = 786433; pub const _NL_IDENTIFICATION_ADDRESS: ::libc::c_uint = 786434; pub const _NL_IDENTIFICATION_CONTACT: ::libc::c_uint = 786435; pub const _NL_IDENTIFICATION_EMAIL: ::libc::c_uint = 786436; pub const _NL_IDENTIFICATION_TEL: ::libc::c_uint = 786437; pub const _NL_IDENTIFICATION_FAX: ::libc::c_uint = 786438; pub const _NL_IDENTIFICATION_LANGUAGE: ::libc::c_uint = 786439; pub const _NL_IDENTIFICATION_TERRITORY: ::libc::c_uint = 786440; pub const _NL_IDENTIFICATION_AUDIENCE: ::libc::c_uint = 786441; pub const _NL_IDENTIFICATION_APPLICATION: ::libc::c_uint = 786442; pub const _NL_IDENTIFICATION_ABBREVIATION: ::libc::c_uint = 786443; pub const _NL_IDENTIFICATION_REVISION: ::libc::c_uint = 786444; pub const _NL_IDENTIFICATION_DATE: ::libc::c_uint = 786445; pub const _NL_IDENTIFICATION_CATEGORY: ::libc::c_uint = 786446; pub const _NL_IDENTIFICATION_CODESET: ::libc::c_uint = 786447; pub const _NL_NUM_LC_IDENTIFICATION: ::libc::c_uint = 786448; pub const _NL_NUM: ::libc::c_uint = 786449; pub type size_t = ::libc::size_t; pub type iconv_t = *mut ::libc::c_void; extern "C" { pub fn setlocale(__category: ::libc::c_int, __locale: *const ::libc::c_char) -> *mut ::libc::c_char; pub fn localeconv() -> *mut Struct_lconv; pub fn newlocale(__category_mask: ::libc::c_int, __locale: *const ::libc::c_char, __base: __locale_t) -> __locale_t; pub fn duplocale(__dataset: __locale_t) -> __locale_t; pub fn freelocale(__dataset: __locale_t) -> (); pub fn uselocale(__dataset: __locale_t) -> __locale_t; pub fn catopen(__cat_name: *const ::libc::c_char, __flag: ::libc::c_int) -> nl_catd; pub fn catgets(__catalog: nl_catd, __set: ::libc::c_int, __number: ::libc::c_int, __string: *const ::libc::c_char) -> *mut ::libc::c_char; pub fn catclose(__catalog: nl_catd) -> ::libc::c_int; pub fn nl_langinfo(__item: nl_item) -> *const ::libc::c_char; pub fn nl_langinfo_l(__item: nl_item, __l: __locale_t) -> *const ::libc::c_char; pub fn iconv_open(__tocode: *const ::libc::c_char, __fromcode: *const ::libc::c_char) -> iconv_t; // NOTE: The C decl has __inbuf as *mut *mut, but it actually isn't pub fn iconv(__cd: iconv_t, __inbuf: *mut *const ::libc::c_char, __inbytesleft: *mut size_t, __outbuf: *mut *mut ::libc::c_char, __outbytesleft: *mut size_t) -> size_t; pub fn iconv_close(__cd: iconv_t) -> ::libc::c_int; }
#![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 IImageScanner(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IImageScanner { type Vtable = IImageScanner_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x53a88f78_5298_48a0_8da3_8087519665e0); } #[repr(C)] #[doc(hidden)] pub struct IImageScanner_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 ImageScannerScanSource) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ImageScannerScanSource, result__: *mut bool) -> ::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 ::windows::core::RawPtr) -> ::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, scansource: ImageScannerScanSource, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, scansource: ImageScannerScanSource, targetstream: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize, #[cfg(all(feature = "Foundation", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, scansource: ImageScannerScanSource, storagefolder: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IImageScannerFeederConfiguration(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IImageScannerFeederConfiguration { type Vtable = IImageScannerFeederConfiguration_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x74bdacee_fa97_4c17_8280_40e39c6dcc67); } #[repr(C)] #[doc(hidden)] pub struct IImageScannerFeederConfiguration_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 bool) -> ::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, #[cfg(feature = "Graphics_Printing")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Graphics::Printing::PrintMediaSize) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_Printing"))] usize, #[cfg(feature = "Graphics_Printing")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Graphics::Printing::PrintMediaSize) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_Printing"))] usize, #[cfg(feature = "Graphics_Printing")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Graphics::Printing::PrintOrientation) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_Printing"))] usize, #[cfg(feature = "Graphics_Printing")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Graphics::Printing::PrintOrientation) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_Printing"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Size) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Graphics_Printing")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pagesize: super::super::Graphics::Printing::PrintMediaSize, pageorientation: super::super::Graphics::Printing::PrintOrientation, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(not(feature = "Graphics_Printing"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::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, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::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, 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 IImageScannerFormatConfiguration(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IImageScannerFormatConfiguration { type Vtable = IImageScannerFormatConfiguration_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xae275d11_dadf_4010_bf10_cca5c83dcbb0); } impl IImageScannerFormatConfiguration { pub fn DefaultFormat(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = self; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } pub fn Format(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = self; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } pub fn SetFormat(&self, value: ImageScannerFormat) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsFormatSupported(&self, value: ImageScannerFormat) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for IImageScannerFormatConfiguration { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{ae275d11-dadf-4010-bf10-cca5c83dcbb0}"); } impl ::core::convert::From<IImageScannerFormatConfiguration> for ::windows::core::IUnknown { fn from(value: IImageScannerFormatConfiguration) -> Self { value.0 .0 } } impl ::core::convert::From<&IImageScannerFormatConfiguration> for ::windows::core::IUnknown { fn from(value: &IImageScannerFormatConfiguration) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IImageScannerFormatConfiguration { 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 IImageScannerFormatConfiguration { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IImageScannerFormatConfiguration> for ::windows::core::IInspectable { fn from(value: IImageScannerFormatConfiguration) -> Self { value.0 } } impl ::core::convert::From<&IImageScannerFormatConfiguration> for ::windows::core::IInspectable { fn from(value: &IImageScannerFormatConfiguration) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IImageScannerFormatConfiguration { 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 IImageScannerFormatConfiguration { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IImageScannerFormatConfiguration_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 ImageScannerFormat) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ImageScannerFormat) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ImageScannerFormat) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ImageScannerFormat, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IImageScannerPreviewResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IImageScannerPreviewResult { type Vtable = IImageScannerPreviewResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x08b7fe8e_8891_441d_be9c_176fa109c8bb); } #[repr(C)] #[doc(hidden)] pub struct IImageScannerPreviewResult_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 bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ImageScannerFormat) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IImageScannerScanResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IImageScannerScanResult { type Vtable = IImageScannerScanResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc91624cd_9037_4e48_84c1_ac0975076bc5); } #[repr(C)] #[doc(hidden)] pub struct IImageScannerScanResult_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_Collections", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Storage")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IImageScannerSourceConfiguration(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IImageScannerSourceConfiguration { type Vtable = IImageScannerSourceConfiguration_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbfb50055_0b44_4c82_9e89_205f9c234e59); } impl IImageScannerSourceConfiguration { #[cfg(feature = "Foundation")] pub fn MinScanArea(&self) -> ::windows::core::Result<super::super::Foundation::Size> { let this = self; unsafe { let mut result__: super::super::Foundation::Size = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Size>(result__) } } #[cfg(feature = "Foundation")] pub fn MaxScanArea(&self) -> ::windows::core::Result<super::super::Foundation::Size> { let this = self; unsafe { let mut result__: super::super::Foundation::Size = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Size>(result__) } } #[cfg(feature = "Foundation")] pub fn SelectedScanRegion(&self) -> ::windows::core::Result<super::super::Foundation::Rect> { let this = self; unsafe { let mut result__: super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Rect>(result__) } } #[cfg(feature = "Foundation")] pub fn SetSelectedScanRegion<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&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() } } pub fn AutoCroppingMode(&self) -> ::windows::core::Result<ImageScannerAutoCroppingMode> { let this = self; unsafe { let mut result__: ImageScannerAutoCroppingMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerAutoCroppingMode>(result__) } } pub fn SetAutoCroppingMode(&self, value: ImageScannerAutoCroppingMode) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsAutoCroppingModeSupported(&self, value: ImageScannerAutoCroppingMode) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } pub fn MinResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = self; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn MaxResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = self; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn OpticalResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = self; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn DesiredResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = self; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn SetDesiredResolution<'a, Param0: ::windows::core::IntoParam<'a, ImageScannerResolution>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ActualResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = self; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn DefaultColorMode(&self) -> ::windows::core::Result<ImageScannerColorMode> { let this = self; unsafe { let mut result__: ImageScannerColorMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerColorMode>(result__) } } pub fn ColorMode(&self) -> ::windows::core::Result<ImageScannerColorMode> { let this = self; unsafe { let mut result__: ImageScannerColorMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerColorMode>(result__) } } pub fn SetColorMode(&self, value: ImageScannerColorMode) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsColorModeSupported(&self, value: ImageScannerColorMode) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } pub fn MinBrightness(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn MaxBrightness(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn BrightnessStep(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn DefaultBrightness(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn Brightness(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetBrightness(&self, value: i32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), value).ok() } } pub fn MinContrast(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn MaxContrast(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn ContrastStep(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn DefaultContrast(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn Contrast(&self) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetContrast(&self, value: i32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), value).ok() } } pub fn DefaultFormat(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = &::windows::core::Interface::cast::<IImageScannerFormatConfiguration>(self)?; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } pub fn Format(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = &::windows::core::Interface::cast::<IImageScannerFormatConfiguration>(self)?; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } pub fn SetFormat(&self, value: ImageScannerFormat) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerFormatConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsFormatSupported(&self, value: ImageScannerFormat) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerFormatConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for IImageScannerSourceConfiguration { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{bfb50055-0b44-4c82-9e89-205f9c234e59}"); } impl ::core::convert::From<IImageScannerSourceConfiguration> for ::windows::core::IUnknown { fn from(value: IImageScannerSourceConfiguration) -> Self { value.0 .0 } } impl ::core::convert::From<&IImageScannerSourceConfiguration> for ::windows::core::IUnknown { fn from(value: &IImageScannerSourceConfiguration) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IImageScannerSourceConfiguration { 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 IImageScannerSourceConfiguration { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IImageScannerSourceConfiguration> for ::windows::core::IInspectable { fn from(value: IImageScannerSourceConfiguration) -> Self { value.0 } } impl ::core::convert::From<&IImageScannerSourceConfiguration> for ::windows::core::IInspectable { fn from(value: &IImageScannerSourceConfiguration) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IImageScannerSourceConfiguration { 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 IImageScannerSourceConfiguration { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<IImageScannerSourceConfiguration> for IImageScannerFormatConfiguration { type Error = ::windows::core::Error; fn try_from(value: IImageScannerSourceConfiguration) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&IImageScannerSourceConfiguration> for IImageScannerFormatConfiguration { type Error = ::windows::core::Error; fn try_from(value: &IImageScannerSourceConfiguration) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerFormatConfiguration> for IImageScannerSourceConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerFormatConfiguration> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerFormatConfiguration> for &IImageScannerSourceConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerFormatConfiguration> { ::core::convert::TryInto::<IImageScannerFormatConfiguration>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } #[repr(C)] #[doc(hidden)] pub struct IImageScannerSourceConfiguration_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::Foundation::Size) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Size) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ImageScannerAutoCroppingMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ImageScannerAutoCroppingMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ImageScannerAutoCroppingMode, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ImageScannerResolution) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ImageScannerResolution) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ImageScannerResolution) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ImageScannerResolution) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ImageScannerResolution) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ImageScannerResolution) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ImageScannerColorMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ImageScannerColorMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ImageScannerColorMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ImageScannerColorMode, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IImageScannerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IImageScannerStatics { type Vtable = IImageScannerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbc57e70e_d804_4477_9fb5_b911b5473897); } #[repr(C)] #[doc(hidden)] pub struct IImageScannerStatics_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, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ImageScanner(pub ::windows::core::IInspectable); impl ImageScanner { pub fn DeviceId(&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__) } } pub fn DefaultScanSource(&self) -> ::windows::core::Result<ImageScannerScanSource> { let this = self; unsafe { let mut result__: ImageScannerScanSource = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerScanSource>(result__) } } pub fn IsScanSourceSupported(&self, value: ImageScannerScanSource) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } pub fn FlatbedConfiguration(&self) -> ::windows::core::Result<ImageScannerFlatbedConfiguration> { 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::<ImageScannerFlatbedConfiguration>(result__) } } pub fn FeederConfiguration(&self) -> ::windows::core::Result<ImageScannerFeederConfiguration> { 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::<ImageScannerFeederConfiguration>(result__) } } pub fn AutoConfiguration(&self) -> ::windows::core::Result<ImageScannerAutoConfiguration> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerAutoConfiguration>(result__) } } pub fn IsPreviewSupported(&self, scansource: ImageScannerScanSource) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), scansource, &mut result__).from_abi::<bool>(result__) } } #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub fn ScanPreviewToStreamAsync<'a, Param1: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStream>>(&self, scansource: ImageScannerScanSource, targetstream: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<ImageScannerPreviewResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), scansource, targetstream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<ImageScannerPreviewResult>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Storage"))] pub fn ScanFilesToFolderAsync<'a, Param1: ::windows::core::IntoParam<'a, super::super::Storage::StorageFolder>>(&self, scansource: ImageScannerScanSource, storagefolder: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<ImageScannerScanResult, u32>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), scansource, storagefolder.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<ImageScannerScanResult, u32>>(result__) } } #[cfg(feature = "Foundation")] pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<ImageScanner>> { Self::IImageScannerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<ImageScanner>>(result__) }) } pub fn GetDeviceSelector() -> ::windows::core::Result<::windows::core::HSTRING> { Self::IImageScannerStatics(|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__) }) } pub fn IImageScannerStatics<R, F: FnOnce(&IImageScannerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<ImageScanner, IImageScannerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for ImageScanner { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Scanners.ImageScanner;{53a88f78-5298-48a0-8da3-8087519665e0})"); } unsafe impl ::windows::core::Interface for ImageScanner { type Vtable = IImageScanner_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x53a88f78_5298_48a0_8da3_8087519665e0); } impl ::windows::core::RuntimeName for ImageScanner { const NAME: &'static str = "Windows.Devices.Scanners.ImageScanner"; } impl ::core::convert::From<ImageScanner> for ::windows::core::IUnknown { fn from(value: ImageScanner) -> Self { value.0 .0 } } impl ::core::convert::From<&ImageScanner> for ::windows::core::IUnknown { fn from(value: &ImageScanner) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ImageScanner { 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 ImageScanner { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ImageScanner> for ::windows::core::IInspectable { fn from(value: ImageScanner) -> Self { value.0 } } impl ::core::convert::From<&ImageScanner> for ::windows::core::IInspectable { fn from(value: &ImageScanner) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ImageScanner { 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 ImageScanner { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ImageScanner {} unsafe impl ::core::marker::Sync for ImageScanner {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ImageScannerAutoConfiguration(pub ::windows::core::IInspectable); impl ImageScannerAutoConfiguration { pub fn DefaultFormat(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = self; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } pub fn Format(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = self; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } pub fn SetFormat(&self, value: ImageScannerFormat) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsFormatSupported(&self, value: ImageScannerFormat) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for ImageScannerAutoConfiguration { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Scanners.ImageScannerAutoConfiguration;{ae275d11-dadf-4010-bf10-cca5c83dcbb0})"); } unsafe impl ::windows::core::Interface for ImageScannerAutoConfiguration { type Vtable = IImageScannerFormatConfiguration_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xae275d11_dadf_4010_bf10_cca5c83dcbb0); } impl ::windows::core::RuntimeName for ImageScannerAutoConfiguration { const NAME: &'static str = "Windows.Devices.Scanners.ImageScannerAutoConfiguration"; } impl ::core::convert::From<ImageScannerAutoConfiguration> for ::windows::core::IUnknown { fn from(value: ImageScannerAutoConfiguration) -> Self { value.0 .0 } } impl ::core::convert::From<&ImageScannerAutoConfiguration> for ::windows::core::IUnknown { fn from(value: &ImageScannerAutoConfiguration) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ImageScannerAutoConfiguration { 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 ImageScannerAutoConfiguration { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ImageScannerAutoConfiguration> for ::windows::core::IInspectable { fn from(value: ImageScannerAutoConfiguration) -> Self { value.0 } } impl ::core::convert::From<&ImageScannerAutoConfiguration> for ::windows::core::IInspectable { fn from(value: &ImageScannerAutoConfiguration) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ImageScannerAutoConfiguration { 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 ImageScannerAutoConfiguration { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<ImageScannerAutoConfiguration> for IImageScannerFormatConfiguration { fn from(value: ImageScannerAutoConfiguration) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&ImageScannerAutoConfiguration> for IImageScannerFormatConfiguration { fn from(value: &ImageScannerAutoConfiguration) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerFormatConfiguration> for ImageScannerAutoConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerFormatConfiguration> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerFormatConfiguration> for &ImageScannerAutoConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerFormatConfiguration> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } unsafe impl ::core::marker::Send for ImageScannerAutoConfiguration {} unsafe impl ::core::marker::Sync for ImageScannerAutoConfiguration {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ImageScannerAutoCroppingMode(pub i32); impl ImageScannerAutoCroppingMode { pub const Disabled: ImageScannerAutoCroppingMode = ImageScannerAutoCroppingMode(0i32); pub const SingleRegion: ImageScannerAutoCroppingMode = ImageScannerAutoCroppingMode(1i32); pub const MultipleRegion: ImageScannerAutoCroppingMode = ImageScannerAutoCroppingMode(2i32); } impl ::core::convert::From<i32> for ImageScannerAutoCroppingMode { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ImageScannerAutoCroppingMode { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ImageScannerAutoCroppingMode { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Scanners.ImageScannerAutoCroppingMode;i4)"); } impl ::windows::core::DefaultType for ImageScannerAutoCroppingMode { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ImageScannerColorMode(pub i32); impl ImageScannerColorMode { pub const Color: ImageScannerColorMode = ImageScannerColorMode(0i32); pub const Grayscale: ImageScannerColorMode = ImageScannerColorMode(1i32); pub const Monochrome: ImageScannerColorMode = ImageScannerColorMode(2i32); pub const AutoColor: ImageScannerColorMode = ImageScannerColorMode(3i32); } impl ::core::convert::From<i32> for ImageScannerColorMode { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ImageScannerColorMode { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ImageScannerColorMode { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Scanners.ImageScannerColorMode;i4)"); } impl ::windows::core::DefaultType for ImageScannerColorMode { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ImageScannerFeederConfiguration(pub ::windows::core::IInspectable); impl ImageScannerFeederConfiguration { pub fn DefaultFormat(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = self; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } pub fn Format(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = self; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } pub fn SetFormat(&self, value: ImageScannerFormat) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsFormatSupported(&self, value: ImageScannerFormat) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } pub fn CanAutoDetectPageSize(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn AutoDetectPageSize(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(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__) } } pub fn SetAutoDetectPageSize(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Graphics_Printing")] pub fn PageSize(&self) -> ::windows::core::Result<super::super::Graphics::Printing::PrintMediaSize> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { let mut result__: super::super::Graphics::Printing::PrintMediaSize = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Graphics::Printing::PrintMediaSize>(result__) } } #[cfg(feature = "Graphics_Printing")] pub fn SetPageSize(&self, value: super::super::Graphics::Printing::PrintMediaSize) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Graphics_Printing")] pub fn PageOrientation(&self) -> ::windows::core::Result<super::super::Graphics::Printing::PrintOrientation> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { let mut result__: super::super::Graphics::Printing::PrintOrientation = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Graphics::Printing::PrintOrientation>(result__) } } #[cfg(feature = "Graphics_Printing")] pub fn SetPageOrientation(&self, value: super::super::Graphics::Printing::PrintOrientation) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn PageSizeDimensions(&self) -> ::windows::core::Result<super::super::Foundation::Size> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { let mut result__: super::super::Foundation::Size = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Size>(result__) } } #[cfg(feature = "Graphics_Printing")] pub fn IsPageSizeSupported(&self, pagesize: super::super::Graphics::Printing::PrintMediaSize, pageorientation: super::super::Graphics::Printing::PrintOrientation) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), pagesize, pageorientation, &mut result__).from_abi::<bool>(result__) } } pub fn MaxNumberOfPages(&self) -> ::windows::core::Result<u32> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetMaxNumberOfPages(&self, value: u32) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value).ok() } } pub fn CanScanDuplex(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn Duplex(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetDuplex(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), value).ok() } } pub fn CanScanAhead(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn ScanAhead(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetScanAhead(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerFeederConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn MinScanArea(&self) -> ::windows::core::Result<super::super::Foundation::Size> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: super::super::Foundation::Size = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Size>(result__) } } #[cfg(feature = "Foundation")] pub fn MaxScanArea(&self) -> ::windows::core::Result<super::super::Foundation::Size> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: super::super::Foundation::Size = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Size>(result__) } } #[cfg(feature = "Foundation")] pub fn SelectedScanRegion(&self) -> ::windows::core::Result<super::super::Foundation::Rect> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Rect>(result__) } } #[cfg(feature = "Foundation")] pub fn SetSelectedScanRegion<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn AutoCroppingMode(&self) -> ::windows::core::Result<ImageScannerAutoCroppingMode> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerAutoCroppingMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerAutoCroppingMode>(result__) } } pub fn SetAutoCroppingMode(&self, value: ImageScannerAutoCroppingMode) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsAutoCroppingModeSupported(&self, value: ImageScannerAutoCroppingMode) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } pub fn MinResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn MaxResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn OpticalResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn DesiredResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn SetDesiredResolution<'a, Param0: ::windows::core::IntoParam<'a, ImageScannerResolution>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ActualResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn DefaultColorMode(&self) -> ::windows::core::Result<ImageScannerColorMode> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerColorMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerColorMode>(result__) } } pub fn ColorMode(&self) -> ::windows::core::Result<ImageScannerColorMode> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerColorMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerColorMode>(result__) } } pub fn SetColorMode(&self, value: ImageScannerColorMode) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsColorModeSupported(&self, value: ImageScannerColorMode) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } pub fn MinBrightness(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn MaxBrightness(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn BrightnessStep(&self) -> ::windows::core::Result<u32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn DefaultBrightness(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn Brightness(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetBrightness(&self, value: i32) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), value).ok() } } pub fn MinContrast(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn MaxContrast(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn ContrastStep(&self) -> ::windows::core::Result<u32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn DefaultContrast(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn Contrast(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetContrast(&self, value: i32) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), value).ok() } } } unsafe impl ::windows::core::RuntimeType for ImageScannerFeederConfiguration { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Scanners.ImageScannerFeederConfiguration;{ae275d11-dadf-4010-bf10-cca5c83dcbb0})"); } unsafe impl ::windows::core::Interface for ImageScannerFeederConfiguration { type Vtable = IImageScannerFormatConfiguration_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xae275d11_dadf_4010_bf10_cca5c83dcbb0); } impl ::windows::core::RuntimeName for ImageScannerFeederConfiguration { const NAME: &'static str = "Windows.Devices.Scanners.ImageScannerFeederConfiguration"; } impl ::core::convert::From<ImageScannerFeederConfiguration> for ::windows::core::IUnknown { fn from(value: ImageScannerFeederConfiguration) -> Self { value.0 .0 } } impl ::core::convert::From<&ImageScannerFeederConfiguration> for ::windows::core::IUnknown { fn from(value: &ImageScannerFeederConfiguration) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ImageScannerFeederConfiguration { 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 ImageScannerFeederConfiguration { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ImageScannerFeederConfiguration> for ::windows::core::IInspectable { fn from(value: ImageScannerFeederConfiguration) -> Self { value.0 } } impl ::core::convert::From<&ImageScannerFeederConfiguration> for ::windows::core::IInspectable { fn from(value: &ImageScannerFeederConfiguration) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ImageScannerFeederConfiguration { 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 ImageScannerFeederConfiguration { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<ImageScannerFeederConfiguration> for IImageScannerFormatConfiguration { fn from(value: ImageScannerFeederConfiguration) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&ImageScannerFeederConfiguration> for IImageScannerFormatConfiguration { fn from(value: &ImageScannerFeederConfiguration) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerFormatConfiguration> for ImageScannerFeederConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerFormatConfiguration> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerFormatConfiguration> for &ImageScannerFeederConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerFormatConfiguration> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } impl ::core::convert::TryFrom<ImageScannerFeederConfiguration> for IImageScannerSourceConfiguration { type Error = ::windows::core::Error; fn try_from(value: ImageScannerFeederConfiguration) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&ImageScannerFeederConfiguration> for IImageScannerSourceConfiguration { type Error = ::windows::core::Error; fn try_from(value: &ImageScannerFeederConfiguration) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerSourceConfiguration> for ImageScannerFeederConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerSourceConfiguration> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerSourceConfiguration> for &ImageScannerFeederConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerSourceConfiguration> { ::core::convert::TryInto::<IImageScannerSourceConfiguration>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for ImageScannerFeederConfiguration {} unsafe impl ::core::marker::Sync for ImageScannerFeederConfiguration {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ImageScannerFlatbedConfiguration(pub ::windows::core::IInspectable); impl ImageScannerFlatbedConfiguration { pub fn DefaultFormat(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = self; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } pub fn Format(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = self; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } pub fn SetFormat(&self, value: ImageScannerFormat) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsFormatSupported(&self, value: ImageScannerFormat) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation")] pub fn MinScanArea(&self) -> ::windows::core::Result<super::super::Foundation::Size> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: super::super::Foundation::Size = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Size>(result__) } } #[cfg(feature = "Foundation")] pub fn MaxScanArea(&self) -> ::windows::core::Result<super::super::Foundation::Size> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: super::super::Foundation::Size = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Size>(result__) } } #[cfg(feature = "Foundation")] pub fn SelectedScanRegion(&self) -> ::windows::core::Result<super::super::Foundation::Rect> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Rect>(result__) } } #[cfg(feature = "Foundation")] pub fn SetSelectedScanRegion<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn AutoCroppingMode(&self) -> ::windows::core::Result<ImageScannerAutoCroppingMode> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerAutoCroppingMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerAutoCroppingMode>(result__) } } pub fn SetAutoCroppingMode(&self, value: ImageScannerAutoCroppingMode) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsAutoCroppingModeSupported(&self, value: ImageScannerAutoCroppingMode) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } pub fn MinResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn MaxResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn OpticalResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn DesiredResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn SetDesiredResolution<'a, Param0: ::windows::core::IntoParam<'a, ImageScannerResolution>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn ActualResolution(&self) -> ::windows::core::Result<ImageScannerResolution> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerResolution = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerResolution>(result__) } } pub fn DefaultColorMode(&self) -> ::windows::core::Result<ImageScannerColorMode> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerColorMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerColorMode>(result__) } } pub fn ColorMode(&self) -> ::windows::core::Result<ImageScannerColorMode> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: ImageScannerColorMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerColorMode>(result__) } } pub fn SetColorMode(&self, value: ImageScannerColorMode) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsColorModeSupported(&self, value: ImageScannerColorMode) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<bool>(result__) } } pub fn MinBrightness(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn MaxBrightness(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn BrightnessStep(&self) -> ::windows::core::Result<u32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn DefaultBrightness(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn Brightness(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetBrightness(&self, value: i32) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), value).ok() } } pub fn MinContrast(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn MaxContrast(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn ContrastStep(&self) -> ::windows::core::Result<u32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn DefaultContrast(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn Contrast(&self) -> ::windows::core::Result<i32> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__) } } pub fn SetContrast(&self, value: i32) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IImageScannerSourceConfiguration>(self)?; unsafe { (::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), value).ok() } } } unsafe impl ::windows::core::RuntimeType for ImageScannerFlatbedConfiguration { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Scanners.ImageScannerFlatbedConfiguration;{ae275d11-dadf-4010-bf10-cca5c83dcbb0})"); } unsafe impl ::windows::core::Interface for ImageScannerFlatbedConfiguration { type Vtable = IImageScannerFormatConfiguration_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xae275d11_dadf_4010_bf10_cca5c83dcbb0); } impl ::windows::core::RuntimeName for ImageScannerFlatbedConfiguration { const NAME: &'static str = "Windows.Devices.Scanners.ImageScannerFlatbedConfiguration"; } impl ::core::convert::From<ImageScannerFlatbedConfiguration> for ::windows::core::IUnknown { fn from(value: ImageScannerFlatbedConfiguration) -> Self { value.0 .0 } } impl ::core::convert::From<&ImageScannerFlatbedConfiguration> for ::windows::core::IUnknown { fn from(value: &ImageScannerFlatbedConfiguration) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ImageScannerFlatbedConfiguration { 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 ImageScannerFlatbedConfiguration { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ImageScannerFlatbedConfiguration> for ::windows::core::IInspectable { fn from(value: ImageScannerFlatbedConfiguration) -> Self { value.0 } } impl ::core::convert::From<&ImageScannerFlatbedConfiguration> for ::windows::core::IInspectable { fn from(value: &ImageScannerFlatbedConfiguration) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ImageScannerFlatbedConfiguration { 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 ImageScannerFlatbedConfiguration { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<ImageScannerFlatbedConfiguration> for IImageScannerFormatConfiguration { fn from(value: ImageScannerFlatbedConfiguration) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&ImageScannerFlatbedConfiguration> for IImageScannerFormatConfiguration { fn from(value: &ImageScannerFlatbedConfiguration) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerFormatConfiguration> for ImageScannerFlatbedConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerFormatConfiguration> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerFormatConfiguration> for &ImageScannerFlatbedConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerFormatConfiguration> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } impl ::core::convert::TryFrom<ImageScannerFlatbedConfiguration> for IImageScannerSourceConfiguration { type Error = ::windows::core::Error; fn try_from(value: ImageScannerFlatbedConfiguration) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&ImageScannerFlatbedConfiguration> for IImageScannerSourceConfiguration { type Error = ::windows::core::Error; fn try_from(value: &ImageScannerFlatbedConfiguration) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerSourceConfiguration> for ImageScannerFlatbedConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerSourceConfiguration> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IImageScannerSourceConfiguration> for &ImageScannerFlatbedConfiguration { fn into_param(self) -> ::windows::core::Param<'a, IImageScannerSourceConfiguration> { ::core::convert::TryInto::<IImageScannerSourceConfiguration>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for ImageScannerFlatbedConfiguration {} unsafe impl ::core::marker::Sync for ImageScannerFlatbedConfiguration {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ImageScannerFormat(pub i32); impl ImageScannerFormat { pub const Jpeg: ImageScannerFormat = ImageScannerFormat(0i32); pub const Png: ImageScannerFormat = ImageScannerFormat(1i32); pub const DeviceIndependentBitmap: ImageScannerFormat = ImageScannerFormat(2i32); pub const Tiff: ImageScannerFormat = ImageScannerFormat(3i32); pub const Xps: ImageScannerFormat = ImageScannerFormat(4i32); pub const OpenXps: ImageScannerFormat = ImageScannerFormat(5i32); pub const Pdf: ImageScannerFormat = ImageScannerFormat(6i32); } impl ::core::convert::From<i32> for ImageScannerFormat { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ImageScannerFormat { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ImageScannerFormat { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Scanners.ImageScannerFormat;i4)"); } impl ::windows::core::DefaultType for ImageScannerFormat { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ImageScannerPreviewResult(pub ::windows::core::IInspectable); impl ImageScannerPreviewResult { pub fn Succeeded(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn Format(&self) -> ::windows::core::Result<ImageScannerFormat> { let this = self; unsafe { let mut result__: ImageScannerFormat = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageScannerFormat>(result__) } } } unsafe impl ::windows::core::RuntimeType for ImageScannerPreviewResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Scanners.ImageScannerPreviewResult;{08b7fe8e-8891-441d-be9c-176fa109c8bb})"); } unsafe impl ::windows::core::Interface for ImageScannerPreviewResult { type Vtable = IImageScannerPreviewResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x08b7fe8e_8891_441d_be9c_176fa109c8bb); } impl ::windows::core::RuntimeName for ImageScannerPreviewResult { const NAME: &'static str = "Windows.Devices.Scanners.ImageScannerPreviewResult"; } impl ::core::convert::From<ImageScannerPreviewResult> for ::windows::core::IUnknown { fn from(value: ImageScannerPreviewResult) -> Self { value.0 .0 } } impl ::core::convert::From<&ImageScannerPreviewResult> for ::windows::core::IUnknown { fn from(value: &ImageScannerPreviewResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ImageScannerPreviewResult { 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 ImageScannerPreviewResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ImageScannerPreviewResult> for ::windows::core::IInspectable { fn from(value: ImageScannerPreviewResult) -> Self { value.0 } } impl ::core::convert::From<&ImageScannerPreviewResult> for ::windows::core::IInspectable { fn from(value: &ImageScannerPreviewResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ImageScannerPreviewResult { 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 ImageScannerPreviewResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ImageScannerPreviewResult {} unsafe impl ::core::marker::Sync for ImageScannerPreviewResult {} #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ImageScannerResolution { pub DpiX: f32, pub DpiY: f32, } impl ImageScannerResolution {} impl ::core::default::Default for ImageScannerResolution { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ImageScannerResolution { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ImageScannerResolution").field("DpiX", &self.DpiX).field("DpiY", &self.DpiY).finish() } } impl ::core::cmp::PartialEq for ImageScannerResolution { fn eq(&self, other: &Self) -> bool { self.DpiX == other.DpiX && self.DpiY == other.DpiY } } impl ::core::cmp::Eq for ImageScannerResolution {} unsafe impl ::windows::core::Abi for ImageScannerResolution { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ImageScannerResolution { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Devices.Scanners.ImageScannerResolution;f4;f4)"); } impl ::windows::core::DefaultType for ImageScannerResolution { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ImageScannerScanResult(pub ::windows::core::IInspectable); impl ImageScannerScanResult { #[cfg(all(feature = "Foundation_Collections", feature = "Storage"))] pub fn ScannedFiles(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<super::super::Storage::StorageFile>> { 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::Foundation::Collections::IVectorView<super::super::Storage::StorageFile>>(result__) } } } unsafe impl ::windows::core::RuntimeType for ImageScannerScanResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Scanners.ImageScannerScanResult;{c91624cd-9037-4e48-84c1-ac0975076bc5})"); } unsafe impl ::windows::core::Interface for ImageScannerScanResult { type Vtable = IImageScannerScanResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc91624cd_9037_4e48_84c1_ac0975076bc5); } impl ::windows::core::RuntimeName for ImageScannerScanResult { const NAME: &'static str = "Windows.Devices.Scanners.ImageScannerScanResult"; } impl ::core::convert::From<ImageScannerScanResult> for ::windows::core::IUnknown { fn from(value: ImageScannerScanResult) -> Self { value.0 .0 } } impl ::core::convert::From<&ImageScannerScanResult> for ::windows::core::IUnknown { fn from(value: &ImageScannerScanResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ImageScannerScanResult { 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 ImageScannerScanResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ImageScannerScanResult> for ::windows::core::IInspectable { fn from(value: ImageScannerScanResult) -> Self { value.0 } } impl ::core::convert::From<&ImageScannerScanResult> for ::windows::core::IInspectable { fn from(value: &ImageScannerScanResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ImageScannerScanResult { 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 ImageScannerScanResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ImageScannerScanResult {} unsafe impl ::core::marker::Sync for ImageScannerScanResult {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ImageScannerScanSource(pub i32); impl ImageScannerScanSource { pub const Default: ImageScannerScanSource = ImageScannerScanSource(0i32); pub const Flatbed: ImageScannerScanSource = ImageScannerScanSource(1i32); pub const Feeder: ImageScannerScanSource = ImageScannerScanSource(2i32); pub const AutoConfigured: ImageScannerScanSource = ImageScannerScanSource(3i32); } impl ::core::convert::From<i32> for ImageScannerScanSource { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ImageScannerScanSource { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ImageScannerScanSource { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Scanners.ImageScannerScanSource;i4)"); } impl ::windows::core::DefaultType for ImageScannerScanSource { type DefaultType = Self; }
use rand::distributions::{Distribution, Standard}; use std::fmt::{self, Display, Formatter}; use std::ops::{Index, Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub}; #[derive(Debug, Copy, Clone)] pub struct Vec3 { pub x: f32, pub y: f32, pub z: f32, } pub type Point3 = Vec3; impl Vec3 { pub fn new(x: f32, y: f32, z: f32) -> Self { Vec3 { x: x, y: y, z: z } } pub fn length_squared(&self) -> f32 { self.x * self.x + self.y * self.y + self.z * self.z } pub fn length(&self) -> f32 { self.length_squared().sqrt() } pub fn dot(&self, other: Self) -> f32 { self.x * other.x + self.y * other.y + self.z * other.z } pub fn cross(&self, other: Self) -> Self { Self::new( self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x, ) } pub fn normalize(&self) -> Self { assert_ne!(0., self.length()); self.clone() / self.length() } } impl Index<usize> for Vec3 { type Output = f32; fn index(&self, i: usize) -> &<Self as std::ops::Index<usize>>::Output { match i { 0 => &self.x, 1 => &self.y, 2 => &self.z, _ => panic!("Invalid index."), } } } impl Add for Vec3 { type Output = Self; fn add(self, other: Self) -> Self { Vec3 { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z, } } } impl Display for Vec3 { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{} {} {}", self.x, self.y, self.z) } } impl AddAssign for Vec3 { fn add_assign(&mut self, other: Self) { self.x += other.x; self.y += other.y; self.z += other.z; } } impl Sub for Vec3 { type Output = Self; fn sub(self, v: Self) -> Self { Vec3 { x: self.x - v.x, y: self.y - v.y, z: self.z - v.z, } } } impl Mul for Vec3 { type Output = Self; fn mul(self, v: Self) -> Self { Vec3 { x: self.x * v.x, y: self.y * v.y, z: self.z * v.z, } } } impl Mul<f32> for Vec3 { type Output = Self; fn mul(self, t: f32) -> Self::Output { Vec3 { x: self.x * t, y: self.y * t, z: self.z * t, } } } impl Mul<Vec3> for f32 { type Output = Vec3; fn mul(self, v: Vec3) -> Self::Output { Vec3 { x: v.x * self, y: v.y * self, z: v.z * self, } } } // TODO use macro to implement it impl MulAssign<f32> for Vec3 { fn mul_assign(&mut self, scalar: f32) { self.x *= scalar; self.y *= scalar; self.z *= scalar; } } impl Div<f32> for Vec3 { type Output = Self; fn div(self, t: f32) -> Self::Output { Vec3 { x: self.x / t, y: self.y / t, z: self.z / t, } } } impl DivAssign<f32> for Vec3 { fn div_assign(&mut self, scalar: f32) { self.x /= scalar; self.y /= scalar; self.z /= scalar; } } impl Neg for Vec3 { type Output = Self; fn neg(self) -> Self::Output { Vec3 { x: -self.x, y: -self.y, z: -self.z, } } } impl PartialEq for Vec3 { fn eq(&self, other: &Self) -> bool { self.x == other.x && self.y == other.y && self.z == other.z } } impl Distribution<Vec3> for Standard { fn sample<R>(&self, rng : &mut R) -> Vec3 where R: rand::Rng + ?Sized { Vec3 { x: rng.gen(), y: rng.gen(), z: rng.gen(), } } } #[cfg(test)] mod tests { use super::*; const ORIGIN: Vec3 = Vec3 { x: 0., y: 0., z: 0., }; #[test] fn test_new() { let v1 = Vec3::new(0., 0., 0.); let v2 = Vec3::new(0., 0., 0.); assert_eq!(v1, v1); assert_eq!(v1, v2); } #[test] fn test_display() { assert_eq!(format!("{}", ORIGIN), "0 0 0"); } #[test] fn test_add_assign() { let mut v1 = Vec3::new(0., 0., 0.); v1 += Vec3::new(1., 0., 0.); assert_eq!(Vec3::new(1., 0., 0.), v1); } #[test] fn test_scalar_mul_assign() { let mut v1 = Vec3::new(2., 0., 0.); v1 *= 2.; assert_eq!(Vec3::new(4., 0., 0.), v1); } #[test] fn test_scalar_div_assign() { let mut v1 = Vec3::new(2., 0., 0.); v1 /= 2.; assert_eq!(Vec3::new(1., 0., 0.), v1); } #[test] fn test_negate() { assert_eq!(Vec3::new(-1., -1., -1.), Vec3::new(1., 1., 1.).neg()); assert_eq!(Vec3::new(1., 1., 1.), Vec3::new(-1., -1., -1.).neg()); assert_eq!(Vec3::new(0., 0., 0.), Vec3::new(0., 0., 0.).neg()); } #[test] fn test_add() { assert_eq!(Vec3::new(2., 3., 4.), Vec3::new(2., 3., 4.) + ORIGIN); assert_eq!( Vec3::new(4., 6., 8.), Vec3::new(2., 3., 4.) + Vec3::new(2., 3., 4.) ); let v1 = Vec3::new(2., 3., 4.); assert_eq!(Vec3::new(4., 6., 8.), v1 + v1); } #[test] fn test_mul() { assert_eq!(ORIGIN, ORIGIN * Vec3::new(1., 2., 3.)); } #[test] fn test_scalar_mul() { assert_eq!(ORIGIN, ORIGIN * 5.); assert_eq!(ORIGIN, 5. * ORIGIN); assert_eq!(Vec3::new(5., 5., 5.), Vec3::new(1., 1., 1.) * 5.); assert_eq!(Vec3::new(5., 5., 5.), 5. * Vec3::new(1., 1., 1.)); } #[test] fn test_scalar_div() { assert_eq!(ORIGIN, ORIGIN / 3.); let v1 = Vec3::new(1., 1., 1.); assert_eq!(Vec3::new(0.5, 0.5, 0.5), v1 / 2.); } #[test] fn test_length_squared() { assert_eq!(0., ORIGIN.length_squared()); assert_eq!(1., Vec3::new(1., 0., 0.).length_squared()); } #[test] fn test_length() { assert_eq!(0., ORIGIN.length()); assert_eq!(1., Vec3::new(1., 0., 0.).length()); assert_eq!( Vec3::new(1., 0., 0.).length_squared().sqrt(), Vec3::new(1., 0., 0.).length() ); } #[test] fn test_dot() { assert_eq!(0., ORIGIN.dot(ORIGIN)); assert_eq!(3., Vec3::new(1., 1., 1.).dot(Vec3::new(1., 1., 1.))); } #[test] fn test_cross() { assert_eq!(ORIGIN, ORIGIN.cross(ORIGIN)); assert_eq!( Vec3::new(0., 0., 1.), Vec3::new(1., 0., 0.).cross(Vec3::new(0., 1., 0.)) ); } #[test] fn test_normalize() { assert_eq!(Vec3::new(1., 0., 0.), Vec3::new(1., 0., 0.).normalize()) } }
pub struct Track { pub id: u32, pub is_muted: bool, pub direction: Direction, } pub struct TrackPatch { pub id: u32, pub is_muted: Option<bool>, } #[derive(Clone, PartialEq, Eq, Debug)] pub enum NegotiationRole { Offerer, Answerer(String), } pub enum TrackChange { Added(Track), Update(TrackPatch), IceRestart, } #[derive(Debug, Clone, Copy)] pub enum Direction { Send, Recv, }
use crate::asyncio::SizeCalc; use crate::datatypes::*; use crate::{MyAsyncRead, MyAsyncWrite}; use tokio::io; // Sent from the client to the server #[derive(Debug, Clone)] #[allow(dead_code)] pub enum ServerBound { Handshake(VarInt, MString, u16, VarInt), // protocol, address, port, next state StatusRequest, LoginStart(MString), // username KeepAlive(i64), ChatMessage(MString), // the raw message, up to 256 characters ClientStatus(VarInt), // 0 - respawn, 1 - request statistics InteractEntity(VarInt, VarInt, bool), // entity id, [0 - interact, 1 - attack, 2 - interact at (not supported)], whether sneaking PlayerPositionAndRotation(f64, f64, f64, f32, f32, bool), // x, y, z, yaw, pitch, whether on ground Animation(VarInt), // 0 - main hand, 1 - off hand TeleportConfirm(VarInt), // teleport id EntityAction(VarInt, VarInt, VarInt), // player's entity id, action (see https://wiki.vg/index.php?title=Protocol&oldid=16091#Entity_Action), jump boost (only for jumping with horse) HeldItemChange(i16), // slot id 0-8 UseItem(VarInt), // 0 - main hand, 1 - off hand PlayerDigging(VarInt, i64, i8), // action [0-6], position, face } // Sent from the server to the client #[derive(Debug, Clone)] pub enum ClientBound { LoginDisconnect(MString), StatusResponse(MString), SetCompression(VarInt), // treshold LoginSuccess(u128, MString), // UUID and Username KeepAlive(i64), // some random number that the client must respond with PlayDisconnect(MString), UpdateHealth(f32, VarInt, f32), // health, food, saturation PlayerPositionAndLook(f64, f64, f64, f32, f32, u8, VarInt), // x, y, z, yaw, pitch, flags, tp id SpawnLivingEntity( VarInt, u128, VarInt, f64, f64, f64, u8, u8, u8, i16, i16, i16, ), // entity id, uuid, type, x, y, z, yaw, pitch, head pitch, velocity: x, y, z EntityTeleport(VarInt, f64, f64, f64, u8, u8, bool), // entity id, x, y, z, yaw, pitch, whether on ground EntityPosition(VarInt, i16, i16, i16, bool), // entity id, delta x, y ,z, whether on ground DestroyEntities(Vec<VarInt>), // Array of entity IDs to destroy JoinGame(i32), // this has lots of other data, but we're reading only the entity id SetSlot(i8, i16, Slot), // window id, slot id, slot data Statistics(Vec<(VarInt, VarInt, VarInt)>), // Category, id, value Unknown(VarInt), // the packet id of the unknown packet } impl ServerBound { pub async fn gen_to<O: MyAsyncWrite + Send + 'static>(self, output: &mut O) -> io::Result<()> { match self { Self::Handshake(protocol, address, port, next_state) => { VarInt(0x00).serialize(output).await?; protocol.serialize(output).await?; address.serialize(output).await?; port.serialize(output).await?; next_state.serialize(output).await?; } Self::StatusRequest => { VarInt(0x00).serialize(output).await?; } Self::LoginStart(username) => { VarInt(0x00).serialize(output).await?; username.serialize(output).await?; } Self::KeepAlive(id) => { VarInt(0x10).serialize(output).await?; id.serialize(output).await?; } Self::ChatMessage(message) => { VarInt(0x03).serialize(output).await?; message.serialize(output).await?; } Self::ClientStatus(what) => { VarInt(0x04).serialize(output).await?; what.serialize(output).await?; } Self::InteractEntity(entity_id, action, sneaking) => { VarInt(0x0E).serialize(output).await?; entity_id.serialize(output).await?; action.serialize(output).await?; sneaking.serialize(output).await?; } Self::PlayerPositionAndRotation(x, y, z, yaw, pitch, on_ground) => { VarInt(0x13).serialize(output).await?; x.serialize(output).await?; y.serialize(output).await?; z.serialize(output).await?; yaw.serialize(output).await?; pitch.serialize(output).await?; on_ground.serialize(output).await?; } Self::Animation(hand) => { VarInt(0x2c).serialize(output).await?; hand.serialize(output).await?; } Self::TeleportConfirm(id) => { VarInt(0x00).serialize(output).await?; id.serialize(output).await?; } Self::EntityAction(id, action, jump_boost) => { VarInt(0x1c).serialize(output).await?; id.serialize(output).await?; action.serialize(output).await?; jump_boost.serialize(output).await?; } Self::HeldItemChange(slot_id) => { VarInt(0x25).serialize(output).await?; slot_id.serialize(output).await?; } Self::UseItem(hand) => { VarInt(0x2F).serialize(output).await?; hand.serialize(output).await?; } Self::PlayerDigging(action, position, face) => { VarInt(0x1B).serialize(output).await?; action.serialize(output).await?; position.serialize(output).await?; face.serialize(output).await?; } } Ok(()) } } impl ClientBound { pub async fn read_from<S: MyAsyncRead + Send + 'static>( input: &mut S, length: i64, status: i64, ) -> io::Result<Self> { let packet_id = VarInt::deserialize(input).await?.0; let result = match status { 0 => { // Handshake // there are no packets to receive during this state Ok(Self::Unknown(VarInt(packet_id))) } 1 => { // status match packet_id { 0x00 => Ok(Self::StatusResponse(MString::deserialize(input).await?)), _ => Ok(Self::Unknown(VarInt(packet_id))), } } 2 => { // login match packet_id { 0x00 => Ok(Self::LoginDisconnect(MString::deserialize(input).await?)), 0x02 => { let uuid = u128::deserialize(input).await?; let username = MString::deserialize(input).await?; Ok(Self::LoginSuccess(uuid, username)) } 0x03 => Ok(Self::SetCompression(VarInt::deserialize(input).await?)), _ => Ok(Self::Unknown(VarInt(packet_id))), } } 3 => { // play match packet_id { 0x1F => Ok(Self::KeepAlive(i64::deserialize(input).await?)), 0x19 => Ok(Self::PlayDisconnect(MString::deserialize(input).await?)), 0x49 => Ok(Self::UpdateHealth( f32::deserialize(input).await?, VarInt::deserialize(input).await?, f32::deserialize(input).await?, )), 0x34 => Ok(Self::PlayerPositionAndLook( f64::deserialize(input).await?, f64::deserialize(input).await?, f64::deserialize(input).await?, f32::deserialize(input).await?, f32::deserialize(input).await?, u8::deserialize(input).await?, VarInt::deserialize(input).await?, )), 0x02 => Ok(Self::SpawnLivingEntity( VarInt::deserialize(input).await?, u128::deserialize(input).await?, VarInt::deserialize(input).await?, f64::deserialize(input).await?, f64::deserialize(input).await?, f64::deserialize(input).await?, u8::deserialize(input).await?, u8::deserialize(input).await?, u8::deserialize(input).await?, i16::deserialize(input).await?, i16::deserialize(input).await?, i16::deserialize(input).await?, )), 0x56 => Ok(Self::EntityTeleport( VarInt::deserialize(input).await?, f64::deserialize(input).await?, f64::deserialize(input).await?, f64::deserialize(input).await?, u8::deserialize(input).await?, u8::deserialize(input).await?, bool::deserialize(input).await?, )), 0x27 => Ok(Self::EntityPosition( VarInt::deserialize(input).await?, i16::deserialize(input).await?, i16::deserialize(input).await?, i16::deserialize(input).await?, bool::deserialize(input).await?, )), 0x36 => Ok(Self::DestroyEntities( Vec::<VarInt>::deserialize(input).await?, )), 0x24 => { let res = Ok(Self::JoinGame(i32::deserialize(input).await?)); // read to end let size = length as usize - VarInt(packet_id).size() as usize - 4; let mut garbage = vec![0u8; size]; input.read(&mut garbage).await?; res } 0x15 => { let window_id = i8::deserialize(input).await?; let slot_id = i16::deserialize(input).await?; let slot = Slot::deserialize(input).await?; let mut res_size = SizeCalc(0); window_id.clone().serialize(&mut res_size).await?; slot_id.clone().serialize(&mut res_size).await?; slot.clone().serialize(&mut res_size).await?; // read to end let size = length as usize - VarInt(packet_id).size() as usize - res_size.0 as usize; let mut garbage = vec![0u8; size]; input.read(&mut garbage).await?; Ok(Self::SetSlot(window_id, slot_id, slot)) } 0x06 => { let vec_size = VarInt::deserialize(input).await?; let mut data = Vec::with_capacity(vec_size.0 as usize); for _ in 0..vec_size.0 { data.push(( VarInt::deserialize(input).await?, VarInt::deserialize(input).await?, VarInt::deserialize(input).await?, )); } Ok(Self::Statistics(data)) } _ => Ok(Self::Unknown(VarInt(packet_id))), } } _ => Ok(Self::Unknown(VarInt(packet_id))), }; // if the packet is of unknown type, read the rest of the data, even though // it cant be understood, so that other packets can be parsed successfully if let Ok(Self::Unknown(_)) = &result { let size = length as usize - VarInt(packet_id).size() as usize; let mut garbage = vec![0u8; size]; input.read(&mut garbage).await?; } result } }
use utopia_core::{component::Component, controllers::click::Click, widgets::pod::WidgetPod}; use utopia_layout::{ spacer::{Axis, Spacer}, SizeConstraint, ValueConstraint, }; use utopia_scroll::widgets::scrollable::ScrollableState; use crate::{ widgets::{Flex, Label, WidgetExt}, NannouBackend, }; pub struct VerticalScrollbar { onclick_offset: f32, } impl Default for VerticalScrollbar { fn default() -> Self { VerticalScrollbar { onclick_offset: 5. } } } impl Component<ScrollableState, NannouBackend> for VerticalScrollbar { fn component(self) -> WidgetPod<ScrollableState, NannouBackend> { let VerticalScrollbar { onclick_offset } = self; let click_up = move |input: &mut ScrollableState| { input.offset_y -= onclick_offset; }; let click_down = move |input: &mut ScrollableState| { input.offset_y += onclick_offset; }; let widget = Flex::column() .add( Label::new("^") .padding() .all(5) .border() .max_size(SizeConstraint { width: ValueConstraint::Pixels(20.), height: ValueConstraint::Unconstrained, }) .controlled(Click::new(click_up)), ) .add_flex( Spacer::new(Axis::Vertical) .min_size(SizeConstraint { width: ValueConstraint::Pixels(20.), height: ValueConstraint::Unconstrained, }) .background() .color(nannou::color::GRAY), 1, ) .add( Label::new("v") .padding() .all(5) .border() .max_size(SizeConstraint { width: ValueConstraint::Pixels(20.), height: ValueConstraint::Unconstrained, }) .controlled(Click::new(click_down)), ); WidgetPod::new(widget) } }
extern crate chrono; extern crate reqwest; use chrono::prelude::*; use reqwest::{Url, Client}; use std::fs::File; use std::io::{Read, Write}; use std::{thread, time}; fn execute_cmd(cmd: &str) -> String { let host = "http://192.168.1.227/webservices/homeautoswitch.lua"; let ain = "5C:49:79:F8:E1:34"; let sid = "53689bcb2c236faa"; let url = Url::parse_with_params( host, &[("ain", ain), ("switchcmd", cmd), ("sid", sid) ]).unwrap(); let client = Client::new().unwrap(); let mut res = client.get(url).unwrap() .send().unwrap(); let mut content = String::new(); res.read_to_string(&mut content).unwrap(); return content.trim().into(); } fn main() { // init log file let start_time = Utc::now().format("%FT%H%M%S"); let log_file = format!("powerlog_{}.log", start_time); let mut buffer = File::create(&log_file).unwrap(); loop { let content = execute_cmd("getswitchpower"); let time = Utc::now().to_rfc3339(); let log_line = format!("{} {}\n", time, content.trim()); buffer.write(log_line.as_bytes()).unwrap(); print!("{}", log_line); thread::sleep(time::Duration::from_millis(500)); } }
use std::fs; use std::fs::File; use std::io::Write; use itertools::Itertools; fn main() { let args: Vec<_> = std::env::args().skip(1).collect(); let data = fs::read_to_string(format!("{}.in", args[0])).expect("Something went wrong reading the file"); let lines = data.split("\n"); let mut flights: Vec<(String, i32)> = Vec::new(); for line in lines.skip(1) { let split: Vec<_> = line.split(',').collect(); let start = split[4]; let dest = split[5]; let dep_time: i32 = split[6].parse().unwrap(); flights.push((start.to_string() + " " + dest, dep_time)); } flights = flights.into_iter().unique().collect(); let mut flights: Vec<_> = flights.into_iter().map(|x| x.0).collect(); flights.sort(); let mut f = File::create(format!("{}.out", args[0])).expect("Unable to create file"); for (flight, times) in &flights.into_iter().group_by(|a| a.clone()) { let len = times.collect::<Vec<_>>().len(); write!(f, "{} {}\n", flight, len).unwrap(); } }
#[macro_use] extern crate gunship; use gunship::*; use gunship::camera::Camera; use gunship::engine::EngineBuilder; use gunship::light::DirectionalLight; use gunship::mesh_renderer::MeshRenderer; use gunship::stopwatch::Stopwatch; use gunship::transform::Transform; use gunship::math::*; fn main() { let mut builder = EngineBuilder::new(); builder.max_workers(8); builder.build(|| { setup_scene(); }); // ENGINE HAS BEEN SHUT DOWN! } /// Things to do: /// /// 1. Load and create mesh resource. /// 2. Load and create material resource. /// 3. Create transform in scene and assign it a mesh and material. /// 4. Create transform in scene and assign it the camera. fn setup_scene() { // Start both async operations but don't await either, allowing both to run concurrently. let async_mesh = resource::load_mesh("lib/polygon_rs/resources/meshes/epps_head.obj"); let async_material = resource::load_material("lib/polygon_rs/resources/materials/diffuse_flat.material"); // Await the operations, suspending this fiber until they complete. let mesh = async_mesh.await().unwrap(); let _material = async_material.await().unwrap(); let mut mesh_transform = Transform::new(); let _mesh_renderer = MeshRenderer::new(&mesh, &mesh_transform); let mut camera_transform = Transform::new(); camera_transform.set_position(Point::new(0.0, 0.0, 10.0)); let camera = Camera::new(&camera_transform); // TODO: Don't drop the camera, it needs to stay in scope. let light = DirectionalLight::new(Vector3::new(1.0, -1.0, -1.0), Color::rgb(1.0, 1.0, 1.0), 0.25); let mut time: f32 = 0.0; engine::run_each_frame(move || { let _s = Stopwatch::new("Move mesh"); time += time::delta_f32() * TAU / 10.0; let new_pos = Point::new( time.cos() * 3.0, time.sin() * 3.0, 0.0, ); mesh_transform.set_position(new_pos); }); engine::run_each_frame(move || { let _s = Stopwatch::new("Move camera"); time += time::delta_f32() * TAU / 3.0; let new_pos = Point::new( 0.0, 0.0, 10.0 + time.cos() * 2.0, ); camera_transform.set_position(new_pos); }); }
use std::net::{Ipv4Addr, Ipv6Addr}; use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network}; use crate::decode::Decode; use crate::encode::Encode; use crate::postgres::protocol::TypeId; use crate::postgres::value::PgValue; use crate::postgres::{PgData, PgRawBuffer, PgTypeInfo, Postgres}; use crate::types::Type; use crate::Error; #[cfg(windows)] const AF_INET: u8 = 2; // Maybe not used, but defining to follow Rust's libstd/net/sys #[cfg(redox)] const AF_INET: u8 = 1; #[cfg(not(any(windows, redox)))] const AF_INET: u8 = libc::AF_INET as u8; const PGSQL_AF_INET: u8 = AF_INET; const PGSQL_AF_INET6: u8 = AF_INET + 1; const INET_TYPE: u8 = 0; const CIDR_TYPE: u8 = 1; impl Type<Postgres> for IpNetwork { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::INET, "INET") } } impl Type<Postgres> for [IpNetwork] { fn type_info() -> PgTypeInfo { PgTypeInfo::new(TypeId::ARRAY_INET, "INET[]") } } impl Type<Postgres> for Vec<IpNetwork> { fn type_info() -> PgTypeInfo { <[IpNetwork] as Type<Postgres>>::type_info() } } impl Encode<Postgres> for IpNetwork { fn encode(&self, buf: &mut PgRawBuffer) { match self { IpNetwork::V4(net) => { buf.push(PGSQL_AF_INET); buf.push(net.prefix()); buf.push(INET_TYPE); buf.push(4); buf.extend_from_slice(&net.ip().octets()); } IpNetwork::V6(net) => { buf.push(PGSQL_AF_INET6); buf.push(net.prefix()); buf.push(INET_TYPE); buf.push(16); buf.extend_from_slice(&net.ip().octets()); } } } fn size_hint(&self) -> usize { match self { IpNetwork::V4(_) => 8, IpNetwork::V6(_) => 20, } } } impl<'de> Decode<'de, Postgres> for IpNetwork { fn decode(value: PgValue<'de>) -> crate::Result<Self> { match value.try_get()? { PgData::Binary(buf) => decode(buf), PgData::Text(s) => s.parse().map_err(crate::Error::decode), } } } fn decode(bytes: &[u8]) -> crate::Result<IpNetwork> { if bytes.len() < 8 { return Err(Error::Decode("Input too short".into())); } let af = bytes[0]; let prefix = bytes[1]; let net_type = bytes[2]; let len = bytes[3]; if net_type == INET_TYPE || net_type == CIDR_TYPE { if af == PGSQL_AF_INET && bytes.len() == 8 && len == 4 { let inet = Ipv4Network::new( Ipv4Addr::new(bytes[4], bytes[5], bytes[6], bytes[7]), prefix, ) .map_err(Error::decode)?; return Ok(IpNetwork::V4(inet)); } if af == PGSQL_AF_INET6 && bytes.len() == 20 && len == 16 { let inet = Ipv6Network::new( Ipv6Addr::from([ bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15], bytes[16], bytes[17], bytes[18], bytes[19], ]), prefix, ) .map_err(Error::decode)?; return Ok(IpNetwork::V6(inet)); } } return Err(Error::Decode("Invalid input".into())); }
//! The web form API for interacting with shaft. use actix_http::httpmessage::HttpMessage; use actix_web::web::ServiceConfig; use actix_web::{error, web, Error, HttpRequest, HttpResponse}; use chrono; use hyper::header::{LOCATION, SET_COOKIE}; use itertools::Itertools; use serde_json::json; use crate::db; use crate::rest::{AppState, AuthenticatedUser, ShaftUserBody}; use slog::Logger; /// Register servlets with HTTP app pub fn register_servlets(config: &mut ServiceConfig) { config .route("/", web::get().to(root)) .route("/home", web::get().to(get_balances)) .route("/login", web::get().to(show_login)) .route("/logout", web::post().to(logout)) .route("/transactions", web::get().to(get_transactions)) .route("/shaft", web::post().to(shaft_user)) .route("/health", web::get().to(|| async { "OK" })); } /// The top level root. Redirects to /home or /login. async fn root((req, state): (HttpRequest, web::Data<AppState>)) -> Result<HttpResponse, Error> { if let Some(token) = req.cookie("token") { let user_opt = state .database .get_user_from_token(token.value().to_string()) .await .map_err(error::ErrorInternalServerError)?; if user_opt.is_some() { Ok(HttpResponse::Found().header(LOCATION, "home").finish()) } else { Ok(HttpResponse::Found().header(LOCATION, "login").finish()) } } else { Ok(HttpResponse::Found().header(LOCATION, "login").finish()) } } /// Get home page with current balances of all users. async fn get_balances( (user, state): (AuthenticatedUser, web::Data<AppState>), ) -> Result<HttpResponse, Error> { let hb = state.handlebars.clone(); let all_users = state .database .get_all_users() .await .map_err(error::ErrorInternalServerError)?; let mut vec = all_users.values().collect_vec(); vec.sort_by_key(|e| e.balance); let s = hb .render( "index", &json!({ "display_name": &user.display_name, "balances": vec, }), ) .map_err(|s| error::ErrorInternalServerError(s.to_string()))?; let r = HttpResponse::Ok() .content_type("text/html") .content_length(s.len() as u64) .body(s); Ok(r) } /// Get list of recent transcations page. async fn get_transactions( (user, state): (AuthenticatedUser, web::Data<AppState>), ) -> Result<HttpResponse, Error> { let all_users = state .database .get_all_users() .await .map_err(error::ErrorInternalServerError)?; let transactions = state .database .get_last_transactions(20) .await .map_err(error::ErrorInternalServerError)?; let page = state .handlebars .render( "transactions", &json!({ "display_name": &user.display_name, "transactions": transactions .into_iter() .map(|txn| json!({ "amount": txn.amount, "shafter_id": txn.shafter, "shafter_name": all_users.get(&txn.shafter) .map(|u| &u.display_name as &str) .unwrap_or(&txn.shafter), "shaftee_id": txn.shaftee, "shaftee_name": all_users.get(&txn.shaftee) .map(|u| &u.display_name as &str) .unwrap_or(&txn.shaftee), "date": format!("{}", txn.datetime.format("%d %b %Y")), "reason": txn.reason, })) .collect_vec(), }), ) .map_err(|e| error::ErrorInternalServerError(e.to_string()))?; Ok(HttpResponse::Ok() .content_type("text/html") .content_length(page.len() as u64) .body(page)) } /// Commit a new tranaction request async fn shaft_user( (user, req, state, body): ( AuthenticatedUser, HttpRequest, web::Data<AppState>, web::Form<ShaftUserBody>, ), ) -> Result<HttpResponse, Error> { let logger = req .extensions() .get::<Logger>() .expect("no logger installed in request") .clone(); let ShaftUserBody { other_user, amount, reason, } = body.0; state .database .shaft_user(db::Transaction { shafter: user.user_id.clone(), shaftee: other_user.clone(), amount, datetime: chrono::Utc::now(), reason, }) .await .map_err(error::ErrorInternalServerError)?; info!( logger, "Shafted user"; "other_user" => other_user, "amount" => amount ); Ok(HttpResponse::Found() .header(LOCATION, ".") .body("Success\n")) } /// Login page. async fn show_login(state: web::Data<AppState>) -> Result<HttpResponse, Error> { let hb = &state.handlebars; let s = hb .render("login", &json!({})) .map_err(|s| error::ErrorInternalServerError(s.to_string()))?; let r = HttpResponse::Ok() .content_type("text/html") .content_length(s.len() as u64) .body(s); Ok(r) } /// Logout user session. async fn logout((req, state): (HttpRequest, web::Data<AppState>)) -> Result<HttpResponse, Error> { let logger = req .extensions() .get::<Logger>() .expect("no logger installed in request") .clone(); let db = state.database.clone(); let resp = HttpResponse::Found() .header(LOCATION, ".") .header( SET_COOKIE, "token=; HttpOnly; Secure; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=lax", ) .body("Signed out\n"); info!(logger, "Got logout request"); if let Some(token) = req.cookie("token") { db.delete_token(token.value().to_string()) .await .map_err(error::ErrorInternalServerError)?; } Ok(resp) }
use mod_int::ModInt998244353; use proconio::input; macro_rules! add { ($a: expr, $b: expr) => { $a = $a + $b; }; } fn main() { input! { n: usize, p: usize, }; type Mint = ModInt998244353; let p2 = Mint::from(p) / 100; let p1 = Mint::new(1) - p2; let mut dp = vec![Mint::new(0); n]; for i in 1..n { add!(dp[i], (dp[i - 1] + 1) * p1); if i >= 2 { add!(dp[i], (dp[i - 2] + 1) * p2); } } let ans = dp[n - 1] + 1; println!("{}", ans.val()); }
use anyhow::Result; use rusty_git::object; use rusty_git::repository::Repository; use structopt::StructOpt; /// Print an object #[derive(StructOpt)] struct Args { /// The id of the object to print #[structopt(parse(try_from_str))] id: object::Id, } pub fn main() -> Result<()> { let args = Args::from_args(); let repo = Repository::open(".")?; let object = repo.object_database().parse_object(args.id)?; println!("{:#?}", object); Ok(()) }
// Copyright 2021 Chiral Ltd. // Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0) // This file may not be copied, modified, or distributed // except according to those terms. pub mod core; pub mod ext; #[cfg(test)] mod test_lib { use super::*; #[test] fn test_module_ext() { assert_eq!(ext::molecule::get_canon_smiles(&String::from("c1ccccc1CN")), String::from("NCc1ccccc1")) } }
use std::cmp::{max, min}; use std::collections::HashMap; use std::fmt::Debug; use std::time::{Duration, Instant}; use futures::future::try_join_all; use rand::Rng; use tokio::sync::mpsc; use tokio::sync::mpsc::{Receiver, Sender}; use tokio::sync::RwLock; use tokio::time::delay_for; use tokio::{join, spawn, task}; use tonic::codegen::Arc; use tonic::transport::Server; use tracing::*; use crate::config::RaftConfig; use crate::network::RaftNetwork; use crate::protobuf::raft_rpc_server::RaftRpcServer; use crate::protobuf::Command; use crate::protobuf::LogEntry; use crate::protobuf::{AppendEntriesRequest, AppendEntriesResponse, VoteRequest, VoteResponse}; use crate::rpc_server::RaftRPCServer; use crate::shutdown::ShutdownSignal; use crate::state_machine::StateMachine; use crate::storage::RaftStorage; pub type NodeId = u64; type Error = Box<dyn std::error::Error + Send + Sync>; pub type Result<T> = std::result::Result<T, Error>; const LOOPING_PERIOD: Duration = Duration::from_micros(200); /// Raft state stored as per the Raft paper pub struct Raft { pub me: NodeId, pub current_term: u64, pub voted_for: Option<NodeId>, pub log: Vec<LogEntry>, commit_index: u64, pub last_log_index: u64, last_log_term: u64, // Initialised for leader only next_index: HashMap<NodeId, u64>, match_index: HashMap<NodeId, u64>, last_applied: Option<u64>, pub target_state: TargetState, pub reelection_timeout: Option<Instant>, next_heartbeat: Option<Instant>, network: Arc<RaftNetwork>, _storage: RaftStorage, config: RaftConfig, state_machine: Arc<dyn StateMachine + Send + Sync>, } /// Container for a shared Raft node #[derive(Clone)] pub struct RaftNode { shutdown_signal: Arc<ShutdownSignal>, pub raft: Arc<RwLock<Raft>>, } #[derive(Debug, Eq, PartialEq)] pub enum TargetState { Unknown, Follower, Candidate, Leader, } impl TargetState { pub fn is_leader(&self) -> bool { *self == TargetState::Leader } pub fn is_follower(&self) -> bool { *self == TargetState::Follower } pub fn is_candidate(&self) -> bool { *self == TargetState::Candidate } } impl Raft { pub fn is_leader(&self) -> bool { self.target_state.is_leader() } pub fn is_follower(&self) -> bool { self.target_state.is_follower() } pub fn is_candidate(&self) -> bool { self.target_state.is_candidate() } } impl Raft { fn update_current_term(&mut self, term: u64, voted_for: Option<NodeId>) { if self.current_term < term { self.current_term = term; self.voted_for = voted_for; } } fn set_target_state(&mut self, target: TargetState) { self.target_state = target; } #[allow(dead_code)] async fn save_hard_state(&mut self) -> Result<()> { // TODO: implement saving the hard state of Raft to [self.storage] Ok(()) } fn get_reelection_timeout(&mut self) -> Instant { self.reelection_timeout.unwrap_or_else(move || { let inst = Instant::now() + self.rand_reelection_timeout(); self.reelection_timeout = Some(inst); inst }) } fn update_reelection_timeout(&mut self) { let inst = Instant::now() + self.rand_reelection_timeout(); self.reelection_timeout = Some(inst); } fn rand_reelection_timeout(&self) -> Duration { let min_timeout = self.config.reelection_timeout_min; let max_timeout = self.config.reelection_timeout_max; if min_timeout == max_timeout { min_timeout } else { rand::thread_rng().gen_range(min_timeout, max_timeout) } } fn get_next_heartbeat(&mut self) -> Instant { self.next_heartbeat.unwrap_or_else(move || { let inst = Instant::now(); self.next_heartbeat = Some(inst); inst }) } fn update_next_heartbeat(&mut self) { let inst = Instant::now() + self.config.heartbeat_period; self.next_heartbeat = Some(inst); } fn update_commit_index(&mut self) { let mut commit_index = self.commit_index; loop { let mut count_committed = 1; for id in self.network.clone().peers.keys() { if let Some(&committed) = self.match_index.get(id) { if committed > commit_index { count_committed += 1; } } } if count_committed > self.network.peers.len() / 2 { commit_index += 1; } else { break; } } info!( "Updating leader commit index from {:} to {:}", self.commit_index, commit_index ); if self.commit_index != commit_index { // Send early heartbeat to reduce the latency on applying logs self.next_heartbeat = Some(Instant::now()); } self.commit_index = commit_index; } async fn replicate_to_state_machine_if_needed(&mut self) -> Result<()> { debug!("replicate_to_state_machine_if_needed called"); while self.last_applied < Some(self.commit_index) && self.last_applied < Some(self.last_log_index) { let applied_index = self.last_applied.map_or(0, |val| val + 1) as usize; if let Some(command) = self.log[applied_index].command.clone() { info!("Applying command {:?}: {:?}", applied_index, command); self.state_machine .apply_command(&command, self.is_leader()) .await; } self.last_applied = Some(applied_index as u64); } Ok(()) } #[tracing::instrument(skip(self), fields(self.me))] pub(crate) async fn handle_request_vote( &mut self, request: &VoteRequest, ) -> Result<VoteResponse> { tracing::trace!("Handling request vote"); // Reject outdated requests if request.term < self.current_term { return Ok(VoteResponse { term: self.current_term, vote_granted: false, }); } // If the request coming from the future, update the local state if request.term > self.current_term { self.update_current_term(request.term, None); self.update_reelection_timeout(); self.set_target_state(TargetState::Follower); } // If the candidate is not at least as uptodate as us, reject the vote let client_is_uptodate = (request.last_log_term >= self.last_log_term) && (request.last_log_index >= self.last_log_index as u64); if !client_is_uptodate { return Ok(VoteResponse { term: self.current_term, vote_granted: false, }); } // Grant vote based on whether we have voted match &self.voted_for { Some(candidate_id) if candidate_id == &request.candidate_id => Ok(VoteResponse { term: self.current_term, vote_granted: true, }), Some(_) => Ok(VoteResponse { term: self.current_term, vote_granted: false, }), None => { self.voted_for = Some(request.candidate_id); self.set_target_state(TargetState::Follower); self.update_reelection_timeout(); Ok(VoteResponse { term: self.current_term, vote_granted: true, }) } } } #[tracing::instrument(skip(self, request), fields(self.me))] pub(crate) async fn handle_append_entries( &mut self, request: &AppendEntriesRequest, ) -> Result<AppendEntriesResponse> { tracing::trace!("Handling append entries"); // Reject outdated requests if request.term < self.current_term { tracing::trace!( self.current_term, rpc_term = request.term, "AppendEntries RPC term is less than current term" ); return Ok(AppendEntriesResponse { term: self.current_term, success: false, }); } self.update_reelection_timeout(); self.commit_index = request.leader_commit; self.update_current_term(request.term, None); self.voted_for = Some(request.leader_id); self.set_target_state(TargetState::Follower); // Check that logs are consistent (ie. last log and terms match) let msg_index_and_term_match = (request.prev_log_index == self.last_log_index as u64) && (request.prev_log_term == self.last_log_term); if msg_index_and_term_match { // Only a heartbeat if request.entries.is_empty() { self.replicate_to_state_machine_if_needed().await?; return Ok(AppendEntriesResponse { term: self.current_term, success: true, }); } self.append_log_entries(&request.entries).await?; self.replicate_to_state_machine_if_needed().await?; return Ok(AppendEntriesResponse { term: self.current_term, success: true, }); } // Log consistency check let last_entry = self.log.get(request.prev_log_index as usize); let last_entry = match last_entry { Some(last_entry) => last_entry, None => { // If the leader's log is further ahead, reply false to get a response with earlier // logs return Ok(AppendEntriesResponse { term: self.current_term, success: false, }); } }; if last_entry.term != request.prev_log_term { // If the log terms are inconsistent, reply false return Ok(AppendEntriesResponse { term: self.current_term, success: false, }); } // If the logs agree, but the leader is sending earlier logs, drop the local logs and us the // leader's logs instead if self.last_log_index > last_entry.index { self.log.truncate(1 + last_entry.index as usize); } self.append_log_entries(&request.entries).await?; self.replicate_to_state_machine_if_needed().await?; Ok(AppendEntriesResponse { term: self.current_term, success: true, }) } #[tracing::instrument(level = "trace", skip(self, entries))] async fn append_log_entries(&mut self, entries: &Vec<LogEntry>) -> Result<()> { for entry in entries { debug!("Appending entry {:?}", entry); self.log.push(entry.clone()); } if let Some(entry) = self.log.last() { self.last_log_index = entry.index; self.last_log_term = entry.term; } Ok(()) } } impl Raft { pub fn new( id: NodeId, config: RaftConfig, state_machine: Arc<dyn StateMachine + Send + Sync>, ) -> Self { Self { me: id, current_term: 0, voted_for: None, log: vec![LogEntry { term: 0, index: 0, command: None, }], commit_index: 0, last_log_index: 0, last_log_term: 0, next_index: HashMap::new(), match_index: HashMap::new(), last_applied: None, target_state: TargetState::Unknown, reelection_timeout: None, next_heartbeat: None, network: Arc::new(RaftNetwork::from_addresses(&config.addresses)), _storage: RaftStorage::new(), config, state_machine, } } } impl RaftNode { pub fn new(raft: Arc<RwLock<Raft>>) -> Self { Self { shutdown_signal: Arc::new(ShutdownSignal::new()), raft, } } pub fn new_with_shutdown( raft: Arc<RwLock<Raft>>, shutdown_signal: Arc<ShutdownSignal>, ) -> Self { Self { shutdown_signal, raft, } } /// Starts an RPC server ([RaftRpcServer]) to reply to peer Raft nodes async fn start_rpc_server(&self) -> Result<()> { let addr = { let raft = self.raft.read().await; let network = &raft.network; let me = network.peers.get(&raft.me).unwrap(); me.addr }; let server = RaftRpcServer::new(RaftRPCServer { raft: self.raft.clone(), }); let signal = self.shutdown_signal.clone(); tracing::trace!("Starting rpc server"); Server::builder() .add_service(server) .serve_with_shutdown(addr, RaftNode::await_shutdown_signal(signal)) .await?; trace!("Shutting down rpc server"); Ok(()) } async fn await_shutdown_signal(signal: Arc<ShutdownSignal>) { let _ = join!(task::spawn( async move { signal.await_shutdown_signal().await } )); } /// Runs a Raft node as per the Raft protocol. /// /// It starts the following threads: /// - [start_rpc_server] /// - [run_heartbeat_loop] /// - [run_reelection_loop] #[tracing::instrument(skip(self))] pub async fn run(&self) -> Result<()> { let mut handles = vec![]; let raft = self.clone(); handles.push(task::spawn(async move { raft.start_rpc_server().await })); let raft = self.clone(); handles.push(task::spawn(async move { raft.run_heartbeat_loop().await })); let raft = self.clone(); handles.push(task::spawn(async move { raft.run_reelection_loop().await })); let _ = try_join_all(handles).await?; trace!("End of run reached"); Ok(()) } #[tracing::instrument(skip(self))] pub async fn start(&self, command: Command) -> Result<bool> { let mut raft = self.raft.write().await; if !raft.is_leader() { trace!("Node is not a leader, aborting start of command"); return Ok(false); } let entry = LogEntry { term: raft.current_term, command: Some(command), index: raft.last_log_index + 1, }; info!("Starting appending new log entry: {:?}", entry); raft.last_log_index += 1; raft.last_log_term = raft.current_term; raft.log.push(entry); raft.next_heartbeat = min( raft.next_heartbeat, Some(Instant::now() + raft.config.batching_period), ); Ok(true) } /// Starts a reelection loop that sends an election request to Raft peers if the current leader /// times out (i.e. if a heartbeat is not heard within the heartbeat period) /// /// This function returns when the shutdown signal was sent to the Raft node or an error /// occured. async fn run_reelection_loop(&self) -> Result<()> { loop { let (terminated, is_leader, reelection_time) = { let mut raft = self.raft.write().await; let terminated = self.shutdown_signal.poll_terminated(); (terminated, raft.is_leader(), raft.get_reelection_timeout()) }; if terminated { trace!("Terminated reelection loop"); return Ok(()); } if !is_leader && Instant::now() >= reelection_time { tracing::info!("Reelection timeout reached, starting reelection"); let res = self.start_reelection().await; if let Err(err) = res { tracing::error!("Reelection error {:?}", err.to_string()); }; } delay_for(LOOPING_PERIOD).await; } } async fn start_reelection(&self) -> Result<()> { let (me, network, term, last_log_index, last_log_term) = { let mut raft = self.raft.write().await; raft.set_target_state(TargetState::Candidate); raft.voted_for = None; raft.current_term += 1; raft.update_reelection_timeout(); ( raft.me, raft.network.clone(), raft.current_term, raft.last_log_index, raft.last_log_term, ) }; let request = VoteRequest { term, candidate_id: me, last_log_index: last_log_index as u64, last_log_term, }; let mut handles = vec![]; let result_handler; { let (s, r) = mpsc::channel(network.peers.len() - 1); for (&id, _) in network.peers.iter().filter(|(&id, _)| id != me) { let raft = self.raft.clone(); let request = request.clone(); let s = s.clone(); handles.push(spawn(async move { RaftNode::send_request_vote(raft, request, id, s).await })); } let quorum_size = { let raft = self.raft.write().await; 1 + raft.network.peers.len() / 2 }; result_handler = RaftNode::handle_election_result(self.raft.clone(), term, quorum_size, r); } let _ = join!(try_join_all(handles), result_handler); Ok(()) } async fn handle_election_result( raft: Arc<RwLock<Raft>>, term: u64, quorum_size: usize, mut r: Receiver<u64>, ) { let mut vote_count = 1; while let Some(_) = r.recv().await { vote_count += 1; debug!("Received vote #{:} out of {:}", vote_count, quorum_size); if vote_count >= quorum_size { break; } } let mut raft = raft.write().await; if raft.current_term != term { return; } let won_election = vote_count >= quorum_size && raft.is_candidate(); if won_election { raft.set_target_state(TargetState::Leader); raft.voted_for = Some(raft.me); raft.next_heartbeat = Some(Instant::now()); raft.voted_for = Some(raft.me); raft.match_index.values_mut().for_each(|val| *val = 0); let last_log_index = raft.last_log_index; raft.next_index .values_mut() .for_each(|val| *val = last_log_index + 1); tracing::info!({ node = raft.me }, "Converted to Leader") } else { raft.set_target_state(TargetState::Follower); } } async fn send_request_vote( raft: Arc<RwLock<Raft>>, request: VoteRequest, id: u64, mut s: Sender<u64>, ) -> Result<()> { let peer = { let raft = raft.read().await; raft.network.peers.get(&id).unwrap().clone() }; tracing::debug!("Sending vote request to {:}: {:?}", id, &request); let response = peer.send_request_vote(request).await?; tracing::debug!("Received vote response from {:}: {:?}", id, response); if response.vote_granted { let _ = s.send(id).await; } else { let mut raft = raft.write().await; raft.update_current_term(response.term, None); raft.set_target_state(TargetState::Follower); } Ok(()) } /// Starts a heartbeat loop that periodically sends heartbeats to other Raft replicas if the /// local replica is the leader of the cluster. /// /// This function returns when the shutdown signal was sent to the Raft node or an error /// occured. async fn run_heartbeat_loop(&self) -> Result<()> { loop { let ( terminated, me, is_leader, current_term, next_heartbeat, network, leader_commit, leader_id, ) = { let mut raft = self.raft.write().await; let next_heartbeat = raft.get_next_heartbeat(); let terminated = self.shutdown_signal.poll_terminated(); ( terminated, raft.me, raft.is_leader(), raft.current_term, next_heartbeat, raft.network.clone(), raft.commit_index, raft.voted_for, ) }; if terminated { trace!("Terminated heartbeat loop"); return Ok(()); } if is_leader && Instant::now() >= next_heartbeat { { let mut raft = self.raft.write().await; raft.update_next_heartbeat(); }; tracing::debug!("Sending heartbeat"); self.send_heartbeats(me, current_term, network.clone(), leader_commit, leader_id) .await?; } else { delay_for(LOOPING_PERIOD).await; } } } async fn send_heartbeats( &self, me: u64, current_term: u64, network: Arc<RaftNetwork>, leader_commit: u64, leader_id: Option<NodeId>, ) -> Result<()> { let others = network .peers .iter() .map(|(id, peer)| (*id, peer.clone())) .filter(|(id, _)| *id != me); for (id, peer) in others { let raft_node = self.clone(); tokio::spawn(async move { let request = raft_node .make_heartbeat_request(current_term, leader_commit, leader_id, id) .await; let last_log_sent = request.prev_log_index + request.entries.len() as u64; tracing::trace!("Sending append entries request to {:}: {:?}", id, request); let response = match peer.send_append_entries(request).await { Ok(response) => response, Err(err) => { error!("Error in sending append entries to {:}: {:?}", id, err); return; } }; tracing::trace!( "Received append entries response from {:}: {:?}", id, response ); if response.term > current_term { let mut raft = raft_node.raft.write().await; if raft.current_term == current_term { raft.update_current_term(response.term, None); raft.set_target_state(TargetState::Follower); raft.voted_for = None; } } else if response.success { let mut raft = raft_node.raft.write().await; if raft.current_term > current_term { return; } tracing::info!( "append entries succeeded, match index to {:} is now {:} from {:}", id, last_log_sent, raft.match_index.get(&id).cloned().unwrap_or(0) ); let prev_match_index = raft.match_index.get(&id).cloned().unwrap_or(0); raft.match_index .insert(id, max(prev_match_index, last_log_sent)); raft.update_commit_index(); raft.replicate_to_state_machine_if_needed().await; } else { tracing::trace!("retrying sending append entries to {:}", id); let mut raft = raft_node.raft.write().await; if raft.current_term > current_term { return; } raft.next_index.entry(id).and_modify(|val| *val -= 1); // (id, last_log_index + 1); } }); } Ok(()) } async fn make_heartbeat_request( &self, current_term: u64, leader_commit: u64, leader_id: Option<u64>, id: u64, ) -> AppendEntriesRequest { let mut raft = self.raft.write().await; let next_index = raft.next_index.get(&id).cloned().unwrap_or(1); let next_index = next_index as usize; trace!("next index to {:} is {:}", id, next_index); let next_index = max(1, min(next_index, raft.log.len())); let prev_log_index = next_index - 1; let prev_log_term = raft .log .get(prev_log_index) .map(|log| log.term) .unwrap_or(0); let entries_end = min(raft.log.len(), next_index + raft.config.batching_size); raft.next_index.insert(id, entries_end as u64); let logs_to_send = raft.log[next_index..entries_end] .iter() .cloned() .collect::<Vec<LogEntry>>(); AppendEntriesRequest { term: current_term, entries: logs_to_send, leader_commit: leader_commit as u64, leader_id: leader_id.unwrap(), prev_log_index: prev_log_index as u64, prev_log_term, } } }
use crate::util::{self, color}; use anyhow::Result; use std::collections::HashMap; use std::io::prelude::*; use std::path::{self, Path}; use std::{env, fs}; use serde::{Deserialize, Serialize}; /// A JSON-serializable struct representing machine-specific overrides. This is used /// to specify values of variables in templates for a specific machine for each /// remote name that is tracked. Machines can also specify where each config should /// end up. /// /// # Fields /// /// * `dest` - A map of remote paths to local paths, overriding the default `dest` map. /// * `templates` - A map from remote template paths to their location after rendering, /// overriding the default `templates` map. /// * `vars` - A map from variable names to values, used for template rendering. #[derive(Serialize, Deserialize, Clone)] pub struct OverrideConfig { dest: HashMap<String, String>, templates: HashMap<String, String>, vars: HashMap<String, String>, } /// A struct representing the JSON in `config.json`. /// /// # Fields /// /// * `overrides` - A map from a machine-id to an OverrideConfig. /// * `dest` - A map of remote paths to local paths, describing where each dotfile /// or directory is stored on the local filesystem. /// * `templates` - A map from remote template paths to their location after rendering. #[derive(Serialize, Deserialize)] pub struct Config { dest: HashMap<String, String>, overrides: HashMap<String, OverrideConfig>, templates: HashMap<String, String>, } impl Config { pub fn dest<S: Into<String>>(&self, remote: S) -> String { let remote = remote.into(); let default_local = &self.dest[&remote]; match util::machine_id() { Err(_) => default_local.clone(), Ok(machine_id) => match self.overrides.get(&machine_id) { None => default_local.clone(), Some(override_config) => override_config .dest .get(&remote) .unwrap_or(default_local) .clone(), }, } } pub fn dests(&self) -> HashMap<String, String> { match util::machine_id() { Err(_) => self.dest.clone(), Ok(machine_id) => match self.overrides.get(&machine_id) { None => self.dest.clone(), Some(override_config) => update_hash_map(&self.dest, &override_config.dest), }, } } pub fn templates(&self) -> HashMap<String, String> { match util::machine_id() { Err(_) => self.templates.clone(), Ok(machine_id) => match self.overrides.get(&machine_id) { None => self.templates.clone(), Some(override_config) => { update_hash_map(&self.templates, &override_config.templates) } }, } } pub fn track_template<R: Into<String>, S: Into<String>>( &mut self, name: R, render_to: S, ) { self.templates.insert(name.into(), render_to.into()); } pub fn track<R: Into<String>, S: Into<String>>(&mut self, remote: R, local: S) { self.dest.insert(remote.into(), local.into()); } pub fn has_remote<S: Into<String>>(&self, remote: S) -> bool { self.dest.contains_key(&remote.into()) } pub fn my_overrides(&self) -> OverrideConfig { let empty = OverrideConfig { dest: HashMap::new(), templates: HashMap::new(), vars: HashMap::new(), }; match util::machine_id() { Err(_) => empty.clone(), Ok(machine_id) => self.overrides.get(&machine_id).unwrap_or(&empty).clone(), } } pub fn set_my_overrides(&mut self, override_config: OverrideConfig) -> Result<()> { let machine_id = util::machine_id()?; self.overrides.insert(machine_id, override_config); Ok(()) } pub fn vars(&self) -> HashMap<String, String> { self.my_overrides().vars } } fn update_hash_map( old: &HashMap<String, String>, new: &HashMap<String, String>, ) -> HashMap<String, String> { old .iter() .map(|(k, v)| (k.to_owned(), new.get(k).unwrap_or(v).to_owned())) .collect() } /// Returns the path of the tittle directory. pub fn tittle_config_dir() -> path::PathBuf { Path::new(&env::var("HOME").unwrap()).join(".tittle") } /// Returns the path of the tittle_cofig.json file. pub fn tittle_config_file() -> path::PathBuf { tittle_config_dir().join("config.json") } /// Create the directory under `tittle_config_dir()` if it doesn't exist. fn create_config_dir_if_not_exists() -> Result<()> { let tittle_config_dir = tittle_config_dir(); if !tittle_config_dir.exists() { fs::create_dir(&tittle_config_dir)?; } Ok(()) } /// Create the `config.json` and initialize it if it doesn't exist. fn create_config_if_not_exists() -> Result<()> { let config_file = tittle_config_file(); if !config_file.exists() { let config = Config { dest: HashMap::new(), overrides: HashMap::new(), templates: HashMap::new(), }; writeln!( fs::File::create(&config_file)?, "{}", serde_json::to_string_pretty(&config)? )?; util::info(format!("Created {}", color::path(config_file))); } Ok(()) } /// Initializes tittle config directory and file. This must be called before any other /// functions from `config::*` are called. pub fn init() -> Result<()> { create_config_dir_if_not_exists()?; create_config_if_not_exists() } /// Returns the Config struct representing `config.json`. pub fn get_config() -> Result<Config> { let config: Config = serde_json::from_str(&fs::read_to_string(tittle_config_file()).unwrap())?; Ok(config) } /// Saves the config `config` to `config.json`. pub fn write_config(config: &Config) -> Result<()> { let config_file = tittle_config_file(); writeln!( fs::File::create(&config_file)?, "{}", serde_json::to_string_pretty(&config)? )?; Ok(()) }
use proconio::input; fn main() { input! { n: usize, s: [String; n], }; let f = s.iter().filter(|s| s.as_str() == "For").count(); if f > n / 2 { println!("Yes"); } else { println!("No"); } }
use rspirv::{ binary::{Assemble as _, Disassemble as _}, dr, lift, }; use std::path::PathBuf; fn test_spv(blob: &[u8]) { let module = dr::load_bytes(blob).unwrap(); let _disasm = module.disassemble(); let _assembly = module.assemble(); let _structured = lift::LiftContext::convert(&module).unwrap(); } fn test_external_dir(dir_path: PathBuf) { use std::fs; let dir_iter = match fs::read_dir(dir_path) { Ok(dir) => dir, Err(_) => return, }; for entry in dir_iter { let entry = match entry { Ok(e) => e, Err(_) => continue, }; let fty = entry.file_type().unwrap(); let path = entry.path(); if fty.is_file() { match path.extension() { Some(ext) => { if ext.to_string_lossy() != "spv" { continue; } } None => continue, } let spv = fs::read(path).unwrap(); test_spv(&spv); } else { test_external_dir(path); } } } #[test] fn test_external_modules() { let dir_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .parent() .unwrap() .join("spirv-blobs"); test_external_dir(dir_path); }
// Copyright 2021 Chiral Ltd. // Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0) // This file may not be copied, modified, or distributed // except according to those terms. //! Extendable Hash Value for Atom use crate::core; use crate::core::graph::*; use super::config; use super::bond; use super::atom; #[derive(Clone)] pub struct AtomExtendable { indexes_atom_visited: Vec<usize>, indexes_atom_boundary: Vec<usize>, bonds: Vec<bond::Bond>, } impl core::graph::VertexExtendableHash for AtomExtendable { type VertexType = atom::Atom; fn init(atom_idx: usize) -> Self { let indexes_atom_visited: Vec<usize> = vec![atom_idx]; let indexes_atom_boundary: Vec<usize> = vec![atom_idx]; let bonds: Vec<bond::Bond> = vec![]; Self { indexes_atom_visited, indexes_atom_boundary, bonds } } fn extend(&mut self, atoms: &Vec<atom::Atom>) { let mut indexes_atom_boundary: Vec<usize> = vec![]; let mut indexes_atom_visited: Vec<usize> = self.indexes_atom_visited.clone(); self.bonds = vec![]; for &idx in self.indexes_atom_boundary.iter() { for bond in atoms[idx].bonds.iter() { if !self.indexes_atom_visited.contains(&bond.tid) { indexes_atom_visited.push(bond.tid); indexes_atom_boundary.push(bond.tid); self.bonds.push(bond.clone()); } } } self.indexes_atom_visited = indexes_atom_visited; self.indexes_atom_boundary = indexes_atom_boundary; } fn is_completed(&self) -> bool { self.indexes_atom_boundary.len() == 0 } fn value(&self, atom_invariant_values: &Vec<core::graph::VertexFixedHashValue>) -> core::graph::VertexExtendableHashValue { let mut values: Vec<usize> = self.bonds.iter() .map(|b| b.fixed_hash_value() * config::MAX_OF_ATOM_FIXED_HASH_VALUE + atom_invariant_values[b.tid]) .collect(); values.sort_unstable(); values.reverse(); values } } #[cfg(test)] mod test_ext_mol_atom_ext { use super::*; use super::super::molecule; use crate::core; #[test] fn test_atom_repr() { let mol = molecule::Molecule::from_smiles("c1ccccc1CN"); let aivs: Vec<core::graph::VertexFixedHashValue> = mol.atoms.iter() .map(|a| a.fixed_hash_value()) .collect(); let mut ar = AtomExtendable::init(5); assert_eq!(ar.value(&aivs), vec![]); assert_eq!(ar.is_completed(), false); ar.extend(&mol.atoms); assert_eq!(ar.value(&aivs), vec![5100210060, 5100210060, 1100200060]); assert_eq!(ar.is_completed(), false); ar.extend(&mol.atoms); assert_eq!(ar.value(&aivs), vec![5100210060, 5100210060, 1100100070]); assert_eq!(ar.is_completed(), false); ar.extend(&mol.atoms); assert_eq!(ar.value(&aivs), vec![5100210060, 5100210060]); assert_eq!(ar.is_completed(), false); } }
pub use sdl2::keyboard::Keycode; use std::thread; use failure::{err_msg, Error, ResultExt}; use rand::{self, Rng}; use sdl2; use sdl2::event::Event; use sdl2::pixels::{Color, PixelFormatEnum}; use sdl2::rect::Point; use sdl2::render::{BlendMode, WindowCanvas}; use world::{Scalar, ScalarState}; pub struct Connection; pub fn run(scene: fn(Connection) -> ()) -> Result<(), Error> { let sdl = sdl2::init() .map_err(err_msg) .context("failed to initialize SDL2")?; let video = sdl .video() .map_err(err_msg) .context("failed to initialize video device")?; let window = video .window("Speeltuin", 640, 480) .build() .context("failed to create window")?; let mut canvas = window .into_canvas() .present_vsync() .target_texture() .build() .context("failed to create canvas")?; let texture_creator = canvas.texture_creator(); let mut event_pump = sdl .event_pump() .map_err(err_msg) .context("failed to initialize event pump")?; thread::Builder::new() .name("scene".to_string()) .spawn(move || scene(Connection))?; let (width, height) = (320, 240); canvas.set_logical_size(width, height)?; let mut texture = texture_creator.create_texture_target(PixelFormatEnum::RGBA8888, width, height)?; texture.set_blend_mode(BlendMode::Blend); let mut draw_result = Ok(()); canvas.with_texture_canvas(&mut texture, |canvas| { draw_result = draw_random_dots(canvas, width, height, 0.1); })?; draw_result?; let mut angle = Scalar::new(0.0, 0.1); let mut xpos = Scalar::new(width as f64 / 2.0, 1.0); let mut ypos = Scalar::new(height as f64 / 2.0, 1.0); loop { for event in event_pump.poll_iter() { match event { Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => return Ok(()), Event::KeyDown { keycode: Some(keycode), repeat: false, .. } => match keycode { Keycode::D => angle.set_state(ScalarState::Increasing), Keycode::A => angle.set_state(ScalarState::Decreasing), Keycode::Left => xpos.set_state(ScalarState::Decreasing), Keycode::Right => xpos.set_state(ScalarState::Increasing), Keycode::Up => ypos.set_state(ScalarState::Decreasing), Keycode::Down => ypos.set_state(ScalarState::Increasing), _ => (), }, Event::KeyUp { keycode: Some(keycode), .. } => match keycode { Keycode::D => angle.unset_state(ScalarState::Increasing), Keycode::A => angle.unset_state(ScalarState::Decreasing), Keycode::Left => xpos.unset_state(ScalarState::Decreasing), Keycode::Right => xpos.unset_state(ScalarState::Increasing), Keycode::Up => ypos.unset_state(ScalarState::Decreasing), Keycode::Down => ypos.unset_state(ScalarState::Increasing), _ => (), }, _ => (), } } angle.update(); xpos.update(); ypos.update(); canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); canvas.copy(&texture, None, None).map_err(err_msg)?; canvas .copy_ex( &texture, None, None, angle.value(), Point::new(xpos.value() as i32, ypos.value() as i32), false, false, ) .map_err(err_msg)?; canvas.present(); } } fn draw_random_dots( canvas: &mut WindowCanvas, width: u32, height: u32, probability: f64, ) -> Result<(), Error> { let mut rng = rand::thread_rng(); canvas.set_draw_color(Color::RGBA(0, 0, 0, 0)); canvas.clear(); canvas.set_draw_color(Color::RGBA(255, 255, 255, 255)); for y in 0..height as i32 { for x in 0..width as i32 { if rng.gen_bool(probability) { canvas.draw_point((x, y)).map_err(err_msg)?; } } } Ok(()) }
/// Prints code that handles the insertion of new objects during the search. use crate::ir::{self, SetRef}; use crate::print; use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, ToTokens}; /// Runs necessary filters after new objects are allocated. This only runs new filters on /// old objects. pub fn filters(ir_desc: &ir::IrDesc) -> TokenStream { ir_desc .set_defs() .map(|(set_def, on_new_object)| { if on_new_object.filter.is_empty() { return quote!(); } let obj = Ident::new("obj", Span::call_site()); let arg = set_def.arg().map(|_| Ident::new("arg", Span::call_site())); // We assume the argument variable is Arg(1) since this is what is generated // by `ir::adapt_to_var_context`. let set = ir::Set::new(set_def, set_def.arg().map(|_| ir::Variable::Arg(1))); // We must use the old template facilities to print the filter call so // generate variables for the old printer. let mut vars = vec![(print::ast::Variable::with_name("obj"), &set)]; if let Some(arg) = set_def.arg() { vars.push((print::ast::Variable::with_name("arg"), arg)); } let body = on_new_object .filter .iter() .map(|(foralls, constraints, filter_call)| { let ctx = print::Context::new_outer(ir_desc, &vars, foralls); let mut conflicts = vars.iter() .map(|(var, set)| print::ast::Conflict::new(var.clone(), set)) .collect(); let loop_vars = (0..foralls.len()).map(ir::Variable::Forall); let loop_nest = print::ast::LoopNest::new( loop_vars, &ctx, &mut conflicts, false); let filter_call = print::choice::RemoteFilterCall::new( filter_call, conflicts, foralls.len(), &ctx); let set_constraints = print::ast::SetConstraint::new( constraints, &ctx); let printed_code = render!(partial_init_filters, <'a>, loop_nest: print::ast::LoopNest<'a> = loop_nest, set_constraints: Vec<print::ast::SetConstraint<'a>> = set_constraints, filter_call: print::choice::RemoteFilterCall<'a> = filter_call); let tokens: TokenStream = printed_code.parse().unwrap(); tokens }).collect(); iter_new_objects(set_def, &obj, arg.as_ref(), &body) }).collect() } /// Iterates on the new objects of `set` and executes `body` for each of them. /// /// Warning: this method differs from the partial_iterators in `print::store`: it may /// call multiple times the same filter. This is because this makes it easier to handle /// reversed sets: we can register them in the non-reversed set instead. This doesn't /// work if the non-reversed set iterator skips some objects because it thinks they are /// handled by the reverse set. To factorize those functions, we would need to consider /// relations instead of parametric sets, thus removing the need to have reversed sets. fn iter_new_objects( set: &ir::SetDef, obj: &Ident, arg: Option<&Ident>, body: &TokenStream, ) -> TokenStream { assert_eq!(set.arg().is_some(), arg.is_some()); let new_objs_iter = print::set::iter_new_objects(&set); let obj_id = print::set::ObjectId::new("obj_id", set); let arg_id = set .arg() .map(|set| print::set::ObjectId::new("arg_id", set.def())); let obj_arg_pattern = arg_id .as_ref() .map(|arg| quote! { (#arg, #obj_id) }) .unwrap_or_else(|| obj_id.clone().into_token_stream()); let arg_def = arg_id.as_ref().map(|id| { let getter = id.fetch_object(None); quote! { let #arg = #getter; } }); let arg = arg.map(|x| x.clone().into()); let obj_getter = obj_id.fetch_object(arg.as_ref()); quote! { for &#obj_arg_pattern in #new_objs_iter.iter() { #arg_def let #obj = #obj_getter; #body } } }
impl Solution { pub fn shuffle(nums: Vec<i32>, n: i32) -> Vec<i32> { let mut ans = Vec::new(); for i in 0..nums.len()/2 { ans.push(nums[i]); ans.push(nums[i + nums.len()/2]); } ans } }
//問題1 構造体user_structを定義して、println!できますか? #[derive(Debug)] struct User{ user_name : String } fn main(){ let user_struct=User { user_name : "yahata".to_string() }; println!("{:?}",user_struct) }
use std::env; use std::io::{self, BufRead}; use std::fs::OpenOptions; use std::io::Write; fn main() { let stdin = io::stdin(); let args: Vec<String> = env::args().collect(); let mut filename="mail.txt"; if args.len()>1 { filename = &args[1]; } let mut file = OpenOptions::new().create(true).append(true).open(filename).expect("cannot open file"); for line in stdin.lock().lines() { let line = line.expect("Could not read line from standard in"); file.write_all(line.as_bytes()).expect("write failed"); file.write_all("\n".as_bytes()).expect("write failed"); } }
use byteorder::{ByteOrder, NetworkEndian}; use crate::arguments::Arguments; use crate::encode::{Encode, IsNull}; use crate::io::BufMut; use crate::postgres::{PgRawBuffer, PgTypeInfo, Postgres}; use crate::types::Type; #[derive(Default,Debug)] pub struct PgArguments { // Types of the bind parameters pub(super) types: Vec<PgTypeInfo>, // Write buffer for serializing bind values pub(super) buffer: PgRawBuffer, } impl Arguments for PgArguments { type Database = super::Postgres; fn reserve(&mut self, len: usize, size: usize) { self.types.reserve(len); self.buffer.reserve(size); } fn add<T>(&mut self, value: T) where T: Type<Self::Database> + Encode<Self::Database>, { // TODO: When/if we receive types that do _not_ support BINARY, we need to check here // TODO: There is no need to be explicit unless we are expecting mixed BINARY / TEXT self.types.push(<T as Type<Postgres>>::type_info()); // Reserves space for the length of the value let pos = self.buffer.len(); self.buffer.put_i32::<NetworkEndian>(0); let len = if let IsNull::No = value.encode_nullable(&mut self.buffer) { (self.buffer.len() - pos - 4) as i32 } else { // Write a -1 for the len to indicate NULL // TODO: It is illegal for [encode] to write any data // if IsSql::No; fail a debug assertion -1 }; // Write-back the len to the beginning of this frame (not including the len of len) NetworkEndian::write_i32(&mut self.buffer[pos..], len as i32); } }
use std::marker::PhantomData; use async_stream::try_stream; use futures_core::Stream; use futures_util::future::ready; use futures_util::TryFutureExt; use crate::arguments::Arguments; use crate::cursor::{Cursor, HasCursor}; use crate::database::Database; use crate::encode::Encode; use crate::executor::{Execute, Executor, RefExecutor}; use crate::row::HasRow; use crate::types::Type; /// Raw SQL query with bind parameters. Returned by [`query`][crate::query::query]. #[must_use = "query must be executed to affect database"] pub struct Query<'q, DB> where DB: Database, { pub(crate) query: &'q str, pub(crate) arguments: DB::Arguments, database: PhantomData<DB>, } /// SQL query that will map its results to owned Rust types. /// /// Returned by [Query::try_map], `query!()`, etc. Has most of the same methods as [Query] but /// the return types are changed to reflect the mapping. However, there is no equivalent of /// [Query::execute] as it doesn't make sense to map the result type and then ignore it. /// /// [Query::bind] is also omitted; stylistically we recommend placing your `.bind()` calls /// before `.try_map()` anyway. #[must_use = "query must be executed to affect database"] pub struct Map<'q, DB, F> where DB: Database, { query: Query<'q, DB>, mapper: F, } // necessary because we can't have a blanket impl for `Query<'q, DB>` // the compiler thinks that `ImmutableArguments<DB>` could be `DB::Arguments` even though // that would be an infinitely recursive type impl<'q, DB> Execute<'q, DB> for Query<'q, DB> where DB: Database, { fn into_parts(self) -> (&'q str, Option<DB::Arguments>) { (self.query, Some(self.arguments)) } } impl<'q, DB> Query<'q, DB> where DB: Database, { /// Bind a value for use with this SQL query. /// /// If the number of times this is called does not match the number of bind parameters that /// appear in the query (`?` for most SQL flavors, `$1 .. $N` for Postgres) then an error /// will be returned when this query is executed. /// /// There is no validation that the value is of the type expected by the query. Most SQL /// flavors will perform type coercion (Postgres will return a database error).s pub fn bind<T>(mut self, value: T) -> Self where T: Type<DB>, T: Encode<DB>, { self.arguments.add(value); self } #[doc(hidden)] pub fn bind_all(self, arguments: DB::Arguments) -> Query<'q, DB> { Query { query: self.query, arguments, database: PhantomData, } } } impl<'q, DB> Query<'q, DB> where DB: Database, { /// Map each row in the result to another type. /// /// The returned type has most of the same methods but does not have /// [`.execute()`][Query::execute] or [`.bind()][Query::bind]. /// /// See also: [query_as][crate::query_as::query_as]. pub fn map<F, O>(self, mapper: F) -> Map<'q, DB, impl TryMapRow<DB, Output = O>> where O: Unpin, F: MapRow<DB, Output = O>, { self.try_map(MapRowAdapter(mapper)) } /// Map each row in the result to another type. /// /// See also: [query_as][crate::query_as::query_as]. pub fn try_map<F>(self, mapper: F) -> Map<'q, DB, F> where F: TryMapRow<DB>, { Map { query: self, mapper, } } } impl<'q, DB> Query<'q, DB> where DB: Database, Self: Execute<'q, DB>, { pub async fn execute<E>(self, mut executor: E) -> crate::Result<u64> where E: Executor<Database = DB>, { executor.execute(self).await } pub fn fetch<'e, E>(self, executor: E) -> <DB as HasCursor<'e, 'q>>::Cursor where E: RefExecutor<'e, Database = DB>, { executor.fetch_by_ref(self) } } impl<'q, DB, F> Map<'q, DB, F> where DB: Database, Query<'q, DB>: Execute<'q, DB>, F: TryMapRow<DB>, { /// Execute the query and get a [Stream] of the results, returning our mapped type. pub fn fetch<'e: 'q, E>( mut self, executor: E, ) -> impl Stream<Item = crate::Result<F::Output>> + Unpin + 'e where 'q: 'e, E: RefExecutor<'e, Database = DB> + 'e, F: 'e, F::Output: 'e, { Box::pin(try_stream! { let mut cursor = executor.fetch_by_ref(self.query); while let Some(next) = cursor.next().await? { let mapped = self.mapper.try_map_row(next)?; yield mapped; } }) } /// Get the first row in the result pub async fn fetch_optional<'e, E>(self, executor: E) -> crate::Result<Option<F::Output>> where E: RefExecutor<'e, Database = DB>, 'q: 'e, { // could be implemented in terms of `fetch()` but this avoids overhead from `try_stream!` let mut cursor = executor.fetch_by_ref(self.query); let mut mapper = self.mapper; let val = cursor.next().await?; val.map(|row| mapper.try_map_row(row)).transpose() } pub async fn fetch_one<'e, E>(self, executor: E) -> crate::Result<F::Output> where E: RefExecutor<'e, Database = DB>, 'q: 'e, { self.fetch_optional(executor) .and_then(|row| match row { Some(row) => ready(Ok(row)), None => ready(Err(crate::Error::RowNotFound)), }) .await } pub async fn fetch_all<'e, E>(mut self, executor: E) -> crate::Result<Vec<F::Output>> where E: RefExecutor<'e, Database = DB>, 'q: 'e, { let mut cursor = executor.fetch_by_ref(self.query); let mut out = vec![]; while let Some(row) = cursor.next().await? { out.push(self.mapper.try_map_row(row)?); } Ok(out) } } // A (hopefully) temporary workaround for an internal compiler error (ICE) involving higher-ranked // trait bounds (HRTBs), associated types and closures. // // See https://github.com/rust-lang/rust/issues/62529 pub trait TryMapRow<DB: Database> { type Output: Unpin; fn try_map_row(&mut self, row: <DB as HasRow>::Row) -> crate::Result<Self::Output>; } pub trait MapRow<DB: Database> { type Output: Unpin; fn map_row(&mut self, row: <DB as HasRow>::Row) -> Self::Output; } // An adapter that implements [MapRow] in terms of [TryMapRow] // Just ends up Ok wrapping it struct MapRowAdapter<F>(F); impl<DB: Database, O, F> TryMapRow<DB> for MapRowAdapter<F> where O: Unpin, F: MapRow<DB, Output = O>, { type Output = O; fn try_map_row(&mut self, row: <DB as HasRow>::Row) -> crate::Result<Self::Output> { Ok(self.0.map_row(row)) } } /// Construct a raw SQL query that can be chained to bind parameters and executed. pub fn query<DB>(sql: &str) -> Query<DB> where DB: Database, { Query { database: PhantomData, arguments: Default::default(), query: sql, } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::convert::TryInto; use std::os::unix::io::AsRawFd; use failure::ResultExt; use fuchsia_zircon as zx; use futures::io::{AsyncReadExt, AsyncWriteExt}; use futures::stream::{StreamExt, TryStreamExt}; use net2::TcpStreamExt; #[derive(argh::FromArgs)] /// Adverse condition `connect` test. struct TopLevel { #[argh(subcommand)] sub_command: SubCommand, } #[derive(argh::FromArgs)] /// Connect to the remote address. #[argh(subcommand, name = "client")] struct Client { #[argh(option)] /// the remote address to connect to remote: std::net::Ipv4Addr, } #[derive(argh::FromArgs)] /// Listen for incoming connections. #[argh(subcommand, name = "server")] struct Server {} #[derive(argh::FromArgs)] #[argh(subcommand)] enum SubCommand { Client(Client), Server(Server), } const NAME: &str = "connect_test"; fn bus_subscribe( sync_manager: &fidl_fuchsia_netemul_sync::SyncManagerProxy, client_name: &str, ) -> Result<fidl_fuchsia_netemul_sync::BusProxy, fidl::Error> { let (client, server) = fidl::endpoints::create_proxy::<fidl_fuchsia_netemul_sync::BusMarker>()?; let () = sync_manager.bus_subscribe(NAME, client_name, server)?; Ok(client) } async fn verify_broken_pipe( mut stream: fuchsia_async::net::TcpStream, ) -> Result<(), failure::Error> { let mut buf = [0xad; 1]; let n = stream.read(&mut buf).await?; if n != 0 { let () = Err(failure::format_err!("read {}/{} bytes", n, 0))?; } match stream.write(&buf).await { Ok(n) => Err(failure::format_err!("unexpectedly wrote {} bytes", n)), Err(io_error) => { if io_error.kind() == std::io::ErrorKind::BrokenPipe { Ok(()) } else { Err(failure::format_err!("unexpected error {}", io_error)) } } } } #[fuchsia_async::run_singlethreaded] async fn main() -> Result<(), failure::Error> { const CLIENT_NAME: &str = "client"; const SERVER_NAME: &str = "server"; const PORT: u16 = 80; fuchsia_syslog::init_with_tags(&[NAME])?; let sync_manager = fuchsia_component::client::connect_to_service::< fidl_fuchsia_netemul_sync::SyncManagerMarker, >()?; let TopLevel { sub_command } = argh::from_env(); match sub_command { SubCommand::Client(Client { remote }) => { println!("Running client."); let bus = bus_subscribe(&sync_manager, CLIENT_NAME)?; // Wait for the server to be attached to the event bus, meaning it's // already bound and listening. let _ = bus .wait_for_clients( &mut Some(SERVER_NAME).into_iter(), zx::Time::INFINITE.into_nanos(), ) .await .context("Failed to observe server joining the bus")?; let sockaddr = std::net::SocketAddr::from((remote, PORT)); println!("Connecting keepalive and retransmit sockets..."); let keepalive_timeout = fuchsia_async::net::TcpStream::connect(sockaddr)?.await?; println!("Connected keepalive."); let mut retransmit_timeout = fuchsia_async::net::TcpStream::connect(sockaddr)?.await?; println!("Connected retransmit."); // Now that we have our connections, partition the network. { let network_context = fuchsia_component::client::connect_to_service::< fidl_fuchsia_netemul_network::NetworkContextMarker, >()?; let network_manager = { let (client, server) = fidl::endpoints::create_proxy::< fidl_fuchsia_netemul_network::NetworkManagerMarker, >()?; let () = network_context.get_network_manager(server)?; client }; let network = network_manager .get_network("net") .await? .ok_or(failure::err_msg("failed to get network"))? .into_proxy()?; let status = network .set_config(fidl_fuchsia_netemul_network::NetworkConfig { latency: None, packet_loss: Some(fidl_fuchsia_netemul_network::LossConfig::RandomRate( 100, )), reorder: None, }) .await?; let () = fuchsia_zircon::ok(status)?; } println!("Network partitioned."); let connect_timeout = fuchsia_async::net::TcpStream::connect(sockaddr)?; let connect_timeout = async { match connect_timeout.await { Ok(_stream) => Err(failure::err_msg("unexpectedly connected")), Err(io_error) => { if io_error.kind() == std::io::ErrorKind::TimedOut { Ok(()) } else { Err(failure::format_err!("unexpected error {}", io_error)) } } } }; // Start the keepalive machinery. let () = keepalive_timeout.std().set_keepalive_ms(Some(0))?; // TODO(tamird): use upstream's setters when // https://github.com/rust-lang-nursery/net2-rs/issues/90 is fixed. // // TODO(tamird): use into_iter after // https://github.com/rust-lang/rust/issues/25725. println!("Setting keepalive options."); for name in [libc::TCP_KEEPCNT, libc::TCP_KEEPINTVL].iter().cloned() { let value = 1u32; // This is safe because `setsockopt` does not retain memory passed to it. if unsafe { libc::setsockopt( keepalive_timeout.std().as_raw_fd(), libc::IPPROTO_TCP, name, &value as *const _ as *const libc::c_void, std::mem::size_of_val(&value).try_into().unwrap(), ) } != 0 { let () = Err(std::io::Error::last_os_error())?; } } // Start the retransmit machinery. let payload = [0xde; 1]; let n = retransmit_timeout.write(&payload).await?; if n != payload.len() { let () = Err(failure::format_err!("wrote {}/{} bytes", n, payload.len()))?; } let keepalive_timeout = verify_broken_pipe(keepalive_timeout); let retransmit_timeout = verify_broken_pipe(retransmit_timeout); // TODO(tamird): revert this to futures::try_join!(...) when the timeouts can be // configured. let interval = std::time::Duration::from_secs(5); let timeout = std::time::Duration::from_secs(600); let periodically_emit = fuchsia_async::Interval::new(interval.into()) .take(timeout.as_secs() / interval.as_secs()) .for_each(|()| { futures::future::ready(println!( "still waiting for TCP timeouts! don't terminate me please" )) }); println!("Waiting for all three timeouts..."); let timeouts = futures::future::try_join3(connect_timeout, keepalive_timeout, retransmit_timeout); futures::pin_mut!(timeouts); match futures::future::select(timeouts, periodically_emit).await { futures::future::Either::Left((timeouts, _logger)) => { let ((), (), ()) = timeouts?; } futures::future::Either::Right(((), _timeouts)) => { let () = Err(failure::err_msg("periodic logger completed unexpectedly"))?; } }; Ok(()) } SubCommand::Server(Server {}) => { println!("Starting server..."); let _listener = std::net::TcpListener::bind(&std::net::SocketAddr::from(( std::net::Ipv4Addr::UNSPECIFIED, PORT, )))?; println!("Server bound."); let bus = bus_subscribe(&sync_manager, SERVER_NAME)?; let stream = bus.take_event_stream().try_filter_map(|event| { async move { Ok(match event { fidl_fuchsia_netemul_sync::BusEvent::OnClientDetached { client } => { match client.as_str() { CLIENT_NAME => Some(()), _client => None, } } fidl_fuchsia_netemul_sync::BusEvent::OnBusData { data: _ } | fidl_fuchsia_netemul_sync::BusEvent::OnClientAttached { client: _ } => { None } }) } }); println!("Waiting for client to detach."); futures::pin_mut!(stream); let () = stream .next() .await .ok_or(failure::err_msg("stream ended before client detached"))??; Ok(()) } } }
use crate::image::*; use crate::tuples::*; use crate::material::*; use crate::geometry::*; pub struct PointLight { pub color: Color, pub pos: Tuple4D } impl PointLight { pub fn new(color: Color, pos: Tuple4D) -> PointLight { PointLight {color, pos} } pub fn lighting(&self, material: &Material, point: &Tuple4D, eye: &Tuple4D, normal: &Tuple4D, in_shadow: bool) -> Color { let effective_color = material.color.mul(&self.color); let light_dir = self.pos.sub(&point).normalized(); let ambient = effective_color.scale(material.ambient); let light2normal = light_dir.dot(&normal); if light2normal < 0.0 || in_shadow { let total = ambient; total } else { let diffuse = effective_color.scale(material.diffuse).scale(light2normal); let reflection_vec = reflect(&light_dir.scale(-1.0), &normal); let reflection = reflection_vec.dot(&eye); if reflection <= 0.0 { let total = ambient.add(&diffuse); total } else { let factor = f64::powf(reflection, material.shininess); let specular = self.color.scale(material.specular).scale(factor); let total = ambient.add(&diffuse).add(&specular); total } } } }
//! Namespace level data buffer structures. pub(crate) mod name_resolver; use std::sync::Arc; use async_trait::async_trait; use data_types::{NamespaceId, TableId}; use metric::U64Counter; use predicate::Predicate; use trace::span::Span; use super::{ partition::resolver::PartitionProvider, post_write::PostWriteObserver, table::{metadata_resolver::TableProvider, TableData}, }; use crate::{ arcmap::ArcMap, deferred_load::DeferredLoad, dml_payload::IngestOp, dml_sink::DmlSink, query::{ projection::OwnedProjection, response::QueryResponse, tracing::QueryExecTracing, QueryError, QueryExec, }, }; /// The string name / identifier of a Namespace. /// /// A reference-counted, cheap clone-able string. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) struct NamespaceName(Arc<str>); impl<T> From<T> for NamespaceName where T: AsRef<str>, { fn from(v: T) -> Self { Self(Arc::from(v.as_ref())) } } impl std::ops::Deref for NamespaceName { type Target = Arc<str>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::fmt::Display for NamespaceName { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } /// Data of a Namespace #[derive(Debug)] pub(crate) struct NamespaceData<O> { namespace_id: NamespaceId, namespace_name: Arc<DeferredLoad<NamespaceName>>, /// A set of tables this [`NamespaceData`] instance has processed /// [`IngestOp`]'s for. /// /// The [`TableProvider`] acts as a [`DeferredLoad`] constructor to /// resolve the catalog [`Table`] for new [`TableData`] out of the hot path. /// /// /// [`Table`]: data_types::Table tables: ArcMap<TableId, TableData<O>>, catalog_table_resolver: Arc<dyn TableProvider>, /// The count of tables initialised in this Ingester so far, across all /// namespaces. table_count: U64Counter, /// The resolver of `(table_id, partition_key)` to [`PartitionData`]. /// /// [`PartitionData`]: super::partition::PartitionData partition_provider: Arc<dyn PartitionProvider>, post_write_observer: Arc<O>, } impl<O> NamespaceData<O> { /// Initialize new tables with default partition template of daily pub(super) fn new( namespace_id: NamespaceId, namespace_name: Arc<DeferredLoad<NamespaceName>>, catalog_table_resolver: Arc<dyn TableProvider>, partition_provider: Arc<dyn PartitionProvider>, post_write_observer: Arc<O>, metrics: &metric::Registry, ) -> Self { let table_count = metrics .register_metric::<U64Counter>( "ingester_tables", "Number of tables known to the ingester", ) .recorder(&[]); Self { namespace_id, namespace_name, tables: Default::default(), catalog_table_resolver, table_count, partition_provider, post_write_observer, } } /// Return the table data by ID. pub(crate) fn table(&self, table_id: TableId) -> Option<Arc<TableData<O>>> { self.tables.get(&table_id) } /// Return the [`NamespaceId`] this [`NamespaceData`] belongs to. pub(crate) fn namespace_id(&self) -> NamespaceId { self.namespace_id } /// Returns the [`NamespaceName`] for this namespace. pub(crate) fn namespace_name(&self) -> &DeferredLoad<NamespaceName> { &self.namespace_name } /// Obtain a snapshot of the tables within this [`NamespaceData`]. /// /// NOTE: the snapshot is an atomic / point-in-time snapshot of the set of /// [`NamespaceData`], but the tables (and partitions) within them may /// change as they continue to buffer DML operations. pub(super) fn tables(&self) -> Vec<Arc<TableData<O>>> { self.tables.values() } } #[async_trait] impl<O> DmlSink for NamespaceData<O> where O: PostWriteObserver, { type Error = mutable_batch::Error; async fn apply(&self, op: IngestOp) -> Result<(), Self::Error> { match op { IngestOp::Write(write) => { // Extract the partition key derived by the router. let partition_key = write.partition_key().clone(); for (table_id, b) in write.into_tables() { // Grab a reference to the table data, or insert a new // TableData for it. let table_data = self.tables.get_or_insert_with(&table_id, || { self.table_count.inc(1); Arc::new(TableData::new( table_id, Arc::new(self.catalog_table_resolver.for_table(table_id)), self.namespace_id, Arc::clone(&self.namespace_name), Arc::clone(&self.partition_provider), Arc::clone(&self.post_write_observer), )) }); let partitioned_data = b.into_partitioned_data(); table_data .buffer_table_write( partitioned_data.sequence_number(), partitioned_data.into_data(), partition_key.clone(), ) .await?; } } } Ok(()) } } #[async_trait] impl<O> QueryExec for NamespaceData<O> where O: Send + Sync + std::fmt::Debug, { type Response = QueryResponse; async fn query_exec( &self, namespace_id: NamespaceId, table_id: TableId, projection: OwnedProjection, span: Option<Span>, predicate: Option<Predicate>, ) -> Result<Self::Response, QueryError> { assert_eq!( self.namespace_id, namespace_id, "buffer tree index inconsistency" ); // Extract the table if it exists. let inner = self .table(table_id) .ok_or(QueryError::TableNotFound(namespace_id, table_id))?; // Delegate query execution to the namespace, wrapping the execution in // a tracing delegate to emit a child span. Ok(QueryResponse::new( QueryExecTracing::new(inner, "table") .query_exec(namespace_id, table_id, projection, span, predicate) .await?, )) } } #[cfg(test)] mod tests { use std::sync::Arc; use metric::{Attributes, Metric}; use super::*; use crate::{ buffer_tree::{ namespace::NamespaceData, partition::resolver::mock::MockPartitionProvider, post_write::mock::MockPostWriteObserver, }, deferred_load, test_util::{ defer_namespace_name_1_ms, make_write_op, PartitionDataBuilder, ARBITRARY_NAMESPACE_ID, ARBITRARY_NAMESPACE_NAME, ARBITRARY_PARTITION_KEY, ARBITRARY_TABLE_ID, ARBITRARY_TABLE_NAME, ARBITRARY_TABLE_PROVIDER, }, }; #[tokio::test] async fn test_namespace_init_table() { let metrics = Arc::new(metric::Registry::default()); // Configure the mock partition provider to return a partition for this // table ID. let partition_provider = Arc::new( MockPartitionProvider::default().with_partition(PartitionDataBuilder::new().build()), ); let ns = NamespaceData::new( ARBITRARY_NAMESPACE_ID, defer_namespace_name_1_ms(), Arc::clone(&*ARBITRARY_TABLE_PROVIDER), partition_provider, Arc::new(MockPostWriteObserver::default()), &metrics, ); // Assert the namespace name was stored let name = ns.namespace_name().to_string(); assert!( (name.as_str() == &***ARBITRARY_NAMESPACE_NAME) || (name == deferred_load::UNRESOLVED_DISPLAY_STRING), "unexpected namespace name: {name}" ); // Assert the namespace does not contain the test data assert!(ns.table(ARBITRARY_TABLE_ID).is_none()); // Write some test data ns.apply(IngestOp::Write(make_write_op( &ARBITRARY_PARTITION_KEY, ARBITRARY_NAMESPACE_ID, &ARBITRARY_TABLE_NAME, ARBITRARY_TABLE_ID, 0, &format!( r#"{},city=Medford day="sun",temp=55 22"#, &*ARBITRARY_TABLE_NAME ), None, ))) .await .expect("buffer op should succeed"); // Referencing the table should succeed assert!(ns.table(ARBITRARY_TABLE_ID).is_some()); // And the table counter metric should increase let tables = metrics .get_instrument::<Metric<U64Counter>>("ingester_tables") .expect("failed to read metric") .get_observer(&Attributes::from([])) .expect("failed to get observer") .fetch(); assert_eq!(tables, 1); // Ensure the deferred namespace name is loaded. let name = ns.namespace_name().get().await; assert_eq!(&*name, &**ARBITRARY_NAMESPACE_NAME); assert_eq!( ns.namespace_name().to_string().as_str(), &***ARBITRARY_NAMESPACE_NAME ); } }
pub struct Solution; impl Solution { pub fn num_trees(n: i32) -> i32 { let n = n as usize; let mut count = vec![0; n + 1]; count[0] = 1; for i in 1..=n { for j in 0..i { count[i] += count[j] * count[i - j - 1]; } } count[n] } } #[test] fn test0096() { assert_eq!(Solution::num_trees(3), 5); }
mod foo { fn bar(offset: uint) { } } fn main(args: vec[str]) { foo::bar(0u); }
use crate::{DocBase, VarType}; const DESCRIPTION: &'static str = r#" The sma function returns the moving average, that is the sum of last y values of x, divided by y. "#; const EXAMPLE: &'static str = r#" ```pine plot(sma(close, 15)) // same on pine, but much less efficient pine_sma(x, y) => sum = 0.0 for i = 0 to y - 1 sum := sum + x[i] / y sum plot(pine_sma(close, 15)) ``` "#; const ARGUMENT: &'static str = r#" **source (series(float))** Series of values to process. **length (int)** Number of bars (length). "#; pub fn gen_doc() -> Vec<DocBase> { let fn_doc = DocBase { var_type: VarType::Function, name: "sma", signatures: vec![], description: DESCRIPTION, example: EXAMPLE, returns: "Simple moving average of x for y bars back.", arguments: ARGUMENT, remarks: "", links: "[ema](#fun-ema) [rma](#fun-rma) [wma](#fun-wma) [vwma](#fun-vwma) [swma](#fun-swma) [alma](#fun-alma)", }; vec![fn_doc] }
use std::io; fn main() { let t: i32 = read_i32_from_stdin(); for _ in 0..t { let (a, b) = read_a_b_from_stdin(); let n: i32 = read_i32_from_stdin(); let result = series_ap(a, b, n); println!("{}", result); } } fn read_i32_from_stdin() -> i32 { loop { let mut input = String::new(); io::stdin().read_line(&mut input).expect("Failed to read number"); match input.trim().parse() { Ok(num) => break num, Err(_) => continue } } } fn read_a_b_from_stdin() -> (i32, i32) { let mut input = String::new(); io::stdin().read_line(&mut input).expect("Failed to read a and b from stdin"); let parts: Vec<&str> = input.split_whitespace().collect(); let a = parts[0].parse().expect("Failed to parse a"); let b = parts[1].parse().expect("Failed to parse b"); (a, b) } fn series_ap(mut a: i32, b: i32, mut n: i32) -> i32 { // Determine the difference let d = b - a; // Starting from 'a', apply 'd' 'n' times while n - 1 > 0 { a += d; n -= 1; } return a; }
/// Sample implementation of the Tree interface. use super::{Altitude, Frontier, Hashable, Recording, Tree}; #[derive(Clone)] pub struct CompleteTree<H: Hashable> { leaves: Vec<H>, current_position: usize, witnesses: Vec<(usize, H)>, checkpoints: Vec<usize>, depth: usize, max_checkpoints: usize, } impl<H: Hashable + Clone> CompleteTree<H> { /// Creates a new, empty binary tree of specified depth. #[cfg(test)] pub fn new(depth: usize, max_checkpoints: usize) -> Self { CompleteTree { leaves: vec![H::empty_leaf(); 1 << depth], current_position: 0, witnesses: vec![], checkpoints: vec![], depth, max_checkpoints, } } } impl<H: Hashable + PartialEq + Clone> CompleteTree<H> { /// Removes the oldest checkpoint. Returns true if successful and false if /// there are no checkpoints. fn drop_oldest_checkpoint(&mut self) -> bool { if self.checkpoints.is_empty() { false } else { self.checkpoints.remove(0); true } } } impl<H: Hashable + Clone> Frontier<H> for CompleteTree<H> { /// Appends a new value to the tree at the next available slot. Returns true /// if successful and false if the tree is full. fn append(&mut self, value: &H) -> bool { if self.current_position == (1 << self.depth) { false } else { self.leaves[self.current_position] = value.clone(); self.current_position += 1; true } } /// Obtains the current root of this Merkle tree. fn root(&self) -> H { lazy_root(self.leaves.clone()) } } impl<H: Hashable + PartialEq + Clone> Tree<H> for CompleteTree<H> { type Recording = CompleteRecording<H>; /// Marks the current tree state leaf as a value that we're interested in /// witnessing. Returns true if successful and false if the tree is empty. fn witness(&mut self) -> bool { if self.current_position == 0 { false } else { let value = self.leaves[self.current_position - 1].clone(); if !self.witnesses.iter().any(|(_, v)| v == &value) { self.witnesses.push((self.current_position - 1, value)); } true } } /// Obtains an authentication path to the value specified in the tree. /// Returns `None` if there is no available authentication path to the /// specified value. fn authentication_path(&self, value: &H) -> Option<(usize, Vec<H>)> { self.witnesses .iter() .find(|witness| witness.1 == *value) .map(|&(pos, _)| { let mut path = vec![]; let mut index = pos; for bit in 0..self.depth { index ^= 1 << bit; path.push(lazy_root::<H>(self.leaves[index..][0..(1 << bit)].to_vec())); index &= usize::MAX << (bit + 1); } (pos, path) }) } /// Marks the specified tree state value as a value we're no longer /// interested in maintaining a witness for. Returns true if successful and /// false if the value is not a known witness. fn remove_witness(&mut self, value: &H) -> bool { if let Some((position, _)) = self .witnesses .iter() .enumerate() .find(|witness| (witness.1).1 == *value) { self.witnesses.remove(position); true } else { false } } /// Marks the current tree state as a checkpoint if it is not already a /// checkpoint. fn checkpoint(&mut self) { self.checkpoints.push(self.current_position); if self.checkpoints.len() > self.max_checkpoints { self.drop_oldest_checkpoint(); } } /// Rewinds the tree state to the previous checkpoint. This function will /// fail and return false if there is no previous checkpoint or in the event /// witness data would be destroyed in the process. fn rewind(&mut self) -> bool { if let Some(checkpoint) = self.checkpoints.pop() { if self.witnesses.iter().any(|&(pos, _)| pos >= checkpoint) { self.checkpoints.push(checkpoint); return false; } self.current_position = checkpoint; if checkpoint != (1 << self.depth) { self.leaves[checkpoint..].fill(H::empty_leaf()); } true } else { false } } /// Start a recording of append operations performed on a tree. fn recording(&self) -> CompleteRecording<H> { CompleteRecording { start_position: self.current_position, current_position: self.current_position, depth: self.depth, appends: vec![], } } /// Plays a recording of append operations back. Returns true if successful /// and false if the recording is incompatible with the current tree state. fn play(&mut self, recording: &CompleteRecording<H>) -> bool { #[allow(clippy::suspicious_operation_groupings)] if recording.start_position == self.current_position && self.depth == recording.depth { for val in recording.appends.iter() { self.append(val); } true } else { false } } } #[derive(Clone)] pub struct CompleteRecording<H: Hashable> { start_position: usize, current_position: usize, depth: usize, appends: Vec<H>, } impl<H: Hashable + Clone> Recording<H> for CompleteRecording<H> { /// Appends a new value to the tree at the next available slot. Returns true /// if successful and false if the tree is full. fn append(&mut self, value: &H) -> bool { if self.current_position == (1 << self.depth) { false } else { self.appends.push(value.clone()); self.current_position += 1; true } } /// Plays a recording of append operations back. Returns true if successful /// and false if the provided recording is incompatible with `Self`. fn play(&mut self, recording: &Self) -> bool { #[allow(clippy::suspicious_operation_groupings)] if self.current_position == recording.start_position && self.depth == recording.depth { self.appends.extend_from_slice(&recording.appends); self.current_position = recording.current_position; true } else { false } } } pub(crate) fn lazy_root<H: Hashable + Clone>(mut leaves: Vec<H>) -> H { //leaves are always at level zero, so we start there. let mut level = Altitude::zero(); while leaves.len() != 1 { leaves = leaves .iter() .enumerate() .filter(|(i, _)| (i % 2) == 0) .map(|(_, a)| a) .zip( leaves .iter() .enumerate() .filter(|(i, _)| (i % 2) == 1) .map(|(_, b)| b), ) .map(|(a, b)| H::combine(level, a, b)) .collect(); level = level + 1; } leaves[0].clone() } #[cfg(test)] mod tests { use crate::tests::{compute_root_from_auth_path, SipHashable}; use crate::{Altitude, Frontier, Hashable, Tree}; use super::CompleteTree; #[test] fn correct_empty_root() { const DEPTH: u8 = 5; let mut expected = SipHashable(0u64); for lvl in 0u8..DEPTH { expected = SipHashable::combine(lvl.into(), &expected, &expected); } let tree = CompleteTree::<SipHashable>::new(DEPTH as usize, 100); assert_eq!(tree.root(), expected); } #[test] fn correct_root() { const DEPTH: usize = 3; let values = (0..(1 << DEPTH)).into_iter().map(SipHashable); let mut tree = CompleteTree::<SipHashable>::new(DEPTH, 100); for value in values { assert!(tree.append(&value)); } assert!(!tree.append(&SipHashable(0))); let expected = SipHashable::combine( <Altitude>::from(2), &SipHashable::combine( Altitude::one(), &SipHashable::combine(Altitude::zero(), &SipHashable(0), &SipHashable(1)), &SipHashable::combine(Altitude::zero(), &SipHashable(2), &SipHashable(3)), ), &SipHashable::combine( Altitude::one(), &SipHashable::combine(Altitude::zero(), &SipHashable(4), &SipHashable(5)), &SipHashable::combine(Altitude::zero(), &SipHashable(6), &SipHashable(7)), ), ); assert_eq!(tree.root(), expected); } #[test] fn correct_auth_path() { const DEPTH: usize = 3; let values = (0..(1 << DEPTH)).into_iter().map(SipHashable); let mut tree = CompleteTree::<SipHashable>::new(DEPTH, 100); for value in values { assert!(tree.append(&value)); tree.witness(); } assert!(!tree.append(&SipHashable(0))); let expected = SipHashable::combine( <Altitude>::from(2), &SipHashable::combine( Altitude::one(), &SipHashable::combine(Altitude::zero(), &SipHashable(0), &SipHashable(1)), &SipHashable::combine(Altitude::zero(), &SipHashable(2), &SipHashable(3)), ), &SipHashable::combine( Altitude::one(), &SipHashable::combine(Altitude::zero(), &SipHashable(4), &SipHashable(5)), &SipHashable::combine(Altitude::zero(), &SipHashable(6), &SipHashable(7)), ), ); assert_eq!(tree.root(), expected); for i in 0..(1 << DEPTH) { let (position, path) = tree.authentication_path(&SipHashable(i)).unwrap(); assert_eq!( compute_root_from_auth_path(SipHashable(i), position, &path), expected ); } } }
//! Authentication Flow interface use std::fmt; use futures::Future as StdFuture; use url::form_urlencoded; use crate::Future; use crate::Modio; use crate::ModioMessage; /// Various forms of authentication credentials supported by [mod.io](https://mod.io). #[derive(Clone, Debug, PartialEq)] pub enum Credentials { ApiKey(String), Token(String), } impl fmt::Display for Credentials { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Credentials::ApiKey(key) => f.write_str(&key), Credentials::Token(token) => f.write_str(&token), } } } /// Various forms of supported external platforms. pub enum Service { Steam(u64), Gog(u64), } /// Authentication Flow interface to retrieve access tokens. See the [mod.io Authentication /// docs](https://docs.mod.io/#email-authentication-flow) for more information. /// /// # Example /// ```no_run /// use std::io::{self, Write}; /// use tokio::runtime::Runtime; /// /// use modio::error::Error; /// use modio::{Credentials, Modio}; /// /// fn prompt(prompt: &str) -> io::Result<String> { /// print!("{}", prompt); /// io::stdout().flush()?; /// let mut buffer = String::new(); /// io::stdin().read_line(&mut buffer)?; /// Ok(buffer.trim().to_string()) /// } /// /// fn main() -> Result<(), Error> { /// let mut rt = Runtime::new().expect("new rt"); /// let modio = Modio::new( /// Credentials::ApiKey(String::from("api-key")), /// )?; /// /// let email = prompt("Enter email: ").expect("read email"); /// rt.block_on(modio.auth().request_code(&email))?; /// /// let code = prompt("Enter security code: ").expect("read code"); /// let token = rt.block_on(modio.auth().security_code(&code))?; /// /// // Consume the endpoint and create an endpoint with new credentials. /// let _modio = modio.with_credentials(token); /// /// Ok(()) /// } /// ``` pub struct Auth { modio: Modio, } #[derive(Deserialize)] struct AccessToken { access_token: String, } impl Auth { pub(crate) fn new(modio: Modio) -> Self { Self { modio } } /// Request a security code be sent to the email of the user. [required: apikey] pub fn request_code(&self, email: &str) -> Future<()> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("email", email) .finish(); Box::new( self.modio .post::<ModioMessage, _>("/oauth/emailrequest", data) .map(|_| ()), ) } /// Get the access token for a security code. [required: apikey] pub fn security_code(&self, code: &str) -> Future<Credentials> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("security_code", code) .finish(); Box::new( self.modio .post::<AccessToken, _>("/oauth/emailexchange", data) .map(|token| Credentials::Token(token.access_token)), ) } /// Link an external account. Requires an auth token from the external platform. /// /// See the [mod.io docs](https://docs.mod.io/#link-external-account) for more information. pub fn link(&self, email: &str, service: Service) -> Future<()> { token_required!(self.modio); let (service, id) = match service { Service::Steam(id) => ("steam", id.to_string()), Service::Gog(id) => ("gog", id.to_string()), }; let data = form_urlencoded::Serializer::new(String::new()) .append_pair("email", email) .append_pair("service", service) .append_pair("service_id", &id) .finish(); Box::new( self.modio .post::<ModioMessage, _>("/external/link", data) .map(|_| ()), ) } /// Get the access token for an encrypted gog app ticket. [required: apikey] /// /// See the [mod.io docs](https://docs.mod.io/#authenticate-via-gog-galaxy) for more /// information. pub fn gog_auth(&self, ticket: &str) -> Future<Credentials> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("appdata", ticket) .finish(); Box::new( self.modio .post::<AccessToken, _>("/external/galaxyauth", data) .map(|token| Credentials::Token(token.access_token)), ) } /// Get the access token for an encrypted steam app ticket. [required: apikey] /// /// See the [mod.io docs](https://docs.mod.io/#authenticate-via-steam) for more information. pub fn steam_auth(&self, ticket: &str) -> Future<Credentials> { apikey_required!(self.modio); let data = form_urlencoded::Serializer::new(String::new()) .append_pair("appdata", ticket) .finish(); Box::new( self.modio .post::<AccessToken, _>("/external/steamauth", data) .map(|token| Credentials::Token(token.access_token)), ) } }
#![allow(dead_code)] use super::error::{PolarResult, RolesValidationError}; use super::events::ResultEvent; use super::rules::GenericRule; use super::terms::*; use std::collections::{HashMap, HashSet}; struct Action { typ: String, name: String, } struct Role { name: String, typ: String, actions: Vec<String>, implied_roles: Vec<String>, } struct Resource { typ: String, name: String, actions: Vec<String>, roles: HashMap<String, Role>, } pub const VALIDATE_ROLES_CONFIG_RESOURCES: &str = "resource(resource, name, actions, roles)"; pub fn validate_actor_has_role_for_resource( rules: &HashMap<Symbol, GenericRule>, ) -> PolarResult<()> { if let Some(actor_role) = rules.get(&sym!("actor_has_role_for_resource")) { let args = vec![ term!(value!(sym!("actor"))), term!(value!(sym!("action"))), term!(value!(sym!("resource"))), ]; let applicable_rules = actor_role.get_applicable_rules(&args); if applicable_rules.is_empty() { return Err(RolesValidationError( "Need to define `actor_has_role_for_resource(actor, role_name, resource)` predicate to use Oso Roles. Make sure to load policy before calling Oso.enable_roles().".to_owned(), ) .into()); } } else { return Err(RolesValidationError( "Need to define `actor_has_role_for_resource(actor, role_name, resource)` predicate to use Oso Roles. Make sure to load policy before calling Oso.enable_roles().".to_owned(), ) .into()); } Ok(()) } pub fn validate_roles_config( rules: &HashMap<Symbol, GenericRule>, roles_config: Vec<Vec<ResultEvent>>, ) -> PolarResult<()> { validate_actor_has_role_for_resource(rules)?; let role_resources = roles_config.first().ok_or_else(|| { // TODO: add link to docs in error message RolesValidationError( "Need to define at least one `resource(type, name, actions, roles)` predicate to use Oso Roles.".to_owned(), ) })?; if role_resources.is_empty() { return Err(RolesValidationError( "Need to define at least one `resource(type, name, actions, roles)` predicate to use Oso Roles.".to_owned(), ) .into()); } let mut resources = HashMap::new(); for result in role_resources { let resource_def = result .bindings .get(&Symbol::new("resource")) .unwrap() .value(); let resource_name = result.bindings.get(&Symbol::new("name")).unwrap().value(); let resource_actions = result .bindings .get(&Symbol::new("actions")) .unwrap() .value(); let resource_roles = result.bindings.get(&Symbol::new("roles")).unwrap().value(); let typ = { if let Value::Expression(Operation { operator: Operator::And, args: and_args, }) = resource_def { match &and_args[..] { [arg] => { if let Value::Expression(Operation { operator: Operator::Isa, args: isa_args, }) = arg.value() { match &isa_args[..] { [this_expr, typ_expr] => { if let Value::Variable(Symbol(sym)) = this_expr.value() { if sym != "_this" { return Err(RolesValidationError( "Invalid resource, no type specializer.".to_owned(), ) .into()); } } else { return Err(RolesValidationError( "Invalid resource, no type specializer.".to_owned(), ) .into()); } if let Value::Pattern(Pattern::Instance(InstanceLiteral { tag, .. })) = typ_expr.value() { tag.0.clone() } else { return Err(RolesValidationError( "Invalid resource, no type specializer.".to_owned(), ) .into()); } } _ => { return Err(RolesValidationError( "Invalid resource, no type specializer.".to_owned(), ) .into()); } } } else { return Err(RolesValidationError( "Invalid resource, no type specializer.".to_owned(), ) .into()); } } _ => { return Err(RolesValidationError( "Invalid resource, no type specializer.".to_owned(), ) .into()); } } } else { return Err(RolesValidationError( "Invalid resource, no type specializer.".to_owned(), ) .into()); } }; let name = { if let Value::String(name) = resource_name { name.clone() } else { return Err(RolesValidationError( "Invalid resource, name is not a string.".to_owned(), ) .into()); } }; let actions: Vec<String> = { let mut action_strings = vec![]; match resource_actions { Value::List(actions) => { for a in actions { if let Value::String(action) = a.value() { action_strings.push(action.clone()); } else { return Err(RolesValidationError( "Invalid action, not a string.".to_owned(), ) .into()); } } } Value::Variable(_) => (), _ => return Err(RolesValidationError("Invalid actions.".to_owned()).into()), } action_strings }; let mut acts = HashSet::new(); for action in &actions { if acts.contains(action) { return Err(RolesValidationError(format!( "Duplicate action {} for {}.", action, typ )) .into()); } acts.insert(action.to_owned()); } let mut role_definitions = HashMap::new(); if let Value::Dictionary(Dictionary { fields: dict }) = resource_roles { for (name_sym, definition) in dict.iter() { let role_name = name_sym.0.clone(); if let Value::Dictionary(Dictionary { fields: def_dict }) = definition.value() { for key in def_dict.keys() { if key.0 != "permissions" && key.0 != "implies" { return Err(RolesValidationError(format!( "Role definition contains invalid key: {}", key.0 )) .into()); } } let actions = { let actions_value = def_dict.get(&Symbol::new("permissions")); if let Some(actions_term) = actions_value { if let Value::List(actions_list) = actions_term.value() { let mut actions = vec![]; for action_term in actions_list { if let Value::String(action) = action_term.value() { actions.push(action.clone()) } else { return Err(RolesValidationError(format!( "Invalid actions for role {}, must be a string.", role_name )) .into()); } } actions } else { return Err(RolesValidationError(format!( "Invalid actions for role {}", role_name )) .into()); } } else { vec![] } }; let implications = { let implications_value = def_dict.get(&Symbol::new("implies")); if let Some(implications_term) = implications_value { if let Value::List(implications_list) = implications_term.value() { let mut implications = vec![]; for implies_term in implications_list { if let Value::String(implies) = implies_term.value() { implications.push(implies.clone()) } else { return Err(RolesValidationError(format!( "Invalid implies for role {}, must be a string.", role_name )) .into()); } } implications } else { return Err(RolesValidationError(format!( "Invalid implies for role {}", role_name )) .into()); } } else { vec![] } }; if actions.is_empty() && implications.is_empty() { return Err(RolesValidationError( "Must define actions or implications for a role.".to_owned(), ) .into()); } let role = Role { name: role_name.clone(), typ: typ.clone(), actions, implied_roles: implications, }; if role_definitions.contains_key(&role_name) { return Err(RolesValidationError(format!( "Duplicate role name {}.", role_name )) .into()); } role_definitions.insert(role_name, role) } else { return Err(RolesValidationError("Invalid role definitions".to_owned()).into()); }; } } if actions.is_empty() && role_definitions.is_empty() { return Err(RolesValidationError("Must define actions or roles.".to_owned()).into()); } let resource = Resource { typ: typ.clone(), name: name.clone(), actions, roles: role_definitions, }; if resources.contains_key(&name) { return Err(RolesValidationError(format!("Duplicate resource name {}.", name)).into()); } resources.insert(name, resource); } Ok(()) }
use async_graphql::*; use futures_util::stream::{Stream, StreamExt}; #[derive(SimpleObject)] struct Object1 { a: i32, } #[derive(SimpleObject)] struct Object2 { b: i32, } #[derive(SimpleObject)] struct Object3 { c: i32, } #[tokio::test] pub async fn test_merged_object_macro() { #[derive(MergedObject)] struct MyObj(Object1, Object2, Object3); struct Query; #[Object] impl Query { async fn obj(&self) -> MyObj { MyObj(Object1 { a: 10 }, Object2 { b: 20 }, Object3 { c: 30 }) } } let schema = Schema::new(Query, EmptyMutation, EmptySubscription); let query = "{ obj { a b c } }"; assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "obj": { "a": 10, "b": 20, "c": 30, } }) ); } #[tokio::test] pub async fn test_merged_object_derive() { #[derive(MergedObject)] struct MyObj(Object1, Object2, Object3); struct Query; #[Object] impl Query { async fn obj(&self) -> MyObj { MyObj(Object1 { a: 10 }, Object2 { b: 20 }, Object3 { c: 30 }) } } let schema = Schema::new(Query, EmptyMutation, EmptySubscription); let query = "{ obj { a b c } }"; assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "obj": { "a": 10, "b": 20, "c": 30, } }) ); } #[tokio::test] pub async fn test_merged_object_default() { mod a { use super::*; #[derive(SimpleObject)] pub struct QueryA { pub a: i32, } impl Default for QueryA { fn default() -> Self { Self { a: 10 } } } } mod b { use super::*; #[derive(SimpleObject)] pub struct QueryB { pub b: i32, } impl Default for QueryB { fn default() -> Self { Self { b: 20 } } } } #[derive(MergedObject, Default)] struct Query(a::QueryA, b::QueryB); let schema = Schema::new(Query::default(), EmptyMutation, EmptySubscription); let query = "{ a b }"; assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "a": 10, "b": 20, }) ); } #[tokio::test] pub async fn test_merged_subscription() { #[derive(Default)] struct Subscription1; #[Subscription] impl Subscription1 { async fn events1(&self) -> impl Stream<Item = i32> { futures_util::stream::iter(0..10) } } #[derive(Default)] struct Subscription2; #[Subscription] impl Subscription2 { async fn events2(&self) -> impl Stream<Item = i32> { futures_util::stream::iter(10..20) } } #[derive(MergedSubscription, Default)] struct Subscription(Subscription1, Subscription2); struct Query; #[Object] impl Query { async fn value(&self) -> i32 { 10 } } let schema = Schema::new(Query, EmptyMutation, Subscription::default()); { let mut stream = schema .execute_stream("subscription { events1 }") .map(|resp| resp.into_result().unwrap().data); for i in 0i32..10 { assert_eq!( value!({ "events1": i, }), stream.next().await.unwrap() ); } assert!(stream.next().await.is_none()); } { let mut stream = schema .execute_stream("subscription { events2 }") .map(|resp| resp.into_result().unwrap().data); for i in 10i32..20 { assert_eq!( value!({ "events2": i, }), stream.next().await.unwrap() ); } assert!(stream.next().await.is_none()); } } #[tokio::test] pub async fn test_merged_entity() { #[derive(SimpleObject)] struct Fruit { id: ID, name: String, } #[derive(SimpleObject)] struct Vegetable { id: ID, name: String, } #[derive(Default)] struct FruitQuery; #[Object] impl FruitQuery { #[graphql(entity)] async fn get_fruit(&self, id: ID) -> Fruit { Fruit { id, name: "Apple".into(), } } } #[derive(Default)] struct VegetableQuery; #[Object] impl VegetableQuery { #[graphql(entity)] async fn get_vegetable(&self, id: ID) -> Vegetable { Vegetable { id, name: "Carrot".into(), } } } #[derive(MergedObject, Default)] struct Query(FruitQuery, VegetableQuery); let schema = Schema::new(Query::default(), EmptyMutation, EmptySubscription); let query = r#"{ _entities(representations: [{__typename: "Fruit", id: "1"}]) { __typename ... on Fruit { id name } } }"#; assert_eq!( schema.execute(query).await.into_result().unwrap().data, value!({ "_entities": [ {"__typename": "Fruit", "id": "1", "name": "Apple"}, ] }) ); } #[tokio::test] pub async fn test_issue_316() { #[derive(SimpleObject)] struct Fruit { id: ID, name: String, } struct Query; #[Object] impl Query { #[graphql(entity)] async fn get_fruit(&self, id: ID) -> Fruit { Fruit { id, name: "Apple".into(), } } } #[derive(Default)] struct Mutation1; #[Object] impl Mutation1 { async fn action1(&self) -> Fruit { Fruit { id: ID("hello".into()), name: "Apple".into(), } } } #[derive(MergedObject, Default)] struct Mutation(Mutation1); // This works let schema = Schema::new(Query, Mutation1, EmptySubscription); assert!(schema.execute("{ _service { sdl }}").await.is_ok()); // This fails let schema = Schema::new(Query, Mutation::default(), EmptySubscription); assert!(schema.execute("{ _service { sdl }}").await.is_ok()); } #[tokio::test] pub async fn test_issue_333() { #[derive(SimpleObject)] struct ObjectA<'a> { field_a: &'a str, } #[derive(SimpleObject)] struct ObjectB<'a> { field_b: &'a str, } #[derive(MergedObject)] pub struct Object<'a>(ObjectA<'a>, ObjectB<'a>); struct Query { a: String, b: String, } #[Object] impl Query { async fn obj(&self) -> Object<'_> { Object(ObjectA { field_a: &self.a }, ObjectB { field_b: &self.b }) } } let schema = Schema::new( Query { a: "haha".to_string(), b: "hehe".to_string(), }, EmptyMutation, EmptySubscription, ); assert_eq!( schema .execute("{ obj { fieldA fieldB } }") .await .into_result() .unwrap() .data, value!({ "obj": { "fieldA": "haha", "fieldB": "hehe", } }) ) } #[tokio::test] pub async fn test_issue_539() { // https://github.com/async-graphql/async-graphql/issues/539#issuecomment-862209442 struct Query; #[Object] impl Query { async fn value(&self) -> i32 { 10 } } #[derive(SimpleObject)] struct A { a: Option<Box<A>>, } #[derive(SimpleObject)] struct B { b: Option<Box<B>>, } #[derive(MergedObject)] pub struct Mutation(A, B); let schema = Schema::new( Query, Mutation(A { a: None }, B { b: None }), EmptySubscription, ); assert_eq!( schema .execute("{ __type(name: \"Mutation\") { fields { name type { name } } } }") .await .into_result() .unwrap() .data, value!({ "__type": { "fields": [ { "name": "a", "type": { "name": "A" }, }, { "name": "b", "type": { "name": "B" }, } ] } }) ) } #[tokio::test] pub async fn test_issue_694() { struct Query; #[Object] impl Query { async fn test(&self) -> bool { true } } #[derive(MergedObject)] pub struct QueryRoot(Query, EmptyMutation); let schema = Schema::new( QueryRoot(Query, EmptyMutation), EmptyMutation, EmptySubscription, ); assert_eq!( schema.execute("{ test }").await.into_result().unwrap().data, value!({ "test": true, }) ); }
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::any::Any; use std::sync::Arc; use std::time::Instant; use common_base::base::GlobalUniqName; use common_exception::ErrorCode; use common_exception::Result; use common_expression::arrow::serialize_column; use common_expression::BlockEntry; use common_expression::BlockMetaInfoDowncast; use common_expression::DataBlock; use common_pipeline_core::processors::port::InputPort; use common_pipeline_core::processors::port::OutputPort; use common_pipeline_core::processors::processor::Event; use common_pipeline_core::processors::Processor; use futures_util::future::BoxFuture; use opendal::Operator; use tracing::info; use crate::pipelines::processors::transforms::aggregator::aggregate_meta::AggregateMeta; use crate::pipelines::processors::transforms::aggregator::aggregate_meta::HashTablePayload; use crate::pipelines::processors::transforms::aggregator::serde::transform_group_by_serializer::serialize_group_by; use crate::pipelines::processors::transforms::group_by::HashMethodBounds; pub struct TransformGroupBySpillWriter<Method: HashMethodBounds> { method: Method, input: Arc<InputPort>, output: Arc<OutputPort>, operator: Operator, location_prefix: String, output_block: Option<DataBlock>, spilling_meta: Option<AggregateMeta<Method, ()>>, spilling_future: Option<BoxFuture<'static, Result<()>>>, } impl<Method: HashMethodBounds> TransformGroupBySpillWriter<Method> { pub fn create( input: Arc<InputPort>, output: Arc<OutputPort>, method: Method, operator: Operator, location_prefix: String, ) -> Box<dyn Processor> { Box::new(TransformGroupBySpillWriter::<Method> { method, input, output, operator, location_prefix, output_block: None, spilling_meta: None, spilling_future: None, }) } } #[async_trait::async_trait] impl<Method: HashMethodBounds> Processor for TransformGroupBySpillWriter<Method> { fn name(&self) -> String { String::from("TransformGroupBySpillWriter") } fn as_any(&mut self) -> &mut dyn Any { self } fn event(&mut self) -> Result<Event> { if self.output.is_finished() { self.input.finish(); return Ok(Event::Finished); } if !self.output.can_push() { self.input.set_not_need_data(); return Ok(Event::NeedConsume); } if self.spilling_future.is_some() { self.input.set_not_need_data(); return Ok(Event::Async); } if let Some(spilled_meta) = self.output_block.take() { self.output.push_data(Ok(spilled_meta)); return Ok(Event::NeedConsume); } if self.spilling_meta.is_some() { self.input.set_not_need_data(); return Ok(Event::Sync); } if self.input.has_data() { let mut data_block = self.input.pull_data().unwrap()?; if let Some(block_meta) = data_block .get_meta() .and_then(AggregateMeta::<Method, ()>::downcast_ref_from) { if matches!(block_meta, AggregateMeta::Spilling(_)) { self.input.set_not_need_data(); let block_meta = data_block.take_meta().unwrap(); self.spilling_meta = AggregateMeta::<Method, ()>::downcast_from(block_meta); return Ok(Event::Sync); } } self.output.push_data(Ok(data_block)); return Ok(Event::NeedConsume); } if self.input.is_finished() { self.output.finish(); return Ok(Event::Finished); } self.input.set_need_data(); Ok(Event::NeedData) } fn process(&mut self) -> Result<()> { if let Some(spilling_meta) = self.spilling_meta.take() { if let AggregateMeta::Spilling(payload) = spilling_meta { let (output_block, spilling_future) = spilling_group_by_payload( self.operator.clone(), &self.method, &self.location_prefix, payload, )?; self.output_block = Some(output_block); self.spilling_future = Some(spilling_future); return Ok(()); } return Err(ErrorCode::Internal( "TransformGroupBySpillWriter only recv AggregateMeta", )); } Ok(()) } async fn async_process(&mut self) -> Result<()> { if let Some(spilling_future) = self.spilling_future.take() { return spilling_future.await; } Ok(()) } } fn get_columns(data_block: DataBlock) -> Vec<BlockEntry> { data_block.columns().to_vec() } fn serialize_spill_file<Method: HashMethodBounds>( method: &Method, payload: HashTablePayload<Method, ()>, ) -> Result<(isize, usize, Vec<Vec<u8>>)> { let bucket = payload.bucket; let data_block = serialize_group_by(method, payload)?; let columns = get_columns(data_block); let mut total_size = 0; let mut columns_data = Vec::with_capacity(columns.len()); for column in columns.into_iter() { let column = column.value.as_column().unwrap(); let column_data = serialize_column(column); total_size += column_data.len(); columns_data.push(column_data); } Ok((bucket, total_size, columns_data)) } pub fn spilling_group_by_payload<Method: HashMethodBounds>( operator: Operator, method: &Method, location_prefix: &str, payload: HashTablePayload<Method, ()>, ) -> Result<(DataBlock, BoxFuture<'static, Result<()>>)> { let (bucket, total_size, data) = serialize_spill_file(method, payload)?; let unique_name = GlobalUniqName::unique(); let location = format!("{}/{}", location_prefix, unique_name); let columns_layout = data.iter().map(Vec::len).collect::<Vec<_>>(); let output_data_block = DataBlock::empty_with_meta( AggregateMeta::<Method, ()>::create_spilled(bucket, location.clone(), columns_layout), ); Ok(( output_data_block, Box::pin(async move { let instant = Instant::now(); // temp code: waiting https://github.com/datafuselabs/opendal/pull/1431 let mut write_data = Vec::with_capacity(total_size); for data in data.into_iter() { write_data.extend(data); } operator.write(&location, write_data).await?; info!( "Write aggregate spill {} successfully, elapsed: {:?}", location, instant.elapsed() ); Ok(()) }), )) }
use std::error::Error; use std::fmt; /// /// Enum for all of the possible `NodeId` errors that could occur. /// #[derive(Debug, Eq, PartialEq)] pub enum NodeIdError { /// Occurs when a `NodeId` is used on a `Tree` from which it did not originate. InvalidNodeIdForTree, /// Occurs when a `NodeId` is used on a `Tree` after the corresponding `Node` has been removed. NodeIdNoLongerValid, } impl NodeIdError { fn to_string(&self) -> &str { match *self { NodeIdError::InvalidNodeIdForTree => "The given NodeId belongs to a different Tree.", NodeIdError::NodeIdNoLongerValid => { "The given NodeId is no longer valid. The Node in question has been \ removed." } } } } impl fmt::Display for NodeIdError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "NodeIdError: {}", self.to_string()) } } impl Error for NodeIdError { fn description(&self) -> &str { self.to_string() } }
use std::{ path::PathBuf, sync::{ atomic::{AtomicBool, AtomicU8}, Arc, }, }; use parking_lot::RwLock; use rayon::prelude::*; use serde::{ser::SerializeTuple, Serialize}; use steamworks::PublishedFileId; use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher}; use crate::{GMAFile, Transaction, WorkshopItem}; const MAX_QUICK_RESULTS: u8 = 10; #[derive(Clone, Serialize, Debug)] #[serde(rename_all = "snake_case")] #[serde(tag = "source", content = "association")] pub enum SearchItemSource { InstalledAddons(PathBuf, Option<PublishedFileId>), MyWorkshop(PublishedFileId), WorkshopItem(PublishedFileId), } #[derive(Debug)] pub struct SearchItem { label: String, terms: Vec<String>, timestamp: u64, len: usize, source: SearchItemSource, } impl PartialOrd for SearchItem { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { let cmp1 = self.timestamp.partial_cmp(&other.timestamp).map(|ord| ord.reverse()); let cmp2 = self.len.partial_cmp(&other.len).map(|ord| ord.reverse()); cmp1.partial_cmp(&cmp2) } } impl Ord for SearchItem { fn cmp(&self, other: &Self) -> std::cmp::Ordering { let cmp1 = self.timestamp.cmp(&other.timestamp).reverse(); let cmp2 = self.len.cmp(&other.len).reverse(); cmp1.cmp(&cmp2) } } impl PartialEq for SearchItem { fn eq(&self, other: &Self) -> bool { match &self.source { SearchItemSource::InstalledAddons(a, _) => match &other.source { SearchItemSource::InstalledAddons(b, _) => a == b, _ => false, }, SearchItemSource::MyWorkshop(a) => match &other.source { SearchItemSource::MyWorkshop(b) => a == b, _ => false, }, _ => unreachable!(), } } } impl Eq for SearchItem {} impl SearchItem { pub fn new<D: Into<u64>>(source: SearchItemSource, label: String, mut terms: Vec<String>, timestamp: D) -> SearchItem { terms.shrink_to_fit(); terms.sort_by(|a, b| a.len().cmp(&b.len())); SearchItem { len: terms.iter().map(|x| x.len()).reduce(|a, b| a.max(b)).unwrap_or(0).max(label.len()), label, terms, timestamp: timestamp.into(), source, } } } impl Serialize for SearchItem { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let mut tup = serializer.serialize_tuple(2)?; tup.serialize_element(&self.label)?; tup.serialize_element(&self.source)?; tup.end() } } pub trait Searchable { fn search_item(&self) -> Option<SearchItem>; } impl Searchable for WorkshopItem { fn search_item(&self) -> Option<SearchItem> { let mut terms = self.tags.clone(); if let Some(steamid) = &self.steamid { terms.push(steamid.raw().to_string()); terms.push(steamid.steamid32()); } Some(SearchItem::new( SearchItemSource::MyWorkshop(self.id), self.title.to_owned(), terms, self.time_updated, )) } } impl Searchable for GMAFile { fn search_item(&self) -> Option<SearchItem> { let (label, terms) = match &self.metadata { Some(metadata) => { let mut terms = metadata.tags().cloned().unwrap_or_default(); if let Some(addon_type) = metadata.addon_type() { terms.push(addon_type.to_string()); } (metadata.title().to_owned(), terms) } None => { if !self.extracted_name.is_empty() { (self.extracted_name.to_owned(), vec![]) } else { return None; } } }; Some(SearchItem::new( SearchItemSource::InstalledAddons( dunce::canonicalize(&self.path).unwrap_or_else(|_| self.path.to_owned()), self.id.to_owned(), ), label, terms, self.modified.unwrap_or(0), )) } } impl Searchable for std::sync::Arc<crate::webview::Addon> { fn search_item(&self) -> Option<SearchItem> { match &**self { crate::webview::Addon::Installed(installed) => installed.search_item(), crate::webview::Addon::Workshop(workshop) => workshop.search_item(), } } } #[derive(Clone, Copy)] struct ResultsPtr(*mut Vec<Option<(i64, Arc<SearchItem>)>>); unsafe impl Send for ResultsPtr {} unsafe impl Sync for ResultsPtr {} pub struct Search { channel: Transaction, dirty: AtomicBool, items: RwLock<Vec<Arc<SearchItem>>>, matcher: SkimMatcherV2, } impl Search { pub fn init() -> Search { Self { channel: transaction!(), items: RwLock::new(Vec::new()), matcher: SkimMatcherV2::default().ignore_case().use_cache(true), dirty: AtomicBool::new(false), } } pub fn dirty(&self) { if !self.dirty.load(std::sync::atomic::Ordering::Acquire) { return; } let mut items = self.items.write(); items.par_sort(); items.dedup(); } pub fn add<V: Searchable>(&self, item: &V) { if let Some(search_item) = item.search_item() { let search_item = Arc::new(search_item); let mut items = self.items.write(); let pos = match items.binary_search(&search_item) { Ok(_) => return, Err(pos) => pos, }; items.insert(pos, search_item); } } pub fn reserve(&self, amount: usize) { self.items.write().reserve(amount); } pub fn add_bulk<V: Searchable>(&self, items: &Vec<V>) { self.dirty.store(true, std::sync::atomic::Ordering::Release); let mut store = self.items.write(); store.reserve(items.len()); store.extend(items.into_iter().filter_map(|v| v.search_item().map(|search_item| Arc::new(search_item)))); } pub fn quick(&self, query: String) -> (Vec<Arc<SearchItem>>, bool) { game_addons!().discover_addons(); //steam!().discover_my_workshop_addons(); self.dirty(); let i = AtomicU8::new(0); let has_more = AtomicBool::new(false); let mut results: Vec<Option<(i64, Arc<SearchItem>)>> = vec![None; MAX_QUICK_RESULTS as usize]; self.items .read() .par_iter() .try_for_each_with(ResultsPtr(&mut results as *mut _), |results, search_item| { if i.load(std::sync::atomic::Ordering::Acquire) >= MAX_QUICK_RESULTS { has_more.store(true, std::sync::atomic::Ordering::Release); return Err(()); } if search_item.len < query.len() { return Ok(()); } let mut winner = None; if search_item.label.len() >= query.len() { if let Some(score) = self.matcher.fuzzy_match(&search_item.label, &query) { winner = Some(score); } } for term in search_item.terms.iter() { if term.len() < query.len() { continue; } if let Some(score) = self.matcher.fuzzy_match(term, &query) { if winner.is_none() || winner.unwrap() < score { winner = Some(score); } } } if let Some(score) = winner { let i = i.fetch_add(1, std::sync::atomic::Ordering::SeqCst); if i >= MAX_QUICK_RESULTS { has_more.store(true, std::sync::atomic::Ordering::Release); return Err(()); } else { (unsafe { &mut *results.0 })[i as usize] = Some((score, search_item.clone())); } } Ok(()) }) .ok(); let i = i.into_inner(); if i == 0 { (vec![], false) } else if i == 1 { (vec![results[0].take().unwrap().1], false) } else { let has_more = has_more.load(std::sync::atomic::Ordering::Acquire); results.sort_by(|a, b| { if let Some(a) = a { if let Some(b) = b { return a.0.cmp(&b.0).reverse(); } else { return std::cmp::Ordering::Less; } } else if b.is_some() { return std::cmp::Ordering::Greater; } return std::cmp::Ordering::Equal; }); (results.into_iter().filter_map(|x| x.map(|x| x.1)).collect(), has_more) } } pub fn full(&'static self, query: String) -> u32 { game_addons!().discover_addons(); //steam!().discover_my_workshop_addons(); self.dirty(); let transaction = transaction!(); let id = transaction.id; rayon::spawn(move || { self.items.read().par_iter().for_each(|search_item| { if search_item.len < query.len() { return; } let mut winner = None; if search_item.label.len() >= query.len() { if let Some(score) = self.matcher.fuzzy_match(&search_item.label, &query) { winner = Some(score); } } for term in search_item.terms.iter() { if term.len() < query.len() { continue; } if let Some(score) = self.matcher.fuzzy_match(term, &query) { if winner.is_none() || winner.unwrap() < score { winner = Some(score); } } } if let Some(score) = winner { transaction.data((score, search_item.clone())); } }); transaction.finished(turbonone!()); }); id } pub fn clear(&self) { *self.items.write() = Vec::new(); } } #[tauri::command] fn search(salt: u32, query: String) { search!().channel.data((salt, search!().quick(query))); } #[tauri::command] fn full_search(query: String) -> u32 { search!().full(query) } #[tauri::command] fn search_channel() -> u32 { search!().channel.id }
extern crate chrono; use chrono::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct HabitLog { pub id: u32, pub quantum: f64, pub notes: String, pub date: NaiveDate, } impl HabitLog { // as well as to the methods... pub fn new(id: u32, quantum: f64, notes: Option<String>) -> Self { Self { id, quantum, notes: match notes { Some(n) if n.len() > 280 => { panic!("Log's note cannot be longer than {} characters!", 280) } Some(n) => n, None => "".into(), }, date: Local::today().naive_local(), } } }
#![allow(dead_code)] pub struct CrabCups<const N: usize> { cups: Vec<usize>, current: usize, steps: usize, } impl <const N: usize> CrabCups <{N}> { pub fn load(labels: &[usize]) -> CrabCups<{N}> { let mut cups = vec![0; N]; for i in 0..N { let cup_index = if i < labels.len() { labels[i] - 1 } else { i }; let next_cup = if (i+1)%N < labels.len() { labels[(i+1)%N] - 1 } else { (i + 1) % N }; cups[cup_index] = next_cup; } CrabCups { current: labels[0] - 1, steps: 0, cups, } } pub fn step(&mut self) { let r1 = self.cups[self.current]; let r2 = self.cups[r1]; let r3 = self.cups[r2]; self.cups[self.current] = self.cups[r3]; for r in &[r1, r2, r3] { self.cups[*r] = N } let mut destination = self.current; destination = loop { destination = (destination + N - 1) % N; if self.cups[destination] != N { break destination; } }; let cup = self.cups[destination]; self.cups[destination] = r1; self.cups[r1] = r2; self.cups[r2] = r3; self.cups[r3] = cup; self.current = self.cups[self.current]; self.steps += 1; } fn to_labels(&self) -> Vec<usize> { let mut cups = self.cups.clone(); let mut next_index = self.steps % N; let mut next_cup = self.current; for _ in 0..N { cups[next_index] = next_cup + 1; next_cup = self.cups[next_cup]; next_index = (next_index + 1) % N } cups } pub fn into_iter(mut self) -> impl Iterator<Item = Vec<usize>> { std::iter::from_fn(move || { self.step(); Some(self.to_labels()) }) } } pub fn day23() { let input = [2,1,9,3,4,7,8,6,5]; let cups: CrabCups<9> = CrabCups::load(&input); println!("crab_cups part 1: {:?}", cups.into_iter().nth(99)); let mut cups: CrabCups<1000000> = CrabCups::load(&input); for _ in 0..10000000 { cups.step(); } let i1 = cups.cups[0] as u64; let i2 = cups.cups[i1 as usize] as u64; println!("crab_cups part 2: {:?}", (i1+1) * (i2+1)); } #[cfg(test)] mod tests { use crate::day23::*; #[test] pub fn test_day23() { let mut cups: CrabCups<9> = CrabCups::load(&[3,8,9,1,2,5,4,6,7]); assert_eq!( cups.cups, vec![1,4,7,5,3,6,2,8,0] ); cups.step(); assert_eq!( cups.cups, vec![4,7,1,5,3,6,2,8,0] ); assert_eq!( cups.current, 1 ); assert_eq!( cups.to_labels(), vec![3,2,8,9,1,5,4,6,7] ); let mut i = cups.into_iter(); assert_eq!( i.nth(0), Some(vec![3,2,5,4,6,7,8,9,1]) ); assert_eq!( i.nth(7), Some(vec![5,8,3,7,4,1,9,2,6]) ); } #[test] pub fn test_day23_big() { let mut cups: CrabCups<1000000> = CrabCups::load(&[3,8,9,1,2,5,4,6,7]); assert_eq!( cups.cups[0..11], [1,4,7,5,3,6,9,8,0,10,11], ); for _ in 0..10000000 { cups.step(); } assert_eq!( cups.cups[0], 934000 ); assert_eq!( cups.cups[934000], 159791 ); } }
#[derive(Debug)] struct User { name: String, email: String, user_id: String, first_name: String, last_name: String, } impl User { fn concatenate_first_last_name(&self) -> String { let mut first_name = String::from(&self.first_name); let last_name = String::from(&self.last_name); first_name.push_str(&last_name); first_name } } impl User { fn convert_name_to_upper_case(&self) -> String { let upper_case_name = String::from(&self.first_name).to_uppercase(); upper_case_name } } fn main() { let user1 = User { email: String::from("another@example.com"), user_id: String::from("anotherusername567"), name: String::from("John"), first_name: String::from("John123 "), last_name: String::from("John456"), }; println!("{}", User::concatenate_first_last_name(&user1)); println!("{}", user1.convert_name_to_upper_case()); // println!("{}", user1); // fn create_user(email: String, userId: String, name: String) -> User { // return User { // email, // userId, // name, // }; // } // let user2 = create_user( // String::from("user1@gmail.com"), // String::from("user1@gmail.com"), // String::from("user1@gmail.com"), // ); // println!("user 1 {}", user1.email); }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn parse_http_generic_error( response: &http::Response<bytes::Bytes>, ) -> Result<smithy_types::Error, smithy_json::deserialize::Error> { crate::json_errors::parse_generic_error(response.body(), response.headers()) } pub fn deser_structure_internal_server_exceptionjson_err( input: &[u8], mut builder: crate::error::internal_server_exception::Builder, ) -> Result<crate::error::internal_server_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Code" => { builder = builder.set_code( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_invalid_request_exceptionjson_err( input: &[u8], mut builder: crate::error::invalid_request_exception::Builder, ) -> Result<crate::error::invalid_request_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Code" => { builder = builder.set_code( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "RequiredParameters" => { builder = builder.set_required_parameters( crate::json_deser::deser_list_parameter_list(tokens)?, ); } "MutuallyExclusiveParameters" => { builder = builder.set_mutually_exclusive_parameters( crate::json_deser::deser_list_parameter_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_limit_exceeded_exceptionjson_err( input: &[u8], mut builder: crate::error::limit_exceeded_exception::Builder, ) -> Result<crate::error::limit_exceeded_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Code" => { builder = builder.set_code( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "ResourceType" => { builder = builder.set_resource_type( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_create_lifecycle_policy( input: &[u8], mut builder: crate::output::create_lifecycle_policy_output::Builder, ) -> Result<crate::output::create_lifecycle_policy_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "PolicyId" => { builder = builder.set_policy_id( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_resource_not_found_exceptionjson_err( input: &[u8], mut builder: crate::error::resource_not_found_exception::Builder, ) -> Result<crate::error::resource_not_found_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Code" => { builder = builder.set_code( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "ResourceType" => { builder = builder.set_resource_type( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "ResourceIds" => { builder = builder.set_resource_ids( crate::json_deser::deser_list_policy_id_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_get_lifecycle_policies( input: &[u8], mut builder: crate::output::get_lifecycle_policies_output::Builder, ) -> Result<crate::output::get_lifecycle_policies_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Policies" => { builder = builder.set_policies( crate::json_deser::deser_list_lifecycle_policy_summary_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_get_lifecycle_policy( input: &[u8], mut builder: crate::output::get_lifecycle_policy_output::Builder, ) -> Result<crate::output::get_lifecycle_policy_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Policy" => { builder = builder.set_policy( crate::json_deser::deser_structure_lifecycle_policy(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_list_tags_for_resource( input: &[u8], mut builder: crate::output::list_tags_for_resource_output::Builder, ) -> Result<crate::output::list_tags_for_resource_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Tags" => { builder = builder.set_tags(crate::json_deser::deser_map_tag_map(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn or_empty_doc(data: &[u8]) -> &[u8] { if data.is_empty() { b"{}" } else { data } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_parameter_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_policy_id_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_lifecycle_policy_summary_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::LifecyclePolicySummary>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_lifecycle_policy_summary(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_lifecycle_policy<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::LifecyclePolicy>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::LifecyclePolicy::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "PolicyId" => { builder = builder.set_policy_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Description" => { builder = builder.set_description( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "State" => { builder = builder.set_state( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::GettablePolicyStateValues::from( u.as_ref(), ) }) }) .transpose()?, ); } "StatusMessage" => { builder = builder.set_status_message( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "ExecutionRoleArn" => { builder = builder.set_execution_role_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "DateCreated" => { builder = builder.set_date_created( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "DateModified" => { builder = builder.set_date_modified( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "PolicyDetails" => { builder = builder.set_policy_details( crate::json_deser::deser_structure_policy_details(tokens)?, ); } "Tags" => { builder = builder.set_tags(crate::json_deser::deser_map_tag_map(tokens)?); } "PolicyArn" => { builder = builder.set_policy_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_tag_map<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<std::string::String, std::string::String>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key.to_unescaped().map(|u| u.into_owned())?; let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_lifecycle_policy_summary<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::LifecyclePolicySummary>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::LifecyclePolicySummary::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "PolicyId" => { builder = builder.set_policy_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Description" => { builder = builder.set_description( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "State" => { builder = builder.set_state( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::GettablePolicyStateValues::from( u.as_ref(), ) }) }) .transpose()?, ); } "Tags" => { builder = builder.set_tags(crate::json_deser::deser_map_tag_map(tokens)?); } "PolicyType" => { builder = builder.set_policy_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::PolicyTypeValues::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_policy_details<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::PolicyDetails>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::PolicyDetails::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "PolicyType" => { builder = builder.set_policy_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::PolicyTypeValues::from(u.as_ref()) }) }) .transpose()?, ); } "ResourceTypes" => { builder = builder.set_resource_types( crate::json_deser::deser_list_resource_type_values_list( tokens, )?, ); } "ResourceLocations" => { builder = builder.set_resource_locations( crate::json_deser::deser_list_resource_location_list(tokens)?, ); } "TargetTags" => { builder = builder.set_target_tags( crate::json_deser::deser_list_target_tag_list(tokens)?, ); } "Schedules" => { builder = builder.set_schedules( crate::json_deser::deser_list_schedule_list(tokens)?, ); } "Parameters" => { builder = builder.set_parameters( crate::json_deser::deser_structure_parameters(tokens)?, ); } "EventSource" => { builder = builder.set_event_source( crate::json_deser::deser_structure_event_source(tokens)?, ); } "Actions" => { builder = builder.set_actions( crate::json_deser::deser_list_action_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_resource_type_values_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::ResourceTypeValues>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::ResourceTypeValues::from(u.as_ref())) }) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_resource_location_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::ResourceLocationValues>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped().map(|u| { crate::model::ResourceLocationValues::from(u.as_ref()) }) }) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_target_tag_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Tag>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_tag(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_schedule_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Schedule>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_schedule(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_parameters<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Parameters>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Parameters::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "ExcludeBootVolume" => { builder = builder.set_exclude_boot_volume( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "NoReboot" => { builder = builder.set_no_reboot( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_event_source<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::EventSource>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::EventSource::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::EventSourceValues::from(u.as_ref()) }) }) .transpose()?, ); } "Parameters" => { builder = builder.set_parameters( crate::json_deser::deser_structure_event_parameters(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_action_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Action>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_action(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_tag<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Tag>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Tag::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Key" => { builder = builder.set_key( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Value" => { builder = builder.set_value( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_schedule<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Schedule>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Schedule::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "CopyTags" => { builder = builder.set_copy_tags( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "TagsToAdd" => { builder = builder.set_tags_to_add( crate::json_deser::deser_list_tags_to_add_list(tokens)?, ); } "VariableTags" => { builder = builder.set_variable_tags( crate::json_deser::deser_list_variable_tags_list(tokens)?, ); } "CreateRule" => { builder = builder.set_create_rule( crate::json_deser::deser_structure_create_rule(tokens)?, ); } "RetainRule" => { builder = builder.set_retain_rule( crate::json_deser::deser_structure_retain_rule(tokens)?, ); } "FastRestoreRule" => { builder = builder.set_fast_restore_rule( crate::json_deser::deser_structure_fast_restore_rule(tokens)?, ); } "CrossRegionCopyRules" => { builder = builder.set_cross_region_copy_rules( crate::json_deser::deser_list_cross_region_copy_rules(tokens)?, ); } "ShareRules" => { builder = builder.set_share_rules( crate::json_deser::deser_list_share_rules(tokens)?, ); } "DeprecateRule" => { builder = builder.set_deprecate_rule( crate::json_deser::deser_structure_deprecate_rule(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_event_parameters<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::EventParameters>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::EventParameters::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "EventType" => { builder = builder.set_event_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::EventTypeValues::from(u.as_ref()) }) }) .transpose()?, ); } "SnapshotOwner" => { builder = builder.set_snapshot_owner( crate::json_deser::deser_list_snapshot_owner_list(tokens)?, ); } "DescriptionRegex" => { builder = builder.set_description_regex( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_action<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Action>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Action::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "CrossRegionCopy" => { builder = builder.set_cross_region_copy( crate::json_deser::deser_list_cross_region_copy_action_list( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_tags_to_add_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Tag>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_tag(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_variable_tags_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Tag>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_tag(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_create_rule<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CreateRule>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CreateRule::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Location" => { builder = builder.set_location( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::LocationValues::from(u.as_ref())) }) .transpose()?, ); } "Interval" => { builder = builder.set_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "IntervalUnit" => { builder = builder.set_interval_unit( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::IntervalUnitValues::from(u.as_ref()) }) }) .transpose()?, ); } "Times" => { builder = builder .set_times(crate::json_deser::deser_list_times_list(tokens)?); } "CronExpression" => { builder = builder.set_cron_expression( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_retain_rule<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::RetainRule>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::RetainRule::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Count" => { builder = builder.set_count( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "Interval" => { builder = builder.set_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "IntervalUnit" => { builder = builder.set_interval_unit( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::RetentionIntervalUnitValues::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_fast_restore_rule<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::FastRestoreRule>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::FastRestoreRule::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Count" => { builder = builder.set_count( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "Interval" => { builder = builder.set_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "IntervalUnit" => { builder = builder.set_interval_unit( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::RetentionIntervalUnitValues::from( u.as_ref(), ) }) }) .transpose()?, ); } "AvailabilityZones" => { builder = builder.set_availability_zones( crate::json_deser::deser_list_availability_zone_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_cross_region_copy_rules<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::CrossRegionCopyRule>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_cross_region_copy_rule(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_share_rules<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::ShareRule>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_share_rule(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_deprecate_rule<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DeprecateRule>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DeprecateRule::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Count" => { builder = builder.set_count( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "Interval" => { builder = builder.set_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "IntervalUnit" => { builder = builder.set_interval_unit( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::RetentionIntervalUnitValues::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_snapshot_owner_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_cross_region_copy_action_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::CrossRegionCopyAction>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_cross_region_copy_action(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_times_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_availability_zone_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_cross_region_copy_rule<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CrossRegionCopyRule>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CrossRegionCopyRule::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "TargetRegion" => { builder = builder.set_target_region( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Target" => { builder = builder.set_target( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "Encrypted" => { builder = builder.set_encrypted( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "CmkArn" => { builder = builder.set_cmk_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "CopyTags" => { builder = builder.set_copy_tags( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "RetainRule" => { builder = builder.set_retain_rule( crate::json_deser::deser_structure_cross_region_copy_retain_rule(tokens)? ); } "DeprecateRule" => { builder = builder.set_deprecate_rule( crate::json_deser::deser_structure_cross_region_copy_deprecate_rule(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_share_rule<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ShareRule>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ShareRule::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "TargetAccounts" => { builder = builder.set_target_accounts( crate::json_deser::deser_list_share_target_account_list( tokens, )?, ); } "UnshareInterval" => { builder = builder.set_unshare_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "UnshareIntervalUnit" => { builder = builder.set_unshare_interval_unit( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::RetentionIntervalUnitValues::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_cross_region_copy_action<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CrossRegionCopyAction>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CrossRegionCopyAction::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Target" => { builder = builder.set_target( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "EncryptionConfiguration" => { builder = builder.set_encryption_configuration( crate::json_deser::deser_structure_encryption_configuration( tokens, )?, ); } "RetainRule" => { builder = builder.set_retain_rule( crate::json_deser::deser_structure_cross_region_copy_retain_rule(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_cross_region_copy_retain_rule<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CrossRegionCopyRetainRule>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CrossRegionCopyRetainRule::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Interval" => { builder = builder.set_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "IntervalUnit" => { builder = builder.set_interval_unit( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::RetentionIntervalUnitValues::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_cross_region_copy_deprecate_rule<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CrossRegionCopyDeprecateRule>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CrossRegionCopyDeprecateRule::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Interval" => { builder = builder.set_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "IntervalUnit" => { builder = builder.set_interval_unit( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::RetentionIntervalUnitValues::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_share_target_account_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_encryption_configuration<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::EncryptionConfiguration>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::EncryptionConfiguration::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Encrypted" => { builder = builder.set_encrypted( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "CmkArn" => { builder = builder.set_cmk_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } }
fn puzzle1(string: String) -> i32 { let mut max_value = 0; let phase_settings_list = generate_phase_settings_list(); println!("{:?}", phase_settings_list); for phase_settings in phase_settings_list { let result = run_phase(string.clone(), phase_settings); if (result > max_value) { max_value = result; } } return max_value; } fn generate_phase_settings_list() -> Vec<String> { return phase_thing(vec![0, 1, 2, 3, 4]); } fn generate_feedback_phase_settings_list() -> Vec<String> { return phase_thing(vec![5, 6, 7, 8, 9]); } fn phase_thing(vec: Vec<i32>) -> Vec<String> { if (vec.is_empty()) { return vec![String::from("")]; } let mut rows = Vec::<String>::new(); for num in &vec { let mut clonevec = vec.clone(); clonevec.retain(|vale| vale.clone() != num.clone()); let output = phase_thing(clonevec); output.iter() .map(|str| { let mut string = num.to_string(); string.push_str(","); string.push_str(str); return string; }) .for_each(|str| rows.push(str)); } return rows; } #[derive(Clone, Debug)] enum ParameterMode { POSITION, IMMEDIATE, } #[derive(Clone, Debug)] enum OpCode { ADD, MULTIPLY, SAVE_INPUT_AT, OUTPUT_VALUE_AT, JUMP_IF_TRUE, JUMP_IF_FALSE, LESS_THAN, EQUALS, END_PROGRAM, UNKNOWN, } #[derive(Clone, Debug)] struct ParameterOpCode { parameter_1_mode: ParameterMode, parameter_2_mode: ParameterMode, parameter_3_mode: ParameterMode, op_code: OpCode, } fn to_parameter_mode(char_input: char) -> ParameterMode { if (char_input == '1') { return ParameterMode::IMMEDIATE; } return ParameterMode::POSITION; } fn to_op_code(char1: char, char2: char) -> OpCode { if (char1 == '0') { if (char2 == '1') { return OpCode::ADD; } else if (char2 == '2') { return OpCode::MULTIPLY; } else if (char2 == '3') { return OpCode::SAVE_INPUT_AT; } else if (char2 == '4') { return OpCode::OUTPUT_VALUE_AT; } else if (char2 == '5') { return OpCode::JUMP_IF_TRUE; } else if (char2 == '6') { return OpCode::JUMP_IF_FALSE; } else if (char2 == '7') { return OpCode::LESS_THAN; } else if (char2 == '8') { return OpCode::EQUALS; } } else if (char1 == '9' && char2 == '9') { return OpCode::END_PROGRAM; } println!("{:?}", char2); return OpCode::UNKNOWN; } fn parse_parameter_op_code(code: &i32) -> ParameterOpCode { let mut formatted_string = format!("{:05}", code); let mut chars = formatted_string.chars(); let char1 = chars.next().unwrap(); let char2 = chars.next().unwrap(); let char3 = chars.next().unwrap(); let char4 = chars.next().unwrap(); let char5 = chars.next().unwrap(); return ParameterOpCode { parameter_1_mode: to_parameter_mode(char3), parameter_2_mode: to_parameter_mode(char2), parameter_3_mode: to_parameter_mode(char1), op_code: to_op_code(char4, char5), }; } fn get_value_at_index(index: usize, mode: ParameterMode, values: &Vec<i32>) -> i32 { return match mode { ParameterMode::POSITION => { let index_a = values[index] as usize; return values[index_a]; } ParameterMode::IMMEDIATE => { return values[index]; } }; } fn set_value_at_index(value: i32, index: usize, mode: ParameterMode, values: &mut Vec<i32>) { return match mode { ParameterMode::POSITION => { let index_a = values[index] as usize; values[index_a] = value; } ParameterMode::IMMEDIATE => { values[index] = value; } }; } fn run_phase(instruction_string: String, phase_string: String) -> i32 { let mut instructions: Vec<i32> = instruction_string.split(",") .map(|s| -> i32 { s.parse::<i32>().unwrap() }) .collect(); let phase_order: Vec<i32> = phase_string.split(",") .filter(|s| -> bool { s.len() > 0 }) .map(|s| -> i32 { s.parse::<i32>().unwrap() }) .collect(); let mut value = 0; for phase in phase_order { value = run_program(&mut instructions.clone(), &mut vec![value, phase]); } return value; } fn run_program(instructions: &mut Vec<i32>, input: &mut Vec<i32>) -> i32 { // let mut instructions = values.clone(); let mut output = Vec::new(); println!("Input: {:?}", input); let mut index = 0; while index < instructions.len() { let op_code = parse_parameter_op_code(&instructions[index]); println!("{:?}", &op_code); match op_code.op_code { OpCode::ADD => { println!("{:?}", &instructions[index..index + 4]); let value_a = get_value_at_index(index + 1, op_code.parameter_1_mode.clone(), instructions); let value_b = get_value_at_index(index + 2, op_code.parameter_2_mode.clone(), instructions); set_value_at_index(value_a + value_b, index + 3, op_code.parameter_3_mode.clone(), instructions); index += 4; } OpCode::MULTIPLY => { println!("{:?}", &instructions[index..index + 4]); let value_a = get_value_at_index(index + 1, op_code.parameter_1_mode.clone(), instructions); let value_b = get_value_at_index(index + 2, op_code.parameter_2_mode.clone(), instructions); set_value_at_index(value_a * value_b, index + 3, op_code.parameter_3_mode.clone(), instructions); index += 4; } OpCode::SAVE_INPUT_AT => { println!("{:?}", &instructions[index..index + 2]); match input.pop() { Some(value) => { println!("Popped Value: {:?}", value); set_value_at_index(value, index + 1, op_code.parameter_1_mode.clone(), instructions) } None => { println!("Cannot Read from input") } } index += 2; } OpCode::OUTPUT_VALUE_AT => { println!("{:?}", &instructions[index..index + 2]); let register = get_value_at_index(index + 1, op_code.parameter_1_mode.clone(), instructions); output.push(register); index += 2; } OpCode::JUMP_IF_TRUE => { println!("{:?}", &instructions[index..index + 3]); let value_a = get_value_at_index(index + 1, op_code.parameter_1_mode.clone(), instructions); if (value_a != 0) { let value_b = get_value_at_index(index + 2, op_code.parameter_2_mode.clone(), instructions); index = value_b as usize; } else { index += 3; } } OpCode::JUMP_IF_FALSE => { println!("{:?}", &instructions[index..index + 3]); let value_a = get_value_at_index(index + 1, op_code.parameter_1_mode.clone(), instructions); if (value_a == 0) { let value_b = get_value_at_index(index + 2, op_code.parameter_2_mode.clone(), instructions); index = value_b as usize; } else { index += 3; } } OpCode::LESS_THAN => { println!("{:?}", &instructions[index..index + 4]); let value_a = get_value_at_index(index + 1, op_code.parameter_1_mode.clone(), instructions); let value_b = get_value_at_index(index + 2, op_code.parameter_2_mode.clone(), instructions); let save_value: i32; if (value_a < value_b) { save_value = 1; } else { save_value = 0; } set_value_at_index(save_value, index + 3, op_code.parameter_3_mode.clone(), instructions); index += 4; } OpCode::EQUALS => { println!("{:?}", &instructions[index..index + 4]); let value_a = get_value_at_index(index + 1, op_code.parameter_1_mode.clone(), instructions); let value_b = get_value_at_index(index + 2, op_code.parameter_2_mode.clone(), instructions); let save_value: i32; if (value_a == value_b) { save_value = 1; } else { save_value = 0; } set_value_at_index(save_value, index + 3, op_code.parameter_3_mode.clone(), instructions); index += 4; } OpCode::END_PROGRAM => break, _ => { index += 4; } } } // let x = output.join(","); println!("{:?}", output); return output.last().unwrap().clone(); } fn puzzle2(string: String) -> i32 { let mut max_value = 0; let phase_settings_list = generate_feedback_phase_settings_list(); println!("{:?}", phase_settings_list); for phase_settings in phase_settings_list { let result = run_phase(string.clone(), phase_settings); if (result > max_value) { max_value = result; } } return max_value; } #[cfg(test)] mod tests { use crate::utils; use crate::day7::{puzzle1, puzzle2, run_phase}; struct Puzzle1Test { test_data: String, phase_setting: String, expected_result: i32, } #[test] fn test_puzzle_1() { // let mut tests: Vec<Puzzle1Test> = Vec::new(); // tests.push(Puzzle1Test { // test_data: String::from("3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0"), // phase_setting: String::from("4,3,2,1,0"), // expected_result: 43210, // }); // tests.push(Puzzle1Test { // test_data: String::from("3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0"), // phase_setting: String::from("0,1,2,3,4"), // expected_result: 54321, // }); // tests.push(Puzzle1Test { // test_data: String::from("3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0"), // phase_setting: String::from("1,0,4,3,2"), // expected_result: 65210, // }); // // for test in tests { // let result = run_phase(test.test_data, test.phase_setting); // assert_eq!(result, test.expected_result); // } match utils::read_lines("data/Day7.txt") { Ok(lines) => { println!("{}", "test"); let result = puzzle1(lines.get(0).unwrap().clone()); assert_eq!(result, 34686); } Err(error) => { println!("{}", error); } } } struct Puzzle2Test { test_data: Vec<String>, phase_setting: String, expected_result: u32, } #[test] fn test_puzzle_2() { // let mut tests: Vec<Puzzle2Test> = Vec::new(); // tests.push(Puzzle2Test { // test_data: vec![String::from("COM)B"), // String::from("B)C"), // String::from("C)D"), // String::from("D)E"), // String::from("E)F"), // String::from("B)G"), // String::from("G)H"), // String::from("D)I"), // String::from("E)J"), // String::from("J)K"), // String::from("K)L"), // String::from("K)YOU"), // String::from("I)SAN")], // expected_result: 4, // }); // // match utils::read_lines("data/Day6.txt") { // Ok(lines) => { // tests.push(Puzzle2Test { // test_data: lines, // expected_result: 496, // }); // for test in tests { // let result = puzzle2(test.test_data); // assert_eq!(result, test.expected_result); // } // } // Err(error) => { // println!("{}", error); // } // } } }
extern crate rand; use rand::{thread_rng, Rng}; static BASE64_CHAR: &'static str = "ABCDEFGHIJKLMNOPQRSTUVWXYZa bcdefghijklmnopqrstuvwxyz0123456789+/="; static HEX_CHAR: &'static str = "1234567890abcdefABCDEF"; const THRESHOLD: u8 = 20; fn main() { let mut random_strs: Vec<String> = vec![]; for i in 0..10 { let length = thread_rng().gen_range(10, 30); let rstr: String = thread_rng() .gen_ascii_chars() .take(length) .collect::<String>(); random_strs.push(rstr); } for rstr in random_strs.iter() { let valid_str = get_string_of_set(&rstr, &BASE64_CHAR); for v_word in valid_str.iter() { println!("shannon entropy: {}", shannon_entropy(&v_word, &BASE64_CHAR)); println!("valid word: {}", v_word); } } } fn shannon_entropy(data: &str, iterator: &str) -> f64 { let mut entropy = 0.0; for ch in iterator.chars() { let length = data.matches(ch).count() as f64; let p_x = length / data.len() as f64; if p_x > 0.0 { entropy += -p_x * p_x.log(2.0); } } entropy } fn get_string_of_set(word: &str, char_set: &str) -> Vec<String> { let mut count = 0; let mut letter: Vec<char> = vec![]; let mut valid_words: Vec<String> = vec![]; for ch in word.chars() { if char_set.matches(ch).count() > 0 { letter.push(ch); count += 1; } else { if count > THRESHOLD { valid_words.push(letter.iter().cloned().collect()); } letter.clear(); count = 0; } } if count > THRESHOLD { valid_words.push(letter.iter().clone().collect()); } valid_words }
#![cfg_attr(feature = "cargo-clippy", allow(unused_parens))] extern crate serde; #[macro_use] extern crate serde_derive; #[cfg(feature = "serde-json")] extern crate serde_json; extern crate toml; use std::env; use std::fs; use std::path::{Path, PathBuf}; mod error; mod escaping; pub use error::{Error, Result}; pub use escaping::MarkupDisplay; pub mod filters; pub struct Config { pub dirs: Vec<PathBuf>, } impl Config { pub fn new() -> Config { let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let filename = root.join(CONFIG_FILE_NAME); if filename.exists() { Self::from_str( &fs::read_to_string(&filename) .expect(&format!("unable to read {}", filename.to_str().unwrap())), ) } else { Self::from_str("") } } pub fn from_str(s: &str) -> Self { let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let default = vec![root.join("templates")]; let raw: RawConfig = toml::from_str(&s).expect(&format!("invalid TOML in {}", CONFIG_FILE_NAME)); let dirs = match raw.general { Some(General { dirs: Some(dirs) }) => { dirs.into_iter().map(|dir| root.join(dir)).collect() } Some(General { dirs: None }) | None => default, }; Self { dirs } } pub fn find_template(&self, path: &str, start_at: Option<&Path>) -> PathBuf { if let Some(root) = start_at { let relative = root.with_file_name(path); if relative.exists() { return relative.to_owned(); } } for dir in &self.dirs { let rooted = dir.join(path); if rooted.exists() { return rooted; } } panic!( "template {:?} not found in directories {:?}", path, self.dirs ) } } #[derive(Deserialize)] struct RawConfig { general: Option<General>, } #[derive(Deserialize)] struct General { dirs: Option<Vec<String>>, } static CONFIG_FILE_NAME: &str = "askama.toml"; #[cfg(test)] mod tests { use super::Config; use std::env; use std::path::{Path, PathBuf}; #[test] fn test_default_config() { let mut root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); root.push("templates"); let config = Config::from_str(""); assert_eq!(config.dirs, vec![root]); } #[test] fn test_config_dirs() { let mut root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); root.push("tpl"); let config = Config::from_str("[general]\ndirs = [\"tpl\"]"); assert_eq!(config.dirs, vec![root]); } fn assert_eq_rooted(actual: &Path, expected: &str) { let mut root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); root.push("templates"); let mut inner = PathBuf::new(); inner.push(expected); assert_eq!(actual.strip_prefix(root).unwrap(), inner); } #[test] fn find_absolute() { let config = Config::new(); let root = config.find_template("a.html", None); let path = config.find_template("sub/b.html", Some(&root)); assert_eq_rooted(&path, "sub/b.html"); } #[test] #[should_panic] fn find_relative_nonexistent() { let config = Config::new(); let root = config.find_template("a.html", None); config.find_template("b.html", Some(&root)); } #[test] fn find_relative() { let config = Config::new(); let root = config.find_template("sub/b.html", None); let path = config.find_template("c.html", Some(&root)); assert_eq_rooted(&path, "sub/c.html"); } #[test] fn find_relative_sub() { let config = Config::new(); let root = config.find_template("sub/b.html", None); let path = config.find_template("sub1/d.html", Some(&root)); assert_eq_rooted(&path, "sub/sub1/d.html"); } }
use simplemm::{client, error, types}; use snafu::{ErrorCompat, ResultExt}; use std::io::Read; static PROGRAM: &str = "simplemmclnt"; static CLIENT_VERSION: &str = env!("CARGO_PKG_VERSION"); fn main() { if let Err(e) = run() { error_abort(e) } } fn run() -> error::Result<()> { let (config, matches) = read_config()?; match matches.subcommand_name().unwrap() { "stop" => action_stop(&config), "ping" => action_ping(&config), "version" => action_client_info(), "subscribe" => action_subscribe(&config, &matches), _ => Ok(()), } } fn action_stop(config: &types::Config) -> error::Result<()> { let _ = client::check_server_is_running(&config)?; client::stop_daemon(config) } fn action_ping(config: &types::Config) -> error::Result<()> { let (pid, state) = client::check_server_is_running(&config)?; println!( "simplemmd v{}, pid = {}, server_start_time: {}, uid = {}, gid = {}", state.server_version, pid, state.start_time, state.config.uid, state.config.gid ); Ok(()) } fn action_client_info() -> error::Result<()> { println!("{} v{}", PROGRAM, CLIENT_VERSION); Ok(()) } fn action_subscribe(config: &types::Config, matches: &clap::ArgMatches) -> error::Result<()> { let mailing_list = matches .subcommand_matches("subscribe") .unwrap() .value_of("list_name") .unwrap(); let mut email_content = String::new(); std::io::stdin() .read_to_string(&mut email_content) .context(error::ReadStdinError {})?; client::send_and_read( config, types::Action::Subscribe, Some(mailing_list.to_string()), Some(email_content), )?; Ok(()) } fn parse_args<'a>() -> clap::ArgMatches<'a> { let app = clap::App::new(PROGRAM) .version(CLIENT_VERSION) .author("by Cohomology, 2020") .setting(clap::AppSettings::SubcommandRequiredElseHelp) .arg( clap::Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .help("configuration file") .takes_value(true), ) .subcommand(clap::SubCommand::with_name("stop").about("Stop simplemmd daemon")) .subcommand(clap::SubCommand::with_name("ping").about("Get server status")) .subcommand(clap::SubCommand::with_name("version").about("Get client version")) .subcommand( clap::SubCommand::with_name("subscribe") .about("Subscribe to mailing list") .arg( clap::Arg::with_name("list_name") .help("Name of the mailing list") .required(true), ), ); app.get_matches() } fn read_config<'a>() -> error::Result<(types::Config, clap::ArgMatches<'a>)> { let arg_matches = parse_args(); let config_file_name = arg_matches .value_of("config") .unwrap_or("/etc/simplemm.conf"); let config = simplemm::config::read_config(config_file_name)?; Ok((config, arg_matches)) } fn error_abort(error: error::Error) -> ! { eprintln!("Error: {}", error); if let Some(backtrace) = ErrorCompat::backtrace(&error) { eprintln!("{}", backtrace); } std::process::exit(-1) }
use clap::Clap; #[derive(Clap)] #[clap(version = std::env!("CARGO_PKG_VERSION"), author = "aki")] struct Opts { cmd: String, #[clap(name = "KEY")] key: Option<String>, #[clap(name = "VALUE")] value: Option<String>, } fn main() { let opts: Opts = Opts::parse(); let mut kv: kvs::KvStore = kvs::KvStore::new(); match opts.cmd.as_str() { "set" => { panic!("unimplemented"); // kv.set(opts.key.expect("unimplemented"), opts.value.expect("unimplemented")); }, "get" => { panic!("unimplemented"); // let res = kv.get(opts.key.expect("must specify key")); // print!("{}", res.unwrap()); }, "rm" => { panic!("unimplemented"); // kv.remove(opts.key.expect("must specify key")); } _ => panic!("unimplemented"), } }
use deadpool_postgres::{ Manager, Pool}; use tokio_postgres::{Config, NoTls,Row}; use std::env; use std::str::FromStr; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[derive(Debug)] struct Todo { id: i32, name: String, } fn row_to_todo(row: &Row) -> Todo { let id: i32 = row.get(0); let name: String = row.get(1); Todo { id, name } } async fn fetch_to_dos(db_pool: &Pool) -> Result<Vec<Todo>> { let client = db_pool.get().await.unwrap(); let rows = client .query("SELECT id, name from todo", &[]) .await .unwrap(); Ok(rows.iter().map(|r| row_to_todo(&r)).collect()) } #[tokio::main] async fn main() { dotenv::dotenv().ok(); let mut cfg = Config::new(); cfg.host(&env::var("HOST").unwrap()); cfg.user(&env::var("USER").unwrap()); cfg.password(&env::var("PASSWORD").unwrap()); cfg.dbname(&env::var("DBNAME").unwrap()); let port = &env::var("DBPORT").unwrap(); cfg.port(port.parse::<u16>().unwrap()); let mgr = Manager::new(cfg, tokio_postgres::NoTls); let pool = Pool::new(mgr, 16); //let pool = pool.clone(); let r: Vec<Todo> = fetch_to_dos(&pool).await.unwrap(); println!("length is {}", r.len()); for i in r.iter() { println!("first name is {:?}", i); } }
extern crate word_fuzzer; use word_fuzzer::fuzz; use std::env; fn main() { for argument in env::args().skip(1) { print!("{} ", fuzz(&argument)); } println!(""); }
use crate::exp::SyntaxError; #[derive(Debug, Clone)] pub enum Input { Plus, Minus, Cross, Division, LParen, RParen, Num(f64), } pub trait Controller { fn get_inputs(&self) -> Vec<Input>; } pub trait Presenter { fn show_error(&self, error: SyntaxError); fn show_result(&self, calculated: f64); }
use std::{net::SocketAddr, sync::Arc}; use thiserror::Error; use bevy::prelude::{AppBuilder, Plugin, IntoQuerySystem}; use quinn::{ ClientConfigBuilder, crypto::rustls::TlsSession, }; use tokio::sync::mpsc::unbounded_channel; use url::Url; use crate::networking::{ crypto::SkipServerVerification, events::{ ReceiveEvent, SendEvent }, systems::{ Connecting, NetworkConnections, SessionEventListenerState, receive_net_events_system, send_net_events_system, SEND_NET_EVENT_STAGE, RECEIVE_NET_EVENT_STAGE } }; pub struct Network { pub addr: SocketAddr, pub url: Url, pub cert: quinn::Certificate, pub accept_any_cert : bool, } impl Plugin for Network { fn build(&self, app: &mut AppBuilder) { // Create mpsc endpoints for received network events and store them in a resources let (send, recv) = unbounded_channel(); app.add_resource(SessionEventListenerState { event_sender: send.clone(), event_receiver: recv, stream_senders: Default::default(), send_event_reader: Default::default(), }); app.init_resource::<NetworkConnections>(); app.add_resource::<NetworkConnections>(Default::default()); app.add_event::<ReceiveEvent>(); app.add_event::<SendEvent>(); // Start a task that waits for the connection to finish opening tokio::spawn( Connecting::new( create_endpoint(&self.addr, &self.url, &self.cert, self.accept_any_cert).expect("Failed to create an endpoint"), send ).run() ); // Add a system that consumes all network events from an MPSC and publishes them as ECS events app.add_system_to_stage(RECEIVE_NET_EVENT_STAGE, receive_net_events_system.system()); // Add a system that consumes ECS events and forwards them to MPSCs which will eventually be sent over the network app.add_system_to_stage(SEND_NET_EVENT_STAGE, send_net_events_system.system()); } } #[derive(Error, Debug)] enum CreateEndpointError { #[error(transparent)] EndpointError(#[from] quinn::EndpointError), #[error(transparent)] ConnectError(#[from] quinn::ConnectError) } fn create_endpoint( addr: &SocketAddr, url: &Url, server_cert: &quinn::Certificate, accept_any_cert: bool ) -> Result<quinn::generic::Connecting<TlsSession>, CreateEndpointError> { let mut client_config = ClientConfigBuilder::default(); client_config.protocols(&[b"hq-29"]); let mut client_config = client_config.build(); if accept_any_cert { let tls_cfg: &mut rustls::ClientConfig = Arc::get_mut(&mut client_config.crypto) .expect("Failed to get mutable reference to crypto configuration"); // this is only available when compiled with "dangerous_configuration" feature tls_cfg .dangerous() .set_certificate_verifier(SkipServerVerification::new()); } else { client_config.add_certificate_authority(server_cert.clone()).expect("Adding cert failed"); } let mut endpoint = quinn::Endpoint::builder(); endpoint.default_client_config(client_config); let (endpoint, _) = endpoint.bind(&"[::]:0".parse().expect("Failed to parse bind address"))?; let connecting = endpoint.connect(addr, &url.host_str().expect("Failed to get host_str from url"))?; Ok(connecting) }
fn main(){ proconio::input!{n:usize,k:usize}; let mut has = vec![true;n]; for _ in 0..k{ proconio::input!{d:usize,a:[usize;d]}; for j in 0..d{ has[a[j]-1] = false; } } println!("{:?}", has.iter().filter(|x|**x).count()) }
use crate::persistence::in_memory_routing_repo::{ShipRoute, RouteRequest}; pub trait Navigator: Send + Sync { fn new() -> Self where Self: Sized; fn build_graph(&mut self); fn calculate_route(&mut self, route_request: RouteRequest) -> Option<ShipRoute>; fn get_number_nodes(&self) -> u32; }
use std::any::{Any, TypeId}; use std::collections::HashMap; use std::io::BufReader; use std::path::PathBuf; use log::info; use serde_derive::Deserialize; use crate::{CoreError, CoreResult}; const ASSETS_DIRECTORY: &str = "assets"; const ASSET_DESCRIPTION_FILE: &str = "asset.json"; pub type GenericLoader = Box<dyn Fn(&Metadata) -> Box<dyn Any>>; #[derive(Default)] pub struct Store { assets: HashMap<TypeId, HashMap<String, Box<dyn Any>>>, asset_loaders: HashMap<TypeId, GenericLoader>, assets_metadata: HashMap<String, Metadata>, } impl Store { pub fn load_assets_metadata(&mut self) -> CoreResult<()> { info!("Loading assets metadata"); let paths = match std::fs::read_dir(Store::asset_directory()?) { Ok(paths) => paths, Err(_) => return Ok(()), }; let asset_directory_paths: Vec<_> = paths .filter_map(Result::ok) .filter(|p| p.path().is_dir()) .collect(); for asset_directory_path in asset_directory_paths { let mut path = asset_directory_path.path(); path.push(ASSET_DESCRIPTION_FILE); if !path.is_file() { return Err(CoreError::AssetDescriptionFileNotFound); } let f = std::fs::File::open(path).map_err(CoreError::AssetDescriptionFileOpenError)?; let reader = BufReader::new(f); let mut asset_metadata: Metadata = serde_json::from_reader(reader) .map_err(CoreError::AssetDescriptionFileParseError)?; asset_metadata.asset_path = asset_directory_path.path(); info!( "Loaded resource metadata identifier={} kind={}", &asset_metadata.identifier, &asset_metadata.kind ); self.assets_metadata .insert(asset_metadata.identifier.clone(), asset_metadata); } info!("Assets metadata loading done."); Ok(()) } pub fn register_loaders<Loader>(&mut self, loaders: Vec<(TypeId, Loader)>) where Loader: 'static + Fn(&Metadata) -> Box<dyn Any>, { for (type_id, loader) in loaders { self.asset_loaders.insert( type_id, Box::new(move |asset_metadata: &Metadata| ((loader)(asset_metadata))), ); } } pub fn register_loader<AssetType, Loader>(&mut self, loader: Loader) where AssetType: 'static + Any, Loader: 'static + Fn(&Metadata) -> Box<AssetType>, { self.asset_loaders.insert( TypeId::of::<AssetType>(), Box::new(move |asset_metadata: &Metadata| ((loader)(asset_metadata))), ); } #[must_use] pub fn has_asset<AssetType>(&self, identifier: &str) -> bool where AssetType: 'static + Any, { let type_id = TypeId::of::<AssetType>(); self.assets.get(&type_id).is_some() && self.assets[&type_id].contains_key(identifier) } pub fn load<AssetType>(&mut self, identifier: &str) -> CoreResult<()> where AssetType: 'static + Any, { if self.has_asset::<AssetType>(identifier) { return Ok(()); } let type_id = TypeId::of::<AssetType>(); let asset_metadata = self .assets_metadata .get(identifier) .ok_or(CoreError::AssetMetadataNotFound)?; let asset_storage = self.assets.entry(type_id).or_insert_with(HashMap::new); asset_storage.insert( identifier.into(), (self .asset_loaders .get(&type_id) .ok_or(CoreError::AssetLoaderNotFound)?)(asset_metadata), ); Ok(()) } pub fn insert_asset<AssetType>( &mut self, asset_metadata: Metadata, asset: AssetType, ) -> CoreResult<()> where AssetType: 'static + Any, { let type_id = TypeId::of::<AssetType>(); let asset_storage = self.assets.entry(type_id).or_insert_with(HashMap::new); asset_storage.insert(asset_metadata.identifier.clone(), Box::new(asset)); self.assets_metadata .insert(asset_metadata.identifier.clone(), asset_metadata); Ok(()) } pub fn stored_asset<AssetType>(&self, identifier: &str) -> CoreResult<&AssetType> where AssetType: 'static + Any, { self.assets .get(&TypeId::of::<AssetType>()) .ok_or(CoreError::AssetStorageNotFound)? .get(identifier) .ok_or(CoreError::AssetNotFound)? .as_ref() .downcast_ref() .ok_or(CoreError::AssetDowncastError) } pub fn asset<AssetType>(&mut self, identifier: &str) -> CoreResult<&AssetType> where AssetType: 'static + Any, { let type_id = TypeId::of::<AssetType>(); let asset_storage = self.assets.get(&type_id); if asset_storage.is_none() || asset_storage.unwrap().get(identifier).is_none() { self.load::<AssetType>(identifier)?; } self.stored_asset::<AssetType>(identifier) } fn asset_directory() -> CoreResult<PathBuf> { let mut path = crate::application_directory()?; path.push(ASSETS_DIRECTORY); Ok(path) } } pub trait IntoLoader<F> { fn into_loader(self) -> GenericLoader; } impl<F> IntoLoader<F> for F where F: 'static + Fn(&Metadata) -> Box<dyn Any>, { fn into_loader(self) -> GenericLoader { Box::new(self) } } #[derive(Deserialize)] pub struct Metadata { pub identifier: String, pub kind: String, pub metadata: HashMap<String, String>, #[serde(skip)] pub asset_path: PathBuf, }
use crate::assets::{AnimationId, Direction, PrefabStorage}; use crate::combat::*; use crate::physics::*; use crate::prelude::*; use amethyst::{ animation::*, assets::Handle, core::{bundle::SystemBundle, transform::*}, ecs::world::LazyBuilder, ecs::*, error::Error, input::{InputHandler, StringBindings}, prelude::*, renderer::{camera::*, SpriteRender}, }; use na::{Isometry2, Vector2}; use ncollide2d::shape::*; use nphysics2d::object::*; const ARENA_WIDTH: f32 = 240.0; const ARENA_HEIGHT: f32 = 160.0; fn standard_camera() -> Camera { Camera::standard_2d(ARENA_WIDTH, ARENA_HEIGHT) } pub fn initialize_camera(builder: impl Builder, player: &Entity) -> Entity { // Setup camera in a way that our screen covers whole arena and (0, 0) is in the bottom left. let mut transform = Transform::default(); transform.set_translation_xyz(0.0, 0.0, 1.0); builder .with(standard_camera()) .with(Parent { entity: *player }) .with(transform) .build() } #[derive(Debug, PartialEq)] pub enum PlayerState { Moving, Attacking(usize), Hit(f32), } #[derive(Component, Debug)] #[storage(VecStorage)] pub struct Player { pub walk_speed: f32, pub state: PlayerState, pub facing: Direction, } fn spawn_player(prefabs: &PrefabStorage, player_builder: LazyBuilder, x: f32, y: f32) -> Entity { let shape = ShapeHandle::new(Ball::new(8.0)); let body = RigidBodyDesc::new() .status(BodyStatus::Dynamic) .mass(10.0) .linear_damping(0.0); let collider = ColliderDesc::new(shape); let mut transform = Transform::default(); transform.set_translation_xyz(x, y, 1.0); player_builder .with(PhysicsDesc::new(body, collider)) .with(prefabs.player.clone()) .with(transform) .with(Player { walk_speed: 100.0, state: PlayerState::Moving, facing: Direction::South, }) .with(Health::new(true, MAX_PLAYER_HEALTH)) .named("player") .build() } #[derive(Component, Debug)] #[storage(VecStorage)] pub struct Pylon; fn spawn_pylon(prefabs: &PrefabStorage, player_builder: LazyBuilder, x: f32, y: f32) -> Entity { let shape = ShapeHandle::new(Ball::new(44.0)); let body = RigidBodyDesc::new().status(BodyStatus::Static); let collider = ColliderDesc::new(shape); let mut transform = Transform::default(); transform.set_translation_xyz(x, y, 1.0); player_builder .with(PhysicsDesc::new(body, collider)) .with(transform) .with(Pylon) .with(Health::new(true, MAX_PYLON_HEALTH)) .named("pylon") .build() } const ATTACK_SENSOR_NAME: &'static str = "player_attack_sensor"; fn spawn_attack_sensor(builder: LazyBuilder, player: Entity, direction: Direction) -> Entity { let offset = direction.tilts() * 8.0 + direction.clockwise().tilts() * 4.0; let shape = ShapeHandle::new(Cuboid::new(Vector2::new(8.0, 8.0))); let collider = ColliderDesc::new(shape) .sensor(true) .position(Isometry2::new(offset, 0.0)); builder .with(AttachedSensor::new(collider)) .with(AttackHitbox { id: rand::random(), hit_type: HitType::FriendlyAttack, damage: 1, }) .with(Parent { entity: player }) .named(ATTACK_SENSOR_NAME) .build() } pub fn spawn_player_world(world: &mut World, x: f32, y: f32) -> Entity { let entities = world.entities(); let update = world.write_resource::<LazyUpdate>(); let builder = update.create_entity(&entities); let prefabs = world.read_resource::<PrefabStorage>(); let player = spawn_player(&prefabs, builder, x, y); let builder = update.create_entity(&entities); initialize_camera(builder, &player); player } pub fn spawn_pylon_world(world: &mut World, x: f32, y: f32) -> Entity { let entities = world.entities(); let update = world.write_resource::<LazyUpdate>(); let builder = update.create_entity(&entities); let prefabs = world.read_resource::<PrefabStorage>(); spawn_pylon(&prefabs, builder, x, y) } struct PlayerAnimationSystem; impl<'s> System<'s> for PlayerAnimationSystem { type SystemData = ( ReadStorage<'s, Player>, ReadStorage<'s, AnimationSet<AnimationId, SpriteRender>>, WriteStorage<'s, AnimationControlSet<AnimationId, SpriteRender>>, Entities<'s>, ); fn run(&mut self, (player, animation_sets, mut control_sets, entities): Self::SystemData) { /* for (player, entity, animation_set) in (&player, &entities, &animation_sets).join() { // Creates a new AnimationControlSet for the entity let control_set = get_animation_set(&mut control_sets, entity).unwrap(); if control_set.is_empty() { // Adds the `Fly` animation to AnimationControlSet and loops infinitely for direction in Direction::vec().iter() { control_set.add_animation( AnimationId::Idle(*direction), &animation_set.get(&AnimationId::Idle(*direction)).unwrap(), EndControl::Loop(None), 1.0, AnimationCommand::Start, ); control_set.add_animation( AnimationId::Walk(*direction), &animation_set.get(&AnimationId::Walk(*direction)).unwrap(), EndControl::Loop(None), 1.0, AnimationCommand::Start, ); } } }*/ } } struct PlayerAttackSystem; impl<'s> System<'s> for PlayerAttackSystem { type SystemData = ( Read<'s, InputHandler<StringBindings>>, Read<'s, Time>, Write<'s, Physics<f32>>, ReadStorage<'s, AttachedSensor>, ReadStorage<'s, PhysicsHandle>, ReadStorage<'s, Named>, ReadStorage<'s, AnimationSet<AnimationId, SpriteRender>>, WriteStorage<'s, AnimationControlSet<AnimationId, SpriteRender>>, WriteStorage<'s, Player>, WriteStorage<'s, AttackHitbox>, Read<'s, LazyUpdate>, SoundPlayer<'s>, Entities<'s>, ); fn run( &mut self, ( input, time, mut physics, sensors, handles, names, animation_sets, mut control_sets, mut player, mut attacks, lazy, sounds, entities, ): Self::SystemData, ) { if let Some((entity, handle, player)) = (&entities, &handles, &mut player).join().next() { if let (Some(animation_set), Some(control_set)) = ( animation_sets.get(entity), get_animation_set(&mut control_sets, entity), ) { match player.state { PlayerState::Moving => { if let Some(sensor) = get_named_entity(&entities, &names, ATTACK_SENSOR_NAME) { lazy.exec(move |world| { world.delete_entity(sensor); }); } if Some(true) == input.action_is_down("attack") { player.state = PlayerState::Attacking(rand::random()); sounds.sword_slash(); spawn_attack_sensor( lazy.create_entity(&entities), entity, player.facing, ); physics.set_velocity(handle, Vector2::new(0.0, 0.0)); set_active_animation( control_set, AnimationId::Attack(player.facing), &animation_set, EndControl::Stay, 1.0, ); } } PlayerState::Attacking(attack_id) => { if let Some(AnimationId::Attack(_)) = get_active_animation(control_set) { } else { player.state = PlayerState::Moving; set_active_animation( control_set, AnimationId::Idle(player.facing), &animation_set, EndControl::Loop(None), 1.0, ); } } PlayerState::Hit(size) => { if let Some(sensor) = get_named_entity(&entities, &names, ATTACK_SENSOR_NAME) { lazy.exec(move |world| { world.delete_entity(sensor); }); } if size < time.delta_seconds() { player.state = PlayerState::Moving; } else { player.state = PlayerState::Hit(size - time.delta_seconds()); set_active_animation( control_set, AnimationId::Staggered(player.facing), &animation_set, EndControl::Stay, 1.0, ); } } _ => {} } } } } } struct PlayerMovementSystem; impl<'s> System<'s> for PlayerMovementSystem { type SystemData = ( Read<'s, InputHandler<StringBindings>>, Write<'s, Physics<f32>>, ReadStorage<'s, PhysicsHandle>, ReadStorage<'s, AnimationSet<AnimationId, SpriteRender>>, WriteStorage<'s, AnimationControlSet<AnimationId, SpriteRender>>, WriteStorage<'s, Player>, Entities<'s>, ); fn run( &mut self, (input, mut physics, handles, animation_sets, mut control_sets, mut player, entities): Self::SystemData, ) { let x_tilt = input.axis_value("leftright"); let y_tilt = input.axis_value("updown"); if let (Some(x_tilt), Some(y_tilt)) = (x_tilt, y_tilt) { if let Some((entity, handle, player)) = (&entities, &handles, &mut player).join().next() { if player.state != PlayerState::Moving { return; } physics.set_velocity( handle, Vector2::new(x_tilt * player.walk_speed, y_tilt * player.walk_speed), ); if let (Some(animation_set), Some(control_set)) = ( animation_sets.get(entity), get_animation_set(&mut control_sets, entity), ) { let direction = { if x_tilt != 0.0 || y_tilt != 0.0 { if f32::abs(x_tilt) >= f32::abs(y_tilt) { if x_tilt >= 0.0 { Direction::East } else { Direction::West } } else { if y_tilt >= 0.0 { Direction::North } else { Direction::South } } } else { player.facing } }; set_active_animation( control_set, if x_tilt != 0.0 || y_tilt != 0.0 { AnimationId::Walk(direction) } else { AnimationId::Idle(direction) }, &animation_set, EndControl::Loop(None), 1.0, ); player.facing = direction; } } } } } pub struct PlayerBundle; impl<'a, 'b> SystemBundle<'a, 'b> for PlayerBundle { fn build( self, _world: &mut World, dispatcher: &mut DispatcherBuilder<'a, 'b>, ) -> Result<(), Error> { dispatcher.add(PlayerAnimationSystem, "player_animation", &[]); dispatcher.add(PlayerAttackSystem, "player_attack", &[]); dispatcher.add(PlayerMovementSystem, "player_movement", &["player_attack"]); Ok(()) } }
use std::net::Shutdown; use byteorder::{ByteOrder, LittleEndian}; use crate::io::{Buf, BufMut, BufStream, MaybeTlsStream}; use crate::mysql::protocol::{Capabilities, Encode, EofPacket, ErrPacket, OkPacket}; use crate::mysql::MySqlError; use crate::url::Url; // Size before a packet is split const MAX_PACKET_SIZE: u32 = 1024; pub(crate) struct MySqlStream { pub(super) stream: BufStream<MaybeTlsStream>, // Is the stream ready to send commands // Put another way, are we still expecting an EOF or OK packet to terminate pub(super) is_ready: bool, // Active capabilities pub(super) capabilities: Capabilities, // Packets in a command sequence have an incrementing sequence number // This number must be 0 at the start of each command pub(super) seq_no: u8, // Packets are buffered into a second buffer from the stream // as we may have compressed or split packets to figure out before // decoding packet_buf: Vec<u8>, packet_len: usize, } impl MySqlStream { pub(super) async fn new(url: &Url) -> crate::Result<Self> { let stream = MaybeTlsStream::connect(&url, 3306).await?; let mut capabilities = Capabilities::PROTOCOL_41 | Capabilities::IGNORE_SPACE | Capabilities::DEPRECATE_EOF | Capabilities::FOUND_ROWS | Capabilities::TRANSACTIONS | Capabilities::SECURE_CONNECTION | Capabilities::PLUGIN_AUTH_LENENC_DATA | Capabilities::MULTI_STATEMENTS | Capabilities::MULTI_RESULTS | Capabilities::PLUGIN_AUTH; if url.database().is_some() { capabilities |= Capabilities::CONNECT_WITH_DB; } if cfg!(feature = "tls") { capabilities |= Capabilities::SSL; } Ok(Self { capabilities, stream: BufStream::new(stream), packet_buf: Vec::with_capacity(MAX_PACKET_SIZE as usize), packet_len: 0, seq_no: 0, is_ready: true, }) } pub(super) fn is_tls(&self) -> bool { self.stream.is_tls() } pub(super) fn shutdown(&self) -> crate::Result<()> { Ok(self.stream.shutdown(Shutdown::Both)?) } #[inline] pub(super) async fn send<T>(&mut self, packet: T, initial: bool) -> crate::Result<()> where T: Encode + std::fmt::Debug, { if initial { self.seq_no = 0; } self.write(packet); self.flush().await } #[inline] pub(super) async fn flush(&mut self) -> crate::Result<()> { Ok(self.stream.flush().await?) } /// Write the packet to the buffered stream ( do not send to the server ) pub(super) fn write<T>(&mut self, packet: T) where T: Encode, { let buf = self.stream.buffer_mut(); // Allocate room for the header that we write after the packet; // so, we can get an accurate and cheap measure of packet length let header_offset = buf.len(); buf.advance(4); packet.encode(buf, self.capabilities); // Determine length of encoded packet // and write to allocated header let len = buf.len() - header_offset - 4; let mut header = &mut buf[header_offset..]; LittleEndian::write_u32(&mut header, len as u32); // Take the last sequence number received, if any, and increment by 1 // If there was no sequence number, we only increment if we split packets header[3] = self.seq_no; self.seq_no = self.seq_no.wrapping_add(1); } #[inline] pub(super) async fn receive(&mut self) -> crate::Result<&[u8]> { self.read().await?; Ok(self.packet()) } pub(super) async fn read(&mut self) -> crate::Result<()> { self.packet_buf.clear(); self.packet_len = 0; // Read the packet header which contains the length and the sequence number // https://dev.mysql.com/doc/dev/mysql-server/8.0.12/page_protocol_basic_packets.html // https://mariadb.com/kb/en/library/0-packet/#standard-packet let mut header = self.stream.peek(4_usize).await?; self.packet_len = header.get_uint::<LittleEndian>(3)? as usize; self.seq_no = header.get_u8()?.wrapping_add(1); self.stream.consume(4); // Read the packet body and copy it into our internal buf // We must have a separate buffer around the stream as we can't operate directly // on bytes returned from the stream. We have various kinds of payload manipulation // that must be handled before decoding. let payload = self.stream.peek(self.packet_len).await?; self.packet_buf.reserve(payload.len()); self.packet_buf.extend_from_slice(payload); self.stream.consume(self.packet_len); // TODO: Implement packet compression // TODO: Implement packet joining Ok(()) } /// Returns a reference to the most recently received packet data. /// A call to `read` invalidates this buffer. #[inline] pub(super) fn packet(&self) -> &[u8] { &self.packet_buf[..self.packet_len] } } impl MySqlStream { pub(crate) async fn maybe_receive_eof(&mut self) -> crate::Result<()> { if !self.capabilities.contains(Capabilities::DEPRECATE_EOF) { let _eof = EofPacket::read(self.receive().await?)?; } Ok(()) } pub(crate) fn maybe_handle_eof(&mut self) -> crate::Result<Option<EofPacket>> { if !self.capabilities.contains(Capabilities::DEPRECATE_EOF) && self.packet()[0] == 0xFE { Ok(Some(EofPacket::read(self.packet())?)) } else { Ok(None) } } pub(crate) fn handle_unexpected<T>(&mut self) -> crate::Result<T> { Err(protocol_err!("unexpected packet identifier 0x{:X?}", self.packet()[0]).into()) } pub(crate) fn handle_err<T>(&mut self) -> crate::Result<T> { self.is_ready = true; Err(MySqlError(ErrPacket::read(self.packet(), self.capabilities)?).into()) } pub(crate) fn handle_ok(&mut self) -> crate::Result<OkPacket> { self.is_ready = true; OkPacket::read(self.packet()) } pub(crate) async fn wait_until_ready(&mut self) -> crate::Result<()> { if !self.is_ready { loop { let packet_id = self.receive().await?[0]; match packet_id { 0xFE if self.packet().len() < 0xFF_FF_FF => { // OK or EOF packet self.is_ready = true; break; } 0xFF => { // ERR packet self.is_ready = true; return self.handle_err(); } _ => { // Something else; skip } } } } Ok(()) } }
use failure_derive::*; use gobble::StrungError; #[derive(Debug, PartialEq, Fail)] #[fail(display = "Err on line {}: {}", line, err)] pub struct LineErr { pub line: usize, pub err: TokErr, } #[derive(Debug, PartialEq, Fail)] pub enum TokErr { #[fail(display = "{}", 0)] Mess(String), #[fail(display = "Not Set : {}", 0)] NotSet(&'static str), #[fail(display = "{}", 0)] ParseErr(StrungError), #[fail(display = "Cannot parse int")] ParseIntErr, #[fail(display = "No Token")] NoToken, #[fail(display = "Cannot work for negative time")] NegativeTime, #[fail(display = "Processing errors {:?}", 0)] Lines(Vec<LineErr>), } impl TokErr { pub fn on_line(self, n: usize) -> LineErr { LineErr { line: n, err: self } } } impl From<&str> for TokErr { fn from(s: &str) -> Self { TokErr::Mess(s.to_string()) } } impl From<String> for TokErr { fn from(s: String) -> Self { TokErr::Mess(s.to_string()) } } impl From<std::num::ParseIntError> for TokErr { fn from(_: std::num::ParseIntError) -> Self { TokErr::ParseIntErr } } impl From<gobble::StrungError> for TokErr { fn from(e: gobble::StrungError) -> Self { TokErr::ParseErr(e) } }
//! # s-expression //! //! ```rust #![doc = include_str!("../../examples/s_expression/parser.rs")] //! ```
pub use atexit::_run_exitfuncs; pub(crate) use atexit::make_module; #[pymodule] mod atexit { use crate::{function::FuncArgs, AsObject, PyObjectRef, PyResult, VirtualMachine}; #[pyfunction] fn register(func: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef { vm.state.atexit_funcs.lock().push((func.clone(), args)); func } #[pyfunction] fn _clear(vm: &VirtualMachine) { vm.state.atexit_funcs.lock().clear(); } #[pyfunction] fn unregister(func: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let mut funcs = vm.state.atexit_funcs.lock(); let mut i = 0; while i < funcs.len() { if vm.bool_eq(&funcs[i].0, &func)? { funcs.remove(i); } else { i += 1; } } Ok(()) } #[pyfunction] pub fn _run_exitfuncs(vm: &VirtualMachine) { let funcs: Vec<_> = std::mem::take(&mut *vm.state.atexit_funcs.lock()); for (func, args) in funcs.into_iter().rev() { if let Err(e) = func.call(args, vm) { let exit = e.fast_isinstance(vm.ctx.exceptions.system_exit); vm.run_unraisable(e, Some("Error in atexit._run_exitfuncs".to_owned()), func); if exit { break; } } } } #[pyfunction] fn _ncallbacks(vm: &VirtualMachine) -> usize { vm.state.atexit_funcs.lock().len() } }
fn main() { // Add glfw to link path println!(r"cargo:rustc-link-search={}", env!("GLFW3_MINGW_LIBS")); }
use serde::{Deserialize, Serialize}; use serde_json; use std::fs::read_to_string; use toml; #[derive(Serialize, Deserialize, Debug)] struct Config { player: PlayerInfo, } #[derive(Serialize, Deserialize, Debug)] struct PlayerInfo { name: String, rank: u32, } fn main() { let contents = read_to_string("test.toml").unwrap(); let config: Config = toml::from_str(&contents).unwrap(); // dbg!(config); println!("{}", serde_json::to_string_pretty(&config).unwrap()); }
/// ```rust,ignore /// 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 /// /// 示例: /// /// 输入:1->2->4, 1->3->4 /// 输出:1->1->2->3->4->4 /// /// 来源:力扣(LeetCode) /// 链接:https:/// leetcode-cn.com/problems/merge-two-sorted-lists /// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 /// ``` // Definition for singly-linked list. #[derive(PartialEq, Eq, Clone, Debug)] pub struct ListNode { pub val: i32, pub next: Option<Box<ListNode>> } impl ListNode { #[inline] fn new(val: i32) -> Self { ListNode { next: None, val } } } #[allow(dead_code, non_snake_case)] pub fn merge_two_lists(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let (mut l1, mut l2) = (l1, l2); let (mut l1Cursor, mut l2Cursor) = (&mut l1, &mut l2); let mut root = Some(Box::new(ListNode::new(0))); let mut cursor = &mut root; let (mut l1IsEnd, mut l2IsEnd); loop { if *l1Cursor == None && *l2Cursor == None{ break; } l1IsEnd = false; l2IsEnd = false; let l1Val = match l1Cursor { Some(node) => { node.val } None => { l1IsEnd = true; 0 } }; let l2Val = match l2Cursor { Some(node) => { node.val } None => { l2IsEnd = true; 0 } }; let mut nextIsL1 = false; if l1IsEnd || l2IsEnd { if l2IsEnd { nextIsL1 = true; } } else { if l1Val < l2Val { nextIsL1 = true; } } if nextIsL1 { cursor.as_mut().unwrap().next = Some(Box::new(ListNode::new(l1Val))); cursor = &mut cursor.as_mut().unwrap().next; l1Cursor = &mut (*l1Cursor).as_mut().unwrap().next; continue; } else { cursor.as_mut().unwrap().next = Some(Box::new(ListNode::new(l2Val))); cursor = &mut cursor.as_mut().unwrap().next; l2Cursor = &mut (*l2Cursor).as_mut().unwrap().next; } } root.unwrap().next } #[cfg(test)] #[allow(unused_imports)] mod test { use super::*; #[test] fn test_merge_two_lists() { } }
pub mod grounds;
fn calc_loop_size(pk: u64) -> i32 { let sn = 7; let mut v = 1; for i in 1..10_000_000 { v *= sn; v %= 20201227; if v == pk { return i; } } -1 } fn derive_enc(sn: u64, loop_size: i32) -> u64 { let mut v = 1; for _ in 0..loop_size { v *= sn; v %= 20201227; } v } fn main() { // test // let card_pk: u64 = 5764801; // let door_pk: u64 = 17807724; let card_pk: u64 = 1614360; let door_pk: u64 = 7734663; let card_ls = calc_loop_size(card_pk); let door_ls = calc_loop_size(door_pk); let door_enc = derive_enc(door_pk, card_ls); let card_enc = derive_enc(card_pk, door_ls); dbg!(card_ls, door_ls, door_enc, card_enc); }
use std::io; use actix::prelude::*; use actix_broker::{Broker, BrokerSubscribe, SystemBroker}; use actix_web::{get, App, Error, HttpRequest, HttpResponse, HttpServer}; #[derive(Clone, Debug, Message)] #[rtype(result = "()")] struct Hello; struct TestActor; impl Actor for TestActor { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { self.subscribe_async::<SystemBroker, Hello>(ctx); } } impl Handler<Hello> for TestActor { type Result = (); fn handle(&mut self, msg: Hello, _ctx: &mut Self::Context) { println!("TestActor: Received {:?}", msg); } } #[get("/")] async fn index(_req: HttpRequest) -> Result<HttpResponse, Error> { Broker::<SystemBroker>::issue_async(Hello); Ok(HttpResponse::Ok().body("Welcome!")) } #[actix_web::main] async fn main() -> io::Result<()> { TestActor.start(); HttpServer::new(|| App::new().service(index)) .bind("127.0.0.1:8080") .unwrap() .run() .await }
extern crate redis; use std::io::process; use std::libc::SIGTERM; pub static SERVER_PORT: int = 38991; struct RedisServer { process: process::Process, } impl RedisServer { fn new() -> RedisServer { let mut process = process::Process::configure(process::ProcessConfig { program: "redis-server", args: [~"-"], stdout: process::Ignored, stderr: process::Ignored, .. process::ProcessConfig::new() }).unwrap(); let input = format!(" bind 127.0.0.1 port {port} ", port=SERVER_PORT); let _ = process.stdin.get_mut_ref().write(input.as_bytes()); process.stdin = None; RedisServer { process: process } } } impl Drop for RedisServer { fn drop(&mut self) { let _ = self.process.signal(SIGTERM as int); let rv = self.process.wait(); assert!(rv.success()); } } struct TestContext { server: RedisServer, client: redis::Client, } impl TestContext { fn new() -> TestContext { let url = format!("redis://127.0.0.1:{port}/0", port=SERVER_PORT); let server = RedisServer::new(); let mut client; loop { match redis::Client::open(url) { Ok(x) => { client = x; break; } Err(redis::ConnectionRefused) => { std::io::timer::sleep(1); } _ => { fail!("Error on connect"); } } } client.get_connection().unwrap().flushdb(); TestContext { server: server, client: client, } } fn connection(&self) -> redis::Connection { self.client.get_connection().unwrap() } } #[test] fn test_ping() { let ctx = TestContext::new(); let mut con = ctx.connection(); assert!(con.ping() == true); } #[test] fn test_info() { let ctx = TestContext::new(); let mut con = ctx.connection(); let info = con.info(); assert!(*info.find(&~"tcp_port").unwrap() == SERVER_PORT.to_str()); } #[test] fn test_basics() { let ctx = TestContext::new(); let mut con = ctx.connection(); con.set("foo", "bar"); assert!(con.get("foo") == Some(~"bar")); con.rename("foo", "bar"); assert!(con.get("foo") == None); assert!(con.get("bar") == Some(~"bar")); con.del("bar"); assert!(con.get("bar") == None); } #[test] fn test_types() { let ctx = TestContext::new(); let mut con = ctx.connection(); con.set("foo", 42); con.set("bar", "test"); assert!(con.get_type("foo") == redis::StringType); assert!(con.get_type("bar") == redis::StringType); assert!(con.get("foo") == Some(~"42")); assert!(con.get_as::<int>("foo") == Some(42)); assert!(con.get("bar") == Some(~"test")); assert!(con.exists("foo") == true); assert!(con.exists("invalid") == false); } #[test] fn test_script() { let ctx = TestContext::new(); let mut con = ctx.connection(); let script = redis::Script::new(" return tonumber(ARGV[1]) + 1; "); assert!(con.call_script(&script, [], [redis::StrArg("42")]) == redis::Int(43)); con.flush_script_cache(); assert!(con.call_script(&script, [], [redis::StrArg("42")]) == redis::Int(43)); } #[test] fn test_blpop() { let ctx = TestContext::new(); let client = ctx.client; let (port, chan) = Chan::new(); spawn(proc() { let mut con = client.get_connection().unwrap(); let rv = con.blpop(["q"], 5.0); assert!(rv == Some((~"q", ~"awesome"))); chan.send(()); }); spawn(proc() { let mut con = client.get_connection().unwrap(); con.rpush("q", "awesome"); }); port.recv(); } #[test] fn test_scan() { let ctx = TestContext::new(); let mut con = ctx.connection(); for x in range(0, 1000) { con.set(format!("key:{}", x), x); } let mut found = [false, .. 1000]; for item in con.scan("key:*") { let num = item.split(':').nth(1).unwrap(); found[from_str::<uint>(num).unwrap()] = true; } for x in range(0, 100) { assert!(found[x] == true); } }
/* DeepSAFL - state parser ------------------------------------------------------ Written and maintained by Liang Jie <liangjie.mailbox.cn@google.com> Copyright 2018. All rights reserved. */ use super::config; use rand; use rand::Rng; #[derive(PartialEq)] #[derive(Debug)] pub enum FuzzingState{ Ready, Select, CalHavocTimes, StateFlip1(u64), StateFlip2(u64), StateFlip4(u64), StateFlip8(u64), StateFlip16(u64), StateFlip32(u64), StateAddArith8((u64,u8)), StateSubArith8((u64,u8)), StateAddArith16((u64,u16)), StateSubArith16((u64,u16)), StateAddArith16AnotherEndian((u64,u16)), StateSubArith16AnotherEndian((u64,u16)), StateAddArith32((u64,u32)), StateSubArith32((u64,u32)), StateAddArith32AnotherEndian((u64,u32)), StateSubArith32AnotherEndian((u64,u32)), StateInterest8((u64,u8)), StateInterest16((u64,u8)), StateInterest16AnotherEndian((u64,u8)), StateInterest32((u64,u8)), StateInterest32AnotherEndian((u64,u8)), StateHavoc((u64,u8)), End } impl Default for FuzzingState { fn default() -> FuzzingState { FuzzingState::Ready } } #[derive(Default)] #[derive(Debug)] pub struct StateParser{ seed_len: u64, mutate_state: FuzzingState, havoc_outer_times: u64, havoc_inner_times: u8, } impl StateParser { pub fn new() -> StateParser { StateParser{ seed_len:0, mutate_state:FuzzingState::Ready, havoc_outer_times: 0, havoc_inner_times: 0, } } fn set_seed_len(&mut self, input_seed_len:u64) { self.seed_len = input_seed_len; } //calculate the havoc times, needs more information like exe_us, bitmap_size, ... //power schedule is implemented here //Attention: In the initial developing stage, we focus on how to mutate the seed, //so we just use a constant number to replace the calculating result, //in future we may use a structure to represent the seed with its information and other things fn calculate_havoc_outer_times(&mut self){ self.havoc_outer_times = 1+rand::thread_rng().gen_range(0, config::HAVOC_CYCLES_INIT as u64); } fn calculate_havoc_inner_times(&mut self){ self.havoc_inner_times = 1 << (1+rand::thread_rng().gen_range(0, config::HAVOC_STACK_POW2)); } fn state_select_next(&self, len:u64)->FuzzingState { if len == 0 { return FuzzingState::End; } FuzzingState::CalHavocTimes } fn state_cal_havoc_next(&self)->FuzzingState { FuzzingState::StateFlip1(0) //just for test, we should use the last line //FuzzingState::StateInterest8((0,0)) } fn state_flip1_next(&self, len:u64, now_count:u64)->FuzzingState { let state_count = (len << 3)-1; if now_count < state_count { // println!("we are in here {:?}", now_count); return FuzzingState::StateFlip1(now_count+1); } FuzzingState::StateFlip2(0) } fn state_flip2_next(&self, len:u64, now_count:u64)->FuzzingState { let state_count = (len << 3)-2; if now_count < state_count { // println!("we are in here {:?}", now_count); return FuzzingState::StateFlip2(now_count+1); } FuzzingState::StateFlip4(0) } fn state_flip4_next(&self, len:u64, now_count:u64)->FuzzingState { let state_count = (len << 3)-4; if now_count < state_count { // println!("we are in here {:?}", now_count); return FuzzingState::StateFlip4(now_count+1); } FuzzingState::StateFlip8(0) } fn state_flip8_next(&self, len:u64, now_count:u64)->FuzzingState { let state_count = len - 1; if now_count < state_count { // println!("we are in here {:?}", now_count); return FuzzingState::StateFlip8(now_count+1); } //the length of the input is not enough for two bytes if len < 2 { return FuzzingState::StateAddArith8((0,0)); } FuzzingState::StateFlip16(0) } fn state_flip16_next(&self, len:u64, now_count:u64)->FuzzingState { let state_count = len - 2; if now_count < state_count { //println!("we are in here {:?}", now_count); return FuzzingState::StateFlip16(now_count+1); } //the length of the input is not enough for four bytes if len < 4 { return FuzzingState::StateAddArith8((0,0)); } FuzzingState::StateFlip32(0) } fn state_flip32_next(&self, len:u64, now_count:u64)->FuzzingState { let state_count = len - 4; if now_count < state_count { //println!("we are in here {:?}", now_count); return FuzzingState::StateFlip32(now_count+1); } FuzzingState::StateAddArith8((0,0)) } fn state_arith8_add_next(&self, len:u64, now_count:u64, arith_count:u8)->FuzzingState { let state_count = len; if now_count < state_count { if arith_count < config::ARITH_MAX { return FuzzingState::StateAddArith8((now_count, arith_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateSubArith8((0,0)) } return FuzzingState::StateAddArith8((now_count+1, 0)); } } FuzzingState::End } fn state_arith8_sub_next(&self, len:u64, now_count:u64, arith_count:u8)->FuzzingState { let state_count = len; if now_count < state_count { if arith_count < config::ARITH_MAX { return FuzzingState::StateSubArith8((now_count, arith_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State //the length of the input is not enough for two bytes if len < 2 { return FuzzingState::StateInterest8((0,0)); } return FuzzingState::StateAddArith16((0, 0)); } return FuzzingState::StateSubArith8((now_count+1, 0)); } } FuzzingState::End } fn state_arith16_add_next(&self, len:u64, now_count:u64, arith_count:u16)->FuzzingState { let state_count = len-1; if now_count < state_count { if arith_count < config::ARITH_MAX as u16 { return FuzzingState::StateAddArith16((now_count, arith_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateSubArith16((0, 0)); } return FuzzingState::StateAddArith16((now_count+1, 0)); } } FuzzingState::End } fn state_arith16_sub_next(&self, len:u64, now_count:u64, arith_count:u16)->FuzzingState { let state_count = len-1; if now_count < state_count { if arith_count < config::ARITH_MAX as u16 { return FuzzingState::StateSubArith16((now_count, arith_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateAddArith16AnotherEndian((0, 0)); } return FuzzingState::StateSubArith16((now_count+1, 0)); } } FuzzingState::End } fn state_arith16_add_another_endian_next(&self, len:u64, now_count:u64, arith_count:u16)->FuzzingState { let state_count = len-1; if now_count < state_count { if arith_count < config::ARITH_MAX as u16 { return FuzzingState::StateAddArith16AnotherEndian((now_count, arith_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateSubArith16AnotherEndian((0, 0)); } return FuzzingState::StateAddArith16AnotherEndian((now_count+1, 0)); } } FuzzingState::End } fn state_arith16_sub_another_endian_next(&self, len:u64, now_count:u64, arith_count:u16)->FuzzingState { let state_count = len-1; if now_count < state_count { if arith_count < config::ARITH_MAX as u16 { return FuzzingState::StateSubArith16AnotherEndian((now_count, arith_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State //the length of the input is not enough for four bytes if len < 4 { return FuzzingState::StateInterest8((0,0)); } return FuzzingState::StateAddArith32((0,0)); } return FuzzingState::StateSubArith16AnotherEndian((now_count+1, 0)); } } FuzzingState::End } fn state_arith32_add_next(&self, len:u64, now_count:u64, arith_count:u32)->FuzzingState { let state_count = len-3; if now_count < state_count { if arith_count < config::ARITH_MAX as u32 { return FuzzingState::StateAddArith32((now_count, arith_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateSubArith32((0,0)); } return FuzzingState::StateAddArith32((now_count+1, 0)); } } FuzzingState::End } fn state_arith32_sub_next(&self, len:u64, now_count:u64, arith_count:u32)->FuzzingState { let state_count = len-3; if now_count < state_count { if arith_count < config::ARITH_MAX as u32 { return FuzzingState::StateSubArith32((now_count, arith_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateAddArith32AnotherEndian((0,0)); } return FuzzingState::StateSubArith32((now_count+1, 0)); } } FuzzingState::End } fn state_arith32_add_another_endian_next(&self, len:u64, now_count:u64, arith_count:u32)->FuzzingState { let state_count = len-3; if now_count < state_count { if arith_count < config::ARITH_MAX as u32 { return FuzzingState::StateAddArith32AnotherEndian((now_count, arith_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateSubArith32AnotherEndian((0,0)); } return FuzzingState::StateAddArith32AnotherEndian((now_count+1, 0)); } } FuzzingState::End } fn state_arith32_sub_another_endian_next(&self, len:u64, now_count:u64, arith_count:u32)->FuzzingState { let state_count = len-3; if now_count < state_count { if arith_count < config::ARITH_MAX as u32 { return FuzzingState::StateSubArith32AnotherEndian((now_count, arith_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateInterest8((0,0)); } return FuzzingState::StateSubArith32AnotherEndian((now_count+1, 0)); } } FuzzingState::End } fn state_interesting8_next(&self, len:u64, now_count:u64, index_count:u8)->FuzzingState { let state_count = len; if now_count < state_count { if index_count < (config::INTERESTING_8_CNT-1) as u8 { return FuzzingState::StateInterest8((now_count, index_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State //the length of the input is not enough for two bytes if len < 2 { return FuzzingState::StateHavoc((0,0)); } return FuzzingState::StateInterest16((0,0)); } return FuzzingState::StateInterest8((now_count+1, 0)); } } FuzzingState::End } fn state_interesting16_next(&self, len:u64, now_count:u64, index_count:u8)->FuzzingState { let state_count = len-1; if now_count < state_count { if index_count < (config::INTERESTING_16_CNT-1) as u8 { return FuzzingState::StateInterest16((now_count, index_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateInterest16AnotherEndian((0,0)); } return FuzzingState::StateInterest16((now_count+1, 0)); } } FuzzingState::End } fn state_interesting16_another_endian_next(&self, len:u64, now_count:u64, index_count:u8)->FuzzingState { let state_count = len-1; if now_count < state_count { if index_count < (config::INTERESTING_16_CNT-1) as u8 { return FuzzingState::StateInterest16AnotherEndian((now_count, index_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State if len < 4 { return FuzzingState::StateHavoc((0,0)); } return FuzzingState::StateInterest32((0,0)); } return FuzzingState::StateInterest16AnotherEndian((now_count+1, 0)); } } FuzzingState::End } fn state_interesting32_next(&self, len:u64, now_count:u64, index_count:u8)->FuzzingState { let state_count = len-3; if now_count < state_count { if index_count < (config::INTERESTING_32_CNT-1) as u8 { return FuzzingState::StateInterest32((now_count, index_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateInterest32AnotherEndian((0,0)); } return FuzzingState::StateInterest32((now_count+1, 0)); } } FuzzingState::End } fn state_interesting32_another_endian_next(&self, len:u64, now_count:u64, index_count:u8)->FuzzingState { let state_count = len-3; if now_count < state_count { if index_count < (config::INTERESTING_32_CNT-1) as u8 { return FuzzingState::StateInterest32AnotherEndian((now_count, index_count+1)); } else { if now_count == state_count-1 { // we have doing all things, let's go to next out State return FuzzingState::StateHavoc((0,0)); //just for a simple test to skip havoc //return FuzzingState::End; } return FuzzingState::StateInterest32AnotherEndian((now_count+1, 0)); } } FuzzingState::End } fn state_havoc_next(&self, outer_count:u64, inner_count:u8)->FuzzingState { if outer_count < self.havoc_outer_times { if inner_count < self.havoc_inner_times{ return FuzzingState::StateHavoc((outer_count, inner_count+1)); } else { if outer_count == self.havoc_outer_times-1 { // we have doing all things, let's go to next out State return FuzzingState::End; } return FuzzingState::StateHavoc((outer_count+1, 0)); } } FuzzingState::End } pub fn get_next_mutate_state(&mut self, input_seed_len:u64)->FuzzingState { match self.mutate_state { //最初始状态,更新存储状态,进入选择状态 FuzzingState::Ready => { self.set_seed_len(input_seed_len); return FuzzingState::Select }, FuzzingState::Select => { return self.state_select_next(self.seed_len) }, FuzzingState::CalHavocTimes => { self.calculate_havoc_outer_times(); self.calculate_havoc_inner_times(); return self.state_cal_havoc_next() }, FuzzingState::StateFlip1(i) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_flip1_next(self.seed_len, i) }, FuzzingState::StateFlip2(i) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_flip2_next(self.seed_len, i) }, FuzzingState::StateFlip4(i) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_flip4_next(self.seed_len, i) }, FuzzingState::StateFlip8(i) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_flip8_next(self.seed_len, i) }, FuzzingState::StateFlip16(i) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_flip16_next(self.seed_len, i) }, FuzzingState::StateFlip32(i) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_flip32_next(self.seed_len, i) }, FuzzingState::StateAddArith8((i,arith_j)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_arith8_add_next(self.seed_len, i, arith_j) }, FuzzingState::StateSubArith8((i,arith_j)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_arith8_sub_next(self.seed_len, i, arith_j) }, FuzzingState::StateAddArith16((i,arith_j)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_arith16_add_next(self.seed_len, i, arith_j) }, FuzzingState::StateSubArith16((i,arith_j)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_arith16_sub_next(self.seed_len, i, arith_j) }, FuzzingState::StateAddArith16AnotherEndian((i,arith_j)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_arith16_add_another_endian_next(self.seed_len, i, arith_j) }, FuzzingState::StateSubArith16AnotherEndian((i,arith_j)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_arith16_sub_another_endian_next(self.seed_len, i, arith_j) }, FuzzingState::StateAddArith32((i,arith_j)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_arith32_add_next(self.seed_len, i, arith_j) }, FuzzingState::StateSubArith32((i,arith_j)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_arith32_sub_next(self.seed_len, i, arith_j) }, FuzzingState::StateAddArith32AnotherEndian((i,arith_j)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_arith32_add_another_endian_next(self.seed_len, i, arith_j) }, FuzzingState::StateSubArith32AnotherEndian((i,arith_j)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_arith32_sub_another_endian_next(self.seed_len, i, arith_j) }, FuzzingState::StateInterest8((i,index_count)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_interesting8_next(self.seed_len, i, index_count) }, FuzzingState::StateInterest16((i,index_count)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_interesting16_next(self.seed_len, i, index_count) }, FuzzingState::StateInterest16AnotherEndian((i, index_count)) => { return self.state_interesting16_another_endian_next(self.seed_len, i, index_count) }, FuzzingState::StateInterest32((i,index_count)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_interesting32_next(self.seed_len, i, index_count) }, FuzzingState::StateInterest32AnotherEndian((i,index_count)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_interesting32_another_endian_next(self.seed_len, i, index_count) }, FuzzingState::StateHavoc((outer_cnt,inner_cnt)) => { // println!("we are now in the state {:?}",self.mutate_state); return self.state_havoc_next(outer_cnt,inner_cnt) }, _=> return FuzzingState::Ready, } } pub fn change_to_next_state(&mut self, next_state: FuzzingState) { self.mutate_state = next_state; println!("We just finish the state {:?}", self.mutate_state); //To do: update next internal state; } }
// This file was generated by gir (https://github.com/gtk-rs/gir) // from ../gir-files // DO NOT EDIT use crate::Address; use crate::AuthDomain; use crate::ClientContext; use crate::Message; #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] use crate::ServerListenOptions; use crate::Socket; #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] use crate::URI; #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] use crate::WebsocketConnection; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::ToValue; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] use std::ptr; glib::wrapper! { #[doc(alias = "SoupServer")] pub struct Server(Object<ffi::SoupServer, ffi::SoupServerClass>); match fn { type_ => || ffi::soup_server_get_type(), } } impl Server { //#[doc(alias = "soup_server_new")] //pub fn new(optname1: &str, : /*Unknown conversion*//*Unimplemented*/Fundamental: VarArgs) -> Option<Server> { // unsafe { TODO: call ffi:soup_server_new() } //} } pub const NONE_SERVER: Option<&Server> = None; pub trait ServerExt: 'static { #[cfg(any(feature = "v2_50", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))] #[doc(alias = "soup_server_accept_iostream")] fn accept_iostream<P: IsA<gio::IOStream>, Q: IsA<gio::SocketAddress>, R: IsA<gio::SocketAddress>>(&self, stream: &P, local_addr: Option<&Q>, remote_addr: Option<&R>) -> Result<(), glib::Error>; #[doc(alias = "soup_server_add_auth_domain")] fn add_auth_domain<P: IsA<AuthDomain>>(&self, auth_domain: &P); //#[cfg(any(feature = "v2_50", feature = "dox"))] //#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))] //#[doc(alias = "soup_server_add_early_handler")] //fn add_early_handler(&self, path: Option<&str>, callback: /*Unimplemented*/Fn(&Server, &Message, &str, /*Unimplemented*/HashTable TypeId { ns_id: 0, id: 28 }/TypeId { ns_id: 0, id: 28 }, &ClientContext), user_data: /*Unimplemented*/Option<Fundamental: Pointer>); //#[doc(alias = "soup_server_add_handler")] //fn add_handler(&self, path: Option<&str>, callback: /*Unimplemented*/Fn(&Server, &Message, &str, /*Unimplemented*/HashTable TypeId { ns_id: 0, id: 28 }/TypeId { ns_id: 0, id: 28 }, &ClientContext), user_data: /*Unimplemented*/Option<Fundamental: Pointer>); #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] #[doc(alias = "soup_server_add_websocket_extension")] fn add_websocket_extension(&self, extension_type: glib::types::Type); #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] #[doc(alias = "soup_server_add_websocket_handler")] fn add_websocket_handler<P: Fn(&Server, &WebsocketConnection, &str, &ClientContext) + 'static>(&self, path: Option<&str>, origin: Option<&str>, protocols: &[&str], callback: P); #[doc(alias = "soup_server_disconnect")] fn disconnect(&self); #[doc(alias = "soup_server_get_async_context")] #[doc(alias = "get_async_context")] fn async_context(&self) -> Option<glib::MainContext>; #[doc(alias = "soup_server_get_listener")] #[doc(alias = "get_listener")] fn listener(&self) -> Option<Socket>; #[doc(alias = "soup_server_get_listeners")] #[doc(alias = "get_listeners")] fn listeners(&self) -> Vec<gio::Socket>; #[doc(alias = "soup_server_get_port")] #[doc(alias = "get_port")] fn port(&self) -> u32; #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] #[doc(alias = "soup_server_get_uris")] #[doc(alias = "get_uris")] fn uris(&self) -> Vec<URI>; #[doc(alias = "soup_server_is_https")] fn is_https(&self) -> bool; #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] #[doc(alias = "soup_server_listen")] fn listen<P: IsA<gio::SocketAddress>>(&self, address: &P, options: ServerListenOptions) -> Result<(), glib::Error>; #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] #[doc(alias = "soup_server_listen_all")] fn listen_all(&self, port: u32, options: ServerListenOptions) -> Result<(), glib::Error>; #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] #[doc(alias = "soup_server_listen_fd")] fn listen_fd(&self, fd: i32, options: ServerListenOptions) -> Result<(), glib::Error>; #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] #[doc(alias = "soup_server_listen_local")] fn listen_local(&self, port: u32, options: ServerListenOptions) -> Result<(), glib::Error>; #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] #[doc(alias = "soup_server_listen_socket")] fn listen_socket<P: IsA<gio::Socket>>(&self, socket: &P, options: ServerListenOptions) -> Result<(), glib::Error>; #[doc(alias = "soup_server_pause_message")] fn pause_message<P: IsA<Message>>(&self, msg: &P); #[doc(alias = "soup_server_quit")] fn quit(&self); #[doc(alias = "soup_server_remove_auth_domain")] fn remove_auth_domain<P: IsA<AuthDomain>>(&self, auth_domain: &P); #[doc(alias = "soup_server_remove_handler")] fn remove_handler(&self, path: &str); #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] #[doc(alias = "soup_server_remove_websocket_extension")] fn remove_websocket_extension(&self, extension_type: glib::types::Type); #[doc(alias = "soup_server_run")] fn run(&self); #[doc(alias = "soup_server_run_async")] fn run_async(&self); #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] #[doc(alias = "soup_server_set_ssl_cert_file")] fn set_ssl_cert_file(&self, ssl_cert_file: &str, ssl_key_file: &str) -> Result<(), glib::Error>; #[doc(alias = "soup_server_unpause_message")] fn unpause_message<P: IsA<Message>>(&self, msg: &P); #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] #[doc(alias = "add-websocket-extension")] fn set_add_websocket_extension(&self, add_websocket_extension: glib::types::Type); #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] #[doc(alias = "http-aliases")] fn http_aliases(&self) -> Vec<glib::GString>; #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] #[doc(alias = "http-aliases")] fn set_http_aliases(&self, http_aliases: &[&str]); #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] #[doc(alias = "https-aliases")] fn https_aliases(&self) -> Vec<glib::GString>; #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] #[doc(alias = "https-aliases")] fn set_https_aliases(&self, https_aliases: &[&str]); fn interface(&self) -> Option<Address>; #[doc(alias = "raw-paths")] fn is_raw_paths(&self) -> bool; #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] #[doc(alias = "remove-websocket-extension")] fn set_remove_websocket_extension(&self, remove_websocket_extension: glib::types::Type); #[doc(alias = "server-header")] fn server_header(&self) -> Option<glib::GString>; #[doc(alias = "server-header")] fn set_server_header(&self, server_header: Option<&str>); #[doc(alias = "ssl-cert-file")] fn ssl_cert_file(&self) -> Option<glib::GString>; #[doc(alias = "ssl-key-file")] fn ssl_key_file(&self) -> Option<glib::GString>; #[cfg(any(feature = "v2_38", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))] #[doc(alias = "tls-certificate")] fn tls_certificate(&self) -> Option<gio::TlsCertificate>; #[doc(alias = "request-aborted")] fn connect_request_aborted<F: Fn(&Self, &Message, &ClientContext) + 'static>(&self, f: F) -> SignalHandlerId; #[doc(alias = "request-finished")] fn connect_request_finished<F: Fn(&Self, &Message, &ClientContext) + 'static>(&self, f: F) -> SignalHandlerId; #[doc(alias = "request-read")] fn connect_request_read<F: Fn(&Self, &Message, &ClientContext) + 'static>(&self, f: F) -> SignalHandlerId; #[doc(alias = "request-started")] fn connect_request_started<F: Fn(&Self, &Message, &ClientContext) + 'static>(&self, f: F) -> SignalHandlerId; #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] #[doc(alias = "add-websocket-extension")] fn connect_add_websocket_extension_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] #[doc(alias = "http-aliases")] fn connect_http_aliases_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] #[doc(alias = "https-aliases")] fn connect_https_aliases_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] #[doc(alias = "remove-websocket-extension")] fn connect_remove_websocket_extension_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; #[doc(alias = "server-header")] fn connect_server_header_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<Server>> ServerExt for O { #[cfg(any(feature = "v2_50", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))] fn accept_iostream<P: IsA<gio::IOStream>, Q: IsA<gio::SocketAddress>, R: IsA<gio::SocketAddress>>(&self, stream: &P, local_addr: Option<&Q>, remote_addr: Option<&R>) -> Result<(), glib::Error> { unsafe { let mut error = ptr::null_mut(); let _ = ffi::soup_server_accept_iostream(self.as_ref().to_glib_none().0, stream.as_ref().to_glib_none().0, local_addr.map(|p| p.as_ref()).to_glib_none().0, remote_addr.map(|p| p.as_ref()).to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } fn add_auth_domain<P: IsA<AuthDomain>>(&self, auth_domain: &P) { unsafe { ffi::soup_server_add_auth_domain(self.as_ref().to_glib_none().0, auth_domain.as_ref().to_glib_none().0); } } //#[cfg(any(feature = "v2_50", feature = "dox"))] //#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))] //fn add_early_handler(&self, path: Option<&str>, callback: /*Unimplemented*/Fn(&Server, &Message, &str, /*Unimplemented*/HashTable TypeId { ns_id: 0, id: 28 }/TypeId { ns_id: 0, id: 28 }, &ClientContext), user_data: /*Unimplemented*/Option<Fundamental: Pointer>) { // unsafe { TODO: call ffi:soup_server_add_early_handler() } //} //fn add_handler(&self, path: Option<&str>, callback: /*Unimplemented*/Fn(&Server, &Message, &str, /*Unimplemented*/HashTable TypeId { ns_id: 0, id: 28 }/TypeId { ns_id: 0, id: 28 }, &ClientContext), user_data: /*Unimplemented*/Option<Fundamental: Pointer>) { // unsafe { TODO: call ffi:soup_server_add_handler() } //} #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] fn add_websocket_extension(&self, extension_type: glib::types::Type) { unsafe { ffi::soup_server_add_websocket_extension(self.as_ref().to_glib_none().0, extension_type.into_glib()); } } #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] fn add_websocket_handler<P: Fn(&Server, &WebsocketConnection, &str, &ClientContext) + 'static>(&self, path: Option<&str>, origin: Option<&str>, protocols: &[&str], callback: P) { let callback_data: Box_<P> = Box_::new(callback); unsafe extern "C" fn callback_func<P: Fn(&Server, &WebsocketConnection, &str, &ClientContext) + 'static>(server: *mut ffi::SoupServer, connection: *mut ffi::SoupWebsocketConnection, path: *const libc::c_char, client: *mut ffi::SoupClientContext, user_data: glib::ffi::gpointer) { let server = from_glib_borrow(server); let connection = from_glib_borrow(connection); let path: Borrowed<glib::GString> = from_glib_borrow(path); let client = from_glib_borrow(client); let callback: &P = &*(user_data as *mut _); (*callback)(&server, &connection, path.as_str(), &client); } let callback = Some(callback_func::<P> as _); unsafe extern "C" fn destroy_func<P: Fn(&Server, &WebsocketConnection, &str, &ClientContext) + 'static>(data: glib::ffi::gpointer) { let _callback: Box_<P> = Box_::from_raw(data as *mut _); } let destroy_call6 = Some(destroy_func::<P> as _); let super_callback0: Box_<P> = callback_data; unsafe { ffi::soup_server_add_websocket_handler(self.as_ref().to_glib_none().0, path.to_glib_none().0, origin.to_glib_none().0, protocols.to_glib_none().0, callback, Box_::into_raw(super_callback0) as *mut _, destroy_call6); } } fn disconnect(&self) { unsafe { ffi::soup_server_disconnect(self.as_ref().to_glib_none().0); } } fn async_context(&self) -> Option<glib::MainContext> { unsafe { from_glib_none(ffi::soup_server_get_async_context(self.as_ref().to_glib_none().0)) } } fn listener(&self) -> Option<Socket> { unsafe { from_glib_none(ffi::soup_server_get_listener(self.as_ref().to_glib_none().0)) } } fn listeners(&self) -> Vec<gio::Socket> { unsafe { FromGlibPtrContainer::from_glib_container(ffi::soup_server_get_listeners(self.as_ref().to_glib_none().0)) } } fn port(&self) -> u32 { unsafe { ffi::soup_server_get_port(self.as_ref().to_glib_none().0) } } #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] fn uris(&self) -> Vec<URI> { unsafe { FromGlibPtrContainer::from_glib_full(ffi::soup_server_get_uris(self.as_ref().to_glib_none().0)) } } fn is_https(&self) -> bool { unsafe { from_glib(ffi::soup_server_is_https(self.as_ref().to_glib_none().0)) } } #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] fn listen<P: IsA<gio::SocketAddress>>(&self, address: &P, options: ServerListenOptions) -> Result<(), glib::Error> { unsafe { let mut error = ptr::null_mut(); let _ = ffi::soup_server_listen(self.as_ref().to_glib_none().0, address.as_ref().to_glib_none().0, options.into_glib(), &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] fn listen_all(&self, port: u32, options: ServerListenOptions) -> Result<(), glib::Error> { unsafe { let mut error = ptr::null_mut(); let _ = ffi::soup_server_listen_all(self.as_ref().to_glib_none().0, port, options.into_glib(), &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] fn listen_fd(&self, fd: i32, options: ServerListenOptions) -> Result<(), glib::Error> { unsafe { let mut error = ptr::null_mut(); let _ = ffi::soup_server_listen_fd(self.as_ref().to_glib_none().0, fd, options.into_glib(), &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] fn listen_local(&self, port: u32, options: ServerListenOptions) -> Result<(), glib::Error> { unsafe { let mut error = ptr::null_mut(); let _ = ffi::soup_server_listen_local(self.as_ref().to_glib_none().0, port, options.into_glib(), &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] fn listen_socket<P: IsA<gio::Socket>>(&self, socket: &P, options: ServerListenOptions) -> Result<(), glib::Error> { unsafe { let mut error = ptr::null_mut(); let _ = ffi::soup_server_listen_socket(self.as_ref().to_glib_none().0, socket.as_ref().to_glib_none().0, options.into_glib(), &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } fn pause_message<P: IsA<Message>>(&self, msg: &P) { unsafe { ffi::soup_server_pause_message(self.as_ref().to_glib_none().0, msg.as_ref().to_glib_none().0); } } fn quit(&self) { unsafe { ffi::soup_server_quit(self.as_ref().to_glib_none().0); } } fn remove_auth_domain<P: IsA<AuthDomain>>(&self, auth_domain: &P) { unsafe { ffi::soup_server_remove_auth_domain(self.as_ref().to_glib_none().0, auth_domain.as_ref().to_glib_none().0); } } fn remove_handler(&self, path: &str) { unsafe { ffi::soup_server_remove_handler(self.as_ref().to_glib_none().0, path.to_glib_none().0); } } #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] fn remove_websocket_extension(&self, extension_type: glib::types::Type) { unsafe { ffi::soup_server_remove_websocket_extension(self.as_ref().to_glib_none().0, extension_type.into_glib()); } } fn run(&self) { unsafe { ffi::soup_server_run(self.as_ref().to_glib_none().0); } } fn run_async(&self) { unsafe { ffi::soup_server_run_async(self.as_ref().to_glib_none().0); } } #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] fn set_ssl_cert_file(&self, ssl_cert_file: &str, ssl_key_file: &str) -> Result<(), glib::Error> { unsafe { let mut error = ptr::null_mut(); let _ = ffi::soup_server_set_ssl_cert_file(self.as_ref().to_glib_none().0, ssl_cert_file.to_glib_none().0, ssl_key_file.to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } fn unpause_message<P: IsA<Message>>(&self, msg: &P) { unsafe { ffi::soup_server_unpause_message(self.as_ref().to_glib_none().0, msg.as_ref().to_glib_none().0); } } #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] fn set_add_websocket_extension(&self, add_websocket_extension: glib::types::Type) { unsafe { glib::gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"add-websocket-extension\0".as_ptr() as *const _, add_websocket_extension.to_value().to_glib_none().0); } } #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] fn http_aliases(&self) -> Vec<glib::GString> { unsafe { let mut value = glib::Value::from_type(<Vec<glib::GString> as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"http-aliases\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `http-aliases` getter") } } #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] fn set_http_aliases(&self, http_aliases: &[&str]) { unsafe { glib::gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"http-aliases\0".as_ptr() as *const _, http_aliases.to_value().to_glib_none().0); } } #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] fn https_aliases(&self) -> Vec<glib::GString> { unsafe { let mut value = glib::Value::from_type(<Vec<glib::GString> as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"https-aliases\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `https-aliases` getter") } } #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] fn set_https_aliases(&self, https_aliases: &[&str]) { unsafe { glib::gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"https-aliases\0".as_ptr() as *const _, https_aliases.to_value().to_glib_none().0); } } fn interface(&self) -> Option<Address> { unsafe { let mut value = glib::Value::from_type(<Address as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"interface\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `interface` getter") } } fn is_raw_paths(&self) -> bool { unsafe { let mut value = glib::Value::from_type(<bool as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"raw-paths\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `raw-paths` getter") } } #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] fn set_remove_websocket_extension(&self, remove_websocket_extension: glib::types::Type) { unsafe { glib::gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"remove-websocket-extension\0".as_ptr() as *const _, remove_websocket_extension.to_value().to_glib_none().0); } } fn server_header(&self) -> Option<glib::GString> { unsafe { let mut value = glib::Value::from_type(<glib::GString as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"server-header\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `server-header` getter") } } fn set_server_header(&self, server_header: Option<&str>) { unsafe { glib::gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"server-header\0".as_ptr() as *const _, server_header.to_value().to_glib_none().0); } } fn ssl_cert_file(&self) -> Option<glib::GString> { unsafe { let mut value = glib::Value::from_type(<glib::GString as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"ssl-cert-file\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `ssl-cert-file` getter") } } fn ssl_key_file(&self) -> Option<glib::GString> { unsafe { let mut value = glib::Value::from_type(<glib::GString as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"ssl-key-file\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `ssl-key-file` getter") } } #[cfg(any(feature = "v2_38", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))] fn tls_certificate(&self) -> Option<gio::TlsCertificate> { unsafe { let mut value = glib::Value::from_type(<gio::TlsCertificate as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"tls-certificate\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `tls-certificate` getter") } } fn connect_request_aborted<F: Fn(&Self, &Message, &ClientContext) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn request_aborted_trampoline<P: IsA<Server>, F: Fn(&P, &Message, &ClientContext) + 'static>(this: *mut ffi::SoupServer, message: *mut ffi::SoupMessage, client: *mut ffi::SoupClientContext, f: glib::ffi::gpointer) { let f: &F = &*(f as *const F); f(Server::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(message), &from_glib_borrow(client)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"request-aborted\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(request_aborted_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } fn connect_request_finished<F: Fn(&Self, &Message, &ClientContext) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn request_finished_trampoline<P: IsA<Server>, F: Fn(&P, &Message, &ClientContext) + 'static>(this: *mut ffi::SoupServer, message: *mut ffi::SoupMessage, client: *mut ffi::SoupClientContext, f: glib::ffi::gpointer) { let f: &F = &*(f as *const F); f(Server::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(message), &from_glib_borrow(client)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"request-finished\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(request_finished_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } fn connect_request_read<F: Fn(&Self, &Message, &ClientContext) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn request_read_trampoline<P: IsA<Server>, F: Fn(&P, &Message, &ClientContext) + 'static>(this: *mut ffi::SoupServer, message: *mut ffi::SoupMessage, client: *mut ffi::SoupClientContext, f: glib::ffi::gpointer) { let f: &F = &*(f as *const F); f(Server::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(message), &from_glib_borrow(client)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"request-read\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(request_read_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } fn connect_request_started<F: Fn(&Self, &Message, &ClientContext) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn request_started_trampoline<P: IsA<Server>, F: Fn(&P, &Message, &ClientContext) + 'static>(this: *mut ffi::SoupServer, message: *mut ffi::SoupMessage, client: *mut ffi::SoupClientContext, f: glib::ffi::gpointer) { let f: &F = &*(f as *const F); f(Server::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(message), &from_glib_borrow(client)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"request-started\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(request_started_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] fn connect_add_websocket_extension_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_add_websocket_extension_trampoline<P: IsA<Server>, F: Fn(&P) + 'static>(this: *mut ffi::SoupServer, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer) { let f: &F = &*(f as *const F); f(Server::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::add-websocket-extension\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(notify_add_websocket_extension_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] fn connect_http_aliases_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_http_aliases_trampoline<P: IsA<Server>, F: Fn(&P) + 'static>(this: *mut ffi::SoupServer, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer) { let f: &F = &*(f as *const F); f(Server::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::http-aliases\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(notify_http_aliases_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] fn connect_https_aliases_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_https_aliases_trampoline<P: IsA<Server>, F: Fn(&P) + 'static>(this: *mut ffi::SoupServer, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer) { let f: &F = &*(f as *const F); f(Server::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::https-aliases\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(notify_https_aliases_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] fn connect_remove_websocket_extension_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_remove_websocket_extension_trampoline<P: IsA<Server>, F: Fn(&P) + 'static>(this: *mut ffi::SoupServer, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer) { let f: &F = &*(f as *const F); f(Server::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::remove-websocket-extension\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(notify_remove_websocket_extension_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } fn connect_server_header_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_server_header_trampoline<P: IsA<Server>, F: Fn(&P) + 'static>(this: *mut ffi::SoupServer, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer) { let f: &F = &*(f as *const F); f(Server::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::server-header\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>(notify_server_header_trampoline::<Self, F> as *const ())), Box_::into_raw(f)) } } } impl fmt::Display for Server { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("Server") } }
use crate::api::v1::ceo::order_detail::model; use crate::errors::ServiceError; use crate::models::order::Order; use crate::models::order_detail::OrderDetail as Object; use crate::models::shop::Shop; use crate::models::DbExecutor; use crate::schema::order::dsl::{order as tb_order, state as order_state}; use crate::schema::order_detail::dsl::{order_detail as tb}; use crate::schema::shop::dsl::shop as tb_shop; use actix::Handler; use diesel; use diesel::prelude::*; impl Handler<model::New> for DbExecutor { type Result = Result<model::NewRes, ServiceError>; fn handle(&mut self, msg: model::New, _: &mut Self::Context) -> Self::Result { let conn = &self.0.get()?; let od = tb_order.find(&msg.order_id).load::<Order>(conn)?.pop(); let s = tb_shop.find(&msg.shop_id).load::<Shop>(conn)?.pop(); match s { Some(s_ok) => { match od { Some(od_ok) => { match od_ok.state { // 거절된 주문 -1 => Err(ServiceError::BadRequest( "이미 거절하신 주문 입니다.".to_string(), )), // 대기중인 주문 1 => match msg.state { //주문상세 취소 0 => Err(ServiceError::BadRequest( "승인된 주문은 거절할수 없습니다.".to_string(), )), //주문상세 승인 1 => { let update_order = diesel::update(tb_order.find(&msg.order_id)) .set(order_state.eq(2)) .get_result::<Order>(conn)?; let item_order_detail: Object = diesel::insert_into(tb) .values(&msg) .get_result::<Object>(conn)?; Ok(model::NewRes { shop: s_ok, order: update_order, order_detail: item_order_detail, }) } //주문상세 수령 2 => Err(ServiceError::BadRequest( "먼저 수락을 해주세요.".to_string(), )), _ => Err(ServiceError::BadRequest("누 구 냐?".to_string())), }, // 수락한 주문 2 => match msg.state { 0 => Err(ServiceError::BadRequest( "이미 수락한 주문입니다. 거절할수 없습니다." .to_string(), )), 1 => Err(ServiceError::BadRequest( "이미 수락한 주문입니다.".to_string(), )), 2 => { let update_order = diesel::update(tb_order.find(&msg.order_id)) .set(order_state.eq(3)) .get_result::<Order>(conn)?; let item_order_detail: Object = diesel::insert_into(tb) .values(&msg) .get_result::<Object>(conn)?; Ok(model::NewRes { shop: s_ok, order: update_order, order_detail: item_order_detail, }) } _ => Err(ServiceError::BadRequest("누구 냐?".to_string())), }, _ => Err(ServiceError::BadRequest("누구냐?".to_string())), } } None => Err(ServiceError::BadRequest( "잘못된 주문번호 입니다.".to_string(), )), } } None => Err(ServiceError::BadRequest( "잘못된 상점 입니다.".to_string(), )), } } }
pub mod cv { pub mod education { pub fn higher_education() { println!("\nwe are in potfolio lib -> cv -> education -> higher_education()"); println!("BSIT from NUST") } pub fn matriculation() { println!("\nwe are in potfolio lib -> cv -> education -> matriculation()"); println!("Pre-medical from DG Khan board"); } } }
// Copyright (c) 2020 zenoxygen // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. extern crate anyhow; extern crate clap; extern crate flate2; extern crate hyper; extern crate indicatif; extern crate tar; extern crate tokio; extern crate url; mod args; mod client; mod server; use crate::args::parse_args; use crate::client::download_file; use crate::server::serve_file; use anyhow::{anyhow, Result}; use url::Url; use std::path::{Path, PathBuf}; /// Parse count. fn parse_count(count: &str) -> usize { match count.parse::<usize>() { Ok(valid_count) => valid_count, Err(_) => 1, } } /// Get executable path. fn get_exe_path() -> Result<PathBuf> { match std::env::current_exe() { Ok(exe_path) => Ok(exe_path), Err(_) => Err(anyhow!("could not access executable path")), } } /// Run program. fn run(args: clap::ArgMatches) -> Result<()> { let ip_addr = args.value_of("ip_addr").unwrap(); let port = args.value_of("port").unwrap(); let count = parse_count(args.value_of("count").unwrap()); // Serve or download file if args.is_present("file") { let file = args.value_of("file").unwrap(); if Path::new(file).exists() { let file_path = PathBuf::from(file); serve_file(file_path, &ip_addr, &port, count)?; } else if Url::parse(file).is_ok() { download_file(file)?; } else { return Err(anyhow!( "unable to find a file/directory to serve or an URL to download from" )); } // Serve itself } else { let exe_path = get_exe_path()?; serve_file(exe_path, &ip_addr, &port, count)?; } Ok(()) } fn main() { // Parse arguments let args = parse_args(); // Run program, eventually exit failure if let Err(error) = run(args) { println!("Error: {}", error); std::process::exit(1); } // Exit success std::process::exit(0); }
mod manager; mod iterator; mod device; mod sysfs; pub use self::manager::SysFsManager; pub use self::iterator::SysFsIterator; pub use self::device::SysFsDevice;
use std::ffi; use std::ops; use std::os::windows::ffi::OsStringExt; #[derive(Debug)] pub struct WideString(Vec<u16>); impl Default for WideString { fn default() -> Self { let buf = vec![0u16; 128]; Self(buf) } } impl WideString { pub fn with_capacity(capacity: usize) -> WideString { let buf = vec![0u16; capacity]; Self(buf) } // Note: those a u8, not a u16 received! #[inline] pub fn truncate(&mut self, bytes: usize) { // `-1` is for dropping the traling `\0` // which we will always have in our cases if let Some(new_size) = (bytes / 2).checked_sub(1) { self.0.truncate(new_size); } } #[inline] pub fn len(&self) -> usize { self.0.len() } } impl From<WideString> for String { fn from(b: WideString) -> Self { let raw = ffi::OsString::from_wide(&b.0); raw.to_string_lossy().to_string() } } impl ops::Deref for WideString { type Target = Vec<u16>; fn deref(&self) -> &Self::Target { &self.0 } } impl ops::DerefMut for WideString { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
// 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 chrono_tz::Tz; use common_exception::ErrorCode; use common_exception::Result; use common_expression::TableSchemaRef; use common_meta_app::principal::FileFormatOptions; use common_meta_app::principal::StageFileFormatType; use common_settings::Settings; use crate::delimiter::RecordDelimiter; use crate::format_option_checker::get_format_option_checker; use crate::output_format::CSVOutputFormat; use crate::output_format::CSVWithNamesAndTypesOutputFormat; use crate::output_format::CSVWithNamesOutputFormat; use crate::output_format::JSONOutputFormat; use crate::output_format::NDJSONOutputFormatBase; use crate::output_format::OutputFormat; use crate::output_format::ParquetOutputFormat; use crate::output_format::TSVOutputFormat; use crate::output_format::TSVWithNamesAndTypesOutputFormat; use crate::output_format::TSVWithNamesOutputFormat; use crate::ClickhouseFormatType; pub trait FileFormatTypeExt { fn get_content_type(&self) -> String; } #[derive(Clone, Debug)] pub struct FileFormatOptionsExt { pub stage: FileFormatOptions, pub ident_case_sensitive: bool, pub headers: usize, pub json_compact: bool, pub json_strings: bool, pub timezone: Tz, } impl FileFormatOptionsExt { pub fn create_from_file_format_options( stage: FileFormatOptions, settings: &Settings, ) -> Result<FileFormatOptionsExt> { let timezone = parse_timezone(settings)?; let options = FileFormatOptionsExt { stage, ident_case_sensitive: false, headers: 0, json_compact: false, json_strings: false, timezone, }; Ok(options) } pub fn create_from_clickhouse_format( clickhouse_type: ClickhouseFormatType, settings: &Settings, ) -> Result<FileFormatOptionsExt> { let timezone = parse_timezone(settings)?; let mut stage = FileFormatOptions::new(); stage.format = clickhouse_type.typ; let mut options = FileFormatOptionsExt { stage, ident_case_sensitive: settings.get_unquoted_ident_case_sensitive()?, headers: 0, json_compact: false, json_strings: false, timezone, }; let suf = &clickhouse_type.suffixes; options.headers = suf.headers; if let Some(json) = &suf.json { options.json_compact = json.is_compact; options.json_strings = json.is_strings; } Ok(options) } pub fn check(&mut self) -> Result<()> { let checker = get_format_option_checker(&self.stage.format)?; checker.check_options_ext(self) } pub fn get_quote_char(&self) -> u8 { self.stage.quote.as_bytes()[0] } pub fn get_field_delimiter(&self) -> u8 { let fd = &self.stage.field_delimiter; if fd.is_empty() { 0 // dummy } else { fd.as_bytes()[0] } } pub fn get_record_delimiter(&self) -> Result<RecordDelimiter> { let fd = &self.stage.record_delimiter; if fd.is_empty() { Ok(RecordDelimiter::Any(0)) // dummy } else { RecordDelimiter::try_from(fd.as_bytes()) } } pub fn get_output_format_from_clickhouse_format( typ: ClickhouseFormatType, schema: TableSchemaRef, settings: &Settings, ) -> Result<Box<dyn OutputFormat>> { let mut options = FileFormatOptionsExt::create_from_clickhouse_format(typ, settings)?; options.get_output_format(schema) } pub fn get_output_format_from_format_options( schema: TableSchemaRef, options: FileFormatOptions, settings: &Settings, ) -> Result<Box<dyn OutputFormat>> { let mut options = FileFormatOptionsExt::create_from_file_format_options(options, settings)?; options.get_output_format(schema) } pub fn get_output_format(&mut self, schema: TableSchemaRef) -> Result<Box<dyn OutputFormat>> { self.check()?; // println!("format {:?} {:?} {:?}", fmt, options, format_settings); let output: Box<dyn OutputFormat> = match &self.stage.format { StageFileFormatType::Csv => match self.headers { 0 => Box::new(CSVOutputFormat::create(schema, self)), 1 => Box::new(CSVWithNamesOutputFormat::create(schema, self)), 2 => Box::new(CSVWithNamesAndTypesOutputFormat::create(schema, self)), _ => unreachable!(), }, StageFileFormatType::Tsv => match self.headers { 0 => Box::new(TSVOutputFormat::create(schema, self)), 1 => Box::new(TSVWithNamesOutputFormat::create(schema, self)), 2 => Box::new(TSVWithNamesAndTypesOutputFormat::create(schema, self)), _ => unreachable!(), }, StageFileFormatType::NdJson => { match (self.headers, self.json_strings, self.json_compact) { // string, compact, name, type // not compact (0, false, false) => Box::new(NDJSONOutputFormatBase::< false, false, false, false, >::create(schema, self)), (0, true, false) => Box::new( NDJSONOutputFormatBase::<true, false, false, false>::create(schema, self), ), // compact (0, false, true) => Box::new( NDJSONOutputFormatBase::<false, true, false, false>::create(schema, self), ), (0, true, true) => Box::new( NDJSONOutputFormatBase::<true, true, false, false>::create(schema, self), ), (1, false, true) => Box::new( NDJSONOutputFormatBase::<false, true, true, false>::create(schema, self), ), (1, true, true) => Box::new( NDJSONOutputFormatBase::<true, true, true, false>::create(schema, self), ), (2, false, true) => Box::new( NDJSONOutputFormatBase::<false, true, true, true>::create(schema, self), ), (2, true, true) => Box::new( NDJSONOutputFormatBase::<true, true, true, true>::create(schema, self), ), _ => unreachable!(), } } StageFileFormatType::Parquet => Box::new(ParquetOutputFormat::create(schema, self)), StageFileFormatType::Json => Box::new(JSONOutputFormat::create(schema, self)), others => { return Err(ErrorCode::InvalidArgument(format!( "Unsupported output file format:{:?}", others.to_string() ))); } }; Ok(output) } } impl FileFormatTypeExt for StageFileFormatType { fn get_content_type(&self) -> String { match self { StageFileFormatType::Tsv => "text/tab-separated-values; charset=UTF-8", StageFileFormatType::Csv => "text/csv; charset=UTF-8", StageFileFormatType::Parquet => "application/octet-stream", StageFileFormatType::NdJson => "application/x-ndjson; charset=UTF-8", StageFileFormatType::Json => "application/json; charset=UTF-8", _ => "text/plain; charset=UTF-8", } .to_string() } } pub fn parse_timezone(settings: &Settings) -> Result<Tz> { let tz = settings.get_timezone()?; tz.parse::<Tz>() .map_err(|_| ErrorCode::InvalidTimezone("Timezone has been checked and should be valid")) }