text
stringlengths
8
4.13M
extern crate queen_attack; use queen_attack::*; #[test] fn test_queen_creation_with_valid_position() { let white_queen = Queen::new((2,4)); assert!(white_queen.is_ok()); } #[test] #[ignore] fn test_queen_creation_with_incorrect_positions() { let white_queen = Queen::new((-1,2)); assert!(white_queen.is_err()); let white_queen = Queen::new((8,2)); assert!(white_queen.is_err()); let white_queen = Queen::new((5,-1)); assert!(white_queen.is_err()); let white_queen = Queen::new((5,8)); assert!(white_queen.is_err()); } #[test] #[ignore] fn test_can_not_attack() { let white_queen = Queen::new((2,4)).unwrap(); let black_queen = Queen::new((6,6)).unwrap(); assert_eq!(false, white_queen.can_attack(&black_queen)); } #[test] #[ignore] fn test_can_attack_on_same_rank() { let white_queen = Queen::new((2,4)).unwrap(); let black_queen = Queen::new((2,6)).unwrap(); assert!(white_queen.can_attack(&black_queen)); } #[test] #[ignore] fn test_can_attack_on_same_file() { let white_queen = Queen::new((4,5)).unwrap(); let black_queen = Queen::new((3,5)).unwrap(); assert!(white_queen.can_attack(&black_queen)); } #[test] #[ignore] fn test_can_attack_on_first_diagonal() { let white_queen = Queen::new((2,2)).unwrap(); let black_queen = Queen::new((0,4)).unwrap(); assert!(white_queen.can_attack(&black_queen)); } #[test] #[ignore] fn test_can_attack_on_second_diagonal() { let white_queen = Queen::new((2,2)).unwrap(); let black_queen = Queen::new((3,1)).unwrap(); assert!(white_queen.can_attack(&black_queen)); } #[test] #[ignore] fn test_can_attack_on_third_diagonal() { let white_queen = Queen::new((2,2)).unwrap(); let black_queen = Queen::new((1,1)).unwrap(); assert!(white_queen.can_attack(&black_queen)); } #[test] #[ignore] fn test_can_attack_on_fourth_diagonal() { let white_queen = Queen::new((2,2)).unwrap(); let black_queen = Queen::new((5,5)).unwrap(); assert!(white_queen.can_attack(&black_queen)); }
use argparse::{ArgumentParser, Store}; use petgraph::prelude::*; use petgraph_layout_force_simulation::{Coordinates, ForceToNode, Simulation}; use petgraph_layout_fruchterman_reingold::FruchtermanReingoldForce; use petgraph_layout_non_euclidean_force_simulation::{Map, SphericalSpace}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::{ collections::HashMap, f32::consts::PI, fs::File, io::{BufReader, BufWriter}, }; #[derive(Clone, Serialize, Deserialize)] struct NodeData<N> { id: usize, x: Option<f32>, y: Option<f32>, data: Option<N>, } #[derive(Clone, Serialize, Deserialize)] struct LinkData<E> { source: usize, target: usize, data: Option<E>, } #[derive(Clone, Serialize, Deserialize)] struct GraphData<N, E> { nodes: Vec<NodeData<N>>, links: Vec<LinkData<E>>, } pub fn read_graph<N: Clone + DeserializeOwned, E: Clone + DeserializeOwned>( input_path: &str, ) -> (Graph<Option<N>, Option<E>, Undirected>, Coordinates<u32>) { let file = File::open(input_path).unwrap(); let reader = BufReader::new(file); let input_graph: GraphData<N, E> = serde_json::from_reader(reader).unwrap(); let mut graph = Graph::new_undirected(); let mut node_ids = HashMap::new(); for node in input_graph.nodes.iter() { node_ids.insert(node.id, graph.add_node(node.data.clone())); } for link in input_graph.links.iter() { graph.add_edge( node_ids[&link.source], node_ids[&link.target], link.data.clone(), ); } let mut coordinates = Coordinates::initial_placement(&graph); for node in input_graph.nodes.iter() { let u = node_ids[&node.id]; if let Some(x) = node.x { coordinates.set_x(u, x); } if let Some(y) = node.y { coordinates.set_x(u, y); } } (graph, coordinates) } pub fn write_graph<N: Clone + Serialize, E: Clone + Serialize>( graph: &Graph<Option<N>, Option<E>, Undirected>, coordinates: &Coordinates<u32>, output_path: &str, ) { let output = GraphData { nodes: graph .node_indices() .map(|u| NodeData { id: u.index(), x: Some(coordinates.x(u).unwrap()), y: Some(coordinates.y(u).unwrap()), data: graph[u].clone(), }) .collect::<Vec<_>>(), links: graph .edge_indices() .map(|e| { let (source, target) = graph.edge_endpoints(e).unwrap(); LinkData { source: source.index(), target: target.index(), data: graph[e].clone(), } }) .collect::<Vec<_>>(), }; let file = File::create(output_path).unwrap(); let writer = BufWriter::new(file); serde_json::to_writer(writer, &output).unwrap(); } fn parse_args(input_path: &mut String, output_path: &mut String) { let mut parser = ArgumentParser::new(); parser .refer(input_path) .add_argument("input", Store, "input file path") .required(); parser .refer(output_path) .add_argument("output", Store, "output file path") .required(); parser.parse_args_or_exit(); } fn layout(graph: &Graph<Option<()>, Option<()>, Undirected>, coordinates: &mut Coordinates<u32>) { for (i, u) in graph.node_indices().enumerate() { coordinates.set_x(u, (2. * PI * i as f32) / graph.node_count() as f32); coordinates.set_y(u, i as f32 + 1.); } let mut tangent_space = Coordinates::initial_placement(&graph); let mut simulation = Simulation::new(); let forces = [FruchtermanReingoldForce::new(&graph, 0.5, 0.01)]; simulation.run(&mut |alpha| { for u in graph.node_indices() { SphericalSpace::map_to_tangent_space( u.index(), &mut coordinates.points, &mut tangent_space.points, ); for force in forces.iter() { force.apply_to_node(u.index(), &mut tangent_space.points, alpha); } SphericalSpace::update_position( u.index(), &mut coordinates.points, &mut tangent_space.points, 0.6, ); } }); } fn main() { let mut input_path = "".to_string(); let mut output_path = "".to_string(); parse_args(&mut input_path, &mut output_path); let (input_graph, mut coordinates) = read_graph(&input_path); layout(&input_graph, &mut coordinates); write_graph(&input_graph, &coordinates, &output_path); }
pub use VkWin32SurfaceCreateFlagsKHR::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkWin32SurfaceCreateFlagsKHR { VK_WIN32_SURFACE_CREATE_NULL_BIT = 0, } use crate::SetupVkFlags; #[repr(C)] #[derive(Clone, Copy, Eq, PartialEq, Hash)] pub struct VkWin32SurfaceCreateFlagBitsKHR(u32); SetupVkFlags!( VkWin32SurfaceCreateFlagsKHR, VkWin32SurfaceCreateFlagBitsKHR );
#![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 IPlatformTelemetryClientStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlatformTelemetryClientStatics { type Vtable = IPlatformTelemetryClientStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9bf3f25d_d5c3_4eea_8dbe_9c8dbb0d9d8f); } #[repr(C)] #[doc(hidden)] pub struct IPlatformTelemetryClientStatics_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, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, settings: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlatformTelemetryRegistrationResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlatformTelemetryRegistrationResult { type Vtable = IPlatformTelemetryRegistrationResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4d8518ab_2292_49bd_a15a_3d71d2145112); } #[repr(C)] #[doc(hidden)] pub struct IPlatformTelemetryRegistrationResult_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 PlatformTelemetryRegistrationStatus) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IPlatformTelemetryRegistrationSettings(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IPlatformTelemetryRegistrationSettings { type Vtable = IPlatformTelemetryRegistrationSettings_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x819a8582_ca19_415e_bb79_9c224bfa3a73); } #[repr(C)] #[doc(hidden)] pub struct IPlatformTelemetryRegistrationSettings_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 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 u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, ); pub struct PlatformTelemetryClient {} impl PlatformTelemetryClient { pub fn Register<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(id: Param0) -> ::windows::core::Result<PlatformTelemetryRegistrationResult> { Self::IPlatformTelemetryClientStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), id.into_param().abi(), &mut result__).from_abi::<PlatformTelemetryRegistrationResult>(result__) }) } pub fn RegisterWithSettings<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, PlatformTelemetryRegistrationSettings>>(id: Param0, settings: Param1) -> ::windows::core::Result<PlatformTelemetryRegistrationResult> { Self::IPlatformTelemetryClientStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), id.into_param().abi(), settings.into_param().abi(), &mut result__).from_abi::<PlatformTelemetryRegistrationResult>(result__) }) } pub fn IPlatformTelemetryClientStatics<R, F: FnOnce(&IPlatformTelemetryClientStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlatformTelemetryClient, IPlatformTelemetryClientStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for PlatformTelemetryClient { const NAME: &'static str = "Windows.System.Diagnostics.Telemetry.PlatformTelemetryClient"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlatformTelemetryRegistrationResult(pub ::windows::core::IInspectable); impl PlatformTelemetryRegistrationResult { pub fn Status(&self) -> ::windows::core::Result<PlatformTelemetryRegistrationStatus> { let this = self; unsafe { let mut result__: PlatformTelemetryRegistrationStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PlatformTelemetryRegistrationStatus>(result__) } } } unsafe impl ::windows::core::RuntimeType for PlatformTelemetryRegistrationResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.System.Diagnostics.Telemetry.PlatformTelemetryRegistrationResult;{4d8518ab-2292-49bd-a15a-3d71d2145112})"); } unsafe impl ::windows::core::Interface for PlatformTelemetryRegistrationResult { type Vtable = IPlatformTelemetryRegistrationResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4d8518ab_2292_49bd_a15a_3d71d2145112); } impl ::windows::core::RuntimeName for PlatformTelemetryRegistrationResult { const NAME: &'static str = "Windows.System.Diagnostics.Telemetry.PlatformTelemetryRegistrationResult"; } impl ::core::convert::From<PlatformTelemetryRegistrationResult> for ::windows::core::IUnknown { fn from(value: PlatformTelemetryRegistrationResult) -> Self { value.0 .0 } } impl ::core::convert::From<&PlatformTelemetryRegistrationResult> for ::windows::core::IUnknown { fn from(value: &PlatformTelemetryRegistrationResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlatformTelemetryRegistrationResult { 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 PlatformTelemetryRegistrationResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlatformTelemetryRegistrationResult> for ::windows::core::IInspectable { fn from(value: PlatformTelemetryRegistrationResult) -> Self { value.0 } } impl ::core::convert::From<&PlatformTelemetryRegistrationResult> for ::windows::core::IInspectable { fn from(value: &PlatformTelemetryRegistrationResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlatformTelemetryRegistrationResult { 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 PlatformTelemetryRegistrationResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PlatformTelemetryRegistrationResult {} unsafe impl ::core::marker::Sync for PlatformTelemetryRegistrationResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct PlatformTelemetryRegistrationSettings(pub ::windows::core::IInspectable); impl PlatformTelemetryRegistrationSettings { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<PlatformTelemetryRegistrationSettings, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn StorageSize(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetStorageSize(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn UploadQuotaSize(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetUploadQuotaSize(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } } unsafe impl ::windows::core::RuntimeType for PlatformTelemetryRegistrationSettings { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.System.Diagnostics.Telemetry.PlatformTelemetryRegistrationSettings;{819a8582-ca19-415e-bb79-9c224bfa3a73})"); } unsafe impl ::windows::core::Interface for PlatformTelemetryRegistrationSettings { type Vtable = IPlatformTelemetryRegistrationSettings_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x819a8582_ca19_415e_bb79_9c224bfa3a73); } impl ::windows::core::RuntimeName for PlatformTelemetryRegistrationSettings { const NAME: &'static str = "Windows.System.Diagnostics.Telemetry.PlatformTelemetryRegistrationSettings"; } impl ::core::convert::From<PlatformTelemetryRegistrationSettings> for ::windows::core::IUnknown { fn from(value: PlatformTelemetryRegistrationSettings) -> Self { value.0 .0 } } impl ::core::convert::From<&PlatformTelemetryRegistrationSettings> for ::windows::core::IUnknown { fn from(value: &PlatformTelemetryRegistrationSettings) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PlatformTelemetryRegistrationSettings { 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 PlatformTelemetryRegistrationSettings { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<PlatformTelemetryRegistrationSettings> for ::windows::core::IInspectable { fn from(value: PlatformTelemetryRegistrationSettings) -> Self { value.0 } } impl ::core::convert::From<&PlatformTelemetryRegistrationSettings> for ::windows::core::IInspectable { fn from(value: &PlatformTelemetryRegistrationSettings) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PlatformTelemetryRegistrationSettings { 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 PlatformTelemetryRegistrationSettings { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for PlatformTelemetryRegistrationSettings {} unsafe impl ::core::marker::Sync for PlatformTelemetryRegistrationSettings {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PlatformTelemetryRegistrationStatus(pub i32); impl PlatformTelemetryRegistrationStatus { pub const Success: PlatformTelemetryRegistrationStatus = PlatformTelemetryRegistrationStatus(0i32); pub const SettingsOutOfRange: PlatformTelemetryRegistrationStatus = PlatformTelemetryRegistrationStatus(1i32); pub const UnknownFailure: PlatformTelemetryRegistrationStatus = PlatformTelemetryRegistrationStatus(2i32); } impl ::core::convert::From<i32> for PlatformTelemetryRegistrationStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PlatformTelemetryRegistrationStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for PlatformTelemetryRegistrationStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.System.Diagnostics.Telemetry.PlatformTelemetryRegistrationStatus;i4)"); } impl ::windows::core::DefaultType for PlatformTelemetryRegistrationStatus { type DefaultType = Self; }
use std::io; use std::i32; use std::mem; use std::time::Duration; use std::ffi::{CStr, CString}; use CoreFoundation_sys as core; use IOKit_sys as iokit; use mach::{port, kern_return}; use super::traits::DataSource; const IOPM_SERVICE_NAME: *const libc::c_char = b"IOPMPowerSource\0".as_ptr() as *const libc::c_char; #[derive(Debug)] pub struct PowerSource(core::dictionary::CFMutableDictionaryRef); impl PowerSource { pub fn get_props() -> io::Result<PowerSource> { let mut master_port: port::mach_port_t = port::MACH_PORT_NULL; let res = unsafe { iokit::IOMasterPort(iokit::kIOMasterPortDefault, &mut master_port) }; if res != kern_return::KERN_SUCCESS { return Err(io::Error::from(io::ErrorKind::NotFound)); }; // `IOServiceMatchingService` consumes `service`, so we do not need to CFRelease it manually let service = unsafe { iokit::IOServiceMatching(IOPM_SERVICE_NAME) }; // It is required to release this object later let battery_service = unsafe { iokit::IOServiceGetMatchingService(master_port, service) }; let mut props: core::dictionary::CFMutableDictionaryRef = unsafe { mem::uninitialized() }; let prop_res = unsafe { iokit::IORegistryEntryCreateCFProperties(battery_service, &mut props, core::kCFAllocatorDefault, 0) }; if prop_res != kern_return::KERN_SUCCESS { return Err(io::Error::from(io::ErrorKind::InvalidData)); } // Uncomment this to see all existing keys in the `props`. // Will write to stderr. Do not use in production. // // unsafe { core::CFShow(props as *const libc::c_void); } unsafe { iokit::IOObjectRelease(battery_service); } Ok(PowerSource(props)) } pub fn get_bool(&self, key: &[u8]) -> Option<bool> { if let Some(value_ptr) = self.get_dict_value_ptr(key) { unsafe { debug_assert!(core::CFGetTypeID(value_ptr) == core::CFBooleanGetTypeID()); } match unsafe { core::CFBooleanGetValue(value_ptr as core::CFBooleanRef) } { 0 => Some(false), 1 => Some(true), _ => unreachable!(), } } else { None } } pub fn get_isize(&self, key: &[u8]) -> Option<isize> { if let Some(value_ptr) = self.get_dict_value_ptr(key) { unsafe { debug_assert!(core::CFGetTypeID(value_ptr) == core::CFNumberGetTypeID()); } let mut value = 0isize; let res = unsafe { core::CFNumberGetValue( value_ptr as core::CFNumberRef, core::kCFNumberNSIntegerType, &mut value as *mut _ as *mut libc::c_void ) }; if res == 1 { Some(value) } else { None } } else { None } } pub fn get_u32(&self, key: &[u8]) -> Option<u32> { if let Some(value_ptr) = self.get_dict_value_ptr(key) { unsafe { debug_assert!(core::CFGetTypeID(value_ptr) == core::CFNumberGetTypeID()); } let mut value = 0u32; let res = unsafe { core::CFNumberGetValue( value_ptr as core::CFNumberRef, core::kCFNumberIntType, &mut value as *mut _ as *mut libc::c_void ) }; if res == 1 { Some(value) } else { None } } else { None } } pub fn get_i32(&self, key: &[u8]) -> Option<i32> { if let Some(value_ptr) = self.get_dict_value_ptr(key) { unsafe { debug_assert!(core::CFGetTypeID(value_ptr) == core::CFNumberGetTypeID()); } let mut value = 0i32; let res = unsafe { core::CFNumberGetValue( value_ptr as core::CFNumberRef, core::kCFNumberIntType, &mut value as *mut _ as *mut libc::c_void ) }; if res == 1 { Some(value) } else { None } } else { None } } pub fn get_string(&self, key: &[u8]) -> Option<String> { if let Some(value_ptr) = self.get_dict_value_ptr(key) { unsafe { debug_assert!(core::CFGetTypeID(value_ptr) == core::CFStringGetTypeID()); } let mut buf = Vec::with_capacity(64); let result = unsafe { core::CFStringGetCString( value_ptr as core::CFStringRef, buf.as_mut_ptr(), 64, core::kCFStringEncodingUTF8, ) }; if result == 0 { return None; } let value = unsafe { CStr::from_ptr(buf.as_ptr()).to_string_lossy() }; Some(value.to_string()) } else { None } } fn get_dict_value_ptr(&self, key: &[u8]) -> Option<*const libc::c_void> { let cstring = CString::new(key).expect("Malformed input for CString"); let cfstring = unsafe { core::CFStringCreateWithCString( core::kCFAllocatorDefault, cstring.as_ptr(), core::kCFStringEncodingUTF8, ) }; if cfstring.is_null() { // TODO: Trace allocation error return None; } let value_ptr = unsafe { core::dictionary::CFDictionaryGetValue(self.0, cfstring as *const libc::c_void) }; if value_ptr.is_null() { None } else { Some(value_ptr) } } } impl DataSource for PowerSource { fn new() -> io::Result<PowerSource> where Self: Sized { PowerSource::get_props() } fn fully_charged(&self) -> bool { self.get_bool(b"FullyCharged") .expect("IOKit is not providing required data") } fn external_connected(&self) -> bool { self.get_bool(b"ExternalConnected") .expect("IOKit is not providing required data") } fn is_charging(&self) -> bool { self.get_bool(b"IsCharging") .expect("IOKit is not providing required data") } fn voltage(&self) -> u32 { self.get_u32(b"Voltage") .expect("IOKit is not providing required data") } fn amperage(&self) -> i32 { self.get_i32(b"Amperage") .expect("IOKit is not providing required data") } fn design_capacity(&self) -> u32 { self.get_u32(b"DesignCapacity") .expect("IOKit is not providing required data") } fn max_capacity(&self) -> u32 { self.get_u32(b"MaxCapacity") .expect("IOKit is not providing required data") } fn current_capacity(&self) -> u32 { self.get_u32(b"CurrentCapacity") .expect("IOKit is not providing required data") } fn temperature(&self) -> Option<f32> { self.get_isize(b"Temperature") .map(|value| value as f32 / 100.0) } fn cycle_count(&self) -> Option<u32> { self.get_u32(b"CycleCount") } fn time_remaining(&self) -> Option<Duration> { self.get_i32(b"TimeRemaining") .and_then(|val| { if val == i32::MAX { None } else { // TODO: Is it possible to have negative `TimeRemaining`? let seconds = val.abs() as u64 * 60; Some(Duration::from_secs(seconds)) } }) } fn manufacturer(&self) -> Option<String> { self.get_string(b"Manufacturer") } fn device_name(&self) -> Option<String> { self.get_string(b"DeviceName") } fn serial_number(&self) -> Option<String> { self.get_string(b"BatterySerialNumber") } } impl Drop for PowerSource { fn drop(&mut self) { unsafe { core::CFRelease(self.0 as *const libc::c_void) } } }
#![allow(clippy::mut_from_ref)] use std::fmt; use typed_arena::Arena; macro_rules! declare_arenas { ( $( $field_name:ident : $arena_type:ty , )* ) => { pub(crate) struct Arenas { $(pub(crate) $field_name : Arena<$arena_type>, )* } impl Default for Arenas{ fn default()->Self{ Arenas{ $( $field_name:Arena::new(), )* } } } impl fmt::Debug for Arenas{ fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ fmt::Debug::fmt("Arenas{..}",f) } } pub trait AllocMethods<T>{ fn alloc(&self, value: T) -> &T { self.alloc_mut(value) } fn alloc_mut(&self, value: T) -> &mut T ; fn alloc_extend<I>(&self, iterable: I) -> &[T] where I: IntoIterator<Item = T> { self.alloc_extend_mut(iterable) } fn alloc_extend_mut<I>(&self, iterable: I) -> &mut [T] where I: IntoIterator<Item = T>; } $( impl AllocMethods<$arena_type> for Arenas{ fn alloc_mut(&self, value: $arena_type) -> &mut $arena_type { self.$field_name.alloc(value) } fn alloc_extend_mut<I>(&self, iterable: I) -> &mut [$arena_type] where I: IntoIterator<Item = $arena_type> { self.$field_name.alloc_extend(iterable) } } )* } } declare_arenas! { vec_meta: Vec<syn::Attribute>, vec_expr: Vec<syn::Expr>, ident: syn::Ident, ident_vec: Vec<syn::Ident>, trait_bound: syn::TraitBound, lifetimes:syn::Lifetime, fields_named: syn::FieldsNamed, types: syn::Type, // metalists: syn::MetaList, lifetime_defs: syn::LifetimeDef, tokenstream: proc_macro2::TokenStream, expr: syn::Expr, strings: String, paths: syn::Path, }
mod button; mod text_input; pub use button::Button; pub use text_input::TextInput;
mod with_non_negative_arity; use super::*; #[test] fn without_non_negative_arity_errors_badarg() { run!( |arc_process| { ( strategy::term::is_function(arc_process.clone()), strategy::term::integer::negative(arc_process.clone()), ) }, |(function, arity)| { prop_assert_is_not_arity!(result(function, arity), arity); Ok(()) }, ); }
use ecology::simulate; use clap::{App, Arg, SubCommand}; use std::env; fn main() { let matches = App::new("My Super Program") .version("1.0") .author("lyndon Mackay") .about("SImulated Forest") .arg( Arg::with_name("Size") .help("The size of the forest an integer greater then 0") .required(true) .index(1), ) .arg( Arg::with_name("multi") .short("m") .long("multi") .help("Run in multi Threaded mode"), ) .get_matches(); let size = matches .value_of("Size") .unwrap() .parse() .expect(" SIze should be an integer greater then 0"); // simulate(size); let muli_thread = matches.is_present("multi"); println!("{}", muli_thread); simulate(size, muli_thread); }
//! Persistent filesystem backed pin store. See [`FsDataStore`] for more information. use super::{filestem_to_pin_cid, pin_path, FsDataStore}; use crate::error::Error; use crate::repo::{PinKind, PinMode, PinModeRequirement, PinStore, References}; use async_trait::async_trait; use cid::Cid; use core::convert::TryFrom; use futures::stream::TryStreamExt; use hash_hasher::HashedSet; use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; use tokio::fs; use tokio::sync::Semaphore; use tokio_stream::{empty, wrappers::ReadDirStream, StreamExt}; use tokio_util::either::Either; // PinStore is a trait from ipfs::repo implemented on FsDataStore defined at ipfs::repo::fs or // parent module. #[async_trait] impl PinStore for FsDataStore { async fn is_pinned(&self, cid: &Cid) -> Result<bool, Error> { let path = pin_path(self.path.clone(), cid); if read_direct_or_recursive(path).await?.is_some() { return Ok(true); } let st = self.list_pinfiles().await.try_filter_map(|(cid, mode)| { futures::future::ready(if mode == PinMode::Recursive { Ok(Some(cid)) } else { Ok(None) }) }); futures::pin_mut!(st); while let Some(recursive) = StreamExt::try_next(&mut st).await? { // TODO: it might be much better to just deserialize the vec one by one and comparing while // going let (_, references) = read_recursively_pinned(self.path.clone(), recursive).await?; // if we always wrote down the cids in some order we might be able to binary search? if references.into_iter().any(move |x| x == *cid) { return Ok(true); } } Ok(false) } async fn insert_direct_pin(&self, target: &Cid) -> Result<(), Error> { let permit = Semaphore::acquire_owned(Arc::clone(&self.lock)).await; let mut path = pin_path(self.path.clone(), target); let span = tracing::Span::current(); tokio::task::spawn_blocking(move || { // move the permit to the blocking thread to ensure we keep it as long as needed let _permit = permit; let _entered = span.enter(); std::fs::create_dir_all(path.parent().expect("shard parent has to exist"))?; path.set_extension("recursive"); if path.is_file() { return Err(anyhow::anyhow!("already pinned recursively")); } path.set_extension("direct"); let f = std::fs::File::create(path)?; f.sync_all()?; Ok(()) }) .await??; Ok(()) } async fn insert_recursive_pin( &self, target: &Cid, referenced: References<'_>, ) -> Result<(), Error> { let set = referenced .try_collect::<std::collections::BTreeSet<_>>() .await?; let permit = Semaphore::acquire_owned(Arc::clone(&self.lock)).await; let mut path = pin_path(self.path.clone(), target); let span = tracing::Span::current(); tokio::task::spawn_blocking(move || { let _permit = permit; // again move to the threadpool thread let _entered = span.enter(); std::fs::create_dir_all(path.parent().expect("shard parent has to exist"))?; let count = set.len(); let cids = set.into_iter().map(|cid| cid.to_string()); path.set_extension("recursive_temp"); let file = std::fs::File::create(&path)?; match sync_write_recursive_pin(file, count, cids) { Ok(_) => { let final_path = path.with_extension("recursive"); std::fs::rename(&path, final_path)? } Err(e) => { let removed = std::fs::remove_file(&path); match removed { Ok(_) => debug!("cleaned up ok after botched recursive pin write"), Err(e) => warn!("failed to cleanup temporary file: {}", e), } return Err(e); } } // if we got this far, we have now written and renamed the recursive_temp into place. // now we just need to remove the direct pin, if it exists path.set_extension("direct"); match std::fs::remove_file(&path) { Ok(_) => { /* good */ } Err(e) if e.kind() == std::io::ErrorKind::NotFound => { /* good as well */ } Err(e) => { warn!( "failed to remove direct pin when adding recursive {:?}: {}", path, e ); } } Ok::<_, Error>(()) }) .await??; Ok(()) } async fn remove_direct_pin(&self, target: &Cid) -> Result<(), Error> { let permit = Semaphore::acquire_owned(Arc::clone(&self.lock)).await; let mut path = pin_path(self.path.clone(), target); let span = tracing::Span::current(); tokio::task::spawn_blocking(move || { let _permit = permit; // move in to threadpool thread let _entered = span.enter(); path.set_extension("recursive"); if path.is_file() { return Err(anyhow::anyhow!("is pinned recursively")); } path.set_extension("direct"); match std::fs::remove_file(&path) { Ok(_) => { trace!("direct pin removed"); Ok(()) } Err(e) if e.kind() == std::io::ErrorKind::NotFound => { Err(anyhow::anyhow!("not pinned or pinned indirectly")) } Err(e) => Err(e.into()), } }) .await??; Ok(()) } async fn remove_recursive_pin(&self, target: &Cid, _: References<'_>) -> Result<(), Error> { let permit = Semaphore::acquire_owned(Arc::clone(&self.lock)).await; let mut path = pin_path(self.path.clone(), target); let span = tracing::Span::current(); tokio::task::spawn_blocking(move || { let _permit = permit; // move into threadpool thread let _entered = span.enter(); path.set_extension("direct"); let mut any = false; match std::fs::remove_file(&path) { Ok(_) => { trace!("direct pin removed"); any |= true; } Err(e) if e.kind() == std::io::ErrorKind::NotFound => { // nevermind, we are just trying to remove the direct as it should go, if it // was left by mistake } // Error::new instead of e.into() to help out the type inference Err(e) => return Err(Error::new(e)), } path.set_extension("recursive"); match std::fs::remove_file(&path) { Ok(_) => { trace!("recursive pin removed"); any |= true; } Err(e) if e.kind() == std::io::ErrorKind::NotFound => { // we may have removed only the direct pin, but if we cleaned out a direct pin // this would have been a success } Err(e) => return Err(e.into()), } if !any { Err(anyhow::anyhow!("not pinned or pinned indirectly")) } else { Ok(()) } }) .await??; Ok(()) } async fn list( &self, requirement: Option<PinMode>, ) -> futures::stream::BoxStream<'static, Result<(Cid, PinMode), Error>> { // no locking, dirty reads are probably good enough until gc let cids = self.list_pinfiles().await; let path = self.path.clone(); let requirement = PinModeRequirement::from(requirement); // depending on what was queried we must iterate through the results in the order of // recursive, direct and indirect. // // if only one kind is required, we must return only those, which may or may not be // easier than doing all of the work. this implementation follows: // // https://github.com/ipfs/go-ipfs/blob/2ae5c52f4f0f074864ea252e90e72e8d5999caba/core/coreapi/pin.go#L222 let st = async_stream::try_stream! { // keep track of all returned not to give out duplicate cids let mut returned: HashedSet<Cid> = HashedSet::default(); // the set of recursive will be interesting after all others let mut recursive: HashedSet<Cid> = HashedSet::default(); let mut direct: HashedSet<Cid> = HashedSet::default(); let collect_recursive_for_indirect = requirement.is_indirect_or_any(); futures::pin_mut!(cids); while let Some((cid, mode)) = StreamExt::try_next(&mut cids).await? { let matches = requirement.matches(&mode); if mode == PinMode::Recursive { if collect_recursive_for_indirect { recursive.insert(cid.clone()); } if matches && returned.insert(cid.clone()) { // the recursive pins can always be returned right away since they have // the highest priority in this listing or output yield (cid, mode); } } else if mode == PinMode::Direct && matches { direct.insert(cid); } } trace!(unique = returned.len(), "completed listing recursive"); // now that the recursive are done, next up in priority order are direct. the set // of directly pinned and recursively pinned should be disjoint, but probably there // are times when 100% accurate results are not possible... Nor needed. for cid in direct { if returned.insert(cid.clone()) { yield (cid, PinMode::Direct) } } trace!(unique = returned.len(), "completed listing direct"); if !collect_recursive_for_indirect { // we didn't collect the recursive to list the indirect so, done. return; } // the threadpool passing adds probably some messaging latency, maybe run small // amount in parallel? let mut recursive = futures::stream::iter(recursive.into_iter().map(Ok)) .map_ok(move |cid| read_recursively_pinned(path.clone(), cid)) .try_buffer_unordered(4); while let Some((_, next_batch)) = StreamExt::try_next(&mut recursive).await? { for indirect in next_batch { if returned.insert(indirect.clone()) { yield (indirect, PinMode::Indirect); } } trace!(unique = returned.len(), "completed batch of indirect"); } }; Box::pin(st) } async fn query( &self, ids: Vec<Cid>, requirement: Option<PinMode>, ) -> Result<Vec<(Cid, PinKind<Cid>)>, Error> { // response vec gets written to whenever we find out what the pin is let mut response = Vec::with_capacity(ids.len()); for _ in 0..ids.len() { response.push(None); } let mut remaining = HashMap::new(); let (check_direct, searched_suffix, gather_indirect) = match requirement { Some(PinMode::Direct) => (true, Some(PinMode::Direct), false), Some(PinMode::Recursive) => (true, Some(PinMode::Recursive), false), Some(PinMode::Indirect) => (false, None, true), None => (true, None, true), }; let searched_suffix = PinModeRequirement::from(searched_suffix); let (mut response, mut remaining) = if check_direct { // find the recursive and direct ones by just seeing if the files exist let base = self.path.clone(); tokio::task::spawn_blocking(move || { for (i, cid) in ids.into_iter().enumerate() { let mut path = pin_path(base.clone(), &cid); if let Some(mode) = sync_read_direct_or_recursive(&mut path) { if searched_suffix.matches(&mode) { response[i] = Some(( cid, match mode { PinMode::Direct => PinKind::Direct, // FIXME: eech that recursive count is now out of place PinMode::Recursive => PinKind::Recursive(0), // FIXME: this is also quite unfortunate, should make an enum // of two? _ => unreachable!(), }, )); continue; } } if !gather_indirect { // if we are only trying to find recursive or direct, we clearly have not // found what we were looking for return Err(anyhow::anyhow!("{} is not pinned", cid)); } // use entry api to discard duplicate cids in input remaining.entry(cid).or_insert(i); } Ok((response, remaining)) }) .await?? } else { for (i, cid) in ids.into_iter().enumerate() { remaining.entry(cid).or_insert(i); } (response, remaining) }; // now remaining must have all of the cids => first_index mappings which were not found to // be recursive or direct. if !remaining.is_empty() { assert!(gather_indirect); trace!( remaining = remaining.len(), "query trying to find remaining indirect pins" ); let recursives = self .list_pinfiles() .await .try_filter_map(|(cid, mode)| { futures::future::ready(if mode == PinMode::Recursive { Ok(Some(cid)) } else { Ok(None) }) }) .map_ok(|cid| read_recursively_pinned(self.path.clone(), cid)) .try_buffer_unordered(4); futures::pin_mut!(recursives); 'out: while let Some((referring, references)) = StreamExt::try_next(&mut recursives).await? { // FIXME: maybe binary search? for cid in references { if let Some(index) = remaining.remove(&cid) { response[index] = Some((cid, PinKind::IndirectFrom(referring.clone()))); if remaining.is_empty() { break 'out; } } } } } if let Some((cid, _)) = remaining.into_iter().next() { // the error can be for any of these return Err(anyhow::anyhow!("{} is not pinned", cid)); } // the input can of course contain duplicate cids so handle them by just giving responses // for the first of the duplicates Ok(response.into_iter().flatten().collect()) } } impl FsDataStore { async fn list_pinfiles( &self, ) -> impl futures::stream::Stream<Item = Result<(Cid, PinMode), Error>> + 'static { let stream = match tokio::fs::read_dir(self.path.clone()).await { Ok(st) => Either::Left(ReadDirStream::new(st)), // make this into a stream which will only yield the initial error Err(e) => Either::Right(futures::stream::once(futures::future::ready(Err(e)))), }; stream .and_then(|d| async move { // map over the shard directories Ok(if d.file_type().await?.is_dir() { Either::Left(ReadDirStream::new(fs::read_dir(d.path()).await?)) } else { Either::Right(empty()) }) }) // flatten each .try_flatten() .map_err(Error::new) // convert the paths ending in ".data" into cid .try_filter_map(|d| { let name = d.file_name(); let path: &std::path::Path = name.as_ref(); let mode = if path.extension() == Some("recursive".as_ref()) { Some(PinMode::Recursive) } else if path.extension() == Some("direct".as_ref()) { Some(PinMode::Direct) } else { None }; let maybe_tuple = mode.and_then(move |mode| { filestem_to_pin_cid(path.file_stem()).map(move |cid| (cid, mode)) }); futures::future::ready(Ok(maybe_tuple)) }) } } /// Reads our serialized format for recusive pins, which is JSON array of stringified Cids. /// /// On file not found error returns an empty Vec as if nothing had happened. This is because we /// do "atomic writes" and file removals are expected to be atomic, but reads don't synchronize on /// writes, so while iterating it's possible that recursive pin is removed. async fn read_recursively_pinned(path: PathBuf, cid: Cid) -> Result<(Cid, Vec<Cid>), Error> { // our fancy format is a Vec<Cid> as json let mut path = pin_path(path, &cid); path.set_extension("recursive"); let contents = match tokio::fs::read(path).await { Ok(vec) => vec, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { // per method comment, return empty Vec; the pins may have seemed to be present earlier // but no longer are. return Ok((cid, Vec::new())); } Err(e) => return Err(e.into()), }; let cids: Vec<&str> = serde_json::from_slice(&contents)?; // returning a stream which is updated 8kB at time or such might be better, but this should // scale quite up as well. let found = cids .into_iter() .map(Cid::try_from) .collect::<Result<Vec<Cid>, _>>()?; trace!(cid = %cid, count = found.len(), "read indirect pins"); Ok((cid, found)) } async fn read_direct_or_recursive(mut block_path: PathBuf) -> Result<Option<PinMode>, Error> { tokio::task::spawn_blocking(move || Ok(sync_read_direct_or_recursive(&mut block_path))).await? } fn sync_read_direct_or_recursive(block_path: &mut PathBuf) -> Option<PinMode> { // important to first check the recursive then only the direct; the latter might be a left over for (ext, mode) in &[ ("recursive", PinMode::Recursive), ("direct", PinMode::Direct), ] { block_path.set_extension(ext); // Path::is_file calls fstat and coerces errors to false; this might be enough, as // we are holding the lock if block_path.is_file() { return Some(*mode); } } None } fn sync_write_recursive_pin( file: std::fs::File, count: usize, cids: impl Iterator<Item = String>, ) -> Result<(), Error> { use serde::{ser::SerializeSeq, Serializer}; use std::io::{BufWriter, Write}; let writer = BufWriter::new(file); let mut serializer = serde_json::ser::Serializer::new(writer); let mut seq = serializer.serialize_seq(Some(count))?; for cid in cids { seq.serialize_element(&cid)?; } seq.end()?; let mut writer = serializer.into_inner(); writer.flush()?; let file = writer.into_inner()?; file.sync_all()?; Ok(()) }
use std::io; use term::Term; pub fn move_cursor_down(out: &Term, n: usize) -> io::Result<()> { if n > 0 { out.write_str(&format!("\x1b[{}B", n)) } else { Ok(()) } } pub fn move_cursor_up(out: &Term, n: usize) -> io::Result<()> { if n > 0 { out.write_str(&format!("\x1b[{}A", n)) } else { Ok(()) } } pub fn clear_line(out: &Term) -> io::Result<()> { out.write_str("\r\x1b[2K") } pub fn clear_screen(out: &Term) -> io::Result<()> { out.write_str("\r\x1b[2J\r\x1b[H") }
use std::convert::TryFrom; // This function should be a method on `Sudoku`, but the functionality is needed elsewhere too fn remove_adjacent(notes: &mut [i32; 81], index: usize, candidate: i32) { let row = (index / 9) * 9; let col = index % 9; let square = (index / 27) * 27 + (col / 3) * 3; let mask = !candidate; for i in 0..9 { notes[row + i] &= mask; notes[col + i * 9] &= mask; } for offset in [0, 1, 2, 9, 10, 11, 18, 19, 20].iter() { notes[square + offset] &= mask; } } #[derive(Clone)] pub struct Sudoku { /// The field of a 9x9-sudoku as 1d-array. But instead of storing the number that is (not) /// written in this field, a binary number is used instead for easy use with the notes-field. /// 0 denotes an empty field field: [i32; 81], /// The notes for each field. The structure of this array is the same as the `field`-field. The /// bits of an element denotes the possible numbers that can be written in this field. The /// smallest bit set indicates a 1 might be written in this field, the second smallest bit set /// indicates a 2 might be written in this field etc. notes: [i32; 81], } impl Sudoku { #[allow(dead_code)] pub fn new() -> Self { Self { field: [0; 81], notes: [0x1ff; 81], } } fn from_arrays(field: [i32; 81], notes: [i32; 81]) -> Self { Self { field, notes, } } fn remove_adjacent(&mut self, field: usize, candidate: i32) { remove_adjacent(&mut self.notes, field, candidate); } fn put(&mut self, field: usize, candidate: i32) { self.field[field] = candidate; self.notes[field] = 0; self.remove_adjacent(field, candidate); } fn singles(&mut self) -> bool { let mut found = false; for i in 0..81 { if self.field[i] != 0 { continue; } let candidates = self.notes[i]; let count = candidates.count_ones(); if count == 0 { return false; } if count == 1 { self.put(i, candidates); found = true; } } found } #[inline(always)] fn hsinglesblock(&mut self, start: usize, inc: usize, skip: usize) -> bool { let mut onceormore = 0; let mut twiceormore = 0; let mut index = start; for _i in 0..3 { for _j in 0..3 { let candidates = self.notes[index]; twiceormore |= onceormore & candidates; onceormore |= candidates; index += inc; } index += skip; } let once = onceormore & !twiceormore; if once == 0 { return false; } index = start; for _i in 0..3 { for _j in 0..3 { let intersect = self.notes[index] & once; if intersect != 0 { self.put(index, intersect); } index += inc; } index += skip; } true } fn hsingles(&mut self) -> bool { for i in 0..9 { let found_something = self.hsinglesblock(i * 9, 1, 0) || self.hsinglesblock(i, 9, 0) || self.hsinglesblock((i / 3) * 27 + (i % 3) * 3, 1, 6); if found_something { return true; } } false } pub fn solve(&mut self) -> bool { let mut found = true; while found { found = self.singles() || self.hsingles(); } let mut min = 10; let mut mindex: i32 = -1; for i in 0..81 { let count = self.notes[i].count_ones(); if self.field[i] == 0 && count < min { min = count; mindex = i as i32; } } if mindex == -1 { return true; } let clone = self.clone(); let mut candidates = self.notes[mindex as usize]; while candidates != 0 { let c = candidates & -candidates; self.put(mindex as usize, c); if self.solve() { return true; } self.field[..].copy_from_slice(&clone.field); self.notes[..].copy_from_slice(&clone.notes); candidates &= !c; } false } pub fn field(&self) -> &[i32; 81] { &self.field } } impl TryFrom<&String> for Sudoku { type Error = (); fn try_from(line: &String) -> Result<Self, Self::Error> { let mut field = [0; 81]; let mut notes = [0x1ff; 81]; for (i, ch) in line.chars().enumerate().take(81) { if ch > '9' || ch < '0' { eprintln!("Illegal digit: {}", ch); return Err(()); } let digit = ch as i32 - '0' as i32; let bit = if digit > 0 { 1 << (digit - 1) } else { 0 }; field[i] = bit; if digit > 0 { if (!notes[i] & bit) != 0 { return Err(()); } notes[i] = 0; remove_adjacent(&mut notes, i, bit); } } Ok(Sudoku::from_arrays(field, notes)) } }
// Copyright 2019 The n-sql Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unused_imports)] #![allow(dead_code)] extern crate codespan; extern crate codespan_reporting; extern crate regex; mod location; mod char_locations; mod parser_source; mod source; mod comment; use self::regex::{RegexSetBuilder, RegexSet}; use self::char_locations::CharLocations; use self::comment::*; use self::source::Source; use self::LexicalError::*; use self::location::{spanned, ByteOffset, Line, Column, ColumnOffset, Span}; pub use self::location::{Position, Spanned, Location}; pub use self::parser_source::ParserSource; #[derive(Clone, PartialEq, Debug)] pub enum Token<'input> { Identifier(&'input str), StringLiteral(String), IntLiteral(i64), ByteLiteral(u8), FloatLiteral(f64), DocComment(Comment), // region [builtin datatype] Text, Int, Float, Numeric, Timestamp, Datetime, Date, Time, // endregion // region [Symbol] /// `(` LeftParen, /// `)` RightParen, /// `|` Pipe, /// `||` DoublePipe, /// `,` Comma, /// `:` Colon, /// `::` DoubleColon, /// `.` Period, /// `=` Equal, /// `!=`,`<>`, `^=`, `~=` NotEqual, /// `<` Less, /// `<=` LessOrEqual, /// `>` Greater, /// `>=` GreaterOrEqual, /// `+` PlusSign, /// `-` MinusSign, /// `*` Asterisk, /// `/` Solidus, // endregion // region [keywords] All, And, As, Asc, Both, By, Case, Cross, Desc, Distinct, Dual, Else, End, Except, From, Full, Group, Having, In, Is, Inner, Intersect, Join, Leading, Left, Limit, Minus, Not, Null, Offset, On, Or, Order, Outer, Right, Select, Skip, Then, Trailing, Union, Unique, When, Where, // endregion // region [function] Abs, Avg, AvgIf, BTrim, Cast, Ceil, Ceiling, Coalesce, Cos, Concat, Count, CountIf, Day, DayAdd, DaySub, Decode, DenseRank, Extract, Floor, Hour, HourAdd, HourSub, Length, Log, Log10, Lower, LPad, LTrim, Max, MaxIf, Median, MedianIf, Min, MinIf, Minute, MinuteAdd, MinuteSub, Month, MonthAdd, MonthSub, Now, Nvl, PadLeft, PadRight, Pow, Power, Replace, Reverse, Rank, Round, Sign, Sin, Sqrt, Stddev, StddevIf, RPad, RTrim, Second, SecondAdd, SecondSub, Substr, Substring, Sum, SumIf, Tan, Trim, TrimStart, TrimEnd, Upper, Year, YearAdd, YearSub, // endregion EOF, // Required for the layout algorithm } const REGEX_SOURCE:[(&str, Token); 123] = [ // region [keyword] ("^([Aa][Ll][Ll])$", Token::All), ("^([Aa][Nn][Dd])$", Token::And), ("^([Aa][Ss])$", Token::As), ("^([Aa][Ss][Cc])$", Token::Asc), ("^([Bb][Oo][Tt][Hh])$", Token::Both), ("^([Bb][Yy])$", Token::By), ("^([Cc][Aa][Ss][Ee])$", Token::Case), ("^([Cc][Rr][Oo][Ss][Ss])$", Token::Cross), ("^([Dd][Ee][Ss][Cc])$", Token::Desc), ("^([Dd][Ii][Ss][Tt][Ii][Nn][Cc][Tt])$", Token::Distinct), ("^([Dd][Uu][Aa][Ll])$", Token::Dual), ("^([Ee][Ll][Ss][Ee])$", Token::Else), ("^([Ee][Nn][Dd])$", Token::End), ("^([Ee][Xx][Cc][Ee][Pp][Tt])$", Token::Except), ("^([Ff][Rr][Oo][Mm])$", Token::From), ("^([Ff][Uu][Ll][Ll])$", Token::Full), ("^([Gg][Rr][Oo][Uu][Pp])$", Token::Group), ("^([Hh][Aa][Vv][Ii][Nn][Gg])$", Token::Having), ("^([Ii][Nn])$", Token::In), ("^([Ii][Ss])$", Token::Is), ("^([Ii][Nn][Nn][Ee][Rr])$", Token::Inner), ("^([Ii][Nn][Tt][Ee][Rr][Ss][Ee][Cc][Tt])$", Token::Intersect), ("^([Jj][Oo][Ii][Nn])$", Token::Join), ("^([Ll][Ee][Aa][Dd][Ii][Nn][Gg])$", Token::Leading), ("^([Ll][Ee][Ff][Tt])$", Token::Left), ("^([Ll][Ii][Mm][Ii][Tt])$", Token::Limit), ("^([Mm][Ii][Nn][Uu][Ss])$", Token::Minus), ("^([Nn][Oo][Tt])$", Token::Not), ("^([Nn][Uu][Ll][Ll])$", Token::Null), ("^([Oo][Ff][Ff][Ss][Ee][Tt])$", Token::Offset), ("^([Oo][Nn])$", Token::On), ("^([Oo][Rr])$", Token::Or), ("^([Oo][Rr][Dd][Ee][Rr])$", Token::Order), ("^([Oo][Uu][Tt][Ee][Rr])$", Token::Outer), ("^([Rr][Ii][Gg][Hh][Tt])$", Token::Right), ("^([Ss][Ee][Ll][Ee][Cc][Tt])$", Token::Select), ("^([Ss][Kk][Ii][Pp])$", Token::Skip), ("^([Tt][Hh][Ee][Nn])$", Token::Then), ("^([Tt][Rr][Aa][Ii][Ll][Ii][Nn][Gg])$", Token::Trailing), ("^([Uu][Nn][Ii][Oo][Nn])$", Token::Union), ("^([Uu][Nn][Ii][Qq][Uu][Ee])$", Token::Unique), ("^([Ww][Hh][Ee][Nn])$", Token::When), ("^([Ww][Hh][Ee][Rr][Ee])$", Token::Where), // endregion, // region [function] ("^([Aa][Bb][Ss])$", Token::Abs), ("^([Aa][Vv][Gg])$", Token::Avg), ("^([Aa][Vv][Gg][Ii][Ff])$", Token::AvgIf), ("^([Bb][Tt][Rr][Ii][Mm])$", Token::BTrim), ("^([Cc][Aa][Ss][Tt])$", Token::Cast), ("^([Cc][Ee][Ii][Ll])$", Token::Ceil), ("^([Cc][Ee][Ii][Ll][Ii][Nn][Gg])$", Token::Ceiling), ("^([Cc][Oo][Aa][Ll][Ee][Ss][Cc][Ee])$", Token::Coalesce), ("^([Cc][Oo][Ss])$", Token::Cos), ("^([Cc][Oo][Nn][Cc][Aa][Tt])$", Token::Concat), ("^([Cc][Oo][Uu][Nn][Tt])$", Token::Count), ("^([Cc][Oo][Uu][Nn][Tt][Ii][Ff])$", Token::CountIf), ("^([Dd][Aa][Yy])$", Token::Day), ("^([Dd][Aa][Yy]_[Aa][Dd][Dd])$", Token::DayAdd), ("^([Dd][Aa][Yy]_[Ss][Uu][Bb])$", Token::DaySub), ("^([Dd][Ee][Cc][Oo][Dd][Ee])$", Token::Decode), ("^([Dd][Ee][Nn][Ss][Ee]_[Rr][Aa][Nn][Kk])$", Token::DenseRank), ("^([Ee][Xx][Tt][Rr][Aa][Cc][Tt])$", Token::Extract), ("^([Ff][Ll][Oo][Oo][Rr])$", Token::Floor), ("^([Hh][Oo][Uu][Rr])$", Token::Hour), ("^([Hh][Oo][Uu][Rr]_[Aa][Dd][Dd])$", Token::HourAdd), ("^([Hh][Oo][Uu][Rr]_[Ss][Uu][Bb])$", Token::HourSub), ("^([Ll][Ee][Nn][Gg][Tt][Hh])$", Token::Length), ("^([Ll][Oo][Gg])$", Token::Log), ("^([Ll][Oo][Gg]10)$", Token::Log10), ("^([Ll][Oo][Ww][Ee][Rr])$", Token::Lower), ("^([Ll][Pp][Aa][Dd])$", Token::LPad), ("^([Ll][Tt][Rr][Ii][Mm])$", Token::LTrim), ("^([Mm][Aa][Xx])$", Token::Max), ("^([Mm][Aa][Xx][Ii][Ff])$", Token::MaxIf), ("^([Mm][Ee][Dd][Ii][Aa][Nn])$", Token::Median), ("^([Mm][Ee][Dd][Ii][Aa][Nn][Ii][Ff])$", Token::MedianIf), ("^([Mm][Ii][Nn])$", Token::Min), ("^([Mm][Ii][Nn][Ii][Ff])$", Token::MinIf), ("^([Mm][Ii][Nn][Uu][Tt][Ee])$", Token::Minute), ("^([Mm][Ii][Nn][Uu][Tt][Ee]_[Aa][Dd][Dd])$", Token::MinuteAdd), ("^([Mm][Ii][Nn][Uu][Tt][Ee]_[Ss][Uu][Bb])$", Token::MinuteSub), ("^([Mm][Oo][Nn][Tt][Hh])$", Token::Month), ("^([Mm][Oo][Nn][Tt][Hh]_[Aa][Dd][Dd])$", Token::MonthAdd), ("^([Mm][Oo][Nn][Tt][Hh]_[Ss][Uu][Bb])$", Token::MonthSub), ("^([Nn][Oo][Ww])$", Token::Now), ("^([Nn][Vv][Ll])$", Token::Nvl), ("^([Pp][Aa][Dd]_[Ll][Ee][Ff][Tt])$", Token::PadLeft), ("^([Pp][Aa][Dd]_[Rr][Ii][Gg][Hh][Tt])$", Token::PadRight), ("^([Pp][Oo][Ww])$", Token::Pow), ("^([Pp][Oo][Ww][Ee][Rr])$", Token::Power), ("^([Rr][Ee][Pp][Ll][Aa][Cc][Ee])$", Token::Replace), ("^([Rr][Ee][Vv][Ee][Rr][Ss][Ee])$", Token::Reverse), ("^([Rr][Aa][Nn][Kk])$", Token::Rank), ("^([Rr][Oo][Uu][Nn][Dd])$", Token::Round), ("^([Ss][Ii][Gg][Nn])$", Token::Sign), ("^([Ss][Ii][Nn])$", Token::Sin), ("^([Ss][Qq][Rr][Tt])$", Token::Sqrt), ("^([Ss][Tt][Dd][Dd][Ee][Vv])$", Token::Stddev), ("^([Ss][Tt][Dd][Dd][Ee][Vv][Ii][Ff])$", Token::StddevIf), ("^([Rr][Pp][Aa][Dd])$", Token::RPad), ("^([Rr][Tt][Rr][Ii][Mm])$", Token::RTrim), ("^([Ss][Ee][Cc][Oo][Nn][Dd])$", Token::Second), ("^([Ss][Ee][Cc][Oo][Nn][Dd]_[Aa][Dd][Dd])$", Token::SecondAdd), ("^([Ss][Ee][Cc][Oo][Nn][Dd]_[Ss][Uu][Bb])$", Token::SecondSub), ("^([Ss][Uu][Bb][Ss][Tt][Rr])$", Token::Substr), ("^([Ss][Uu][Bb][Ss][Tt][Rr][Ii][Nn][Gg])$", Token::Substring), ("^([Ss][Uu][Mm])$", Token::Sum), ("^([Ss][Uu][Mm][Ii][Ff])$", Token::SumIf), ("^([Tt][Aa][Nn])$", Token::Tan), ("^([Tt][Rr][Ii][Mm])$", Token::Trim), ("^([Tt][Rr][Ii][Mm]_[Ss][Tt][Aa][Rr][Tt])$", Token::TrimStart), ("^([Tt][Rr][Ii][Mm]_[Ee][Nn][Dd])$", Token::TrimEnd), ("^([Uu][Pp][Pp][Ee][Rr])$", Token::Upper), ("^([Yy][Ee][Aa][Rr])$", Token::Year), ("^([Yy][Ee][Aa][Rr]_[Aa][Dd][Dd])$", Token::YearAdd), ("^([Yy][Ee][Aa][Rr]_[Ss][Uu][Bb])$", Token::YearSub), // endregion // region ("^([Tt][Ee][Xx][Tt])$", Token::Text), ("^([Ii][Nn][Tt])$", Token::Int), ("^([Ff][Ll][Oo][Aa][Tt])$", Token::Float), ("^([Nn][Uu][Mm][Ee][Rr][Ii][Cc])$", Token::Numeric), ("^([Tt][Ii][Mm][Ee][Ss][Tt][Aa][Mm][Pp])$", Token::Timestamp), ("^([Dd][Aa][Tt][Ee][Tt][Ii][Mm][Ee])$", Token::Datetime), ("^([Dd][Aa][Tt][Ee])$", Token::Date), ("^([Tt][Ii][Mm][Ee])$", Token::Time), // endregion ]; impl<'input> Token<'input> { fn token_type(&self) -> &'static str { use self::Token::*; match self { Select | From | Where | Group | Order | Skip | Limit | By | In | Not => "keyword", Nvl | Day => "function", StringLiteral(_) => "string", IntLiteral(_) | FloatLiteral(_) => "number", DocComment(_) => "comment", _ => "unknown" } } } struct MatcherBuilder { regex_set: RegexSet, } impl MatcherBuilder { fn new() -> Self { let regex_set = RegexSetBuilder::new(REGEX_SOURCE.iter().map(|(s, _)| s)).build().unwrap(); MatcherBuilder{regex_set} } fn matcher<'input, 'builder>(&'builder self, s: &'input str) -> Matcher<'input, 'builder> { Matcher { text: s, consumed: 0, regex_set: &self.regex_set, } } } struct Matcher<'input, 'builder> { text: &'input str, consumed: usize, regex_set: &'builder regex::RegexSet } impl<'input, 'builder> Iterator for Matcher<'input, 'builder> { type Item = Token<'input>; //noinspection RsTypeCheck fn next(&mut self) -> Option<Self::Item> { let matches: Vec<usize> = self.regex_set.matches(self.text).into_iter().collect(); if matches.len() > 1 { panic!("Non-unique matching error!"); } if let Some(i) = matches.first() { let (_, t) = &REGEX_SOURCE[*i]; Some(t.clone()) } else { None } } } //noinspection ALL #[derive(Clone, Debug, PartialEq, Eq)] pub enum LexicalError { /// empty char literal EmptyCharLiteral, /// unexpected character UnexpectedChar(char), /// unexpected end of file UnexpectedEof, /// unexpected escape code UnexpectedEscapeCode(char), /// unterminated string literal UnterminatedStringLiteral, /// cannot parse integer, probable overflow NonParseableInt, /// cannot parse hex literal, overflow HexLiteralOverflow, /// cannot parse hex literal, underflow HexLiteralUnderflow, /// wrong hex literal prefix, should start as '0x' or '-0x' HexLiteralWrongPrefix, /// cannot parse hex literal, incomplete HexLiteralIncomplete } pub type SpannedToken<'input> = Spanned<Token<'input>, Location>; pub type SpannedError = Spanned<LexicalError, Location>; pub fn is_identifier_start(ch: char) -> bool { match ch { '_' | 'a'...'z' | 'A'...'Z' | '\u{4E00}'...'\u{9FA5}' | '\u{F900}'...'\u{FA2D}' => true, _ => false, } } pub fn is_identifier_continue(ch: char) -> bool { match ch { '0'...'9' | '\'' => true, ch => is_identifier_start(ch), } } pub fn is_digit(ch: char) -> bool { ch.is_digit(10) } pub fn is_hex(ch: char) -> bool { ch.is_digit(16) } pub struct Lexer<'input> { input: &'input str, chars: CharLocations<'input>, lookahead: Option<(Location, char)>, start_index: Position, builder: MatcherBuilder, } impl<'input> Lexer<'input> { pub fn new<S>(input: &'input S) -> Self where S: ?Sized + ParserSource { let mut chars = CharLocations::new(input); Lexer { input: input.src(), start_index: input.start_index(), lookahead: chars.next(), chars, builder: MatcherBuilder::new() } } pub fn tokenizer(self) -> Tokenizer<'input> { Tokenizer(self) } fn bump(&mut self) -> Option<(Location, char)> { match self.lookahead { Some((location, ch)) => { self.lookahead = self.chars.next(); Some((location, ch)) } None => None, } } fn skip_to_end(&mut self) { while let Some(_) = self.bump() {} } fn next_location(&self) -> Location { self.lookahead.as_ref().map_or(self.chars.location, |l| l.0) } fn identifier(&mut self, start: Location) -> Result<SpannedToken<'input>, SpannedError> { let (mut end, mut identifier) = self.take_while(start, is_identifier_continue); match self.lookahead { Some((_, c)) if c == '!' => { self.bump(); end.column += 1.into(); end.absolute += 1.into(); identifier = self.slice(start, end); } _ => (), } let token =match self.builder.matcher(identifier).next() { Some(t) => t, None => Token::Identifier(identifier) }; // let token = Token::Identifier(identifier); Ok(spanned(start, end, token)) } fn numeric_literal(&mut self, start: Location) -> Result<SpannedToken<'input>, SpannedError> { let (end, int) = self.take_while(start, is_digit); let (start, end, token) = if int.chars().next().unwrap() == '.' { match self.lookahead { Some((_, ch)) if ch.is_whitespace() => (start, end, Token::FloatLiteral(int.parse().unwrap())), None => (start, end, Token::FloatLiteral(int.parse().unwrap())), _ => panic!("错误") } } else { match self.lookahead { Some((_, '.')) => { self.bump(); // Skip '.' let (end, float) = self.take_while(start, is_digit); match self.lookahead { Some((_, ch)) if is_identifier_start(ch) => { return self.error(end, UnexpectedChar(ch)); } _ => (start, end, Token::FloatLiteral(float.parse().unwrap())), } } Some((_, 'x')) => { self.bump(); // Skip 'x' let int_start = self.next_location(); let (end, hex) = self.take_while(int_start, is_hex); match int { "0" | "-0" => match self.lookahead { Some((_, ch)) if is_identifier_start(ch) => { return self.error(end, UnexpectedChar(ch)); } _ => { if hex.is_empty() { return self.error(start, HexLiteralIncomplete); } let is_positive = int == "0"; match i64_from_hex(hex, is_positive) { Ok(val) => (start, end, Token::IntLiteral(val)), Err(err) => return self.error(start, err), } } }, _ => return self.error(start, HexLiteralWrongPrefix), } } Some((_, 'b')) => { self.bump(); // Skip 'b' let end = self.next_location(); match self.lookahead { Some((pos, ch)) if is_identifier_start(ch) => { return self.error(pos, UnexpectedChar(ch)); } _ => { if let Ok(val) = int.parse() { (start, end, Token::ByteLiteral(val)) } else { return self.error(start, NonParseableInt); } } } } Some((start, ch)) if is_identifier_start(ch) => return self.error(start, UnexpectedChar(ch)), None | Some(_) => { if let Ok(val) = int.parse() { (start, end, Token::IntLiteral(val)) } else { return self.error(start, NonParseableInt); } } } }; Ok(spanned(start, end, token)) } fn test_lookahead<F: FnMut(char) -> bool>(&self, mut test: F) -> bool { self.lookahead.map_or(false, |(_, ch)| test(ch)) } fn line_comment(&mut self, start: Location) -> Option<SpannedToken<'input>> { let (end, comment) = self.take_until(start, |ch| ch == '\n'); if comment.starts_with("--") { let skip = if comment.starts_with("-- ") { 3 } else { 2 }; let comment = Token::DocComment(Comment { r#type: CommentType::Line, content: comment[skip..].to_string(), }); Some(spanned(start, end, comment)) } else { None } } fn eof_error<T>(&mut self) -> Result<T, SpannedError> { let location = self.next_location(); self.error(location, UnexpectedEof) } fn error<T>(&mut self, location: Location, code: LexicalError) -> Result<T, SpannedError> { self.skip_to_end(); Err(spanned(location, location, code)) } fn escape_code(&mut self) -> Result<char, SpannedError> { match self.bump() { Some((_, '\'')) => Ok('\''), Some((_, '\\')) => Ok('\\'), Some((_, '/')) => Ok('/'), Some((_, 'n')) => Ok('\n'), Some((_, 'r')) => Ok('\r'), Some((_, 't')) => Ok('\t'), // TODO: Unicode escape codes Some((start, ch)) => self.error(start, UnexpectedEscapeCode(ch)), None => self.eof_error(), } } fn slice(&self, start: Location, end: Location) -> &'input str { let start = start.absolute - ByteOffset(self.start_index.to_usize() as i64); let end = end.absolute - ByteOffset(self.start_index.to_usize() as i64); &self.input[start.to_usize()..end.to_usize()] } fn take_while<F: FnMut(char) -> bool>(&mut self, start: Location, mut keep_going: F) -> (Location, &'input str) { self.take_until(start, |c| !keep_going(c)) } fn take_until<F: FnMut(char) -> bool>(&mut self, start: Location, mut terminate: F) -> (Location, &'input str) { while let Some((end, ch)) = self.lookahead { if terminate(ch) { return (end, self.slice(start, end)); } else { self.bump(); } } (self.next_location(), self.slice(start, self.next_location())) } fn string_literal(&mut self, start: Location) -> Result<SpannedToken<'input>, SpannedError> { let mut string = String::new(); while let Some((_, ch)) = self.bump() { match ch { '\'' => { if self.test_lookahead(|c| c == '\'') { self.bump(); // skip '\'' string.push(ch); } else { let end = self.next_location(); let token = Token::StringLiteral(string); return Ok(spanned(start, end, token)); } }, ch => string.push(ch), } } self.error(start, UnterminatedStringLiteral) } } impl<'input> Iterator for Lexer<'input> { type Item = Result<SpannedToken<'input>, SpannedError>; fn next(&mut self) -> Option<Self::Item> { while let Some((start, ch)) = self.bump(){ return match ch { ch if ch.is_whitespace() => continue, '-' if self.test_lookahead(|ch| ch == '-') => match self.line_comment(start) { Some(token) => Some(Ok(token)), None => continue, }, '!' | '^' | '~' if self.test_lookahead(|ch| ch == '=') => { self.bump(); // skip '=' Some(Ok(spanned(start, self.next_location(), Token::NotEqual))) }, ':' => { if self.test_lookahead(|ch| ch == ':') { self.bump(); // skip ':' Some(Ok(spanned(start, self.next_location(), Token::DoubleColon))) } else { Some(Ok(spanned(start, self.next_location(), Token::Colon))) } }, '|' => { if self.test_lookahead(|ch| ch == '|') { self.bump(); // skip ':' Some(Ok(spanned(start, self.next_location(), Token::DoublePipe))) } else { Some(Ok(spanned(start, self.next_location(), Token::Pipe))) } }, '<' => { if let Some((_, ch)) = self.lookahead { match ch { '=' => { self.bump(); // skip '=' Some(Ok(spanned(start, self.next_location(), Token::LessOrEqual))) }, '>' => { self.bump(); // skip '>' Some(Ok(spanned(start, self.next_location(), Token::NotEqual))) } _ => Some(Ok(spanned(start, self.next_location(), Token::Less))) } } else { Some(Ok(spanned(start, self.next_location(), Token::Less))) } }, '>' => { if self.test_lookahead(|ch| ch == '=') { self.bump(); // skip '=' Some(Ok(spanned(start, self.next_location(), Token::GreaterOrEqual))) } else { Some(Ok(spanned(start, self.next_location(), Token::Greater))) } }, ch if is_digit(ch) || ((ch == '-' || ch == '.') && self.test_lookahead(is_digit)) => { Some(self.numeric_literal(start)) }, '\'' => Some(self.string_literal(start)), '(' => Some(Ok(spanned(start, self.next_location(), Token::LeftParen))), ')' => Some(Ok(spanned(start, self.next_location(), Token::RightParen))), ',' => Some(Ok(spanned(start, self.next_location(), Token::Comma))), '.' => Some(Ok(spanned(start, self.next_location(), Token::Period))), '=' => Some(Ok(spanned(start, self.next_location(), Token::Equal))), '+' => Some(Ok(spanned(start, self.next_location(), Token::PlusSign))), '-' => Some(Ok(spanned(start, self.next_location(), Token::MinusSign))), '*' => Some(Ok(spanned(start, self.next_location(), Token::Asterisk))), '/' => Some(Ok(spanned(start, self.next_location(), Token::Solidus))), ch if is_identifier_start(ch) => Some(self.identifier(start)), ch => unimplemented!("{:?}", ch) } } // Return EOF instead of None so that the layout algorithm receives the eof location // Some(Ok(spanned( // self.next_location(), // self.next_location(), // Token::EOF, // ))) None } } pub struct Tokenizer<'input>(Lexer<'input>); impl<'input> Iterator for Tokenizer<'input> { type Item = Result<(Position, Token<'input>, Position), SpannedError>; fn next(&mut self) -> Option<Self::Item> { match self.0.next() { Some(t) => Some(match t { Ok(t) => Ok((t.span.start().absolute, t.value, t.span.end().absolute)), Err(t) => Err(t) }), None => None, } } } /// Converts partial hex literal (i.e. part after `0x` or `-0x`) to 64 bit signed integer. /// /// This is basically a copy and adaptation of `std::num::from_str_radix`. fn i64_from_hex(hex: &str, is_positive: bool) -> Result<i64, LexicalError> { const RADIX: u32 = 16; let digits = hex.as_bytes(); let sign: i64 = if is_positive { 1 } else { -1 }; let mut result = 0i64; for &c in digits { let x = (c as char).to_digit(RADIX).expect("valid hex literal"); result = result .checked_mul(RADIX as i64) .and_then(|result| result.checked_add((x as i64) * sign)) .ok_or_else(|| { if is_positive { HexLiteralOverflow } else { HexLiteralUnderflow } })?; } Ok(result) } #[cfg(test)] mod test{ use super::*; use super::Token::*; fn location(byte: u32) -> Location { Location { line: Line(0), column: Column(byte + 1), absolute: Position(byte + 1), } } fn tokenizer<'input>( input: &'input str, ) -> impl Iterator<Item = Result<SpannedToken<'input>, SpannedError>> + 'input { Box::new(Iterator::take_while(Lexer::new(input), |token| match *token { Ok(Spanned { value: Token::EOF, .. }) => false, _ => true, })) } fn test(input: &str, expected: Vec<(&str, Token)>) { use super::Source; let mut tokenizer = tokenizer(input); let mut count = 0; let length = expected.len(); let source = self::codespan::FileMap::new("test".into(), input.to_string()); for (token, (expected_span, expected_tok)) in tokenizer.by_ref().zip(expected.into_iter()) { count += 1; let start_byte = source.span().start() + ByteOffset(expected_span.find("~").unwrap() as i64); let mut start = Source::location(&source, start_byte).unwrap(); start.column += ColumnOffset(1); let end_byte = source.span().start() + ByteOffset(expected_span.rfind("~").unwrap() as i64 + 1); let mut end = Source::location(&source, end_byte.into()).unwrap(); end.column += ColumnOffset(1); assert_eq!(Ok(spanned(start, end, expected_tok)), token); } assert_eq!(count, length); assert_eq!(true, count > 0); // Make sure that there is nothing else to consume assert_eq!(None, tokenizer.next()); } #[test] fn builtin_operators() { test( r#". : = | ( ) + - * / > < , <= >= != <> ^= ~= ::"#, vec![ (r#"~ "#, Period), (r#" ~ "#, Colon), (r#" ~ "#, Equal), (r#" ~ "#, Pipe), (r#" ~ "#, LeftParen), (r#" ~ "#, RightParen), (r#" ~ "#, PlusSign), (r#" ~ "#, MinusSign), (r#" ~ "#, Asterisk), (r#" ~ "#, Solidus), (r#" ~ "#, Greater), (r#" ~ "#, Less), (r#" ~ "#, Comma), (r#" ~~ "#, LessOrEqual), (r#" ~~ "#, GreaterOrEqual), (r#" ~~ "#, NotEqual), (r#" ~~ "#, NotEqual), (r#" ~~ "#, NotEqual), (r#" ~~ "#, NotEqual), (r#" ~~"#, DoubleColon), ], ); } #[test] fn line_comments() { test( r#"h-i -- hellooo"#, vec![ (r#"~ "#, Identifier("h")), (r#" ~ "#, MinusSign), (r#" ~ "#, Identifier("i")), (r#" ~~ ~~~~~~~"#, DocComment(Comment{r#type: CommentType::Line, content: "hellooo".to_string()})) ], ); } #[test] fn string_literals() { test( r#"'abc' mn 'hjk''xyz'"#, vec![ (r#"~~~~~ "#, StringLiteral("abc".to_string())), (r#" ~~ "#, Identifier("mn")), (r#" ~~~~~~~~~~"#, StringLiteral(r#"hjk'xyz"#.to_string()), ), ], ); } #[test] fn float_literals() { test( r#"3.2 4.236 -9.365"#, vec![ (r#"~~~ "#, FloatLiteral(3.2)), (r#" ~~~~~ "#, FloatLiteral(4.236)), (r#" ~~~~~~"#, FloatLiteral(-9.365)), ], ); } #[test] fn keywords() { test( r#"select * from order left"#, vec![ (r#"~~~~~~ "#, Select), (r#" ~ "#, Asterisk), (r#" ~~~~ "#, From), (r#" ~~~~~ "#, Order), (r#" ~~~~"#, Left), ], ); } #[test] fn variable(){ test( r#"a = : m"#, vec![ (r#"~ "#, Identifier("a")), (r#" ~ "#, Equal), (r#" ~ "#, Colon), (r#" ~"#, Identifier("m")), ], ); } #[test] fn test1() { test("a >-3.2", vec![ ("~ ", Identifier("a")), (" ~ ", Greater), (" ~~~~", FloatLiteral(-3.2)), ], ) } #[test] fn test2() { test("a > '3.2'", vec![ ("~ ", Identifier("a")), (" ~ ", Greater), (" ~~~~~", StringLiteral("3.2".to_string())), ], ) } #[test] fn test3(){ test("trim(trailing 'a' from 'abc')", vec![ ("~~~~ ", Trim), (" ~ ", LeftParen), (" ~~~~~~~~ ", Trailing), (" ~~~ ", StringLiteral("a".to_string())), (" ~~~~ ", From), (" ~~~~~ ", StringLiteral("abc".to_string())), (" ~", RightParen), ], ) } }
use hyper::{Body, Method, Request, Client}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let req = Request::builder() .method(Method::POST) .uri("http://httpbin.org/post") .header("content-type", "applicaton/json") .body(Body::from(r#"{"library": "hyper"}"#))?; let client = Client::new(); let resp = client.request(req).await?; println!("Response: {:?}", resp.status()); Ok(()) }
use crate::context::RpcContext; use crate::v02::types::reply::BlockStatus; use crate::v04::types::TransactionWithHash; use anyhow::{anyhow, Context}; use pathfinder_common::{BlockId, BlockNumber}; use serde::Deserialize; #[derive(Deserialize, Debug, PartialEq, Eq)] #[cfg_attr(test, derive(Copy, Clone))] pub struct GetBlockInput { block_id: BlockId, } crate::error::generate_rpc_error_subset!(GetBlockError: BlockNotFound); /// Get block information with full transactions given the block id pub async fn get_block_with_txs( context: RpcContext, input: GetBlockInput, ) -> Result<types::Block, GetBlockError> { let block_id = input.block_id; let block_id = match block_id { BlockId::Pending => { match context .pending_data .ok_or_else(|| anyhow!("Pending data not supported in this configuration"))? .block() .await { Some(block) => { return Ok(types::Block::from_sequencer(block.as_ref().clone().into())) } None => return Err(GetBlockError::BlockNotFound), } } other => other.try_into().expect("Only pending cast should fail"), }; let storage = context.storage.clone(); let span = tracing::Span::current(); tokio::task::spawn_blocking(move || { let _g = span.enter(); let mut connection = storage .connection() .context("Opening database connection")?; let transaction = connection .transaction() .context("Creating database transaction")?; let header = transaction .block_header(block_id) .context("Reading block from database")? .ok_or(GetBlockError::BlockNotFound)?; let l1_accepted = transaction.block_is_l1_accepted(header.number.into())?; let block_status = if l1_accepted { BlockStatus::AcceptedOnL1 } else { BlockStatus::AcceptedOnL2 }; let transactions = get_block_transactions(&transaction, header.number)?; Ok(types::Block::from_parts(header, block_status, transactions)) }) .await .context("Database read panic or shutting down")? } /// This function assumes that the block ID is valid i.e. it won't check if the block hash or number exist. fn get_block_transactions( db_tx: &pathfinder_storage::Transaction<'_>, block_number: BlockNumber, ) -> Result<Vec<TransactionWithHash>, GetBlockError> { let txs = db_tx .transaction_data_for_block(block_number.into()) .context("Reading transactions from database")? .context("Transaction data missing for block")? .into_iter() .map(|(tx, _rx)| tx.into()) .collect(); Ok(txs) } mod types { use crate::felt::RpcFelt; use crate::v02::types::reply::BlockStatus; use crate::v04::types::TransactionWithHash; use pathfinder_common::{ BlockHash, BlockHeader, BlockNumber, BlockTimestamp, SequencerAddress, StateCommitment, }; use serde::Serialize; use serde_with::{serde_as, skip_serializing_none}; use stark_hash::Felt; /// L2 Block as returned by the RPC API. #[serde_as] #[skip_serializing_none] #[derive(Clone, Debug, Serialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct Block { pub status: BlockStatus, #[serde_as(as = "Option<RpcFelt>")] pub block_hash: Option<BlockHash>, #[serde_as(as = "RpcFelt")] pub parent_hash: BlockHash, pub block_number: Option<BlockNumber>, #[serde_as(as = "Option<RpcFelt>")] pub new_root: Option<StateCommitment>, pub timestamp: BlockTimestamp, #[serde_as(as = "RpcFelt")] pub sequencer_address: SequencerAddress, pub transactions: Vec<TransactionWithHash>, } impl Block { pub fn from_parts( header: BlockHeader, status: BlockStatus, transactions: Vec<TransactionWithHash>, ) -> Self { Self { status, block_hash: Some(header.hash), parent_hash: header.parent_hash, block_number: Some(header.number), new_root: Some(header.state_commitment), timestamp: header.timestamp, sequencer_address: header.sequencer_address, transactions, } } /// Constructs [Block] from [sequencer's block representation](starknet_gateway_types::reply::Block) pub fn from_sequencer(block: starknet_gateway_types::reply::MaybePendingBlock) -> Self { use starknet_gateway_types::reply::MaybePendingBlock; match block { MaybePendingBlock::Block(block) => Self { status: block.status.into(), block_hash: Some(block.block_hash), parent_hash: block.parent_block_hash, block_number: Some(block.block_number), new_root: Some(block.state_commitment), timestamp: block.timestamp, sequencer_address: block .sequencer_address // Default value for cairo <0.8.0 is 0 .unwrap_or(SequencerAddress(Felt::ZERO)), transactions: block.transactions.into_iter().map(|t| t.into()).collect(), }, MaybePendingBlock::Pending(pending) => Self { status: pending.status.into(), block_hash: None, parent_hash: pending.parent_hash, block_number: None, new_root: None, timestamp: pending.timestamp, sequencer_address: pending.sequencer_address, transactions: pending.transactions.into_iter().map(|t| t.into()).collect(), }, } } } } #[cfg(test)] mod tests { use super::*; use assert_matches::assert_matches; use jsonrpsee::types::Params; use pathfinder_common::macro_prelude::*; use pathfinder_common::BlockNumber; use starknet_gateway_types::pending::PendingData; #[test] fn parsing() { let number = BlockId::Number(BlockNumber::new_or_panic(123)); let hash = BlockId::Hash(block_hash!("0xbeef")); [ (r#"["pending"]"#, BlockId::Pending), (r#"{"block_id": "pending"}"#, BlockId::Pending), (r#"["latest"]"#, BlockId::Latest), (r#"{"block_id": "latest"}"#, BlockId::Latest), (r#"[{"block_number":123}]"#, number), (r#"{"block_id": {"block_number":123}}"#, number), (r#"[{"block_hash": "0xbeef"}]"#, hash), (r#"{"block_id": {"block_hash": "0xbeef"}}"#, hash), ] .into_iter() .enumerate() .for_each(|(i, (input, expected))| { let actual = Params::new(Some(input)) .parse::<GetBlockInput>() .unwrap_or_else(|error| panic!("test case {i}: {input}, {error}")); assert_eq!( actual, GetBlockInput { block_id: expected }, "test case {i}: {input}" ); }); } type TestCaseHandler = Box<dyn Fn(usize, &Result<types::Block, GetBlockError>)>; /// Execute a single test case and check its outcome for both: `get_block_with_[txs|tx_hashes]` async fn check(test_case_idx: usize, test_case: &(RpcContext, BlockId, TestCaseHandler)) { let (context, block_id, f) = test_case; let result = get_block_with_txs( context.clone(), GetBlockInput { block_id: *block_id, }, ) .await; f(test_case_idx, &result); } /// Common assertion type for most of the test cases fn assert_hash(expected: &'static [u8]) -> TestCaseHandler { Box::new(|i: usize, result| { assert_matches!(result, Ok(block) => assert_eq!( block.block_hash, Some(block_hash_bytes!(expected)), "test case {i}" )); }) } impl PartialEq for GetBlockError { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Internal(l), Self::Internal(r)) => l.to_string() == r.to_string(), _ => core::mem::discriminant(self) == core::mem::discriminant(other), } } } /// Common assertion type for most of the error paths fn assert_error(expected: GetBlockError) -> TestCaseHandler { Box::new(move |i: usize, result| { assert_matches!(result, Err(error) => assert_eq!(*error, expected, "test case {i}"), "test case {i}"); }) } #[tokio::test] async fn happy_paths_and_major_errors() { let ctx = RpcContext::for_tests_with_pending().await; let ctx_with_pending_empty = RpcContext::for_tests().with_pending_data(PendingData::default()); let ctx_with_pending_disabled = RpcContext::for_tests(); let cases: &[(RpcContext, BlockId, TestCaseHandler)] = &[ // Pending ( ctx.clone(), BlockId::Pending, Box::new(|i, result| { assert_matches!(result, Ok(block) => assert_eq!( block.parent_hash, block_hash_bytes!(b"latest"), "test case {i}" ), "test case {i}") }), ), ( ctx_with_pending_empty, BlockId::Pending, assert_error(GetBlockError::BlockNotFound), ), ( ctx_with_pending_disabled, BlockId::Pending, assert_error(GetBlockError::Internal(anyhow!( "Pending data not supported in this configuration" ))), ), // Other block ids (ctx.clone(), BlockId::Latest, assert_hash(b"latest")), ( ctx.clone(), BlockId::Number(BlockNumber::GENESIS), assert_hash(b"genesis"), ), ( ctx.clone(), BlockId::Hash(block_hash_bytes!(b"genesis")), assert_hash(b"genesis"), ), ( ctx.clone(), BlockId::Number(BlockNumber::new_or_panic(9999)), assert_error(GetBlockError::BlockNotFound), ), ( ctx, BlockId::Hash(block_hash_bytes!(b"non-existent")), assert_error(GetBlockError::BlockNotFound), ), ]; for (i, test_case) in cases.iter().enumerate() { check(i, test_case).await; } } }
use bytesize::ByteSize; use std::time::Duration; #[derive(Debug, Clone)] pub struct Config { /// The maximum size of the payload part of a loqui frame. pub max_payload_size: ByteSize, /// The duration of time from when a client makes a request to when we stop waiting for a response /// from the server. pub request_timeout: Duration, /// The duration of time from when a client starts a connect to when we stop trying to handshake. pub handshake_timeout: Duration, /// Supported encodings. pub supported_encodings: &'static [&'static str], }
use itertools::Itertools; pub trait Model<X, Y> { fn predict(&self, x: &X, y: &mut Y); fn predict_map(&self, x: &Vec<X>, y: &mut Vec<Y>) { for i in 0..x.len() { self.predict(&x[i], &mut y[i]); } } }
use crate::context::*; use crate::types::*; use crate::util::*; use itertools::Itertools; use lsp_types::request::*; use lsp_types::*; use serde::Deserialize; use std::str; use url::Url; pub fn text_document_hover(meta: EditorMeta, params: EditorParams, ctx: &mut Context) { let params = PositionParams::deserialize(params).unwrap(); let req_params = HoverParams { text_document_position_params: TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: Url::from_file_path(&meta.buffile).unwrap(), }, position: get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(), }, work_done_progress_params: Default::default(), }; ctx.call::<HoverRequest, _>(meta, req_params, move |ctx: &mut Context, meta, result| { editor_hover(meta, params, result, ctx) }); } pub fn editor_hover( meta: EditorMeta, params: PositionParams, result: Option<Hover>, ctx: &mut Context, ) { let diagnostics = ctx.diagnostics.get(&meta.buffile); let pos = get_lsp_position(&meta.buffile, &params.position, ctx).unwrap(); let diagnostics = diagnostics .map(|x| { x.iter() .filter(|x| { let start = x.range.start; let end = x.range.end; (start.line < pos.line && pos.line < end.line) || (start.line == pos.line && pos.line == end.line && start.character <= pos.character && pos.character <= end.character) || (start.line == pos.line && pos.line <= end.line && start.character <= pos.character) || (start.line <= pos.line && end.line == pos.line && pos.character <= end.character) }) .map(|x| str::trim(&x.message)) .filter(|x| !x.is_empty()) .map(|x| format!("• {}", x)) .join("\n") }) .unwrap_or_else(String::new); let contents = match result { None => "".to_string(), Some(result) => match result.contents { HoverContents::Scalar(contents) => contents.plaintext(), HoverContents::Array(contents) => contents .into_iter() .map(|x| str::trim(&x.plaintext()).to_owned()) .filter(|x| !x.is_empty()) .map(|x| format!("• {}", x)) .join("\n"), HoverContents::Markup(contents) => contents.value, }, }; if contents.is_empty() && diagnostics.is_empty() { return; } let command = format!( "lsp-show-hover {} %§{}§ %§{}§", params.position, contents.replace("§", "\\§"), diagnostics.replace("§", "\\§") ); ctx.exec(meta, command); } trait PlainText { fn plaintext(self) -> String; } impl PlainText for MarkedString { fn plaintext(self) -> String { match self { MarkedString::String(contents) => contents, MarkedString::LanguageString(contents) => contents.value, } } }
extern crate image_resizer; use std::process; use image_resizer::*; fn main() { let config = Config::from_cli(); match config { Ok(config) => { match run(config) { Ok(es) => { process::exit(es); } Err(error) => { eprintln!("{}", error); process::exit(-1); } } } Err(err) => { eprintln!("{}", err); process::exit(-1); } } }
use std::{future::Future, str::FromStr}; use chrono::Utc; use cron::Schedule; pub struct Builder { name: String, schedule: Schedule, } pub fn new(name: &str, cron: &str) -> Builder { Builder { name: name.to_owned(), schedule: Schedule::from_str(cron).unwrap(), } } impl Builder { pub fn with_state<S: Clone>(self, state: S) -> StatefulBuilder<S> { StatefulBuilder { name: self.name, schedule: self.schedule, state, } } pub fn spawn_with_task<R, F>(self, task: F) where R: Future<Output = ()> + Send + 'static, F: Fn(()) -> R + Send + 'static, { self.with_state(()).spawn_with_task(task); } pub async fn run_with_task<R, F>(self, task: F) where R: Future<Output = ()> + Send + 'static, F: Fn(()) -> R + Send + 'static, { self.with_state(()).run_with_task(task).await; } } pub struct StatefulBuilder<S: Clone> { name: String, schedule: Schedule, state: S, } impl<S: Clone + Send + 'static> StatefulBuilder<S> { pub fn spawn_with_task<R, F>(self, task: F) where R: Future<Output = ()> + Send + 'static, F: Fn(S) -> R + Send + 'static, { tokio::task::spawn(self.run_with_task(task)); } async fn run_with_task<R, F>(self, task: F) where R: Future<Output = ()> + Send + 'static, F: Fn(S) -> R + Send + 'static, { for next in self.schedule.upcoming(Utc) { log::info!("next run of '{}' is scheduled for {}", self.name, next); let dur = next - Utc::now(); let dur = dur.to_std().unwrap(); tokio::time::delay_for(dur).await; log::info!("running task '{}'", self.name); tokio::task::spawn((task)(self.state.clone())); } } }
use gilrs::Axis; use std::time::Duration; use rppal::gpio::Gpio; mod controller; mod hardware; use crate::controller::XboxController; fn main() { // INITIALIZATION let mut con = XboxController::new(); let gpio = Gpio::new().unwrap(); let left_motor = hardware::Motor::new(&gpio, 1, 2); let right_motor = hardware::Motor::new(&gpio, 3, 4); loop { con.update(); left_motor.set(con.get_axis(Axis::LeftStickY)); right_motor.set(con.get_axis(Axis::RightStickY)); std::thread::sleep(Duration::from_millis(10)); } }
// Copyright 2020 Folyd // Copyright 1999 Google LLC // // 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 // // https://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::ffi::CStr; use std::os::raw::c_char; use robotstxt::{DefaultMatcher, DefaultCachingMatcher}; #[no_mangle] pub extern "C" fn is_user_agent_allowed( robotstxt: *const c_char, user_agent: *const c_char, url: *const c_char, ) -> bool { if let (Ok(robotstxt), Ok(user_agent), Ok(url)) = unsafe { assert!(!robotstxt.is_null()); assert!(!user_agent.is_null()); assert!(!url.is_null()); ( CStr::from_ptr(robotstxt).to_str(), CStr::from_ptr(user_agent).to_str(), CStr::from_ptr(url).to_str(), ) } { println!("{} {} {}", robotstxt, user_agent, url); let mut matcher = DefaultMatcher::default(); matcher.one_agent_allowed_by_robots(&robotstxt, user_agent, url) } else { panic!("Invalid parameters"); } } #[no_mangle] pub extern "C" fn is_user_agent_allowed_caching( robotstxt: *const c_char, user_agent: *const c_char, url: *const c_char, ) -> bool { if let (Ok(robotstxt), Ok(user_agent), Ok(url)) = unsafe { assert!(!robotstxt.is_null()); assert!(!user_agent.is_null()); assert!(!url.is_null()); ( CStr::from_ptr(robotstxt).to_str(), CStr::from_ptr(user_agent).to_str(), CStr::from_ptr(url).to_str(), ) } { println!("{} {} {}", robotstxt, user_agent, url); let mut matcher = DefaultCachingMatcher::new(DefaultMatcher::default()); matcher.parse(&robotstxt); matcher.one_agent_allowed_by_robots(user_agent, url) } else { panic!("Invalid parameters"); } } #[no_mangle] pub extern "C" fn is_valid_user_agent_to_obey(user_agent: *const c_char) -> bool { if let Ok(user_agent) = unsafe { assert!(!user_agent.is_null()); CStr::from_ptr(user_agent).to_str() } { DefaultMatcher::is_valid_user_agent_to_obey(user_agent) } else { panic!("Invalid parameters"); } }
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-tidy-linelength // compile-flags:-Zprint-mono-items=eager // compile-flags:-Zinline-in-all-cgus #![deny(dead_code)] #![feature(coerce_unsized)] #![feature(unsize)] #![feature(start)] use std::marker::Unsize; use std::ops::CoerceUnsized; trait Trait { fn foo(&self); } // Simple Case impl Trait for bool { fn foo(&self) {} } impl Trait for char { fn foo(&self) {} } // Struct Field Case struct Struct<T: ?Sized> { _a: u32, _b: i32, _c: T } impl Trait for f64 { fn foo(&self) {} } // Custom Coercion Case impl Trait for u32 { fn foo(&self) {} } #[derive(Clone, Copy)] struct Wrapper<T: ?Sized>(*const T); impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Wrapper<U>> for Wrapper<T> {} //~ MONO_ITEM fn unsizing::start[0] #[start] fn start(_: isize, _: *const *const u8) -> isize { // simple case let bool_sized = &true; //~ MONO_ITEM fn core::ptr[0]::drop_in_place[0]<bool> @@ unsizing0[Internal] //~ MONO_ITEM fn unsizing::{{impl}}[0]::foo[0] let _bool_unsized = bool_sized as &Trait; let char_sized = &'a'; //~ MONO_ITEM fn core::ptr[0]::drop_in_place[0]<char> @@ unsizing0[Internal] //~ MONO_ITEM fn unsizing::{{impl}}[1]::foo[0] let _char_unsized = char_sized as &Trait; // struct field let struct_sized = &Struct { _a: 1, _b: 2, _c: 3.0f64 }; //~ MONO_ITEM fn core::ptr[0]::drop_in_place[0]<f64> @@ unsizing0[Internal] //~ MONO_ITEM fn unsizing::{{impl}}[2]::foo[0] let _struct_unsized = struct_sized as &Struct<Trait>; // custom coercion let wrapper_sized = Wrapper(&0u32); //~ MONO_ITEM fn core::ptr[0]::drop_in_place[0]<u32> @@ unsizing0[Internal] //~ MONO_ITEM fn unsizing::{{impl}}[3]::foo[0] let _wrapper_sized = wrapper_sized as Wrapper<Trait>; 0 }
use std::cell::Ref; use std::sync::Arc; use sourcerenderer_core::graphics::{ AddressMode, Backend, BarrierAccess, BarrierSync, BindingFrequency, CommandBuffer, Device, Filter, Format, PipelineBinding, SampleCount, SamplerInfo, TextureDimension, TextureInfo, TextureLayout, TextureUsage, TextureViewInfo, WHOLE_BUFFER, ShaderType, CompareFunc, }; use sourcerenderer_core::{ Platform, Vec2UI, Matrix4, }; use super::rt_shadows::RTShadowPass; use super::shadow_map::ShadowMapPass; use super::visibility_buffer::VisibilityBufferPass; use crate::renderer::passes::ssao::SsaoPass; use crate::renderer::render_path::RenderPassParameters; use crate::renderer::renderer_assets::RendererTexture; use crate::renderer::renderer_resources::{ HistoryResourceEntry, RendererResources, }; use crate::renderer::shader_manager::{ ComputePipelineHandle, ShaderManager, }; pub struct ShadingPass<P: Platform> { sampler: Arc<<P::GraphicsBackend as Backend>::Sampler>, shadow_sampler: Arc<<P::GraphicsBackend as Backend>::Sampler>, pipeline: ComputePipelineHandle, } impl<P: Platform> ShadingPass<P> { pub const SHADING_TEXTURE_NAME: &'static str = "Shading"; pub fn new( device: &Arc<<P::GraphicsBackend as Backend>::Device>, resolution: Vec2UI, resources: &mut RendererResources<P::GraphicsBackend>, shader_manager: &mut ShaderManager<P>, _init_cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer, ) -> Self { let pipeline = shader_manager.request_compute_pipeline("shaders/shading.comp.spv"); let sampler = device.create_sampler(&SamplerInfo { mag_filter: Filter::Linear, min_filter: Filter::Linear, mip_filter: Filter::Linear, address_mode_u: AddressMode::Repeat, address_mode_v: AddressMode::Repeat, address_mode_w: AddressMode::Repeat, mip_bias: 0.0, max_anisotropy: 0.0, compare_op: None, min_lod: 0.0, max_lod: None, }); resources.create_texture( Self::SHADING_TEXTURE_NAME, &TextureInfo { dimension: TextureDimension::Dim2D, format: Format::RGBA16Float, width: resolution.x, height: resolution.y, depth: 1, mip_levels: 1, array_length: 1, samples: SampleCount::Samples1, usage: TextureUsage::STORAGE | TextureUsage::SAMPLED, supports_srgb: true, }, false, ); let shadow_sampler = device.create_sampler(&SamplerInfo { mag_filter: Filter::Linear, min_filter: Filter::Linear, mip_filter: Filter::Linear, address_mode_u: AddressMode::ClampToEdge, address_mode_v: AddressMode::ClampToEdge, address_mode_w: AddressMode::ClampToEdge, mip_bias: 0.0f32, max_anisotropy: 0.0f32, compare_op: Some(CompareFunc::Less), min_lod: 0f32, max_lod: None, }); Self { sampler, shadow_sampler, pipeline } } #[profiling::function] pub(super) fn execute( &mut self, cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer, pass_params: &RenderPassParameters<'_, P> ) { let (width, height) = { let info = pass_params.resources.texture_info(Self::SHADING_TEXTURE_NAME); (info.width, info.height) }; cmd_buffer.begin_label("Shading Pass"); let output = pass_params.resources.access_view( cmd_buffer, Self::SHADING_TEXTURE_NAME, BarrierSync::COMPUTE_SHADER, BarrierAccess::STORAGE_WRITE, TextureLayout::Storage, true, &TextureViewInfo::default(), HistoryResourceEntry::Current, ); let ids = pass_params.resources.access_view( cmd_buffer, VisibilityBufferPass::PRIMITIVE_ID_TEXTURE_NAME, BarrierSync::COMPUTE_SHADER, BarrierAccess::STORAGE_READ, TextureLayout::Storage, false, &TextureViewInfo::default(), HistoryResourceEntry::Current, ); let barycentrics = pass_params.resources.access_view( cmd_buffer, VisibilityBufferPass::BARYCENTRICS_TEXTURE_NAME, BarrierSync::COMPUTE_SHADER, BarrierAccess::STORAGE_READ, TextureLayout::Storage, false, &TextureViewInfo::default(), HistoryResourceEntry::Current, ); let light_bitmask_buffer = pass_params.resources.access_buffer( cmd_buffer, super::light_binning::LightBinningPass::LIGHT_BINNING_BUFFER_NAME, BarrierSync::COMPUTE_SHADER, BarrierAccess::STORAGE_READ, HistoryResourceEntry::Current, ); let ssao = pass_params.resources.access_view( cmd_buffer, SsaoPass::<P>::SSAO_TEXTURE_NAME, BarrierSync::FRAGMENT_SHADER | BarrierSync::COMPUTE_SHADER, BarrierAccess::SAMPLING_READ, TextureLayout::Sampled, false, &TextureViewInfo::default(), HistoryResourceEntry::Current, ); let rt_shadows: Ref<Arc<<P::GraphicsBackend as Backend>::TextureView>>; let shadows = if pass_params.device.supports_ray_tracing() { rt_shadows = pass_params.resources.access_view( cmd_buffer, RTShadowPass::SHADOWS_TEXTURE_NAME, BarrierSync::FRAGMENT_SHADER, BarrierAccess::SAMPLING_READ, TextureLayout::Sampled, false, &TextureViewInfo::default(), HistoryResourceEntry::Current, ); &*rt_shadows } else { pass_params.zero_textures.zero_texture_view }; let cascade_count = { let shadow_map_info = pass_params.resources.texture_info(ShadowMapPass::<P>::SHADOW_MAP_NAME); shadow_map_info.array_length }; let shadow_map = pass_params.resources.access_view( cmd_buffer, ShadowMapPass::<P>::SHADOW_MAP_NAME, BarrierSync::COMPUTE_SHADER, BarrierAccess::SAMPLING_READ, TextureLayout::Sampled, false, &TextureViewInfo { base_array_layer: 0, array_layer_length: cascade_count, mip_level_length: 1, base_mip_level: 0, format: None }, HistoryResourceEntry::Current, ); let pipeline = pass_params.shader_manager.get_compute_pipeline(self.pipeline); cmd_buffer.set_pipeline(PipelineBinding::Compute(&pipeline)); cmd_buffer.bind_storage_texture(BindingFrequency::VeryFrequent, 1, &ids); cmd_buffer.bind_storage_texture(BindingFrequency::VeryFrequent, 2, &barycentrics); cmd_buffer.bind_storage_texture(BindingFrequency::VeryFrequent, 3, &output); cmd_buffer.bind_sampler(BindingFrequency::VeryFrequent, 4, &self.sampler); cmd_buffer.bind_storage_buffer( BindingFrequency::VeryFrequent, 5, &light_bitmask_buffer, 0, WHOLE_BUFFER, ); cmd_buffer.bind_sampling_view_and_sampler( BindingFrequency::VeryFrequent, 6, &pass_params.scene.lightmap.unwrap().view, pass_params.resources.linear_sampler(), ); cmd_buffer.bind_sampling_view_and_sampler( BindingFrequency::VeryFrequent, 7, shadows, pass_params.resources.linear_sampler(), ); cmd_buffer.bind_sampling_view_and_sampler( BindingFrequency::VeryFrequent, 8, &ssao, pass_params.resources.linear_sampler(), ); cmd_buffer.bind_sampling_view_and_sampler( BindingFrequency::VeryFrequent, 9, &shadow_map, &self.shadow_sampler ); cmd_buffer.flush_barriers(); cmd_buffer.finish_binding(); cmd_buffer.dispatch((width + 7) / 8, (height + 7) / 8, 1); cmd_buffer.end_label(); } }
#[doc = "Reader of register CRCRSLTPP"] pub type R = crate::R<u32, super::CRCRSLTPP>; #[doc = "Reader of field `RSLTPP`"] pub type RSLTPP_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - Post Processing Result"] #[inline(always)] pub fn rsltpp(&self) -> RSLTPP_R { RSLTPP_R::new((self.bits & 0xffff_ffff) as u32) } }
use ::http::HeaderValue; use async_graphql::*; #[tokio::test] pub async fn test_schema_default() { #[derive(Default)] struct Query; #[Object] impl Query { async fn value(&self) -> i32 { 10 } } type MySchema = Schema<Query, EmptyMutation, EmptySubscription>; let _schema = MySchema::default(); } #[tokio::test] pub async fn test_http_headers() { #[derive(Default)] struct Query; #[Object] impl Query { async fn value(&self, ctx: &Context<'_>) -> i32 { ctx.insert_http_header("A", "1"); 10 } async fn err(&self, ctx: &Context<'_>) -> FieldResult<i32> { ctx.insert_http_header("A", "1"); Err("error".into()) } } let schema = Schema::new(Query, EmptyMutation, EmptySubscription); let resp = schema.execute("{ value }").await; assert_eq!( resp.http_headers.get("A"), Some(&HeaderValue::from_static("1")) ); let resp = schema.execute("{ err }").await; assert_eq!( resp.http_headers.get("A"), Some(&HeaderValue::from_static("1")) ); }
use std::io; use std::env; use std::io::prelude::*; //helper for converting meta data of pgm to width, height, max tuple fn meta_tuple<'a>(meta: &Vec<&'a str>) -> (i32,i32,i32) { let width:i32 = meta[1].parse().unwrap(); let height:i32 = meta[2].parse().unwrap() ; let max :i32 = meta[3].parse().unwrap(); (width, height, max) } ///based on the pgm meta data, read pixels line by line ///into a 1-D response vector fn read_img(meta: &Vec<&str>) -> Result<Vec<i32>, &'static str> { let mut buf = String::new(); let (width, height, max) = meta_tuple(meta); io::stdin().read_to_string((&mut buf)).unwrap(); let res = buf.split_whitespace().map(|s| s.trim().parse::<i32>().unwrap()).collect::<Vec<i32>>(); if res.iter().any(|&x| x>max || x<0) { return Err("pixel out of range"); } else if res.len() != (width*height) as usize{ return Err("Read an incorrect number of pixels"); } Ok(res) } ///flipts img horizontally. pgm_meta contains meta header row to get height and width dimensions fn flip_horizontal <'a> (img: &Vec<i32>, pgm_meta: &Vec<&'a str>) -> (Vec<i32>, Vec<&'a str>){ let width = meta_tuple(pgm_meta).0; let mut res = img.clone(); res.chunks_mut(width as usize).map(|mut x| x.reverse()).count(); (res, pgm_meta.clone()) } ///flipts img vertically. pgm_meta contains meta header row to get height and width dimensions fn flip_vertical <'a> (img: &mut Vec<i32>, pgm_meta: &Vec<&'a str>) -> (Vec<i32>, Vec<&'a str>){ let mut res: Vec<i32> =Vec::new(); let width = meta_tuple(pgm_meta).0; img.chunks_mut(width as usize).rev() .map(| x| { res.extend_from_slice(x); } ).count(); (res, pgm_meta.clone()) } // rotate a 1D vector points 90 degrees right. // a 2d matrix represented as 1D has points that // translate according to the formula i = y*height + width, where // i is the index in the 1D array, y is the y coordinate in a 2D array, // and height and width are the height and width of the 2D array. //Rotating 90 degrees means height and width dimensions get inverted fn rotate_right<'a>(img: &mut Vec<i32>, pgm_meta: &Vec<&'a str>) -> (Vec<i32>, Vec<&'a str>){ let (width, height, _) = meta_tuple(pgm_meta); let mut res_meta = Vec::new(); res_meta.push(pgm_meta[0]); res_meta.push(pgm_meta[2]); res_meta.push(pgm_meta[1]); res_meta.push(pgm_meta[3]); let mut result:Vec<i32> = vec![0;(width*height) as usize]; for i in 0..img.len() as i32{ let (x,y) = (i%width, i/width ); let (a, b) = ( (height-y-1), x); let j = (b * height) + a; result[ (j) as usize] = img[i as usize] ; } (result, res_meta) } //See notes on rotate_right for methodology. Same method, but rotating in opposite direction fn rotate_left<'a>(img: &mut Vec<i32>, pgm_meta: &Vec<&'a str>) -> (Vec<i32>, Vec<&'a str>){ let (width, height, _) = meta_tuple(pgm_meta); let mut res_meta = Vec::new(); res_meta.push(pgm_meta[0]); res_meta.push(pgm_meta[2]); res_meta.push(pgm_meta[1]); res_meta.push(pgm_meta[3]); let mut result:Vec<i32> = vec![0;(width*height) as usize]; for i in 0..img.len() as i32{ let (x,y) = (i%width, i/width ); let (a, b) = ( y , (width-x-1)); let j = (b * height) + a; result[ (j) as usize] = img[i as usize] ; } (result, res_meta) } pub fn solution(){ let mut pgm_head = String::new(); io::stdin().read_line(&mut pgm_head).unwrap(); let pgm_meta:Vec<&str> = pgm_head.split_whitespace().collect(); let original_img: Vec<i32> = read_img(&pgm_meta).unwrap(); //process operation let op = env::args().nth(1).unwrap().clone(); let mut result = (original_img.clone(), pgm_meta.clone()); for x in op.chars(){ match x{ 'H' => { result = flip_horizontal(&result.0, &result.1); }, 'V' => { result = flip_vertical(&mut result.0, &result.1); }, 'R' => { result = rotate_right(&mut result.0, &result.1); }, 'L' => { result = rotate_left(&mut result.0, &result.1); }, _ => { println!("Invalid input: {}", op); } } } for m in result.1{ print!("{} ", m); } println!(""); for x in result.0 { println!("{}", x); } }
struct Monster { health: i32, damage: i32 } fn main () { let m = Monster {health: 10, damage: 20}; println!("{}", m.health); println!("{}", m.damage); }
use crate::image_format::ImageFormat; use crate::texture_flags::TextureFlags; use std::io::{Read, Result as IOResult, Error as IOError, Seek, SeekFrom, ErrorKind}; use crate::read_util::PrimitiveRead; const EXPECTED_SIGNATURE: u32 = 0x00465456; pub struct Header { /// File signature ("VTF\0"). (or as little-endian integer, 0x00465456) pub signature: u32, /// version[0].version[1] (currently 7.2). pub version: [u32; 2], /// Size of the header struct (16 byte aligned; currently 80 bytes) + size of the resources dictionary (7.3+). pub header_size: u32, /// Width of the largest mipmap in pixels. Must be a power of 2. pub width: u16, /// Height of the largest mipmap in pixels. Must be a power of 2. pub height: u16, /// VTF flags. pub flags: TextureFlags, /// Number of frames, if animated (1 for no animation). pub frames: u16, /// First frame in animation (0 based). pub first_frame: u16, /// reflectivity padding (16 byte alignment). pub padding0: [u8; 4], /// reflectivity vector. pub reflectivity: [f32; 3], /// reflectivity padding (8 byte packing). pub padding1: [u8; 4], /// Bumpmap scale. pub bumpmap_scale: f32, /// High resolution image format. pub high_res_image_format: ImageFormat, /// Number of mipmaps. pub mipmap_count: u8, /// Low resolution image format (always DXT1). pub low_res_image_format: ImageFormat, /// Low resolution image width. pub low_res_image_width: u8, /// Low resolution image height. pub low_res_image_height: u8, // 7.2+ /// Depth of the largest mipmap in pixels. /// Must be a power of 2. Can be 0 or 1 for a 2D texture (v7.2 only). pub depth: u16, // 7.3+ /// depth padding (4 byte alignment). pub padding2: [u8; 3], /// Number of resources this vtf has pub num_resources: u32 } impl Header { pub(super) fn check_file<T: Read + Seek>(reader: &mut T) -> IOResult<bool> { let signature = reader.read_u32()?; Ok(signature == EXPECTED_SIGNATURE) } pub fn read<T: Read + Seek>(reader: &mut T) -> IOResult<Self> { let signature = reader.read_u32()?; if signature != EXPECTED_SIGNATURE { return Err(IOError::new(ErrorKind::Other, "File is not a VTF file")); } let version = [reader.read_u32()?, reader.read_u32()?]; let header_size = reader.read_u32()?; let width = reader.read_u16()?; let height = reader.read_u16()?; let flags = TextureFlags::from_bits(reader.read_u32()?).unwrap(); let frames = reader.read_u16()?; let first_frame = reader.read_u16()?; reader.seek(SeekFrom::Current(4))?; let reflectivity = [reader.read_f32()?, reader.read_f32()?, reader.read_f32()?]; reader.seek(SeekFrom::Current(4))?; let bumpmap_scale = reader.read_f32()?; let high_res_image_format: ImageFormat = unsafe { std::mem::transmute(reader.read_u32()?) }; let mipmap_count = reader.read_u8()?; let low_res_image_format: ImageFormat = unsafe { std::mem::transmute(reader.read_u32()?) }; let low_res_image_width = reader.read_u8()?; let low_res_image_height = reader.read_u8()?; let depth = if version[0] > 7 || version[0] == 7 && version[1] >= 2 { reader.read_u16()? } else { 0u16 }; let num_resources = if version[0] > 7 || version[0] == 7 && version[1] >= 3 { reader.seek(SeekFrom::Current(3))?; reader.read_u32()? } else { 0u32 }; Ok(Self { signature, version, header_size, width, height, flags, frames, first_frame, padding0: Default::default(), reflectivity, padding1: Default::default(), bumpmap_scale, high_res_image_format, mipmap_count, low_res_image_format, low_res_image_width, low_res_image_height, depth, padding2: Default::default(), num_resources }) } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use failure::{format_err, Error}; use fuchsia_syslog as syslog; use std::io::{BufWriter, Write}; pub struct Printer<T: Write> { writer: BufWriter<T>, } impl<T> Printer<T> where T: Write, { pub fn new(output: T) -> Printer<T> { Printer { writer: BufWriter::new(output) } } pub fn println(&mut self, contents: String) { if let Err(e) = self.writer.write_all(contents.as_bytes()) { syslog::fx_log_err!("Error writing to buffer: {}", e); return; } if let Err(e) = self.writer.write_all("\n".as_bytes()) { syslog::fx_log_err!("Error writing to buffer: {}", e); } } // Consumes `BufWriter` and returns the underlying buffer. // Note that we never call `into_inner()` for the `io::stdout()` variant; so we need to // suppress rustc's `dead_code` lint warning here. pub fn into_inner(self) -> Result<T, Error> { match self.writer.into_inner() { Ok(w) => Ok(w), Err(e) => Err(format_err!("Error getting writer: {}", e)), } } }
//! Central solver data structure. //! //! This module defines the `Context` data structure which holds all data used by the solver. It //! also contains global notification functions that likely need to be extended when new parts are //! added to the solver. use partial_ref::{part, partial, PartialRef, PartialRefTarget}; use crate::{ analyze_conflict::AnalyzeConflict, assumptions::Assumptions, binary::BinaryClauses, clause::{ClauseActivity, ClauseAlloc, ClauseDb}, config::{SolverConfig, SolverConfigUpdate}, decision::vsids::Vsids, model::Model, proof::Proof, prop::{Assignment, ImplGraph, Trail, Watchlists}, schedule::Schedule, state::SolverState, tmp::{TmpData, TmpFlags}, variables::Variables, }; /// Part declarations for the [`Context`] struct. pub mod parts { use super::*; part!(pub AnalyzeConflictP: AnalyzeConflict); part!(pub AssignmentP: Assignment); part!(pub BinaryClausesP: BinaryClauses); part!(pub ClauseActivityP: ClauseActivity); part!(pub ClauseAllocP: ClauseAlloc); part!(pub ClauseDbP: ClauseDb); part!(pub ImplGraphP: ImplGraph); part!(pub AssumptionsP: Assumptions); part!(pub ModelP: Model); part!(pub ProofP<'a>: Proof<'a>); part!(pub ScheduleP: Schedule); part!(pub SolverConfigP: SolverConfig); part!(pub SolverStateP: SolverState); part!(pub TmpDataP: TmpData); part!(pub TmpFlagsP: TmpFlags); part!(pub TrailP: Trail); part!(pub VariablesP: Variables); part!(pub VsidsP: Vsids); part!(pub WatchlistsP: Watchlists); } use parts::*; /// Central solver data structure. /// /// This struct contains all data kept by the solver. Most functions operating on multiple fields of /// the context use partial references provided by the `partial_ref` crate. This documents the data /// dependencies and makes the borrow checker happy without the overhead of passing individual /// references. #[derive(PartialRefTarget, Default)] pub struct Context<'a> { #[part(AnalyzeConflictP)] pub analyze_conflict: AnalyzeConflict, #[part(AssignmentP)] pub assignment: Assignment, #[part(BinaryClausesP)] pub binary_clauses: BinaryClauses, #[part(ClauseActivityP)] pub clause_activity: ClauseActivity, #[part(ClauseAllocP)] pub clause_alloc: ClauseAlloc, #[part(ClauseDbP)] pub clause_db: ClauseDb, #[part(ImplGraphP)] pub impl_graph: ImplGraph, #[part(AssumptionsP)] pub assumptions: Assumptions, #[part(ModelP)] pub model: Model, #[part(ProofP<'a>)] pub proof: Proof<'a>, #[part(ScheduleP)] pub schedule: Schedule, #[part(SolverConfigP)] pub solver_config: SolverConfig, #[part(SolverStateP)] pub solver_state: SolverState, #[part(TmpDataP)] pub tmp_data: TmpData, #[part(TmpFlagsP)] pub tmp_flags: TmpFlags, #[part(TrailP)] pub trail: Trail, #[part(VariablesP)] pub variables: Variables, #[part(VsidsP)] pub vsids: Vsids, #[part(WatchlistsP)] pub watchlists: Watchlists, } /// Update structures for a new variable count. pub fn set_var_count( mut ctx: partial!( Context, mut AnalyzeConflictP, mut AssignmentP, mut BinaryClausesP, mut ImplGraphP, mut TmpFlagsP, mut VsidsP, mut WatchlistsP, ), count: usize, ) { ctx.part_mut(AnalyzeConflictP).set_var_count(count); ctx.part_mut(AssignmentP).set_var_count(count); ctx.part_mut(BinaryClausesP).set_var_count(count); ctx.part_mut(ImplGraphP).set_var_count(count); ctx.part_mut(TmpFlagsP).set_var_count(count); ctx.part_mut(VsidsP).set_var_count(count); ctx.part_mut(WatchlistsP).set_var_count(count); } /// The solver configuration has changed. pub fn config_changed( mut ctx: partial!(Context, mut VsidsP, mut ClauseActivityP, SolverConfigP), _update: &SolverConfigUpdate, ) { let (config, mut ctx) = ctx.split_part(SolverConfigP); ctx.part_mut(VsidsP).set_decay(config.vsids_decay); ctx.part_mut(ClauseActivityP) .set_decay(config.clause_activity_decay); }
use crate::parse::{Node, ParsedHand}; use crate::yaku::situation::SituationYaku; use crate::tiles::{Tile, Dragon, Wind}; use crate::groups::{Tiles, OpenSet, Set, Sets, Hand}; use crate::yaku::hand::{HandYaku, Yakuman}; use crate::score::{Fu, Score, Han}; use crate::yaku::YakuAttributes; use std::fmt::{Display, Formatter, Error}; pub use std::str::FromStr; pub struct Evaluator { /// 確定している状況役(リーチ、ツモなど) situation: Vec<SituationYaku>, /// 採用されている役満 adopted_yakuman_list: Vec<Yakuman>, /// 採用されている手役 adopted_yaku_list: Vec<HandYaku>, /// 風 prevalent_wind: Option<Tile>, /// 自風 seat_wind: Option<Tile>, /// ドラ dora: Vec<Tile>, /// 裏ドラ ura_dora: Vec<Tile>, } impl Evaluator { pub fn new(prevalent_wind: Option<Tile>, seat_wind: Option<Tile>, dora: Vec<Tile>, ura_dora: Vec<Tile>) -> Self { let adopted_yaku_list = Self::default_adopted_yaku_list(&seat_wind, &prevalent_wind); let adopted_yakuman_list = Self::default_adopted_yakuman_list(); Self { situation: Vec::new(), adopted_yakuman_list, adopted_yaku_list, prevalent_wind, seat_wind, dora, ura_dora } } pub fn default_adopted_yaku_list(seat_wind: &Option<Tile>, prevalent_wind: &Option<Tile>) -> Vec<HandYaku> { let (seat_wind, prevalent_wind) = (seat_wind.clone(), prevalent_wind.clone()); let nopoints = HandYaku::new("平和 / No-points hand", None, Box::new(|candidate: &Wait| { if !candidate.closed() { return None; } match candidate { Wait::Ryanmen(node, fu, _) => { if node.sets.iter().all(|set| match set { Set::Pung(_) => false, _ => true, }) { if fu == &Fu(30) || fu == &Fu(22) { return Some(Han(1)); } } None } _ => None } }), Some(Box::new(|draw: &bool| { if draw.clone() { Fu(20) } else { Fu(30) } }))); let oneset = HandYaku::new("一盃口 / One set of identical sequences", None, Box::new(|candidate: &Wait| { if !candidate.closed() { return None; } let sets = candidate.node().clone().sets; // 重複を調べる let mut chows: Vec<Set> = Vec::new(); sets.iter().for_each(|set| match set { Set::Chow(_) => chows.push(set.clone()), _ => {} }); if chows.iter().any(|set| sets.iter().filter(|set_| set_ == &set).count() == 2) { Some(Han(1)) } else { None } }), None); let twoset = HandYaku::new("二盃口 / Two set of identical sequences", Some(Box::new(oneset)), Box::new(|candidate: &Wait| { if !candidate.closed() { return None; } let sets = candidate.node().clone().sets; // 重複を調べる let mut chows: Vec<Set> = Vec::new(); sets.iter().for_each(|set| match set { Set::Chow(_) => { chows.push(set.clone()) } _ => {} }); // vec.iter().all()はiterの中身が無い場合trueになってしまう(七対子などが該当する) if chows.len() != 4 { return None; } if chows.iter().all(|set| sets.iter().filter(|set_| set_ == &set).count() == 2) { Some(Han(3)) } else { None } }), None); let seven_pairs = HandYaku::new("七対子 / Seven pairs", None, Box::new(|candidate: &Wait| { if !candidate.closed() { return None; } let sets = &candidate.node().sets; // 7つの面子からなる if sets.len() == 7 && // 全て対子である sets.iter().all(|set| match set { Set::Pair(_) => true, _ => false }) { Some(Han(2)) } else { None } }), Some(Box::new(|_draw: &bool| { Fu(25) }))); let all_simple = HandYaku::new("タンヤオ / All simple", None, Box::new(|candidate: &Wait| { let sets = &candidate.node().sets; let open_sets = &candidate.node().open_sets; // 手牌に么九牌がない if sets.iter().all(|set| !set.contains_yaotyu()) && // 晒した牌にもない open_sets.iter().all(|open| !open.contains_yaotyu()) { Some(Han(1)) } else { None } }), None); let three_colour_straight = HandYaku::new("三色同順 / Three colour straight", None, Box::new(|candidate: &Wait| { let mut chow_sums = Vec::new(); candidate.node().sets.iter().for_each(|set| { if set.is_sequential() { chow_sums.push(set.sum_tile().unwrap()); } }); candidate.node().open_sets.iter().for_each(|set| { if set.is_sequential() { chow_sums.push(set.sum_tile().unwrap()); } }); // 順子が3つ以上ないならfalse if chow_sums.len() < 3 { return None; } // すべての順子について、三色同順の構成要素になりうるかvalidation if chow_sums.iter().any(|chow| { let sum = match chow { Tile::Character(u) => { u } Tile::Circle(u) => { u } Tile::Bamboo(u) => { u } _ => unreachable!() }.clone(); let (mut character, mut circle, mut bamboo) = (false, false, false); for chow_sum in &chow_sums { if match chow_sum { Tile::Character(u) => { u } Tile::Circle(u) => { u } Tile::Bamboo(u) => { u } _ => unreachable!() }.clone() == sum { match chow_sum { Tile::Character(_) => { character = true; } Tile::Circle(_) => { circle = true; } Tile::Bamboo(_) => { bamboo = true; } _ => unreachable!() } } } character && circle && bamboo }) { Some(Han(if candidate.closed() { 2 } else { 1 })) } else { None } }), None); let straight = HandYaku::new("一気通貫 / Straight", None, Box::new(|candidate: &Wait| { let mut chow_sums = Vec::new(); candidate.node().sets.iter().for_each(|set| { if set.is_sequential() { chow_sums.push(set.sum_tile().unwrap()); } }); candidate.node().open_sets.iter().for_each(|set| { if set.is_sequential() { chow_sums.push(set.sum_tile().unwrap()); } }); // 順子が3つ以上ないならfalse if chow_sums.len() < 3 { return None; } // すべての順子について、一気通貫の構成要素になりうるかvalidation if false || chow_sums.contains(&Tile::Character(6)) && chow_sums.contains(&Tile::Character(15)) && chow_sums.contains(&Tile::Character(24)) || chow_sums.contains(&Tile::Circle(6)) && chow_sums.contains(&Tile::Circle(15)) && chow_sums.contains(&Tile::Circle(24)) || chow_sums.contains(&Tile::Bamboo(6)) && chow_sums.contains(&Tile::Bamboo(15)) && chow_sums.contains(&Tile::Bamboo(24)) { Some(Han(if candidate.closed() { 2 } else { 1 })) } else { None } }), None); let all_triplet_hand = HandYaku::new("対々和 / All triplet hand", None, Box::new(|candidate: &Wait| { if candidate.node().sets.len() == 7 { return None; } if candidate.node().sets.iter().all(|set| set.is_flat()) && candidate.node().open_sets.iter().all(|set| set.is_flat()) { Some(Han(2)) } else { None } }), None); let three_closed_triplets = HandYaku::new("三暗刻 / Three closed triplets", None, Box::new(|candidate: &Wait| { // 雀頭もis_flatがtrueになる点に注意 if candidate.node().sets.iter().filter(|set| set.is_flat()).count() + candidate.node().open_sets.iter().filter(|set| match set { OpenSet::ConcealedKong(_) => true, _ => false, }).count() == 3 + 1 { Some(Han(2)) } else { None } }), None); let three_colour_triplets = HandYaku::new("三色同刻 / Three colour triplets", None, Box::new(|candidate: &Wait| { let mut pong_sums = Vec::new(); candidate.node().sets.iter().for_each(|set| { match set { Set::Pung(_) => { if let Some(tile) = set.sum_tile() { pong_sums.push(tile); } } _ => {} } }); candidate.node().open_sets.iter().for_each(|set| { match set { OpenSet::Pung(_) | OpenSet::Kong(_) | OpenSet::ConcealedKong(_) => { if let Some(tile) = set.sum_tile() { pong_sums.push(tile); } } _ => {} } }); // 刻子が3つ以上ないならfalse if pong_sums.len() < 3 { return None; } // すべての刻子について、三食同刻の構成要素になりうるかvalidation if pong_sums.iter().any(|sum| match sum { Tile::Character(u) => pong_sums.contains(&Tile::Circle(u.clone())) && pong_sums.contains(&Tile::Bamboo(u.clone())), Tile::Circle(u) => pong_sums.contains(&Tile::Character(u.clone())) && pong_sums.contains(&Tile::Bamboo(u.clone())), Tile::Bamboo(u) => pong_sums.contains(&Tile::Character(u.clone())) && pong_sums.contains(&Tile::Circle(u.clone())), _ => unreachable!() }) { Some(Han(2)) } else { None } }), None); let honor_tiles = HandYaku::new("役牌 / Honor tiles", None, Box::new(move |candidate: &Wait| { let mut han = Han(0); han += Han(candidate.node().open_sets.iter().filter(|set| { set.count(&Dragon::White.tile()) >= 3 || set.count(&Dragon::Green.tile()) >= 3 || set.count(&Dragon::Red.tile()) >= 3 || if let Some(seat_wind) = seat_wind.clone() { set.count(&seat_wind) >= 3 } else { false } || if let Some(wind) = prevalent_wind.clone() { set.count(&wind) >= 3 } else { false } }).count() as u32); han += Han(candidate.node().sets.iter().filter(|set| { set.count(&Dragon::White.tile()) >= 3 || set.count(&Dragon::Green.tile()) >= 3 || set.count(&Dragon::Red.tile()) >= 3 || if let Some(seat_wind) = seat_wind.clone() { set.count(&seat_wind) >= 3 } else { false } || if let Some(wind) = prevalent_wind.clone() { set.count(&wind) >= 3 } else { false } }).count() as u32); if han == Han(0) { None } else { Some(han) } }), None); let terminal_or_honor_in_each_set = HandYaku::new("混全帯么九 / Terminal or honor in each set", None, Box::new(|candidate: &Wait| { if candidate.node().sets.iter().all(|set| { set.contains_yaotyu() }) && candidate.node().open_sets.iter().all(|set| set.contains_yaotyu()) { if candidate.closed() { Some(Han(2)) } else { Some(Han(1)) } } else { None } }), None); let terminal_in_each_set = HandYaku::new("純全帯么九 / Terminal in each set", Some(Box::new(terminal_or_honor_in_each_set)), Box::new(|candidate: &Wait| { if candidate.node().sets.iter().all(|set| set.contains_terminal()) && candidate.node().open_sets.iter().all(|set| set.contains_terminal()) { if candidate.closed() { Some(Han(3)) } else { Some(Han(2)) } } else { None } }), None); let all_terminals_and_honors = HandYaku::new("混老頭 / All terminals and honors", Some(Box::new(terminal_in_each_set)), Box::new(|candidate: &Wait| { if candidate.node().sets.iter().all(|set| set.contains_yaotyu() && set.is_flat()) && candidate.node().open_sets.iter().all(|set| set.contains_yaotyu() && set.is_flat()) { if candidate.closed() { Some(Han(2)) } else { Some(Han(2)) } } else { None } }), None); let little_three_dragons = HandYaku::new("小三元 / Little three dragons", None, Box::new(|candidate: &Wait| { if candidate.node().sets.iter().any(|set| set.count(&Dragon::White.tile()) >= 3) || candidate.node().open_sets.iter().any(|set| set.count(&Dragon::White.tile()) >= 3) && candidate.node().sets.iter().any(|set| set.count(&Dragon::Green.tile()) >= 3) || candidate.node().open_sets.iter().any(|set| set.count(&Dragon::Green.tile()) >= 3) && candidate.node().sets.iter().any(|set| set.count(&Dragon::Red.tile()) >= 3) || candidate.node().open_sets.iter().any(|set| set.count(&Dragon::Red.tile()) >= 3) { Some(Han(2)) } else { None } }), None); let half_flush = HandYaku::new("混一色 / Half flush", None, Box::new(|candidate: &Wait| { let node = candidate.node(); if node.sets.iter().all(|set| set.all_character() || set.all_honor()) && node.open_sets.iter().all(|set| set.all_circle() || set.all_honor()) || node.sets.iter().all(|set| set.all_character() || set.all_honor()) && node.open_sets.iter().all(|set| set.all_circle() || set.all_honor()) || node.sets.iter().all(|set| set.all_bamboo() || set.all_honor()) && node.open_sets.iter().all(|set| set.all_bamboo() || set.all_honor()) { if candidate.closed() { Some(Han(3)) } else { Some(Han(2)) } } else { None } }), None); let flush = HandYaku::new("清一色 / Flush", Some(Box::new(half_flush)), Box::new(|candidate: &Wait| { let node = candidate.node(); if node.sets.iter().all(|set| set.all_character()) && node.open_sets.iter().all(|set| set.all_circle()) || node.sets.iter().all(|set| set.all_character()) && node.open_sets.iter().all(|set| set.all_circle()) || node.sets.iter().all(|set| set.all_bamboo()) && node.open_sets.iter().all(|set| set.all_bamboo()) { if candidate.closed() { Some(Han(6)) } else { Some(Han(5)) } } else { None } }), None); vec![all_simple, nopoints, three_closed_triplets, three_colour_triplets, little_three_dragons, all_terminals_and_honors, all_triplet_hand, flush, straight, twoset, three_colour_straight, seven_pairs, honor_tiles] } pub fn default_adopted_yakuman_list() -> Vec<Yakuman> { let thirteen_orphans = Yakuman::new("国士無双 / Thirteen orphans", Box::new(|_candidate: &Wait, _original_tiles: &Vec<Tile>| { if _original_tiles.contains(&Tile::Character(1)) && _original_tiles.contains(&Tile::Character(9)) && _original_tiles.contains(&Tile::Circle(1)) && _original_tiles.contains(&Tile::Circle(9)) && _original_tiles.contains(&Tile::Bamboo(1)) && _original_tiles.contains(&Tile::Bamboo(9)) && _original_tiles.contains(&Wind::East.tile()) && _original_tiles.contains(&Wind::South.tile()) && _original_tiles.contains(&Wind::West.tile()) && _original_tiles.contains(&Wind::North.tile()) && _original_tiles.contains(&Dragon::White.tile()) && _original_tiles.contains(&Dragon::Green.tile()) && _original_tiles.contains(&Dragon::Red.tile()) && _original_tiles.all_yaotyu() { 1 } else { 0 } }), None); let thirteen_orphans_13_wait = Yakuman::new("国士無双一三面待ち / Thirteen orphans 13 wait", Box::new(|_candidate: &Wait, _original_tiles: &Vec<Tile>| { if _original_tiles.len() != 14 { return 0; } let winning = _candidate.winning(); let mut original_tiles: Vec<Tile> = _original_tiles.iter().filter(|tile| tile != &&winning).map(|t| t.clone()).collect(); original_tiles.push(winning); original_tiles.sort(); if original_tiles.len() != 13 { return 0; } if original_tiles[..13] == vec![Tile::Character(1), Tile::Character(9), Tile::Circle(1), Tile::Circle(9), Tile::Bamboo(1), Tile::Bamboo(9), Wind::East.tile(), Wind::South.tile(), Wind::West.tile(), Wind::North.tile(), Dragon::White.tile(), Dragon::Green.tile(), Dragon::Red.tile()][..] && original_tiles.all_yaotyu() { 2 } else { 0 } }), Some(Box::new(thirteen_orphans))); let big_three_dragons = Yakuman::new("大三元 / Big three dragons", Box::new(|_candidate: &Wait, _original_tiles: &Vec<Tile>| { let dragons = vec![Dragon::White.tile(), Dragon::Green.tile(), Dragon::Red.tile()]; if dragons.iter().all(|dragon| { _candidate.node().sets.iter().any(|set| set.count(dragon) >= 3) || _candidate.node().open_sets.iter().any(|set| set.count(dragon) >= 3) }) { 1 } else { 0 } }), None); let four_concealed_triplets = Yakuman::new("四暗刻 / Four concealed triplets", Box::new(|_candidate: &Wait, _original_tiles: &Vec<Tile>| { if _candidate.node().sets.iter().filter(|set| set.is_flat()).count() + _candidate.node().open_sets .iter() .filter(|set| match set { OpenSet::ConcealedKong(_) => true, _ => false, }).count() == 4 + 1 { 1 } else { 0 } }), None); let little_four_winds = Yakuman::new("小四喜 / Little four dragons", Box::new(|_candidate: &Wait, _original_tiles: &Vec<Tile>| { let dragons = vec![Wind::East.tile(), Wind::South.tile(), Wind::West.tile(), Wind::North.tile()]; if dragons.iter().all(|dragon| { _candidate.node().sets.iter().any(|set| set.count(dragon) >= 2) || _candidate.node().open_sets.iter().any(|set| set.count(dragon) >= 2) }) { 1 } else { 0 } }), None); let big_four_winds = Yakuman::new("大四喜 / Big four dragons", Box::new(|_candidate: &Wait, _original_tiles: &Vec<Tile>| { let dragons = vec![Wind::East.tile(), Wind::South.tile(), Wind::West.tile(), Wind::North.tile()]; if dragons.iter().all(|dragon| { _candidate.node().sets.iter().any(|set| set.count(dragon) >= 3) || _candidate.node().open_sets.iter().any(|set| set.count(dragon) >= 3) }) { 1 } else { 0 } }), Some(Box::new(little_four_winds))); let all_honors = Yakuman::new("字一色 / All honors", Box::new(|_candidate: &Wait, _original_tiles: &Vec<Tile>| { if _candidate.node().sets.iter().all(|set| set.all_honor()) && _candidate.node().open_sets.iter().all(|set| set.all_honor()) { 1 } else { 0 } }), None); let all_terminals = Yakuman::new("清老頭 / All terminals", Box::new(|_candidate: &Wait, _original_tiles: &Vec<Tile>| { if _candidate.node().sets.iter().all(|set| set.all_terminal()) && _candidate.node().open_sets.iter().all(|set| set.all_terminal()) { 1 } else { 0 } }), None); let all_green = Yakuman::new("緑一色 / All green", Box::new(|_candidate: &Wait, _original_tiles: &Vec<Tile>| { let greens = vec![Tile::Bamboo(2), Tile::Bamboo(3), Tile::Bamboo(4), Tile::Bamboo(6), Tile::Bamboo(8), Dragon::Green.tile()]; if _candidate.node().sets.iter().all(|set| set.consists_of(&greens)) && _candidate.node().open_sets.iter().all(|set| set.consists_of(&greens)) { 1 } else { 0 } }), None); let nine_gates = Yakuman::new("九蓮宝燈 / Nine gates", Box::new(|_candidate: &Wait, _original_tiles: &Vec<Tile>| { let mut original_tiles = _original_tiles.clone(); original_tiles.sort(); if original_tiles.count(&Tile::Character(1)) >= 3 && original_tiles.count(&Tile::Character(2)) >= 1 && original_tiles.count(&Tile::Character(3)) >= 1 && original_tiles.count(&Tile::Character(4)) >= 1 && original_tiles.count(&Tile::Character(5)) >= 1 && original_tiles.count(&Tile::Character(6)) >= 1 && original_tiles.count(&Tile::Character(7)) >= 1 && original_tiles.count(&Tile::Character(8)) >= 1 && original_tiles.count(&Tile::Character(9)) >= 3 && _candidate.node().sets.iter().all(|set| set.all_character()) && _candidate.node().open_sets.iter().all(|set| set.all_character()) || original_tiles.count(&Tile::Circle(1)) >= 3 && original_tiles.count(&Tile::Circle(2)) >= 1 && original_tiles.count(&Tile::Circle(3)) >= 1 && original_tiles.count(&Tile::Circle(4)) >= 1 && original_tiles.count(&Tile::Circle(5)) >= 1 && original_tiles.count(&Tile::Circle(6)) >= 1 && original_tiles.count(&Tile::Circle(7)) >= 1 && original_tiles.count(&Tile::Circle(8)) >= 1 && original_tiles.count(&Tile::Circle(9)) >= 3 && _candidate.node().sets.iter().all(|set| set.all_circle()) && _candidate.node().open_sets.iter().all(|set| set.all_circle()) || original_tiles.count(&Tile::Bamboo(1)) >= 3 && original_tiles.count(&Tile::Bamboo(2)) >= 1 && original_tiles.count(&Tile::Bamboo(3)) >= 1 && original_tiles.count(&Tile::Bamboo(4)) >= 1 && original_tiles.count(&Tile::Bamboo(5)) >= 1 && original_tiles.count(&Tile::Bamboo(6)) >= 1 && original_tiles.count(&Tile::Bamboo(7)) >= 1 && original_tiles.count(&Tile::Bamboo(8)) >= 1 && original_tiles.count(&Tile::Bamboo(9)) >= 3 && _candidate.node().sets.iter().all(|set| set.all_bamboo()) && _candidate.node().open_sets.iter().all(|set| set.all_bamboo()) { 1 } else { 0 } }), None); vec![thirteen_orphans_13_wait, big_three_dragons, four_concealed_triplets, big_four_winds, all_honors, all_terminals, nine_gates, all_green] } } impl Evaluator { pub fn evaluate(&self, parsed_hand: &ParsedHand, draw: bool, situation: &Vec<SituationYaku>) -> Option<Evaluated> { self.evaluate_all(parsed_hand, draw, situation).last().cloned() } pub fn evaluate_all(&self, parsed_hand: &ParsedHand, draw: bool, situation: &Vec<SituationYaku>) -> Vec<Evaluated> { let waits = Waits::from_vec(parsed_hand, draw, &self.prevalent_wind, &self.seat_wind); let mut scores: Vec<Evaluated> = waits.waits .iter().map(|c| self.evaluate_wait(&waits.original_hand, c, draw, situation)).collect(); scores.sort_by(|a, b| a.score.score(false).cmp(&b.score.score(false))); scores } fn evaluate_yaku(&self, yaku: &Box<HandYaku>, yaku_list: &mut Vec<String>, candidate: &Wait, han: &mut Han) { let rule = &yaku.rule; if let Some(han_) = rule(candidate) { *han += han_; yaku_list.push(yaku.name()); } else { if let Some(ref yaku) = yaku.sub { self.evaluate_yaku(yaku, yaku_list, candidate, han); } } } fn evaluate_yakuman(&self, yakuman: &Box<Yakuman>, yakuman_list: &mut Vec<String>, candidate: &Wait, original_hand: &Vec<Tile>) -> u32 { let rule = &yakuman.rule; if 0 != rule(candidate, &original_hand) { yakuman_list.push(yakuman.name()); rule(candidate, &original_hand) } else { if let Some(ref yakuman) = yakuman.sub { self.evaluate_yakuman(yakuman, yakuman_list, candidate, original_hand) } else { 0 } } } fn evaluate_wait(&self, original_hand: &Vec<Tile>, wait: &Wait, draw: bool, situation: &Vec<SituationYaku>) -> Evaluated { let mut yakuman_list = Vec::new(); let mut multiple = 0; self.adopted_yakuman_list.iter().for_each(|yakuman| { let rule = &yakuman.rule; if 0 != rule(wait, &original_hand) { yakuman_list.push(yakuman.name()); multiple += rule(wait, &original_hand); } else { if let Some(ref yakuman) = yakuman.sub { multiple += self.evaluate_yakuman(yakuman, &mut yakuman_list, wait, original_hand); } } }); if multiple != 0 { return Evaluated { score: Score::yakuman(multiple as u8), node: wait.node().clone(), yaku_list: yakuman_list }; } let mut han = Han(0); let mut fu = Option::None; let mut yaku_list = Vec::new(); for st in situation { yaku_list.push(st.name()); han += st.han_value(); } for adopted_yaku in &self.adopted_yaku_list { let rule = &adopted_yaku.rule; if let Some(han_) = rule(wait) { han += han_; yaku_list.push(adopted_yaku.name()); // 平和等の場合 if let Some(fu_rule) = &adopted_yaku.fu { fu = Some(fu_rule(&draw)); } } else { if let Some(ref yaku) = adopted_yaku.sub { self.evaluate_yaku(yaku, &mut yaku_list, wait, &mut han); } } } let fu = match fu { Some(fu) => fu, None => wait.fu(), }; Evaluated { score: Score::new(han, fu), node: wait.node().clone(), yaku_list } } pub fn evaluate_str(&self, string: &str, draw: bool, situation: &Vec<SituationYaku>) -> Result<Option<Evaluated>, failure::Error> { let hand = Hand::from_str(string)?; let parsed_hand = ParsedHand::new(&hand); Ok(Evaluator::new(None, None, Vec::new(), Vec::new()).evaluate(&parsed_hand, draw, situation)) } pub fn evaluate_all_str(&self, string: &str, draw: bool, situation: &Vec<SituationYaku>) -> Result<Vec<Evaluated>, failure::Error> { let hand = Hand::from_str(string)?; let parsed_hand = ParsedHand::new(&hand); Ok(Evaluator::new(None, None, Vec::new(), Vec::new()).evaluate_all(&parsed_hand, draw, situation)) } } /// 牌形と点数 #[derive(Clone)] pub struct Evaluated { node: Node, score: Score, yaku_list: Vec<String>, } impl Display for Evaluated { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { writeln!(f, "{}", self.node)?; writeln!(f, "{}", self.yaku_list.join(","))?; writeln!(f, "{}", self.score) } } /// 最終型候補一覧 #[derive(Debug)] pub struct Waits { original_hand: Vec<Tile>, waits: Vec<Wait>, } impl Waits { pub fn new(original_hand: Vec<Tile>, waits: Vec<Wait>) -> Self { Waits { original_hand, waits } } pub fn from_vec(parsed_hand: &ParsedHand, draw: bool, prevalent_wind: &Option<Tile>, seat_wind: &Option<Tile>) -> Waits { let nodes = parsed_hand.nodes.clone(); let mut waits = Vec::new(); nodes.iter().for_each(|node| waits.append(&mut Wait::from(&node, parsed_hand.winning.clone(), draw, prevalent_wind.clone(), seat_wind.clone()))); let original_hand = parsed_hand.tiles.clone(); Waits::new(original_hand, waits) } } /// 最終形候補 #[derive(Debug)] pub enum Wait { Ryanmen(Node, Fu, Tile), Kanchan(Node, Fu, Tile), Penchan(Node, Fu, Tile), Tanki(Node, Fu, Tile), Shanpon(Node, Fu, Tile), } impl Wait { fn from(node: &Node, winning: Tile, draw: bool, prevalent_wind: Option<Tile>, seat_wind: Option<Tile>) -> Vec<Wait> { // 待ち候補 let mut wait_candidates = Vec::new(); node.sets.iter().for_each(|set| { if set.count(&winning) > 0 { wait_candidates.push(set.clone()) } }); let mut candidates = Vec::new(); // 府計算 let mut fu = if draw { Fu(22) } else if node.open_sets.len() == 0 { Fu(30) } else { Fu(20) }; node.sets.iter().for_each(|set| fu += set.fu()); node.open_sets.iter().for_each(|set| fu += set.fu()); // 雀頭による符 if let Some(Set::Pair(head)) = node.sets.first() { let (head1, head2) = (head.get(0), head.get(1)); if (head1, head2) == (prevalent_wind.as_ref(), prevalent_wind.as_ref()) || (head1, head2) == (seat_wind.as_ref(), seat_wind.as_ref()) || (head1, head2) == (Some(&Dragon::White.tile()), Some(&Dragon::White.tile())) || (head1, head2) == (Some(&Dragon::Green.tile()), Some(&Dragon::Green.tile())) || (head1, head2) == (Some(&Dragon::Red.tile()), Some(&Dragon::Red.tile())) { fu += Fu(2); } } wait_candidates.iter().for_each(|set| { match set { Set::Pair(_) => { candidates.push(Wait::Tanki(node.clone(), fu + Fu(2), winning.clone())); } _ => { if set.is_flat() { candidates.push(Wait::Shanpon(node.clone(), fu, winning.clone())); } else { let set = match set.clone() { Set::Chow(set) => set, _ => unreachable!() }; if Some(&winning) == set.first() || Some(&winning) == set.last() { if set.contains_yaotyu() && !winning.is_yaotyu() { candidates.push(Wait::Penchan(node.clone(), fu + Fu(2), winning.clone())); } else { candidates.push(Wait::Ryanmen(node.clone(), fu, winning.clone())); } } else { candidates.push(Wait::Kanchan(node.clone(), fu + Fu(2), winning.clone())); } } } } }); candidates } fn winning(&self) -> Tile { match &self { Wait::Ryanmen(_, _, winning) => winning, Wait::Kanchan(_, _, winning) => winning, Wait::Penchan(_, _, winning) => winning, Wait::Tanki(_, _, winning) => winning, Wait::Shanpon(_, _, winning) => winning, }.clone() } /// 門前orNot pub fn closed(&self) -> bool { match &self { Wait::Ryanmen(node, _, _) => { node } Wait::Kanchan(node, _, _) => { node } Wait::Penchan(node, _, _) => { node } Wait::Shanpon(node, _, _) => { node } Wait::Tanki(node, _, _) => { node } }.open_sets.iter().all(|set| match set { OpenSet::ConcealedKong(_) => true, _ => false, }) } /// nodeを取得 pub fn node(&self) -> &Node { match &self { Wait::Ryanmen(node, _, _) => { node } Wait::Kanchan(node, _, _) => { node } Wait::Penchan(node, _, _) => { node } Wait::Shanpon(node, _, _) => { node } Wait::Tanki(node, _, _) => { node } } } /// 府数を取得 pub fn fu(&self) -> Fu { match &self { Wait::Ryanmen(_, fu, _) => fu, Wait::Kanchan(_, fu, _) => fu, Wait::Penchan(_, fu, _) => fu, Wait::Tanki(_, fu, _) => fu, Wait::Shanpon(_, fu, _) => fu, }.clone() } } impl Display for Wait { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match &self { Wait::Ryanmen(node, fu, _) => { writeln!(f, "両面待ち: Ryanmen {} / {}", fu, node) } Wait::Kanchan(node, fu, _) => { writeln!(f, "嵌張待ち: Kanchan {} / {}", fu, node) } Wait::Penchan(node, fu, _) => { writeln!(f, "辺張待ち: Penchan {} / {}", fu, node) } Wait::Shanpon(node, fu, _) => { writeln!(f, "双碰待ち: Shanpon {} / {}", fu, node) } Wait::Tanki(node, fu, _) => { writeln!(f, "単騎待ち: Tanki {} / {}", fu, node) } } } }
use std::collections::HashMap; use std::fmt; use std::ops::Index; use bitflags::bitflags; use serde::de::{Deserialize, Deserializer}; use serde::ser::{Serialize, Serializer}; use url::Url; // macro: enum_number {{{ macro_rules! enum_number { ( $(#[$outer:meta])* pub enum $name:ident { $( $(#[$inner:ident $($args:tt)*])* $variant:ident = $value:expr, )* } ) => { $(#[$outer])* #[derive(Clone, Copy)] pub enum $name { $( $(#[$inner $($args)*])* $variant = $value, )* } impl fmt::Display for $name { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (*self as u8).fmt(f) } } impl Serialize for $name { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { // Serialize the enum as a u64. serializer.serialize_u64(*self as u64) } } impl<'de> Deserialize<'de> for $name { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = $name; fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.write_str("positive integer") } fn visit_u64<E>(self, value: u64) -> Result<$name, E> where E: serde::de::Error, { match value { $( $value => Ok($name::$variant), )* _ => Err(E::custom(format!( "unknown {} value {}", stringify!($name), value ))), } } } deserializer.deserialize_u64(Visitor) } } }; } // }}} // macro: bitflags_serde {{{ macro_rules! bitflags_serde { ($name:ident, $type:ty) => { impl<'de> Deserialize<'de> for $name { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = $name; fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.write_str("positive integer") } fn visit_u64<E>(self, value: u64) -> Result<$name, E> where E: serde::de::Error, { $name::from_bits(value as $type).ok_or_else(|| { E::custom(format!("invalid {} bits {}", stringify!($name), value)) }) } } deserializer.deserialize_u64(Visitor) } } impl fmt::Display for $name { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.bits.fmt(f) } } }; } // }}} /// See the [Message Object](https://docs.mod.io/#message-object) docs for more information. #[derive(Debug, Deserialize)] pub struct ModioMessage { pub code: u16, pub message: String, } #[doc(hidden)] #[deprecated(since = "0.4.1", note = "Use `EntityResult`")] pub type ModioResult<T> = EntityResult<T>; /// Result type for editing games, mods and files. #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum EntityResult<T> { Entity(T), /// The request was successful however no new data was submitted. #[serde(deserialize_with = "deserialize_message")] NoChanges, } fn deserialize_message<'de, D>(deserializer: D) -> Result<(), D::Error> where D: serde::Deserializer<'de>, { ModioMessage::deserialize(deserializer).map(|_| ()) } /// See the [Multiple Item Response](https://docs.mod.io/#response-formats) docs for more /// information. #[derive(Debug, Deserialize)] pub struct List<T> { pub data: Vec<T>, #[serde(rename = "result_count")] pub count: u32, #[serde(rename = "result_total")] pub total: u32, #[serde(rename = "result_limit")] pub limit: u32, #[serde(rename = "result_offset")] pub offset: u32, } impl<T> List<T> { pub fn first(&self) -> Option<&T> { self.data.get(0) } pub fn shift(&mut self) -> Option<T> { if self.data.is_empty() { None } else { Some(self.data.remove(0)) } } } impl<T> Index<usize> for List<T> { type Output = T; fn index(&self, index: usize) -> &Self::Output { &self.data[index] } } impl<T> IntoIterator for List<T> { type Item = T; type IntoIter = ::std::vec::IntoIter<T>; fn into_iter(self) -> Self::IntoIter { self.data.into_iter() } } impl<'a, T> IntoIterator for &'a List<T> { type Item = &'a T; type IntoIter = ::std::slice::Iter<'a, T>; fn into_iter(self) -> Self::IntoIter { self.data.iter() } } /// See the [Error Object](https://docs.mod.io/#error-object) docs for more information. #[derive(Debug, Deserialize)] pub struct ModioErrorResponse { #[serde(rename = "error")] pub error: ClientError, } /// See the [Error Object](https://docs.mod.io/#error-object) docs for more information. #[derive(Debug, Deserialize)] pub struct ClientError { pub code: u16, pub message: String, pub errors: Option<HashMap<String, String>>, } /// See the [User Object](https://docs.mod.io/#user-object) docs for more information. #[derive(Debug, Deserialize)] pub struct User { pub id: u32, pub name_id: String, pub username: String, pub date_online: u32, #[serde(deserialize_with = "deserialize_avatar")] pub avatar: Option<Avatar>, pub timezone: String, pub language: String, pub profile_url: Url, } /// See the [Avatar Object](https://docs.mod.io/#avatar-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Avatar { pub filename: String, pub original: Url, pub thumb_50x50: Url, pub thumb_100x100: Url, } /// See the [Logo Object](https://docs.mod.io/#logo-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Logo { pub filename: String, pub original: Url, pub thumb_320x180: Url, pub thumb_640x360: Url, pub thumb_1280x720: Url, } enum_number! { /// See [Status & Visibility](https://docs.mod.io/#status-amp-visibility) docs for more information. #[derive(Debug)] pub enum Status { NotAccepted = 0, Accepted = 1, Archived = 2, Deleted = 3, } } /// See the [User Event Object](https://docs.mod.io/#user-event-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Event { pub id: u32, pub game_id: u32, pub mod_id: u32, pub user_id: u32, pub date_added: u64, pub event_type: EventType, } #[derive(Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum EventType { /// User has joined a team. UserTeamJoin, /// User has left a team. UserTeamLeave, /// User has subscribed to a mod. UserSubscribe, /// User has unsubscribed to a mod. UserUnsubscribe, } impl fmt::Display for EventType { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { EventType::UserTeamJoin => "USER_TEAM_JOIN", EventType::UserTeamLeave => "USER_TEAM_LEAVE", EventType::UserSubscribe => "USER_SUBSCRIBE", EventType::UserUnsubscribe => "USER_UNSUBSCRIBE", } .fmt(fmt) } } /// Deserialize empty objects for the `avatar` property of the User object as `None`. /// /// The mod.io api returns `{"avatar": {}}` for users without avatars instead of returning /// `{"avatar": null}`. fn deserialize_avatar<'de, D>(deserializer: D) -> Result<Option<Avatar>, D::Error> where D: Deserializer<'de>, { match Avatar::deserialize(deserializer) { Ok(avatar) => Ok(Some(avatar)), Err(err) => { let err_s = err.to_string(); if err_s.starts_with("missing field `filename`") || err_s.starts_with("invalid type: null") { Ok(None) } else { Err(err) } } } } pub mod game { use super::*; use std::fmt; /// See the [Game Object](https://docs.mod.io/#game-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Game { pub id: u32, pub status: Status, pub submitted_by: User, pub date_added: u64, pub date_updated: u64, pub date_live: u64, pub presentation_option: PresentationOption, pub submission_option: SubmissionOption, pub curation_option: CurationOption, pub community_options: CommunityOptions, pub revenue_options: RevenueOptions, pub api_access_options: ApiAccessOptions, pub maturity_options: MaturityOptions, pub ugc_name: String, pub icon: Icon, pub logo: Logo, pub header: HeaderImage, pub name: String, pub name_id: String, pub summary: String, pub instructions: Option<String>, pub instructions_url: Option<Url>, pub profile_url: Url, pub tag_options: Vec<TagOption>, } enum_number! { /// Presentation style used on the mod.io website. #[derive(Debug)] pub enum PresentationOption { /// Displays mods in a grid. GridView = 0, /// Displays mods in a table. TableView = 1, } } enum_number! { /// Submission process modders must follow. #[derive(Debug)] pub enum SubmissionOption { /// Mod uploads must occur via the API using a tool by the game developers. ApiOnly = 0, /// Mod uploads can occur from anywhere, include the website and API. Anywhere = 1, } } enum_number! { /// Curation process used to approve mods. #[derive(Debug)] pub enum CurationOption { /// No curation: Mods are immediately available to play. No = 0, /// Paid curation: Mods are immediately to play unless they choose to receive /// donations. These mods must be accepted to be listed. Paid = 1, /// Full curation: All mods must be accepted by someone to be listed. Full = 2, } } enum_number! { /// Option to allow developers to select if they flag their mods containing mature content. #[derive(Debug)] pub enum MaturityOptions { NotAllowed = 0, /// Allow flagging mods as mature. Allowed = 1, } } bitflags! { /// Community features enabled on the mod.io website. pub struct CommunityOptions: u8 { /// Discussion board enabled. const DISCUSSIONS = 0b0001; /// Guides & News enabled. const GUIDES_NEWS = 0b0010; const ALL = Self::DISCUSSIONS.bits | Self::GUIDES_NEWS.bits; } } bitflags_serde!(CommunityOptions, u8); bitflags! { /// Revenue capabilities mods can enable. pub struct RevenueOptions: u8 { /// Allow mods to be sold. const SELL = 0b0001; /// Allow mods to receive donations. const DONATIONS = 0b0010; /// Allow mods to be traded. const TRADE = 0b0100; /// Allow mods to control supply and scarcity. const SCARCITY = 0b1000; const ALL = Self::SELL.bits | Self::DONATIONS.bits | Self::TRADE.bits | Self::SCARCITY.bits; } } bitflags_serde!(RevenueOptions, u8); bitflags! { /// Level of API access allowed by a game. pub struct ApiAccessOptions: u8 { /// Allow third parties to access a game's API endpoints. const ALLOW_THIRD_PARTY = 0b0001; /// Allow mods to be downloaded directly. const ALLOW_DIRECT_DOWNLOAD = 0b0010; const ALL = Self::ALLOW_THIRD_PARTY.bits | Self::ALLOW_DIRECT_DOWNLOAD.bits; } } bitflags_serde!(ApiAccessOptions, u8); /// See the [Icon Object](https://docs.mod.io/#icon-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Icon { pub filename: String, pub original: Url, pub thumb_64x64: Url, pub thumb_128x128: Url, pub thumb_256x256: Url, } /// See the [Header Image Object](https://docs.mod.io/#header-image-object) docs for more /// information. #[derive(Debug, Deserialize)] pub struct HeaderImage { pub filename: String, pub original: Url, } /// See the [Game Tag Option Object](https://docs.mod.io/#game-tag-option-object) docs for more /// information. #[derive(Debug, Deserialize)] pub struct TagOption { pub name: String, #[serde(rename = "type")] pub kind: TagType, pub hidden: bool, pub tags: Vec<String>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "lowercase")] pub enum TagType { Checkboxes, Dropdown, } impl fmt::Display for TagType { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match *self { TagType::Checkboxes => write!(fmt, "checkboxes"), TagType::Dropdown => write!(fmt, "dropdown"), } } } } pub mod mods { use super::*; use serde::de::{Deserialize, Deserializer}; /// See the [Mod Object](https://docs.mod.io/#mod-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Mod { pub id: u32, pub game_id: u32, pub status: Status, pub visible: Visibility, pub submitted_by: User, pub date_added: u64, pub date_updated: u64, pub date_live: u64, pub maturity_option: MaturityOption, pub logo: Logo, pub homepage_url: Option<Url>, pub name: String, pub name_id: String, pub summary: String, pub description: Option<String>, pub description_plaintext: Option<String>, pub metadata_blob: Option<String>, pub profile_url: Url, #[serde(deserialize_with = "deserialize_modfile")] pub modfile: Option<File>, pub media: Media, #[serde(rename = "metadata_kvp", deserialize_with = "deserialize_kvp")] pub metadata: MetadataMap, pub tags: Vec<Tag>, pub stats: Statistics, } enum_number! { /// See [Status & Visibility](https://docs.mod.io/#status-amp-visibility) docs for more information. #[derive(Debug)] pub enum Visibility { Hidden = 0, Public = 1, } } bitflags! { /// Maturity options a mod can be flagged. /// /// This is only relevant if the parent game allows mods to be labelled as mature. pub struct MaturityOption: u8 { const ALCOHOL = 0b0001; const DRUGS = 0b0010; const VIOLENCE = 0b0100; const EXPLICIT = 0b1000; const ALL = Self::ALCOHOL.bits | Self::DRUGS.bits | Self::VIOLENCE.bits | Self::EXPLICIT.bits; } } bitflags_serde!(MaturityOption, u8); /// See the [Mod Event Object](https://docs.mod.io/#mod-event-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Event { pub id: u32, pub mod_id: u32, pub user_id: u32, pub date_added: u64, pub event_type: EventType, } #[derive(Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum EventType { /// Primary file changed, the mod should be updated. ModfileChanged, /// Mod is marked as accepted and public. ModAvailable, /// Mod is marked as not accepted, deleted or hidden. ModUnavailable, /// Mod has been updated. ModEdited, /// Mod has been permanently deleted. ModDeleted, /// User has joined or left the mod team. ModTeamChanged, /// User has joined a team. UserTeamJoin, /// User has left a team. UserTeamLeave, /// User has subscribed to a mod. UserSubscribe, /// User has unsubscribed to a mod. UserUnsubscribe, } impl fmt::Display for EventType { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { EventType::ModfileChanged => "MODFILE_CHANGED", EventType::ModAvailable => "MOD_AVAILABLE", EventType::ModUnavailable => "MOD_UNAVAILABLE", EventType::ModEdited => "MOD_EDITED", EventType::ModDeleted => "MOD_DELETED", EventType::ModTeamChanged => "MOD_TEAM_CHANGED", EventType::UserTeamJoin => "USER_TEAM_JOIN", EventType::UserTeamLeave => "USER_TEAM_LEAVE", EventType::UserSubscribe => "USER_SUBSCRIBE", EventType::UserUnsubscribe => "USER_UNSUBSCRIBE", } .fmt(fmt) } } /// See the [Mod Dependency Object](https://docs.mod.io/#mod-dependencies-object) docs for more /// information. #[derive(Debug, Deserialize)] pub struct Dependency { pub mod_id: u32, pub date_added: u64, } /// See the [Mod Media Object](https://docs.mod.io/#mod-media-object) docs for more /// information. #[derive(Debug, Deserialize)] pub struct Media { #[serde(default = "Vec::new")] pub youtube: Vec<String>, #[serde(default = "Vec::new")] pub sketchfab: Vec<String>, #[serde(default = "Vec::new")] pub images: Vec<Image>, } /// See the [Image Object](https://docs.mod.io/#image-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Image { pub filename: String, pub original: Url, pub thumb_320x180: Url, } /// See the [Statistics Object](https://docs.mod.io/#stats-object) docs for more /// information. #[derive(Debug, Deserialize)] pub struct Statistics { pub mod_id: u32, pub downloads_total: u32, pub subscribers_total: u32, #[serde(flatten)] pub popularity: Popularity, #[serde(flatten)] pub ratings: Ratings, pub date_expires: u64, } #[derive(Debug, Deserialize)] pub struct Popularity { #[serde(rename = "popularity_rank_position")] pub rank_position: u32, #[serde(rename = "popularity_rank_total_mods")] pub rank_total: u32, } #[derive(Debug, Deserialize)] pub struct Ratings { #[serde(rename = "ratings_total")] pub total: u32, #[serde(rename = "ratings_positive")] pub positive: u32, #[serde(rename = "ratings_negative")] pub negative: u32, #[serde(rename = "ratings_percentage_positive")] pub percentage_positive: u32, #[serde(rename = "ratings_weighted_aggregate")] pub weighted_aggregate: f32, #[serde(rename = "ratings_display_text")] pub display_text: String, } /// See the [Rating Object](https://docs.mod.io/#rating-object) docs for more information. #[derive(Debug)] pub enum Rating { Positive { game_id: u32, mod_id: u32, date_added: u64, }, Negative { game_id: u32, mod_id: u32, date_added: u64, }, } impl<'de> Deserialize<'de> for Rating { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { use serde::de::Error; #[derive(Deserialize)] struct R { game_id: u32, mod_id: u32, rating: i8, date_added: u64, } match R::deserialize(deserializer) { Ok(R { game_id, mod_id, rating: 1, date_added, }) => Ok(Rating::Positive { game_id, mod_id, date_added, }), Ok(R { game_id, mod_id, rating: -1, date_added, }) => Ok(Rating::Negative { game_id, mod_id, date_added, }), Ok(R { rating, .. }) => Err(D::Error::custom(format!( "invalid rating value: {}", rating, ))), Err(e) => Err(e), } } } /// See the [Mod Tag Object](https://docs.mod.io/#mod-tag-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Tag { pub name: String, pub date_added: u64, } impl fmt::Display for Tag { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { self.name.fmt(fmt) } } /// See the [Metadata KVP Object](https://docs.mod.io/#metadata-kvp-object) docs for more /// information. pub type MetadataMap = HashMap<String, Vec<String>>; /// Deserialize a sequence of key-value objects to a `MetadataMap`. /// /// Input /// ```json /// [ /// {"metakey": "pistol-dmg", "metavalue": "800"}, /// {"metakey": "smg-dmg", "metavalue": "1200"}, /// {"metakey": "pistol-dmg", "metavalue": "850"} /// ] /// ``` /// Result /// ```json /// { /// "pistol-dmg": ["800", "850"], /// "smg-dmg": ["1000"] /// } /// ``` fn deserialize_kvp<'de, D>(deserializer: D) -> Result<MetadataMap, D::Error> where D: Deserializer<'de>, { use serde::de::{SeqAccess, Visitor}; struct MetadataVisitor; impl<'de> Visitor<'de> for MetadataVisitor { type Value = MetadataMap; fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { fmt.write_str("metadata kvp") } fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> { #[derive(Deserialize)] struct KV { metakey: String, metavalue: String, } let mut map = MetadataMap::new(); while let Ok(Some(elem)) = seq.next_element::<KV>() { map.entry(elem.metakey) .or_insert_with(Vec::new) .push(elem.metavalue); } Ok(map) } } deserializer.deserialize_seq(MetadataVisitor) } /// See the [Comment Object](https://docs.mod.io/#comment-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Comment { pub id: u32, pub mod_id: u32, pub user: User, pub date_added: u64, pub reply_id: u32, pub thread_position: String, pub karma: u32, pub karma_guest: u32, pub content: String, } /// See the [Modfile Object](https://docs.mod.io/#modfile-object) docs for more information. #[derive(Debug, Deserialize)] pub struct File { pub id: u32, pub mod_id: u32, pub date_added: u64, pub date_scanned: u64, pub virus_status: u32, pub virus_positive: u32, pub virustotal_hash: Option<String>, pub filesize: u64, pub filehash: FileHash, pub filename: String, pub version: Option<String>, pub changelog: Option<String>, pub metadata_blob: Option<String>, pub download: Download, } /// See the [Filehash Object](https://docs.mod.io/#filehash-object) docs for more information. #[derive(Debug, Deserialize)] pub struct FileHash { pub md5: String, } /// See the [Download Object](https://docs.mod.io/#download-object) docs for more information. #[derive(Debug, Deserialize)] pub struct Download { pub binary_url: Url, pub date_expires: u64, } /// See the [Team Member Object](https://docs.mod.io/#team-member-object) docs for more /// information. #[derive(Debug, Deserialize)] pub struct TeamMember { pub id: u32, pub user: User, pub level: TeamLevel, pub date_added: u64, pub position: String, } enum_number! { #[derive(Debug)] pub enum TeamLevel { Moderator = 1, Creator = 4, Admin = 8, } } impl TeamLevel { pub fn value(self) -> u64 { self as u64 } } /// Deserialize empty objects for the `modfile` property of the Mod object as `None`. /// /// The mod.io api returns `{"modfile": {}}` for mods without files instead of returning /// `{"modfile": null}`. fn deserialize_modfile<'de, D>(deserializer: D) -> Result<Option<File>, D::Error> where D: Deserializer<'de>, { match File::deserialize(deserializer) { Ok(file) => Ok(Some(file)), Err(err) => { let err_s = err.to_string(); if err_s.starts_with("missing field `id`") || err_s.starts_with("invalid type: null") { Ok(None) } else { Err(err) } } } } } // vim: fdm=marker
#[derive(Debug)] pub enum InputError { Io(std::io::Error), Parse(std::num::ParseIntError), Regex(regex::Error), }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::convert::TryInto; use std::fmt::Debug; use common_meta_kvapi::kvapi::GetKVReply; use common_meta_kvapi::kvapi::GetKVReq; use common_meta_kvapi::kvapi::ListKVReply; use common_meta_kvapi::kvapi::ListKVReq; use common_meta_kvapi::kvapi::MGetKVReply; use common_meta_kvapi::kvapi::MGetKVReq; use common_meta_kvapi::kvapi::UpsertKVReply; use common_meta_kvapi::kvapi::UpsertKVReq; use common_meta_types::protobuf::meta_service_client::MetaServiceClient; use common_meta_types::protobuf::ClientInfo; use common_meta_types::protobuf::RaftRequest; use common_meta_types::protobuf::WatchRequest; use common_meta_types::protobuf::WatchResponse; use common_meta_types::TxnReply; use common_meta_types::TxnRequest; use tonic::codegen::InterceptedService; use tonic::transport::Channel; use tonic::Request; use crate::grpc_client::AuthInterceptor; use crate::message::ExportReq; use crate::message::GetClientInfo; use crate::message::GetEndpoints; use crate::message::MakeClient; /// Bind a request type to its corresponding response type. pub trait RequestFor { type Reply; } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, derive_more::From)] pub enum MetaGrpcReq { UpsertKV(UpsertKVReq), GetKV(GetKVReq), MGetKV(MGetKVReq), ListKV(ListKVReq), } impl TryInto<MetaGrpcReq> for Request<RaftRequest> { type Error = tonic::Status; fn try_into(self) -> Result<MetaGrpcReq, Self::Error> { let raft_request = self.into_inner(); let json_str = raft_request.data.as_str(); let req = serde_json::from_str::<MetaGrpcReq>(json_str) .map_err(|e| tonic::Status::internal(e.to_string()))?; Ok(req) } } impl TryInto<Request<RaftRequest>> for MetaGrpcReq { type Error = serde_json::Error; fn try_into(self) -> Result<Request<RaftRequest>, Self::Error> { let raft_request = RaftRequest { data: serde_json::to_string(&self)?, }; let request = tonic::Request::new(raft_request); Ok(request) } } impl RequestFor for GetKVReq { type Reply = GetKVReply; } impl RequestFor for MGetKVReq { type Reply = MGetKVReply; } impl RequestFor for ListKVReq { type Reply = ListKVReply; } impl RequestFor for UpsertKVReq { type Reply = UpsertKVReply; } impl RequestFor for WatchRequest { type Reply = tonic::codec::Streaming<WatchResponse>; } impl RequestFor for ExportReq { type Reply = tonic::codec::Streaming<WatchResponse>; } impl RequestFor for MakeClient { type Reply = MetaServiceClient<InterceptedService<Channel, AuthInterceptor>>; } impl RequestFor for GetEndpoints { type Reply = Vec<String>; } impl RequestFor for TxnRequest { type Reply = TxnReply; } impl RequestFor for GetClientInfo { type Reply = ClientInfo; }
use super::get_bytes::*; use collections::vec::*; use collections::string::*; // offset and number could be a tuple const NAME_OFFSET: usize = 0; //11 const ATTRIBUTE_OFFSET: usize = 11; //1 const FIRST_CLUSTER_HIGH_OFFSET: usize = 20; //2 const FIRST_CLUSTER_LOW_OFFSET: usize = 26; //2 const FILE_SIZE_OFFSET: usize = 28; //4 //File [sic!] cant be a proper BlockDevice yet ->see BlockDevice comments // should be a handle, that knows the mbr driver (?) /// just a simple container /// can represent a file or a directory pub struct DirectoryEntry { name_extension: String, is_file: bool, first_cluster_entry_number: usize, file_size: usize, } impl DirectoryEntry { pub fn new(directory_entry: &[u8]) -> DirectoryEntry { if directory_entry.len() != 32 { panic!("32"); } let mut name_vec = Vec::with_capacity(8); for i in 0..8 { name_vec.push(directory_entry[i] as u16); } let name = String::from(String::from_utf16_lossy(&name_vec).trim()).to_lowercase(); let mut extension_vec = Vec::with_capacity(3); for i in 8..11 { extension_vec.push(directory_entry[i] as u16); } let extension = String::from(String::from_utf16_lossy(&extension_vec).trim()) .to_lowercase(); let mut name_extension = String::with_capacity(11); name_extension.push_str(&name); if !extension.is_empty() { name_extension.push('.'); name_extension.push_str(&extension); } let high = two_bytes_at_offset(&directory_entry, FIRST_CLUSTER_HIGH_OFFSET) as u32; let low = two_bytes_at_offset(&directory_entry, FIRST_CLUSTER_LOW_OFFSET) as u32; let first_cluster_entry_number = (high << 16 | low) as usize; let mut is_file = true; let attr = directory_entry[ATTRIBUTE_OFFSET]; let no_name = directory_entry[NAME_OFFSET]; let mut is_volume_id = false; let mut is_directory = false; if attr & 0x08 != 0 { is_volume_id = true; } if attr & 0x10 != 0 { is_directory = true; } if is_volume_id || is_directory { is_file = false; } else if no_name == 0xE5 || no_name == 0 { is_file = false; } let file_size = four_bytes_at_offset(&directory_entry, FILE_SIZE_OFFSET) as usize; DirectoryEntry { name_extension: name_extension, is_file: is_file, first_cluster_entry_number: first_cluster_entry_number, file_size: file_size, } } pub fn first_cluster(&self) -> usize { self.first_cluster_entry_number } pub fn is_file(&self) -> bool { self.is_file } pub fn file_size(&self) -> usize { self.file_size } pub fn name_extension(&self) -> &String { &self.name_extension } }
use futures::Future; use my; use my::prelude::*; use trawler::{StoryId, UserId, Vote}; pub(crate) fn handle<F>( c: F, acting_as: Option<UserId>, story: StoryId, v: Vote, ) -> Box<dyn Future<Item = (my::Conn, bool), Error = my::error::Error> + Send> where F: 'static + Future<Item = my::Conn, Error = my::error::Error> + Send, { let user = acting_as.unwrap(); Box::new( c.and_then(move |c| { c.prep_exec( "SELECT `stories`.* \ FROM `stories` \ WHERE `stories`.`short_id` = ?", (::std::str::from_utf8(&story[..]).unwrap(),), ) .and_then(|result| result.collect_and_drop::<my::Row>()) .map(|(c, mut story)| (c, story.swap_remove(0))) }) .and_then(move |(c, story)| { let id = story.get::<u32, _>("id").unwrap(); c.drop_exec( "SELECT `votes`.* \ FROM `votes` \ WHERE `votes`.`user_id` = ? \ AND `votes`.`story_id` = ? \ AND `votes`.`comment_id` IS NULL", (user, id), ) .map(move |c| (c, id)) }) .and_then(move |(c, story)| { // TODO: do something else if user has already voted // TODO: technically need to re-load story under transaction // NOTE: MySQL technically does everything inside this and_then in a transaction, // but let's be nice to it c.drop_exec( "INSERT INTO `votes` \ (`user_id`, `story_id`, `vote`) \ VALUES \ (?, ?, ?)", ( user, story, match v { Vote::Up => 1, Vote::Down => 0, }, ), ) }) .map(|c| (c, false)), ) }
extern crate r6; use std::collections::HashMap; use std::rc::Rc; use std::io::BufReader; use std::borrow::Cow; use r6::runtime::Runtime; use r6::compiler::{Compiler, EnvVar, Syntax}; use r6::primitive::PRIM_ADD; use r6::parser::Parser; macro_rules! assert_evaluates_to { ($src:expr, $expected:expr) => ( { let mut src_reader = BufReader::new($src.as_bytes()); let mut src_parser = Parser::new(&mut src_reader); let sourcecode = match src_parser.parse_datum() { Ok(code) => code, Err(e) => panic!("failed to parse source: {:?}", e) }; let mut res_reader = BufReader::new($expected.as_bytes()); let mut res_parser = Parser::new(&mut res_reader); let expected = match res_parser.parse_datum() { Ok(val) => val, Err(e) => panic!("failed to parse result: {:?}", e) }; let mut glob = HashMap::new(); glob.insert(Cow::Borrowed("lambda"), EnvVar::Syntax(Syntax::Lambda)); glob.insert(Cow::Borrowed("+"), EnvVar::PrimFunc("+", Rc::new(PRIM_ADD))); let mut compiler = Compiler::new(&glob); let bytecode = match compiler.compile(&sourcecode) { Ok(code) => code, Err(e) => panic!("compile failure: {:?}", e) }; let mut runtime = Runtime::new(bytecode); let result = runtime.run(); if !((result == expected) && (expected == result)) { panic!("test failed: expected `{:?}` but got `{:?}`", expected, result); } } ) } #[test] fn lexical_scoping() { // (\y f -> f 2) #f ((\y -> (\x -> y)) #t) // If it's dynamic scope, it should return 0 // If it's static scope, it should return 1 assert_evaluates_to!("((lambda (y f) (f 2)) #f ((lambda (y) (lambda (x) y)) #t))", "#t") }
use amethyst::{ core::transform::Transform, ecs::prelude::*, }; use amethyst_imgui::imgui; use crate::{Inspect, InspectControl}; use imgui::im_str; #[derive(Default, Clone)] pub struct TransformInspectorData { radians: bool, } impl<'a> Inspect<'a> for Transform { type SystemData = ( ReadStorage<'a, Self>, Read<'a, LazyUpdate>, Write<'a, TransformInspectorData>, ); const CAN_ADD: bool = true; fn inspect((storage, lazy, data): &mut Self::SystemData, entity: Entity, ui: &imgui::Ui<'_>) { let me = if let Some(x) = storage.get(entity) { x } else { return; }; let mut new_me = me.clone(); let mut changed = false; ui.push_id(im_str!("Transform")); changed = new_me.translation_mut().control(0., 0.05, im_str!("translation"), ui) || changed; if data.radians { let mut rotation = new_me.rotation().euler_angles().2; changed = rotation.control(0., 0.25f32.to_radians(), im_str!("rotation"), ui) || changed; new_me.set_rotation_2d(rotation); } else { let mut rotation = new_me.rotation().euler_angles().2.to_degrees(); if rotation == -180. { rotation = 180.; } changed = rotation.control(0., 0.25, im_str!("rotation"), ui) || changed; new_me.set_rotation_2d(rotation.to_radians()); } ui.checkbox(im_str!("radians"), &mut data.radians); changed = new_me.scale_mut().control(1., 0.01, im_str!("scale"), ui) || changed; if changed { lazy.insert(entity, new_me); } ui.pop_id(); } fn add((_storage, lazy, _): &mut Self::SystemData, entity: Entity) { lazy.insert(entity, Transform::default()); } }
use crate::pathtracer::camera::Ray; use crate::pathtracer::material::Material; use nalgebra_glm::Vec3; use crate::pathtracer::hit::{Hit, Hitable}; pub struct Triangle { id: u32, pub vertex_a: Vec3, pub vertex_b: Vec3, pub vertex_c: Vec3, pub material: Material, } impl Triangle { pub fn new(id: u32, vertex_a: Vec3, vertex_b: Vec3, vertex_c: Vec3, material: Material) -> Triangle { Triangle { id, vertex_a, vertex_b, vertex_c, material, } } } impl Hitable for Triangle { fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<Hit> { // Source: https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm // // + a // |\ // | \ // v0v1 | \ v0v2 // | \ // | \ // | \ // b +------+ c let v0v1: Vec3 = self.vertex_b - self.vertex_a; let v0v2: Vec3 = self.vertex_c - self.vertex_a; const K_EPSILON: f32 = 0.0000001; let plane: Vec3 = ray.direction.cross(&v0v2); let angle_triangle_to_camera: f32 = v0v1.dot(&plane); // Parallel ? // To enable backface culling, remove the "angle_triangle_to_camera >= 0.0" check. if angle_triangle_to_camera < K_EPSILON && angle_triangle_to_camera >= 0.0 { return None; } let f: f32 = 1. / angle_triangle_to_camera; let s: Vec3 = ray.origin - self.vertex_a; let u: f32 = f * s.dot(&plane); if u < 0. || u > 1. { return None; } let q: Vec3 = s.cross(&v0v1); let v: f32 = f * ray.direction.dot(&q); if v < 0. || u + v > 1. { return None; } let t: f32 = f * v0v2.dot(&q); // Is the triangle behind us or outside bounds of the test if t <= 0. || t < t_min || t >= t_max { return None; } let normal: Vec3 = v0v1.cross(&v0v2).normalize(); Some(Hit { t, point: ray.point_at_parameter(t), normal, material: self.material.clone() }) } fn id(&self) -> u32 { self.id } }
use crate::{Error, Module, Trait}; use crypto::encryption::ElGamal; use crypto::types::{Cipher as BigCipher, PublicKey as ElGamalPK}; use num_bigint::BigUint; use sp_std::vec::Vec; /// all functions related to ballot operations in the offchain worker impl<T: Trait> Module<T> { pub fn shuffle_ciphers( pk: &ElGamalPK, ciphers: Vec<BigCipher>, ) -> Result<(Vec<BigCipher>, Vec<BigUint>, Vec<usize>), Error<T>> { let q = pk.params.q(); let size = ciphers.len(); // check that there are ballots to shuffle if size == 0 { return Err(Error::<T>::ShuffleCiphersSizeZeroError); } // get the permuation or else return error let permutation: Vec<usize> = Self::generate_permutation(size)?; // get the random values let randoms: Vec<BigUint> = Self::get_random_biguints_less_than(&q, size)?; // shuffle the ciphers let shuffle = ElGamal::shuffle(&ciphers, &permutation, &randoms, &pk); let shuffled_ciphers: Vec<BigCipher> = shuffle.into_iter().map(|item| item.0).collect(); // return the shuffled ciphers, randoms, permutation as result Ok((shuffled_ciphers, randoms, permutation)) } }
use openexr_sys as sys; pub use sys::Imf_Channel_t as Channel; use crate::core::{ cppstd::CppString, refptr::{OpaquePtr, Ref, RefMut}, }; use std::ffi::{CStr, CString}; use std::marker::PhantomData; #[repr(transparent)] pub struct ChannelList(pub(crate) *mut sys::Imf_ChannelList_t); #[repr(transparent)] #[derive(Clone)] pub(crate) struct ChannelListConstIterator( pub(crate) sys::Imf_ChannelList_ConstIterator_t, ); // #[repr(transparent)] // pub(crate) struct ChannelListIterator( // pub(crate) sys::Imf_ChannelList_Iterator_t, // ); pub const CHANNEL_HALF: Channel = Channel { type_: sys::Imf_PixelType_HALF, x_sampling: 1, y_sampling: 1, p_linear: true, }; pub const CHANNEL_FLOAT: Channel = Channel { type_: sys::Imf_PixelType_FLOAT, x_sampling: 1, y_sampling: 1, p_linear: true, }; pub const CHANNEL_UINT: Channel = Channel { type_: sys::Imf_PixelType_UINT, x_sampling: 1, y_sampling: 1, p_linear: true, }; unsafe impl OpaquePtr for ChannelList { type SysPointee = sys::Imf_ChannelList_t; type Pointee = ChannelList; } pub type ChannelListRef<'a, P = ChannelList> = Ref<'a, P>; pub type ChannelListRefMut<'a, P = ChannelList> = RefMut<'a, P>; impl ChannelList { /// Create a Default channel list /// pub fn new() -> ChannelList { ChannelList::default() } /// Insert a channel /// pub fn insert(&mut self, name: &str, channel: &Channel) { unsafe { let cname = CString::new(name).expect("Inner NUL bytes in name"); sys::Imf_ChannelList_insert(self.0, cname.as_ptr(), channel) .into_result() .unwrap(); } } /// Get a reference to a channel by name. /// /// # Returns /// * `Some(&Channel)` - if the channel called `name` exists /// * `None` - otherwise /// pub fn get(&self, name: &str) -> Option<&Channel> { unsafe { let cname = CString::new(name).expect("Inner NUL bytes in name"); let mut ptr = std::ptr::null(); sys::Imf_ChannelList_findChannel_const( self.0, &mut ptr, cname.as_ptr(), ) .into_result() .unwrap(); if ptr.is_null() { None } else { Some(&*ptr) } } } /// Get a mutable reference to a channel by name. /// /// # Returns /// * `Some(&Channel)` - if the channel called `name` exists /// * `None` - otherwise /// pub fn get_mut(&mut self, name: &str) -> Option<&mut Channel> { unsafe { let cname = CString::new(name).expect("Inner NUL bytes in name"); let mut ptr = std::ptr::null_mut(); sys::Imf_ChannelList_findChannel(self.0, &mut ptr, cname.as_ptr()) .into_result() .unwrap(); if ptr.is_null() { None } else { Some(&mut *ptr) } } } /// Get an iterator over the channels in the channel list /// pub fn iter(&self) -> ChannelListIter { unsafe { let mut ptr = sys::Imf_ChannelList_ConstIterator_t::default(); sys::Imf_ChannelList_begin_const(self.0, &mut ptr) .into_result() .unwrap(); let ptr = ChannelListConstIterator(ptr); let mut end = sys::Imf_ChannelList_ConstIterator_t::default(); sys::Imf_ChannelList_end_const(self.0, &mut end) .into_result() .unwrap(); let end = ChannelListConstIterator(end); ChannelListIter { ptr, end, _p: PhantomData, } } } } impl ChannelList { //! # Layers //! In an image file with many channels it is sometimes useful to //! group the channels into "layers", that is, into sets of channels //! that logically belong together. Grouping channels into layers //! is done using a naming convention: channel C in layer L is //! called "L.C". //! //! For example, a computer graphic image may contain separate //! R, G and B channels for light that originated at each of //! several different virtual light sources. The channels in //! this image might be called "light1.R", "light1.G", "light1.B", //! "light2.R", "light2.G", "light2.B", etc. //! //! Note that this naming convention allows layers to be nested; //! for example, "light1.specular.R" identifies the "R" channel //! in the "specular" sub-layer of layer "light1". //! //! Channel names that don't contain a "." or that contain a //! "." only at the beginning or at the end are not considered //! to be part of any layer. /// Get the set of layers in the file. /// /// pub fn layers(&self) -> Vec<String> { unsafe { // FIXME: dealing with STL at the boundary is pretty gnarly. // Should probably provide a high-level pub(crate) mod for these let mut set = std::ptr::null_mut(); sys::std_set_string_ctor(&mut set); sys::Imf_ChannelList_layers(self.0, set); let mut ptr = sys::std_set_string_iterator_t::default(); sys::std_set_string_cbegin(set, &mut ptr) .into_result() .unwrap(); let mut end = sys::std_set_string_iterator_t::default(); sys::std_set_string_cend(set, &mut end) .into_result() .unwrap(); let mut size = 0; sys::std_set_string_size(set, &mut size) .into_result() .unwrap(); let mut result = Vec::with_capacity(size as usize); loop { let mut eq = false; sys::std_set_string_const_iterator_eq(&mut eq, &ptr, &end); if eq { break; } let mut str_ptr = std::ptr::null(); sys::std_set_string_iterator_deref(&ptr, &mut str_ptr) .into_result() .unwrap(); let mut char_ptr = std::ptr::null(); sys::std_string_c_str(str_ptr, &mut char_ptr) .into_result() .unwrap(); result.push( CStr::from_ptr(char_ptr).to_string_lossy().to_string(), ); let mut dummy = std::ptr::null_mut(); sys::std_set_string_iterator_inc(&mut ptr, &mut dummy) .into_result() .unwrap(); } result } } /// Get an iterator over the channels belonging to a particular layer /// pub fn channels_in_layer(&self, layer: &str) -> ChannelListIter { let mut ptr = sys::Imf_ChannelList_ConstIterator_t::default(); let mut end = sys::Imf_ChannelList_ConstIterator_t::default(); unsafe { let s = CppString::new(layer); sys::Imf_ChannelList_channelsInLayer_const( self.0, s.0, &mut ptr, &mut end, ) .into_result() .unwrap(); ChannelListIter { ptr: ChannelListConstIterator(ptr), end: ChannelListConstIterator(end), _p: PhantomData, } } } /// Get an iterator over all channels whose name starts with prefix `prefix` /// pub fn channels_with_prefix(&self, prefix: &str) -> ChannelListIter { let mut ptr = sys::Imf_ChannelList_ConstIterator_t::default(); let mut end = sys::Imf_ChannelList_ConstIterator_t::default(); unsafe { let cprefix = CString::new(prefix).expect("NUL bytes in prefix"); sys::Imf_ChannelList_channelsWithPrefix_const( self.0, cprefix.as_ptr(), &mut ptr, &mut end, ) .into_result() .unwrap(); ChannelListIter { ptr: ChannelListConstIterator(ptr), end: ChannelListConstIterator(end), _p: PhantomData, } } } } impl Default for ChannelList { fn default() -> ChannelList { unsafe { let mut ptr = std::ptr::null_mut(); sys::Imf_ChannelList_ctor(&mut ptr); ChannelList(ptr) } } } impl PartialEq for ChannelList { fn eq(&self, rhs: &ChannelList) -> bool { unsafe { let mut result = false; sys::Imf_ChannelList__eq(self.0, &mut result, rhs.0) .into_result() .unwrap(); result } } } pub struct ChannelListIter<'a> { ptr: ChannelListConstIterator, end: ChannelListConstIterator, _p: PhantomData<&'a ChannelList>, } impl<'a> IntoIterator for &'a ChannelList { type Item = (&'a str, &'a Channel); type IntoIter = ChannelListIter<'a>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a> Iterator for ChannelListIter<'a> { type Item = (&'a str, &'a Channel); fn next(&mut self) -> Option<(&'a str, &'a Channel)> { let ptr_curr = self.ptr.clone(); let mut ptr_next = self.ptr.clone(); unsafe { let mut dummy = std::ptr::null_mut(); sys::Imf_ChannelList_ConstIterator__op_inc( &mut ptr_next.0, &mut dummy, ) .into_result() .unwrap(); } if ptr_curr == self.end { None } else { self.ptr = ptr_next; unsafe { let mut nameptr = std::ptr::null(); sys::Imf_ChannelList_ConstIterator_name( &ptr_curr.0, &mut nameptr, ) .into_result() .unwrap(); if nameptr.is_null() { panic!("ChannelList::ConstIterator::name() returned NULL"); } let mut chanptr = std::ptr::null(); sys::Imf_ChannelList_ConstIterator_channel( &ptr_curr.0, &mut chanptr, ) .into_result() .unwrap(); Some(( CStr::from_ptr(nameptr) .to_str() .expect("NUL bytes in channel name"), &*chanptr, )) } } } } impl PartialEq for ChannelListConstIterator { fn eq(&self, rhs: &ChannelListConstIterator) -> bool { unsafe { let mut result = false; sys::Imf_channel_list_const_iter_eq(&mut result, &self.0, &rhs.0) .into_result() .unwrap(); result } } } #[cfg(test)] #[test] fn iter1() { use crate::core::PixelType; let mut list = ChannelList::new(); let channel = Channel { type_: PixelType::Half.into(), x_sampling: 1, y_sampling: 1, p_linear: true, }; list.insert("R", &channel); list.insert("G", &channel); list.insert("B", &channel); list.insert("A", &channel); assert_eq!( list.iter().map(|(name, _)| { name }).collect::<Vec<&str>>(), ["A", "B", "G", "R"] ) } #[cfg(test)] #[test] fn iter2() { use crate::core::PixelType; let mut list = ChannelList::new(); let channel = Channel { type_: PixelType::Half.into(), x_sampling: 1, y_sampling: 1, p_linear: true, }; list.insert("R", &channel); list.insert("G", &channel); list.insert("B", &channel); list.insert("A", &channel); for (_name, _channel) in &list { // ... } } #[cfg(test)] #[test] fn eq() { use crate::core::PixelType; let mut list1 = ChannelList::new(); let mut list2 = ChannelList::new(); let mut list3 = ChannelList::new(); let channel = Channel { type_: PixelType::Half.into(), x_sampling: 1, y_sampling: 1, p_linear: true, }; list1.insert("R", &channel); list1.insert("G", &channel); list1.insert("B", &channel); list1.insert("A", &channel); list2.insert("R", &channel); list2.insert("G", &channel); list2.insert("B", &channel); list2.insert("A", &channel); list3.insert("R", &channel); list3.insert("G", &channel); list3.insert("B", &channel); assert!(list1 == list2); assert!(list1 != list3); } #[cfg(test)] #[test] fn layers() { use crate::core::PixelType; let mut list = ChannelList::new(); let channel = Channel { type_: PixelType::Half.into(), x_sampling: 1, y_sampling: 1, p_linear: true, }; list.insert("diffuse.R", &channel); list.insert("diffuse.G", &channel); list.insert("diffuse.B", &channel); list.insert("specular.R", &channel); list.insert("specular.G", &channel); list.insert("specular.B", &channel); let layers = list.layers(); assert_eq!(layers, ["diffuse", "specular"]); } #[cfg(test)] #[test] fn channels_in_layer() { use crate::core::PixelType; let mut list = ChannelList::new(); let channel = Channel { type_: PixelType::Half.into(), x_sampling: 1, y_sampling: 1, p_linear: true, }; list.insert("diffuse.R", &channel); list.insert("diffuse.G", &channel); list.insert("diffuse.B", &channel); list.insert("specular.R", &channel); list.insert("specular.G", &channel); list.insert("specular.B", &channel); assert_eq!( list.channels_in_layer("diffuse") .map(|(name, _)| { name }) .collect::<Vec<&str>>(), ["diffuse.B", "diffuse.G", "diffuse.R"] ) } #[cfg(test)] #[test] fn channels_with_prefix() { use crate::core::PixelType; let mut list = ChannelList::new(); let channel = Channel { type_: PixelType::Half.into(), x_sampling: 1, y_sampling: 1, p_linear: true, }; list.insert("diffuse.R", &channel); list.insert("diffuse.G", &channel); list.insert("diffuse.B", &channel); list.insert("specular.R", &channel); list.insert("specular.G", &channel); list.insert("specular.B", &channel); assert_eq!( list.channels_with_prefix("spec") .map(|(name, _)| { name }) .collect::<Vec<&str>>(), ["specular.B", "specular.G", "specular.R"] ) } // pub struct ChannelListIterMut { // ptr: ChannelListIterator, // end: ChannelListIterator, // } // impl PartialEq for ChannelListIterator { // fn eq(&self, rhs: &ChannelListIterator) -> bool { // let mut a = sys::Imf_ChannelList_ConstIterator_t::default(); // let mut b = sys::Imf_ChannelList_ConstIterator_t::default(); // unsafe { // sys::Imf_ChannelList_ConstIterator_from_mut(&mut a, &self.0); // sys::Imf_ChannelList_ConstIterator_from_mut(&mut b, &rhs.0); // sys::Imf_channel_list_const_iter_eq(&a, &b) // } // } // }
use nabi::{Result, Error, HandleRights}; use nil::{Ref, KernelRef}; pub type HandleOffset = u32; /// A Handle represents an atomically reference-counted object with specfic rights. /// Handles can be duplicated if they have the `HandleRights::DUPLICATE` right. pub struct Handle { /// Reference-counted ptr to the stored kernel object. refptr: Ref<KernelRef>, /// This handle's access rights to `Ref`. rights: HandleRights, } impl Handle { pub fn new<T: KernelRef>(refptr: Ref<T>, rights: HandleRights) -> Handle { Handle { refptr, rights, } } pub fn cast<T: KernelRef>(&self) -> Result<Ref<T>> { self.refptr.cast() .ok_or(Error::WRONG_TYPE) } pub fn cast_ref<T: KernelRef>(&self) -> Result<&T> { self.refptr.cast_ref() .ok_or(Error::WRONG_TYPE) } /// Duplicate the handle if it has the `DUPLICATE` right. pub fn duplicate(&self, new_rights: HandleRights) -> Option<Handle> { if self.rights.contains(new_rights | HandleRights::DUPLICATE) { // `new_rights` contains the same or fewer rights and `HandleRights::DUPLICATE` // so it's okay to duplicate it. Some(Handle { refptr: self.refptr.clone(), rights: new_rights, }) } else { None } } pub fn check_rights(&self, rights: HandleRights) -> Result<&Handle> { if self.rights.contains(rights) { Ok(self) } else { Err(Error::ACCESS_DENIED) } } #[inline] pub fn rights(&self) -> HandleRights { self.rights } }
extern crate data_encoding; use std::env::args; use std::io::{self, Read}; use data_encoding::hex; fn encrypt(msg: &str, key: &str) -> Vec<u8> { msg.bytes().zip(key.bytes().cycle()).map(|(msg_byte, key_byte)| msg_byte ^ key_byte).collect() } fn main() { let mut args = args(); if let Some(key) = args.nth(1) { let mut stdin = io::stdin(); let mut buffer = String::new(); stdin.read_to_string(&mut buffer).unwrap(); let e_msg = encrypt(buffer.trim(), &key); println!("{}", hex::encode(&e_msg)); } else { println!("Give key pls."); } }
use std::env; fn main() { let args: Vec<_> = env::args().collect(); if args.len() < 2 { println!("Error: Please provide a number as argument."); return; } let i: i32 = args[1].parse().unwrap(); println!("{} has the minimum {} Collatz steps", total_steps(i), i); } fn total_steps(i: i32) -> i32 { let mut current_number: i32 = 1; loop { let collatz_number = collatz(current_number); if collatz_number == i { return current_number; } else { current_number += 1 } } } fn collatz(n: i32) -> i32 { if n == 1 { return 0; } match n % 2 { 0 => { 1 + collatz(n/2) } _ => { 1 + collatz(n*3+1) } } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type BackgroundAudioTrack = *mut ::core::ffi::c_void; pub type EmbeddedAudioTrack = *mut ::core::ffi::c_void; pub type MediaClip = *mut ::core::ffi::c_void; pub type MediaComposition = *mut ::core::ffi::c_void; pub type MediaOverlay = *mut ::core::ffi::c_void; pub type MediaOverlayLayer = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct MediaTrimmingPreference(pub i32); impl MediaTrimmingPreference { pub const Fast: Self = Self(0i32); pub const Precise: Self = Self(1i32); } impl ::core::marker::Copy for MediaTrimmingPreference {} impl ::core::clone::Clone for MediaTrimmingPreference { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct VideoFramePrecision(pub i32); impl VideoFramePrecision { pub const NearestFrame: Self = Self(0i32); pub const NearestKeyFrame: Self = Self(1i32); } impl ::core::marker::Copy for VideoFramePrecision {} impl ::core::clone::Clone for VideoFramePrecision { fn clone(&self) -> Self { *self } }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. /// Host information. /// /// Brought back from obscurity by RFC 8482. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct HostInformation<'a> { /// `CPU` field. /// /// In RFC 8482, this will be `RFC8482`. pub cpu: &'a [u8], /// `OS` field. /// /// In RFC 8482, this will be ``. pub os: &'a [u8], } impl<'a> HostInformation<'a> { /// Is this a RFC 8482 answer to the `ANY` / `*` `QTYPE` question? #[inline(always)] pub fn is_rfc_8482_answer_to_any_question(&self) -> bool { self.cpu == b"RFC8482" && self.os.is_empty() } /// Is this a CloudFlare answer to the `ANY` / `*` `QTYPE` question? #[inline(always)] pub fn is_cloudflare_answer_to_any_question(&self) -> bool { self.cpu == b"ANY obsoleted" && self.os == b"See draft-ietf-dnsop-refuse-any" } }
#[doc = "Reader of register MACRxFCR"] pub type R = crate::R<u32, super::MACRXFCR>; #[doc = "Writer for register MACRxFCR"] pub type W = crate::W<u32, super::MACRXFCR>; #[doc = "Register MACRxFCR `reset()`'s with value 0"] impl crate::ResetValue for super::MACRXFCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RFE`"] pub type RFE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RFE`"] pub struct RFE_W<'a> { w: &'a mut W, } impl<'a> RFE_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 } } #[doc = "Reader of field `UP`"] pub type UP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `UP`"] pub struct UP_W<'a> { w: &'a mut W, } impl<'a> UP_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 } } impl R { #[doc = "Bit 0 - RFE"] #[inline(always)] pub fn rfe(&self) -> RFE_R { RFE_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - UP"] #[inline(always)] pub fn up(&self) -> UP_R { UP_R::new(((self.bits >> 1) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - RFE"] #[inline(always)] pub fn rfe(&mut self) -> RFE_W { RFE_W { w: self } } #[doc = "Bit 1 - UP"] #[inline(always)] pub fn up(&mut self) -> UP_W { UP_W { w: self } } }
//! Contains structure which provides futures::Stream to websocket-feed of Coinbase api extern crate url; use std::time::{SystemTime, UNIX_EPOCH}; use self::url::Url; use futures::{Future, Sink, Stream}; use serde_json; use tokio_tungstenite::connect_async; use hyper::Method; use {private::Private, ASync}; use super::tokio_tungstenite::tungstenite::Message as TMessage; use error::WSError; use structs::wsfeed::*; pub struct WSFeed; fn convert_msg(msg: TMessage) -> Message { match msg { TMessage::Text(str) => serde_json::from_str(&str).unwrap_or_else(|e| { Message::InternalError(WSError::Serde { error: e, data: str, }) }), _ => unreachable!(), // filtered in stream } } impl WSFeed { // Constructor for simple subcription with product_ids and channels pub fn new( uri: &str, product_ids: &[&str], channels: &[ChannelType], ) -> impl Stream<Item = Message, Error = WSError> { let subscribe = Subscribe { _type: SubscribeCmd::Subscribe, product_ids: product_ids.into_iter().map(|x| x.to_string()).collect(), channels: channels .to_vec() .into_iter() .map(|x| Channel::Name(x)) .collect::<Vec<_>>(), auth: None }; Self::new_with_sub(uri, subscribe) } // Constructor for extended subcription via Subscribe structure pub fn new_with_sub( uri: &str, subsribe: Subscribe, ) -> impl Stream<Item = Message, Error = WSError> { let url = Url::parse(uri).unwrap(); connect_async(url) .map_err(WSError::Connect) .and_then(move |(ws_stream, _)| { debug!("WebSocket handshake has been successfully completed"); let (sink, stream) = ws_stream.split(); let subsribe = serde_json::to_string(&subsribe).unwrap(); sink.send(TMessage::Text(subsribe)) .map_err(WSError::Send) .and_then(|_| { debug!("subsription sent"); let stream = stream .filter(|msg| msg.is_text()) .map_err(WSError::Read) .map(convert_msg); Ok(stream) }) }).flatten_stream() } // Constructor for simple subcription with product_ids and channels with auth pub fn new_with_auth( uri: &str, product_ids: &[&str], channels: &[ChannelType], key: &str, secret: &str, passphrase: &str ) -> impl Stream<Item = Message, Error = WSError> { let timestamp = SystemTime::now() .duration_since(UNIX_EPOCH) .expect("leap-second") .as_secs(); let signature = Private::<ASync>::sign(secret, timestamp, Method::GET, "/users/self/verify", ""); let auth = Auth { signature, key: key.to_string(), passphrase: passphrase.to_string(), timestamp: timestamp.to_string() }; let subscribe = Subscribe { _type: SubscribeCmd::Subscribe, product_ids: product_ids.into_iter().map(|x| x.to_string()).collect(), channels: channels .to_vec() .into_iter() .map(|x| Channel::Name(x)) .collect::<Vec<_>>(), auth: Some(auth) }; Self::new_with_sub(uri, subscribe) } }
pub mod gi; pub mod filter; pub mod base; pub use self::gi::*; pub use self::filter::*; pub use self::base::*;
extern crate futures; extern crate tokio_core; extern crate trust_dns_proto; extern crate trust_dns_resolver; use futures::Future; use std::net::Ipv4Addr; use tokio_core::reactor::{Core, Handle}; use trust_dns_proto::rr::RData; use trust_dns_resolver::ResolverFuture; use trust_dns_resolver::config::{ResolverConfig, ResolverOpts}; use trust_dns_resolver::error::*; use trust_dns_resolver::lookup::Lookup; use trust_dns_resolver::lookup_ip::LookupIp; pub trait ResolverWrapper { fn lookup_ip(&self, host: &str) -> Box<Future<Item = LookupIp, Error = ResolveError>>; } pub struct ResolverWrapperReal { delegate: ResolverFuture, } impl ResolverWrapper for ResolverWrapperReal { fn lookup_ip(&self, host: &str) -> Box<Future<Item = LookupIp, Error = ResolveError>> { Box::new(self.delegate.lookup_ip(host)) } } pub struct ResolverWrapperFactory; impl ResolverWrapperFactory { fn resolver( &self, config: ResolverConfig, options: ResolverOpts, reactor: &Handle, ) -> Box<ResolverWrapper> { Box::new(ResolverWrapperReal { delegate: ResolverFuture::new(config, options, reactor), }) } } pub struct MockResolveWrapper; impl ResolverWrapper for MockResolveWrapper { fn lookup_ip(&self, _host: &str) -> Box<Future<Item = LookupIp, Error = ResolveError>> { let lookup: Lookup = RData::A(Ipv4Addr::new(127, 0, 0, 1)).into(); let lookup_ip = lookup.into(); Box::new(futures::future::ok(lookup_ip)) } } pub struct MockResolveWrapperFactory; impl MockResolveWrapperFactory { fn resolver(&self) -> Box<ResolverWrapper> { Box::new(MockResolveWrapper) } } fn lookup( resolver: Box<ResolverWrapper>, host: &str, ) -> Box<Future<Item = LookupIp, Error = ResolveError>> { resolver.lookup_ip(host) } fn main() { let mut core = Core::new().expect("core failed"); let real = ResolverWrapperFactory.resolver(Default::default(), Default::default(), &core.handle()); let mock = MockResolveWrapperFactory.resolver(); println!( "real lookup: {:#?}", core.run(lookup(real, "www.example.com.")) .expect("lookup failed") ); println!( "mock lookup: {:#?}", core.run(lookup(mock, "www.example.com.")) .expect("lookup failed") ); }
extern crate eosio_macros; use eosio_macros::s; fn main() { let _ = s!(256, "EOS"); }
use actix_web::HttpRequest; use reqwest::StatusCode; use reqwest_middleware::ClientWithMiddleware; use serde::Deserialize; /// Make a GET request to the pokeapi for the provided pokemon species /// /// # Errors: /// Will return [`Err`] if the http connection could not be made, /// if the API responded with an error status code /// or if the response body contained invalid JSON. /// /// Will return [`Ok(None)`] if the API returned a 404 status code pub async fn get_species( client: &ClientWithMiddleware, req: &HttpRequest, pokemon_name: &str, ) -> Result<Option<Species>, Box<dyn std::error::Error>> { let resp = client .get(req.url_for("pokemon_species", &[pokemon_name])?) .send() .await?; match resp.status() { StatusCode::NOT_FOUND => Ok(None), _ => Ok(Some(resp.error_for_status()?.json().await?)), } } #[derive(Debug, Deserialize)] pub struct Habitat { pub name: String, } #[derive(Debug, Deserialize)] pub struct FlavorText { pub flavor_text: String, pub language: Language, } #[derive(Debug, Deserialize)] pub struct Language { pub name: String, } #[derive(Debug, Deserialize)] pub struct Species { pub name: String, pub is_legendary: bool, pub habitat: Habitat, pub flavor_text_entries: Vec<FlavorText>, }
use std::env; use std::fmt; use std::io::stdout; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread::{sleep, spawn}; use std::time::{Duration, SystemTime}; use crossterm::event::{poll, read, Event, KeyCode, KeyEvent}; use crossterm::style::{Color, Colors, Print, SetColors}; use crossterm::terminal::{ enable_raw_mode, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, }; use crossterm::{cursor, execute}; use terminal_size::{terminal_size, Height, Width}; fn detect() -> Option<bool> { if !poll(Duration::from_millis(100)).unwrap_or_default() { return None; } match read().unwrap() { Event::Key(KeyEvent { code: KeyCode::Char('q'), .. }) => Some(true), _ => None, } } struct Time(usize, usize, usize); impl From<String> for Time { fn from(s: String) -> Self { let s = s.split(':'); let s: Vec<usize> = s.rev().take(3).map(|x| x.parse().unwrap_or(0)).collect(); Time( *s.get(2).unwrap_or(&0), *s.get(1).unwrap_or(&0), *s.get(0).unwrap_or(&0), ) } } impl fmt::Display for Time { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}h{}m{}s\nIf it's all 0's separate it by hours:minute:seconds", self.0, self.1, self.2 ) } } fn main() { // in seconds let args: Vec<String> = env::args().collect(); let message = args[1].to_owned(); let time = args[2].to_owned(); let time = Time::from(time); let mut total = time.0 * 3600 + time.1 * 60 + time.0; const SECONDS_IN_HOUR: usize = 3600; const SECONDS_IN_MINUTES: usize = 60; enable_raw_mode().unwrap(); execute!(stdout(), cursor::Hide, EnterAlternateScreen).unwrap(); let exit = Arc::new(AtomicBool::new(false)); let exit_signal = exit.clone(); spawn(move || { while !exit_signal.load(Ordering::SeqCst) { if let Some(signal) = detect() { exit_signal.store(signal, Ordering::SeqCst); }; } }); let original = total; while total != 0 { if exit.load(Ordering::SeqCst) { break; } let hours = total / SECONDS_IN_HOUR; let mut remaining_seconds = total - hours * SECONDS_IN_HOUR; let minutes = remaining_seconds / SECONDS_IN_MINUTES; remaining_seconds = remaining_seconds - minutes * SECONDS_IN_MINUTES; let seconds = remaining_seconds; let size = terminal_size(); let dim = if let Some((Width(w), Height(h))) = size { (w, h) } else { panic!("Unable to get screen dimensions"); }; let w = dim.0 / 2; let h = dim.1 / 2; let display = format!("{}\n", message); let display_length = display.len() as u16 / 2; let time_left = format!("{}h {}m {}s", hours, minutes, seconds); let left_length = time_left.len() as u16 / 2; let help = "Press 'q' to quit.\n".to_string(); let help_length = help.len() as u16 / 2; let color = { if total >= original * 5 / 10 { Colors::new(Color::Green, Color::Black) } else if total <= original * 5 / 10 { Colors::new(Color::Yellow, Color::Black) } else if total <= original * 3 / 10 { Colors::new(Color::Red, Color::Black) } else { Colors::new(Color::DarkRed, Color::Black) } }; execute!( stdout(), Clear(ClearType::All), SetColors(color), // Moves the display message to the top center if the screen. cursor::MoveTo(w - left_length, h), Print(time_left), // Moves to center SetColors(Colors::new(Color::Green, Color::Black)), cursor::MoveTo(w - display_length, h - 5), Print(display), // Moves to bottom center cursor::MoveTo(w - help_length, h + 3), Print(help) ) .unwrap(); let current = SystemTime::now(); sleep(Duration::from_secs(1)); let elapsed = current.elapsed().unwrap().as_secs() as usize; total -= elapsed; } execute!(stdout(), LeaveAlternateScreen, cursor::Show).unwrap(); exit.store(true, Ordering::SeqCst); }
mod common; use common::deduce_boolean; use rustollens::boolean::{False, True}; #[test] fn type_level_booleans_can_be_grouped() { deduce_boolean::<True>(); deduce_boolean::<False>(); } #[test] fn type_level_booleans_are_convertible_to_runtime_booleans() { assert!(*True); assert!(!*False); } #[test] fn type_level_booleans_can_be_shown() { assert_eq!(True.to_string(), "True"); assert_eq!(False.to_string(), "False"); }
use super::constants; use super::deck; use super::user_input; use super::utils; use super::Card; use super::Hand; pub fn player_has_valid_hand(hands: &Vec<Hand>) -> bool { let hand_validities: Vec<bool> = utils::iter_map_collect(hands, |h| h.is_valid()); hand_validities.contains(&true) } pub fn player_has_blackjack(hands: &Vec<Hand>) -> bool { hands.len() == 1 && hands.get(0).unwrap().is_blackjack() } pub fn should_dealer_hit(hand: &Hand) -> bool { hand.total() < constants::DEALER_STANDS_VALUE } pub fn get_round_result(player: &Vec<Hand>, dealer: &Hand) -> (bool, String) { let dealer_total = dealer.total(); let player_totals: Vec<u32> = utils::iter_map_collect(player, |h| h.total()); let result = player_totals .iter() .any(|&t| t > dealer_total && t <= constants::BLACKJACK_MAXIMUM); let player_totals_display = utils::iter_map_collect(&player_totals, |&t| t.to_string()).join(", "); let message = format!( " You: {}\n Dealer: {}", player_totals_display, dealer_total ); (result, message) } fn player_answers_yes(choice: &str) -> bool { let options: &str = constants::YES_OPTIONS; let lower_choice: &str = &choice.to_lowercase(); options.contains(lower_choice) } pub fn play_again(round: u32, cards: Vec<Card>, callback: &Fn(Vec<Card>, u32)) { println!("Play again?"); let trimmed = user_input::take(); utils::clear_console(); if player_answers_yes(&trimmed) { let next_round = round + 1; let next_round_deck = if cards.len() < 25 { deck::get_shuffled_deck() } else { cards }; callback(next_round_deck, next_round); } else { println!("Bye!"); } }
use super::{ context::UseProvider, fiber::Fiber, heap::{Closure, Text}, }; use crate::{ heap::{HirId, InlineObject}, tracer::FiberTracer, }; use candy_frontend::{ hir::Id, module::{Module, UsePath}, rich_ir::ToRichIr, }; impl<FT: FiberTracer> Fiber<FT> { pub fn use_module( &mut self, use_provider: &dyn UseProvider, current_module: Module, relative_path: InlineObject, ) -> Result<(), String> { let path: Text = relative_path .try_into() .map_err(|_| "The path has to be a text.".to_string())?; let target = UsePath::parse(path.get())?; let module = target.resolve_relative_to(current_module)?; let lir = use_provider .use_module(module.clone()) .ok_or_else(|| format!("`use` couldn't import the module `{module}`."))?; let closure = Closure::create_from_module_lir(&mut self.heap, lir.as_ref().to_owned()); let responsible = HirId::create(&mut self.heap, Id::dummy()); self.call_closure(closure, &[], responsible); Ok(()) } }
use serde::{Deserialize, Serialize}; use crate::smp::SMPool; use chrono::Utc; #[repr(C)] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct SignalData { running: bool, } impl Default for SignalData { fn default() -> Self { Self { running: true } } } #[derive(Clone)] pub struct SignalHandler { pool: SMPool<SignalData>, } unsafe impl Send for SignalHandler {} impl Default for SignalHandler { fn default() -> Self { let time = Utc::now(); let name = time.timestamp_nanos().to_string(); Self { pool: SMPool::create(name).unwrap(), } } } impl SignalHandler { pub fn load(id: &str) -> Self { Self { pool: SMPool::open(id).unwrap(), } } pub fn name(&self) -> &str { self.pool.name() } pub fn get_running(&self) -> bool { self.pool.with_inner(|x| x.running).unwrap() } pub fn set_running(&self, running: bool) { self.pool.with_inner(|x| x.running = running).unwrap() } }
#[doc = "Reader of register MBMON"] pub type R = crate::R<u32, super::MBMON>; #[doc = "Reader of field `SCL`"] pub type SCL_R = crate::R<bool, bool>; #[doc = "Reader of field `SDA`"] pub type SDA_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - I2C SCL Status"] #[inline(always)] pub fn scl(&self) -> SCL_R { SCL_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - I2C SDA Status"] #[inline(always)] pub fn sda(&self) -> SDA_R { SDA_R::new(((self.bits >> 1) & 0x01) != 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 std::fmt::Display; use std::fmt::Formatter; use common_meta_app::principal::FileFormatOptions; use common_meta_app::principal::PrincipalIdentity; use common_meta_app::principal::UserIdentity; use super::*; use crate::ast::write_comma_separated_list; use crate::ast::Expr; use crate::ast::Identifier; use crate::ast::Query; use crate::ast::TableReference; // SQL statement #[allow(clippy::large_enum_variant)] #[derive(Debug, Clone, PartialEq)] pub enum Statement { Query(Box<Query>), Explain { kind: ExplainKind, query: Box<Statement>, }, ExplainAnalyze { query: Box<Statement>, }, Copy(CopyStmt), Call(CallStmt), ShowSettings { like: Option<String>, }, ShowProcessList, ShowMetrics, ShowEngines, ShowFunctions { limit: Option<ShowLimit>, }, ShowTableFunctions { limit: Option<ShowLimit>, }, KillStmt { kill_target: KillTarget, object_id: String, }, SetVariable { is_global: bool, variable: Identifier, value: Box<Expr>, }, UnSetVariable(UnSetStmt), SetRole { is_default: bool, role_name: String, }, Insert(InsertStmt), Replace(ReplaceStmt), Delete { table_reference: TableReference, selection: Option<Expr>, }, Update(UpdateStmt), // Catalogs ShowCatalogs(ShowCatalogsStmt), ShowCreateCatalog(ShowCreateCatalogStmt), CreateCatalog(CreateCatalogStmt), DropCatalog(DropCatalogStmt), // Databases ShowDatabases(ShowDatabasesStmt), ShowCreateDatabase(ShowCreateDatabaseStmt), CreateDatabase(CreateDatabaseStmt), DropDatabase(DropDatabaseStmt), UndropDatabase(UndropDatabaseStmt), AlterDatabase(AlterDatabaseStmt), UseDatabase { database: Identifier, }, // Tables ShowTables(ShowTablesStmt), ShowCreateTable(ShowCreateTableStmt), DescribeTable(DescribeTableStmt), ShowTablesStatus(ShowTablesStatusStmt), CreateTable(CreateTableStmt), DropTable(DropTableStmt), UndropTable(UndropTableStmt), AlterTable(AlterTableStmt), RenameTable(RenameTableStmt), TruncateTable(TruncateTableStmt), OptimizeTable(OptimizeTableStmt), AnalyzeTable(AnalyzeTableStmt), ExistsTable(ExistsTableStmt), // Columns ShowColumns(ShowColumnsStmt), // Views CreateView(CreateViewStmt), AlterView(AlterViewStmt), DropView(DropViewStmt), // User ShowUsers, CreateUser(CreateUserStmt), AlterUser(AlterUserStmt), DropUser { if_exists: bool, user: UserIdentity, }, ShowRoles, CreateRole { if_not_exists: bool, role_name: String, }, DropRole { if_exists: bool, role_name: String, }, Grant(GrantStmt), ShowGrants { principal: Option<PrincipalIdentity>, }, Revoke(RevokeStmt), // UDF CreateUDF { if_not_exists: bool, udf_name: Identifier, parameters: Vec<Identifier>, definition: Box<Expr>, description: Option<String>, }, DropUDF { if_exists: bool, udf_name: Identifier, }, AlterUDF { udf_name: Identifier, parameters: Vec<Identifier>, definition: Box<Expr>, description: Option<String>, }, // Stages CreateStage(CreateStageStmt), ShowStages, DropStage { if_exists: bool, stage_name: String, }, DescribeStage { stage_name: String, }, RemoveStage { location: String, pattern: String, }, ListStage { location: String, pattern: String, }, // UserDefinedFileFormat CreateFileFormat { if_not_exists: bool, name: String, file_format_options: FileFormatOptions, }, DropFileFormat { if_exists: bool, name: String, }, ShowFileFormats, Presign(PresignStmt), // share CreateShare(CreateShareStmt), DropShare(DropShareStmt), GrantShareObject(GrantShareObjectStmt), RevokeShareObject(RevokeShareObjectStmt), AlterShareTenants(AlterShareTenantsStmt), DescShare(DescShareStmt), ShowShares(ShowSharesStmt), ShowObjectGrantPrivileges(ShowObjectGrantPrivilegesStmt), ShowGrantsOfShare(ShowGrantsOfShareStmt), } #[derive(Debug, Clone, PartialEq)] pub struct StatementMsg { pub(crate) stmt: Statement, pub(crate) format: Option<String>, } impl Statement { pub fn to_mask_sql(&self) -> String { match self { Statement::Copy(copy) => { let mut copy_clone = copy.clone(); if let CopyUnit::UriLocation(location) = &mut copy_clone.src { location.connection = location.connection.mask() } if let CopyUnit::UriLocation(location) = &mut copy_clone.dst { location.connection = location.connection.mask() } format!("{}", Statement::Copy(copy_clone)) } Statement::CreateStage(stage) => { let mut stage_clone = stage.clone(); if let Some(location) = &mut stage_clone.location { location.connection = location.connection.mask() } format!("{}", Statement::CreateStage(stage_clone)) } _ => format!("{}", self), } } } impl Display for Statement { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Statement::Explain { kind, query } => { write!(f, "EXPLAIN")?; match *kind { ExplainKind::Ast(_) => write!(f, " AST")?, ExplainKind::Syntax(_) => write!(f, " SYNTAX")?, ExplainKind::Graph => write!(f, " GRAPH")?, ExplainKind::Pipeline => write!(f, " PIPELINE")?, ExplainKind::Fragments => write!(f, " FRAGMENTS")?, ExplainKind::Raw => write!(f, " RAW")?, ExplainKind::Plan => (), ExplainKind::AnalyzePlan => write!(f, " ANALYZE")?, ExplainKind::JOIN => write!(f, " JOIN")?, ExplainKind::Memo(_) => write!(f, " MEMO")?, } write!(f, " {query}")?; } Statement::ExplainAnalyze { query } => { write!(f, "EXPLAIN ANALYZE {query}")?; } Statement::Query(query) => write!(f, "{query}")?, Statement::Insert(insert) => write!(f, "{insert}")?, Statement::Replace(replace) => write!(f, "{replace}")?, Statement::Delete { table_reference, selection, .. } => { write!(f, "DELETE FROM {table_reference}")?; if let Some(conditions) = selection { write!(f, "WHERE {conditions} ")?; } } Statement::Update(update) => write!(f, "{update}")?, Statement::Copy(stmt) => write!(f, "{stmt}")?, Statement::ShowSettings { like } => { write!(f, "SHOW SETTINGS")?; if like.is_some() { write!(f, " LIKE '{}'", like.as_ref().unwrap())?; } } Statement::ShowProcessList => write!(f, "SHOW PROCESSLIST")?, Statement::ShowMetrics => write!(f, "SHOW METRICS")?, Statement::ShowEngines => write!(f, "SHOW ENGINES")?, Statement::ShowFunctions { limit } => { write!(f, "SHOW FUNCTIONS")?; if let Some(limit) = limit { write!(f, " {limit}")?; } } Statement::ShowTableFunctions { limit } => { write!(f, "SHOW TABLE_FUNCTIONS")?; if let Some(limit) = limit { write!(f, " {limit}")?; } } Statement::KillStmt { kill_target, object_id, } => { write!(f, "KILL")?; match *kill_target { KillTarget::Query => write!(f, " QUERY")?, KillTarget::Connection => write!(f, " CONNECTION")?, } write!(f, " '{object_id}'")?; } Statement::SetVariable { is_global, variable, value, } => { write!(f, "SET ")?; if *is_global { write!(f, "GLOBAL ")?; } write!(f, "{variable} = {value}")?; } Statement::UnSetVariable(unset) => write!(f, "{unset}")?, Statement::SetRole { is_default, role_name, } => { write!(f, "SET ROLE ")?; if *is_default { write!(f, "DEFAULT")?; } else { write!(f, "{role_name}")?; } } Statement::ShowCatalogs(stmt) => write!(f, "{stmt}")?, Statement::ShowCreateCatalog(stmt) => write!(f, "{stmt}")?, Statement::CreateCatalog(stmt) => write!(f, "{stmt}")?, Statement::DropCatalog(stmt) => write!(f, "{stmt}")?, Statement::ShowDatabases(stmt) => write!(f, "{stmt}")?, Statement::ShowCreateDatabase(stmt) => write!(f, "{stmt}")?, Statement::CreateDatabase(stmt) => write!(f, "{stmt}")?, Statement::DropDatabase(stmt) => write!(f, "{stmt}")?, Statement::UndropDatabase(stmt) => write!(f, "{stmt}")?, Statement::AlterDatabase(stmt) => write!(f, "{stmt}")?, Statement::UseDatabase { database } => write!(f, "USE {database}")?, Statement::ShowTables(stmt) => write!(f, "{stmt}")?, Statement::ShowColumns(stmt) => write!(f, "{stmt}")?, Statement::ShowCreateTable(stmt) => write!(f, "{stmt}")?, Statement::DescribeTable(stmt) => write!(f, "{stmt}")?, Statement::ShowTablesStatus(stmt) => write!(f, "{stmt}")?, Statement::CreateTable(stmt) => write!(f, "{stmt}")?, Statement::DropTable(stmt) => write!(f, "{stmt}")?, Statement::UndropTable(stmt) => write!(f, "{stmt}")?, Statement::AlterTable(stmt) => write!(f, "{stmt}")?, Statement::RenameTable(stmt) => write!(f, "{stmt}")?, Statement::TruncateTable(stmt) => write!(f, "{stmt}")?, Statement::OptimizeTable(stmt) => write!(f, "{stmt}")?, Statement::AnalyzeTable(stmt) => write!(f, "{stmt}")?, Statement::ExistsTable(stmt) => write!(f, "{stmt}")?, Statement::CreateView(stmt) => write!(f, "{stmt}")?, Statement::AlterView(stmt) => write!(f, "{stmt}")?, Statement::DropView(stmt) => write!(f, "{stmt}")?, Statement::ShowUsers => write!(f, "SHOW USERS")?, Statement::ShowRoles => write!(f, "SHOW ROLES")?, Statement::CreateUser(stmt) => write!(f, "{stmt}")?, Statement::AlterUser(stmt) => write!(f, "{stmt}")?, Statement::DropUser { if_exists, user } => { write!(f, "DROP USER")?; if *if_exists { write!(f, " IF EXISTS")?; } write!(f, " {user}")?; } Statement::CreateRole { if_not_exists, role_name: role, } => { write!(f, "CREATE ROLE")?; if *if_not_exists { write!(f, " IF NOT EXISTS")?; } write!(f, " '{role}'")?; } Statement::DropRole { if_exists, role_name: role, } => { write!(f, "DROP ROLE")?; if *if_exists { write!(f, " IF EXISTS")?; } write!(f, " '{role}'")?; } Statement::Grant(stmt) => write!(f, "{stmt}")?, Statement::ShowGrants { principal } => { write!(f, "SHOW GRANTS")?; if let Some(principal) = principal { write!(f, " FOR")?; write!(f, "{principal}")?; } } Statement::Revoke(stmt) => write!(f, "{stmt}")?, Statement::CreateUDF { if_not_exists, udf_name, parameters, definition, description, } => { write!(f, "CREATE FUNCTION")?; if *if_not_exists { write!(f, " IF NOT EXISTS")?; } write!(f, " {udf_name} AS (")?; write_comma_separated_list(f, parameters)?; write!(f, ") -> {definition}")?; if let Some(description) = description { write!(f, " DESC = '{description}'")?; } } Statement::DropUDF { if_exists, udf_name, } => { write!(f, "DROP FUNCTION")?; if *if_exists { write!(f, " IF EXISTS")?; } write!(f, " {udf_name}")?; } Statement::AlterUDF { udf_name, parameters, definition, description, } => { write!(f, "ALTER FUNCTION {udf_name} AS (")?; write_comma_separated_list(f, parameters)?; write!(f, ") -> {definition}")?; if let Some(description) = description { write!(f, " DESC = '{description}'")?; } } Statement::ListStage { location, pattern } => { write!(f, "LIST @{location}")?; if !pattern.is_empty() { write!(f, " PATTERN = '{pattern}'")?; } } Statement::ShowStages => write!(f, "SHOW STAGES")?, Statement::DropStage { if_exists, stage_name, } => { write!(f, "DROP STAGES")?; if *if_exists { write!(f, " IF EXISTS")?; } write!(f, " {stage_name}")?; } Statement::CreateStage(stmt) => write!(f, "{stmt}")?, Statement::RemoveStage { location, pattern } => { write!(f, "REMOVE STAGE @{location}")?; if !pattern.is_empty() { write!(f, " PATTERN = '{pattern}'")?; } } Statement::DescribeStage { stage_name } => write!(f, "DESC STAGE {stage_name}")?, Statement::CreateFileFormat { if_not_exists, name, file_format_options, } => { write!(f, "CREATE FILE_FORMAT")?; if *if_not_exists { write!(f, " IF NOT EXISTS")?; } write!(f, " {name}")?; write!(f, " {file_format_options}")?; } Statement::DropFileFormat { if_exists, name } => { write!(f, "DROP FILE_FORMAT")?; if *if_exists { write!(f, " IF EXISTS")?; } write!(f, " {name}")?; } Statement::ShowFileFormats => write!(f, "SHOW FILE FORMATS")?, Statement::Call(stmt) => write!(f, "{stmt}")?, Statement::Presign(stmt) => write!(f, "{stmt}")?, Statement::CreateShare(stmt) => write!(f, "{stmt}")?, Statement::DropShare(stmt) => write!(f, "{stmt}")?, Statement::GrantShareObject(stmt) => write!(f, "{stmt}")?, Statement::RevokeShareObject(stmt) => write!(f, "{stmt}")?, Statement::AlterShareTenants(stmt) => write!(f, "{stmt}")?, Statement::DescShare(stmt) => write!(f, "{stmt}")?, Statement::ShowShares(stmt) => write!(f, "{stmt}")?, Statement::ShowObjectGrantPrivileges(stmt) => write!(f, "{stmt}")?, Statement::ShowGrantsOfShare(stmt) => write!(f, "{stmt}")?, } Ok(()) } }
//! The search process. use crate::{ cells::{CellRef, State}, config::NewState, rules::Rule, world::World, }; use rand::{thread_rng, Rng}; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; /// Search status. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] pub enum Status { /// Initial status. Waiting to start. Initial, /// A result is found. Found, /// Such pattern does not exist. None, /// Still searching. Searching, /// Paused. Paused, } /// Reasons for setting a cell. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] pub(crate) enum Reason { /// Decides the state of a cell by choice, /// and remembers its position in the `search_list` of the world. Decide(usize), /// Determines the state of a cell by other cells. Deduce, /// Tries another state of a cell when the original state /// leads to a conflict. /// /// Remembers its position in the `search_list` of the world, /// and the number of remaining states to try. TryAnother(usize, usize), } /// Records the cells whose values are set and their reasons. #[derive(Clone, Copy)] pub(crate) struct SetCell<'a, R: Rule> { /// The set cell. pub(crate) cell: CellRef<'a, R>, /// The reason for setting a cell. pub(crate) reason: Reason, } impl<'a, R: Rule> SetCell<'a, R> { /// Get a reference to the set cell. pub(crate) fn new(cell: CellRef<'a, R>, reason: Reason) -> Self { SetCell { cell, reason } } } impl<'a, R: Rule> World<'a, R> { /// Consistifies a cell. /// /// Examines the state and the neighborhood descriptor of the cell, /// and makes sure that it can validly produce the cell in the next /// generation. If possible, determines the states of some of the /// cells involved. /// /// Returns `false` if there is a conflict, /// `true` if the cells are consistent. fn consistify(&mut self, cell: CellRef<'a, R>) -> bool { Rule::consistify(self, cell) } /// Consistifies a cell, its neighbors, and its predecessor. /// /// Returns `false` if there is a conflict, /// `true` if the cells are consistent. fn consistify10(&mut self, cell: CellRef<'a, R>) -> bool { self.consistify(cell) && { if let Some(pred) = cell.pred { self.consistify(pred) } else { true } } && cell .nbhd .iter() .all(|&neigh| self.consistify(neigh.unwrap())) } /// Deduces all the consequences by `consistify` and symmetry. /// /// Returns `false` if there is a conflict, /// `true` if the cells are consistent. fn proceed(&mut self) -> bool { while self.check_index < self.set_stack.len() { let cell = self.set_stack[self.check_index].cell; let state = cell.state.get().unwrap(); // Determines some cells by symmetry. for &sym in cell.sym.iter() { if let Some(old_state) = sym.state.get() { if state != old_state { return false; } } else if !self.set_cell(sym, state, Reason::Deduce) { return false; } } // Determines some cells by `consistify`. if !self.consistify10(cell) { return false; } self.check_index += 1; } true } /// Backtracks to the last time when a unknown cell is decided by choice, /// and switch that cell to the other state. /// /// Returns `true` if it backtracks successfully, /// `false` if it goes back to the time before the first cell is set. fn backup(&mut self) -> bool { while let Some(set_cell) = self.set_stack.pop() { let cell = set_cell.cell; match set_cell.reason { Reason::Decide(i) => { self.check_index = self.set_stack.len(); self.search_index = i + 1; if R::IS_GEN { let State(j) = cell.state.get().unwrap(); let state = State((j + 1) % self.rule.gen()); self.clear_cell(cell); if self.set_cell(cell, state, Reason::TryAnother(i, self.rule.gen() - 2)) { return true; } } else { let state = !cell.state.get().unwrap(); self.clear_cell(cell); if self.set_cell(cell, state, Reason::Deduce) { return true; } } } Reason::TryAnother(i, n) => { self.check_index = self.set_stack.len(); self.search_index = i + 1; let State(j) = cell.state.get().unwrap(); let state = State((j + 1) % self.rule.gen()); self.clear_cell(cell); let reason = if n == 1 { Reason::Deduce } else { Reason::TryAnother(i, n - 1) }; if self.set_cell(cell, state, reason) { return true; } } Reason::Deduce => { self.clear_cell(cell); } } } self.check_index = 0; self.search_index = 0; false } /// Keeps proceeding and backtracking, /// until there are no more cells to examine (and returns `true`), /// or the backtracking goes back to the time before the first cell is set /// (and returns `false`). /// /// It also records the number of steps it has walked in the parameter /// `step`. A step consists of a `proceed` and a `backup`. /// /// The difference between `step` and `self.steps` is that the former /// will be reset in each `search`. fn go(&mut self, step: &mut u64) -> bool { loop { *step += 1; if self.proceed() { return true; } else { self.conflicts += 1; if !self.backup() { return false; } } } } /// Makes a decision. /// /// Chooses an unknown cell, assigns a state for it, /// and push a reference to it to the `set_stack`. /// /// Returns `None` is there is no unknown cell, /// `Some(false)` if the new state leads to an immediate conflict. fn decide(&mut self) -> Option<bool> { if let Some((i, cell)) = self.get_unknown(self.search_index) { self.search_index = i + 1; let state = match self.config.new_state { NewState::ChooseDead => cell.background, NewState::ChooseAlive => !cell.background, NewState::Random => State(thread_rng().gen_range(0, self.rule.gen())), }; Some(self.set_cell(cell, state, Reason::Decide(i))) } else { None } } /// The search function. /// /// Returns `Found` if a result is found, /// `None` if such pattern does not exist, /// `Searching` if the number of steps exceeds `max_step` /// and no results are found. pub fn search(&mut self, max_step: Option<u64>) -> Status { let mut step_count = 0; if self.get_unknown(0).is_none() && !self.backup() { return Status::None; } while self.go(&mut step_count) { if let Some(result) = self.decide() { if !result && !self.backup() { return Status::None; } } else if self.nontrivial() { if self.config.reduce_max { self.config.max_cell_count = Some(self.cell_count() - 1); } return Status::Found; } else if !self.backup() { return Status::None; } if let Some(max) = max_step { if step_count > max { return Status::Searching; } } } Status::None } /// Set the max cell counts. pub(crate) fn set_max_cell_count(&mut self, max_cell_count: Option<usize>) { self.config.max_cell_count = max_cell_count; if let Some(max) = self.config.max_cell_count { while self.cell_count() > max { if !self.backup() { break; } } } } }
use std::collections::HashMap; pub fn count(nucleotide: char, dna: &str) -> Result<usize, char> { let is_valid = |c| match c { 'A' | 'C' | 'G' | 'T' => true, _ => false, }; if !is_valid(nucleotide) { return Err(nucleotide); } let mut sum = 0; for c in dna.chars() { if !is_valid(c) { return Err(c); } if c == nucleotide { sum += 1; } } Ok(sum) } pub fn nucleotide_counts(dna: &str) -> Result<HashMap<char, usize>, char> { ['A', 'C', 'G', 'T'] .iter() .map(|c| count(*c, dna).map(|count| (*c, count))) .collect() }
use std::cmp::{min, max}; #[derive(PartialEq, Eq)] struct Item { name: &'static str, cost: i32, damage: i32, armor: i32, } const WEAPONS: [Item; 5] = [ Item{name: "Dagger", cost: 8, damage: 4, armor: 0}, Item{name: "Shortsword", cost: 10, damage: 5, armor: 0}, Item{name: "Warhammer", cost: 25, damage: 6, armor: 0}, Item{name: "Longsword", cost: 40, damage: 7, armor: 0}, Item{name: "Greataxe", cost: 74, damage: 8, armor: 0}, ]; const ARMOR: [Item; 6] = [ Item{name: "None", cost: 0, damage: 0, armor: 0}, Item{name: "Leather", cost: 13, damage: 0, armor: 1}, Item{name: "Chainmail", cost: 31, damage: 0, armor: 2}, Item{name: "Splintmail", cost: 53, damage: 0, armor: 3}, Item{name: "Bandedmail", cost: 75, damage: 0, armor: 4}, Item{name: "Platemail", cost: 102, damage: 0, armor: 5}, ]; const RINGS: [Item; 8] = [ Item{name: "None", cost: 0, damage: 0, armor: 0}, Item{name: "None", cost: 0, damage: 0, armor: 0}, Item{name: "Damage +1", cost: 25, damage: 1, armor: 0}, Item{name: "Damage +2", cost: 50, damage: 2, armor: 0}, Item{name: "Damage +3", cost: 100, damage: 3, armor: 0}, Item{name: "Defense +1", cost: 20, damage: 0, armor: 1}, Item{name: "Defense +2", cost: 40, damage: 0, armor: 2}, Item{name: "Defense +3", cost: 80, damage: 0, armor: 3}, ]; const BOSS_HIT_POINTS: i32 = 100; const BOSS_ARMOR: i32 = 2; const BOSS_DAMAGE: i32 = 8; const PLAYER_HIT_POINTS: i32 = 100; fn simulate(player_damage: i32, player_armor: i32) -> bool { let mut boss_health = BOSS_HIT_POINTS; let mut player_health = PLAYER_HIT_POINTS; loop { boss_health -= max(1, player_damage - BOSS_ARMOR); if boss_health <= 0 { return true; } player_health -= max(1, BOSS_DAMAGE - player_armor); if player_health <= 0 { return false; } } } fn main() { let mut best_win = 1000000; let mut worst_loss = 0; for w in WEAPONS.into_iter() { for a in ARMOR.into_iter() { for r in RINGS.into_iter() { for s in RINGS.into_iter() { if r == s { continue } let cost = w.cost + a.cost + r.cost + s.cost; let pl_dam = w.damage + a.damage + r.damage + s.damage; let pl_arm = w.armor + a.armor + r.armor + s.armor; if simulate(pl_dam, pl_arm) { best_win = min(best_win, cost); } else { worst_loss = max(worst_loss, cost); } } } } } println!("{}", best_win); println!("{}", worst_loss); }
pub const UNSAFE_HINT: &str = r#" // For `pin_utils` crate, // consider replacing it with `pin_project` or `pin_project_lite` // since they can detect any unsafe usage. "#; pub const FUNCTOR_HINT: &str = r#" // For Option or Result: // Bad if a.is_some() { let a = opt.unwrap(); a.do_something(); } // Good if let Some(a) = opt { a.do_something(); } // Good opt.map(|a| a.do_something())? // Good: tranform it to result opt.map(|a| a.do_something()).ok_or_else(|| some_err)? // Consider using `and_then` or `or_else` for nested Option and Result. opt.and_then(|a| func_produce_option(a)) // result is a single layer Option "#; pub const INDEX_EXPR_HINT: &str = r#" // Here variable `arr` can be array, Vec, String, and so on. // Bad if arr.len() >= 3 { let v = arr[2]; v.do_something(); } // Good if let Some(v) = arr.get(2) { v.do_something(); } // Bad if "value" == &arr[..5] { do_something(); } // Good let sub_str = arr.get(..5).ok_or_else(|| some_err)?; if "value" == sub_str { do_something(); } "#;
use std::collections::VecDeque; pub type Item = usize; #[aoc_generator(day9)] pub fn input_generator(input: &str) -> Vec<Item> { input.lines().map(|s| s.parse().unwrap()).collect() } #[aoc(day9, part1)] pub fn solve_part1(input: &[Item]) -> usize { validate(25, input.to_vec()).unwrap() } fn validate(preamble_size: usize, xs: Vec<Item>) -> Option<usize> { let mut buf = VecDeque::with_capacity(5); let mut it = xs.into_iter(); for _ in 0..preamble_size { buf.push_back(it.next().unwrap()); } for i in it { if !check_sums(i, &buf) { return Some(i); } buf.pop_front(); buf.push_back(i); } None } fn check_sums(target: usize, buf: &VecDeque<usize>) -> bool { for (i, x) in buf.iter().enumerate() { for (j, y) in buf.iter().enumerate() { if i == j { continue; } if x + y == target { return true; } } } false } fn find_weakness(target: usize, pos: usize, buf: &[usize]) -> usize { for idx in pos..buf.len() { let sum: usize = buf[pos..idx].iter().sum(); if sum == target { return buf[pos..idx].iter().min().unwrap() + buf[pos..idx].iter().max().unwrap(); } else if sum > target { return find_weakness(target, pos + 1, buf); } } unreachable!() } #[aoc(day9, part2)] pub fn solve_part2(input: &[Item]) -> usize { let xs = input.to_vec(); let target = validate(25, xs).unwrap(); find_weakness(target, 0, input) } #[cfg(test)] mod tests { #![allow(unused)] use super::*; const INPUT: &str = r##"35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576"##; #[test] fn test_something() { assert_eq!(127, validate(5, input_generator(INPUT)).unwrap()); } #[test] fn test_something2() { let input = input_generator(INPUT); assert_eq!(127, validate(5, input.to_vec()).unwrap()); assert_eq!(62, find_weakness(127, 0, &input)); } }
#![feature(use_extern_macros)] extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen] /// A user defined comment pub struct Comment { name: String, comment: String, /// The position this comment /// should exist at pub count: u32, color: Color, } #[wasm_bindgen] impl Comment { #[wasm_bindgen(method)] /// The name of the user who /// posted this comment pub fn name(&self) -> String { self.name.clone() } #[wasm_bindgen(method)] /// The content of this comment pub fn comment(&self) -> String { self.comment.clone() } #[wasm_bindgen(constructor)] pub fn new(name: String, comment: String, count: u32) -> Comment { let color = if count % 2 == 0 { Color::Blue } else { Color::Pink }; Comment { name, comment, count, color, } } #[wasm_bindgen(method)] /// What color should this comment be pub fn color(&self) -> Color { self.color.clone() } } /// The border of a comment #[wasm_bindgen] #[derive(Clone)] pub enum Color { Blue, Pink, }
#[doc = "Reader of register ICACHE_CRR1"] pub type R = crate::R<u32, super::ICACHE_CRR1>; #[doc = "Writer for register ICACHE_CRR1"] pub type W = crate::W<u32, super::ICACHE_CRR1>; #[doc = "Register ICACHE_CRR1 `reset()`'s with value 0x0200"] impl crate::ResetValue for super::ICACHE_CRR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0200 } } #[doc = "Reader of field `BASEADDR`"] pub type BASEADDR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `BASEADDR`"] pub struct BASEADDR_W<'a> { w: &'a mut W, } impl<'a> BASEADDR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff); self.w } } #[doc = "Reader of field `RSIZE`"] pub type RSIZE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RSIZE`"] pub struct RSIZE_W<'a> { w: &'a mut W, } impl<'a> RSIZE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 9)) | (((value as u32) & 0x07) << 9); self.w } } #[doc = "Reader of field `REN`"] pub type REN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `REN`"] pub struct REN_W<'a> { w: &'a mut W, } impl<'a> REN_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 `REMAPADDR`"] pub type REMAPADDR_R = crate::R<u16, u16>; #[doc = "Write proxy for field `REMAPADDR`"] pub struct REMAPADDR_W<'a> { w: &'a mut W, } impl<'a> REMAPADDR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07ff << 16)) | (((value as u32) & 0x07ff) << 16); self.w } } #[doc = "Reader of field `MSTSEL`"] pub type MSTSEL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MSTSEL`"] pub struct MSTSEL_W<'a> { w: &'a mut W, } impl<'a> MSTSEL_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 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `HBURST`"] pub type HBURST_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HBURST`"] pub struct HBURST_W<'a> { w: &'a mut W, } impl<'a> HBURST_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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bits 0:7 - BASEADDR"] #[inline(always)] pub fn baseaddr(&self) -> BASEADDR_R { BASEADDR_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 9:11 - RSIZE"] #[inline(always)] pub fn rsize(&self) -> RSIZE_R { RSIZE_R::new(((self.bits >> 9) & 0x07) as u8) } #[doc = "Bit 15 - REN"] #[inline(always)] pub fn ren(&self) -> REN_R { REN_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bits 16:26 - REMAPADDR"] #[inline(always)] pub fn remapaddr(&self) -> REMAPADDR_R { REMAPADDR_R::new(((self.bits >> 16) & 0x07ff) as u16) } #[doc = "Bit 28 - MSTSEL"] #[inline(always)] pub fn mstsel(&self) -> MSTSEL_R { MSTSEL_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 31 - HBURST"] #[inline(always)] pub fn hburst(&self) -> HBURST_R { HBURST_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:7 - BASEADDR"] #[inline(always)] pub fn baseaddr(&mut self) -> BASEADDR_W { BASEADDR_W { w: self } } #[doc = "Bits 9:11 - RSIZE"] #[inline(always)] pub fn rsize(&mut self) -> RSIZE_W { RSIZE_W { w: self } } #[doc = "Bit 15 - REN"] #[inline(always)] pub fn ren(&mut self) -> REN_W { REN_W { w: self } } #[doc = "Bits 16:26 - REMAPADDR"] #[inline(always)] pub fn remapaddr(&mut self) -> REMAPADDR_W { REMAPADDR_W { w: self } } #[doc = "Bit 28 - MSTSEL"] #[inline(always)] pub fn mstsel(&mut self) -> MSTSEL_W { MSTSEL_W { w: self } } #[doc = "Bit 31 - HBURST"] #[inline(always)] pub fn hburst(&mut self) -> HBURST_W { HBURST_W { w: self } } }
use gl_bindings::gl; use std::ffi::CString; pub struct UniformLocationCache { uniform_name: CString, cached_program_gl: gl::uint, cached_location: gl::int, } impl UniformLocationCache { pub fn get(&mut self, program_gl: gl::uint) -> Option<gl::int> { if self.cached_program_gl != program_gl || self.cached_location == 0 { self.cached_program_gl = program_gl; self.cached_location = unsafe { let name_ptr = self.uniform_name.as_ptr() as *const gl::char; gl::GetUniformLocation(program_gl, name_ptr) }; } if self.cached_location != 0 { Some(self.cached_location) } else { None } } pub fn new(uniform_name: &str) -> Self { Self { uniform_name: CString::new(uniform_name).unwrap(), cached_program_gl: 0, cached_location: 0, } } } //pub struct Uniform<T: UniformValue> { // //}
#[macro_use] extern crate error_chain; mod errors; use errors::*; fn run_lazy() -> Result<()> { let input = [2, 2, 3]; let iterator = input.iter(); let mapped = iterator .inspect(|&x| println!("Pre map:\t{}", x)) .map(|&x| x * 10) // This gets fed into... .inspect(|&x| println!("First map:\t{}", x)) .map(|x| x + 5) // ... This. .inspect(|&x| println!("Second map:\t{}", x)); let a = mapped.collect::<Vec<usize>>(); println!("{:?}", a); Ok(()) } pub fn run() { let run = run_lazy; if let Err(ref e) = run() { println!("error: {}", e); for e in e.iter().skip(1) { println!(" caused by: {}", e); } if let Some(backtrace) = e.backtrace() { println!("backtrace: {:?}", backtrace); } std::process::exit(1) } }
use crate::{ domain::{EpochHeight, StakeTokenValue, YoctoNear, YoctoStake}, near::UNSTAKED_NEAR_FUNDS_NUM_EPOCHS_TO_UNLOCK, }; use near_sdk::{ borsh::{self, BorshDeserialize, BorshSerialize}, env, }; #[derive(BorshSerialize, BorshDeserialize, Clone, Copy, Debug)] pub struct RedeemStakeBatchReceipt { redeemed_stake: YoctoStake, stake_token_value: StakeTokenValue, } impl RedeemStakeBatchReceipt { pub fn new(redeemed_stake: YoctoStake, stake_token_value: StakeTokenValue) -> Self { Self { redeemed_stake, stake_token_value, } } /// used to track claims against the receipt - as accounts claim NEAR funds for the STAKE they /// redeemed in the batch, the STAKE is debited /// - when all NEAR funds are claimed, i.e., then the receipt is deleted from storage pub fn redeemed_stake(&self) -> YoctoStake { self.redeemed_stake } /// returns the STAKE token value at the point in time when the batch was run pub fn stake_token_value(&self) -> StakeTokenValue { self.stake_token_value } /// returns the epoch within which the unstaked NEAR funds will be available for withdrawal from /// the staking pool pub fn unstaked_near_withdrawal_availability(&self) -> EpochHeight { self.stake_token_value.block_time_height().epoch_height() + UNSTAKED_NEAR_FUNDS_NUM_EPOCHS_TO_UNLOCK } /// returns true if unstaked funds are available to withdraw, i.e., at least 3 epochs have passed /// since the funds were unstaked pub fn unstaked_funds_available_for_withdrawal(&self) -> bool { self.unstaked_near_withdrawal_availability().value() <= env::epoch_height() } /// Used to track when an account has claimed their STAKE tokens for the NEAR they have staked pub fn stake_tokens_redeemed(&mut self, redeemed_stake: YoctoStake) { self.redeemed_stake -= redeemed_stake; } /// returns true if all NEAR tokens have been claimed for the redeemed STAKE tokens, i.e., when /// [redeemed_stake](RedeemStakeBatchReceipt::redeemed_stake) balance is zero pub fn all_claimed(&self) -> bool { self.redeemed_stake.value() == 0 } /// converts the redeemed STAKE tokens into NEAR tokens based on the receipt's [stake_token_value](RedeemStakeBatchReceipt::stake_token_value) pub fn stake_near_value(&self) -> YoctoNear { self.stake_token_value.stake_to_near(self.redeemed_stake) } }
#[macro_use] extern crate log; #[macro_use] pub mod geometry; pub mod error; pub mod mydxf; pub mod rrxml; use crate::geometry::traits::relative::Relative; use crate::mydxf::MyDxf; use crate::rrxml::parcel::Parcel; use crate::rrxml::RrXml; pub fn check_mydxf_in_rrxmls(mydxf: &MyDxf, rrxmls: Vec<RrXml>) -> Option<Vec<Parcel>> { let mut parcels = vec![]; for rrxml in rrxmls { if let Some(ref mut parcel) = check_mydxf_in_rrxml(mydxf, &rrxml) { parcels.append(parcel); } } match parcels.len() { 0 => None, _ => Some(parcels), } } pub fn check_mydxf_in_rrxml(mydxf: &MyDxf, rrxml: &RrXml) -> Option<Vec<Parcel>> { if rrxml.is_empty() { return None; }; let mut parcels = vec![]; for parcel in &rrxml.parcels { if check_mydxf_in_parcel(&mydxf, &parcel) { parcels.push(parcel.clone()); } } match parcels.len() { 0 => None, _ => Some(parcels), } } pub fn check_mydxf_in_parcel(mydxf: &MyDxf, parcel: &Parcel) -> bool { match mydxf.entities.relate_entities(&parcel.entities) { Some(_) => { debug!("got intersect with {}", parcel.number); true } None => false, } } #[cfg(test)] mod test { use super::*; use crate::mydxf::MyDxf; use crate::rrxml::RrXml; use std::path::{Path, PathBuf}; #[test] fn test_dxf() { let rr_block = RrXml::from_file(PathBuf::from( r"src\test_files\xmls\KPT CadastralBlock 77 03 0009007.xml", )) .unwrap(); println!("{}", rr_block); let rr_parcel = RrXml::from_file(PathBuf::from( r"src\test_files\xmls\KVZU Parcel 21 01 010206 115.xml", )) .unwrap(); println!("{}", rr_parcel); let mydxf = MyDxf::from_file(PathBuf::from(r"src\test_files\mydxfs\6 1228.dxf")).unwrap(); println!("{:?}", mydxf); let res_block = check_mydxf_in_rrxml(&mydxf, &rr_block).unwrap(); assert_eq!(res_block.len(), 4); let res_parcel = check_mydxf_in_rrxml(&mydxf, &rr_parcel); assert!(res_parcel.is_none()); } #[test] fn test_from_rrtools_python() { let xml_dir = Path::new(r"src\test_files\tests_from_rrtools_python\xml"); let mut rrxmls = vec![]; for f in xml_dir.read_dir().expect("dir call error") { if let Ok(f) = f { if let Some(ext) = f.path().extension() { if ext == "xml" { let rrxml = RrXml::from_file(f.path()).unwrap(); rrxmls.push(rrxml); } } } } let mydxf = MyDxf::from_file(dxf_path(1)).unwrap(); let res = check_mydxf_in_rrxmls(&mydxf, rrxmls.clone()).unwrap(); assert_eq!(res.len(), 4); let mydxf = MyDxf::from_file(dxf_path(2)).unwrap(); let res = check_mydxf_in_rrxmls(&mydxf, rrxmls.clone()).unwrap(); assert_eq!(res.len(), 3); let mydxf = MyDxf::from_file(dxf_path(3)).unwrap(); let res = check_mydxf_in_rrxmls(&mydxf, rrxmls.clone()).unwrap(); assert_eq!(res.len(), 2); let mydxf = MyDxf::from_file(dxf_path(4)).unwrap(); let res = check_mydxf_in_rrxmls(&mydxf, rrxmls.clone()).unwrap(); assert_eq!(res.len(), 2); let mydxf = MyDxf::from_file(dxf_path(5)).unwrap(); let res = check_mydxf_in_rrxmls(&mydxf, rrxmls.clone()).unwrap(); assert_eq!(res.len(), 3); let mydxf = MyDxf::from_file(dxf_path(6)).unwrap(); let res = check_mydxf_in_rrxmls(&mydxf, rrxmls.clone()); assert!(res.is_none()); fn dxf_path(i: i32) -> PathBuf { PathBuf::from(format!( r"src\test_files\tests_from_rrtools_python\mydxf\test {}.dxf", i )) } } }
fn main() { println!("Hello, world!"); another_function(444, 666); statment_function(); } fn another_function(x: i32, y: i32) { println!("x = {}", x); println!("y = {}", y); } fn statment_function() { // unused variable let x = 5; let y = { let x = 3; x + 1 }; println!("y 的數值為:{}", y); }
// auto generated, do not modify. // created: Wed Jan 20 00:44:03 2016 // src-file: /QtNetwork/qnetworkreply.h // dst-file: /src/network/qnetworkreply.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::super::core::qiodevice::QIODevice; // 771 use std::ops::Deref; use super::super::core::qbytearray::QByteArray; // 771 use super::qnetworkrequest::QNetworkRequest; // 773 use super::qsslconfiguration::QSslConfiguration; // 773 use super::super::core::qurl::QUrl; // 771 use super::qnetworkaccessmanager::QNetworkAccessManager; // 773 use super::super::core::qobject::QObject; // 771 use super::qsslpresharedkeyauthenticator::QSslPreSharedKeyAuthenticator; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QNetworkReply_Class_Size() -> c_int; // proto: void QNetworkReply::ignoreSslErrors(); fn _ZN13QNetworkReply15ignoreSslErrorsEv(qthis: u64 /* *mut c_void*/); // proto: bool QNetworkReply::hasRawHeader(const QByteArray & headerName); fn _ZNK13QNetworkReply12hasRawHeaderERK10QByteArray(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char; // proto: void QNetworkReply::setReadBufferSize(qint64 size); fn _ZN13QNetworkReply17setReadBufferSizeEx(qthis: u64 /* *mut c_void*/, arg0: c_longlong); // proto: QNetworkRequest QNetworkReply::request(); fn _ZNK13QNetworkReply7requestEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QNetworkReply::abort(); fn _ZN13QNetworkReply5abortEv(qthis: u64 /* *mut c_void*/); // proto: bool QNetworkReply::isRunning(); fn _ZNK13QNetworkReply9isRunningEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QList<QByteArray> QNetworkReply::rawHeaderList(); fn _ZNK13QNetworkReply13rawHeaderListEv(qthis: u64 /* *mut c_void*/); // proto: const QList<RawHeaderPair> & QNetworkReply::rawHeaderPairs(); fn _ZNK13QNetworkReply14rawHeaderPairsEv(qthis: u64 /* *mut c_void*/); // proto: void QNetworkReply::setSslConfiguration(const QSslConfiguration & configuration); fn _ZN13QNetworkReply19setSslConfigurationERK17QSslConfiguration(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QUrl QNetworkReply::url(); fn _ZNK13QNetworkReply3urlEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QNetworkReply::isSequential(); fn _ZNK13QNetworkReply12isSequentialEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QByteArray QNetworkReply::rawHeader(const QByteArray & headerName); fn _ZNK13QNetworkReply9rawHeaderERK10QByteArray(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: QNetworkAccessManager * QNetworkReply::manager(); fn _ZNK13QNetworkReply7managerEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QNetworkReply::QNetworkReply(QObject * parent); fn _ZN13QNetworkReplyC2EP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QNetworkReply::close(); fn _ZN13QNetworkReply5closeEv(qthis: u64 /* *mut c_void*/); // proto: bool QNetworkReply::isFinished(); fn _ZNK13QNetworkReply10isFinishedEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: qint64 QNetworkReply::readBufferSize(); fn _ZNK13QNetworkReply14readBufferSizeEv(qthis: u64 /* *mut c_void*/) -> c_longlong; // proto: QSslConfiguration QNetworkReply::sslConfiguration(); fn _ZNK13QNetworkReply16sslConfigurationEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: const QMetaObject * QNetworkReply::metaObject(); fn _ZNK13QNetworkReply10metaObjectEv(qthis: u64 /* *mut c_void*/); // proto: void QNetworkReply::~QNetworkReply(); fn _ZN13QNetworkReplyD2Ev(qthis: u64 /* *mut c_void*/); fn QNetworkReply_SlotProxy_connect__ZN13QNetworkReply16downloadProgressExx(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QNetworkReply_SlotProxy_connect__ZN13QNetworkReply8finishedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QNetworkReply_SlotProxy_connect__ZN13QNetworkReply15metaDataChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QNetworkReply_SlotProxy_connect__ZN13QNetworkReply14uploadProgressExx(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QNetworkReply_SlotProxy_connect__ZN13QNetworkReply9encryptedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QNetworkReply_SlotProxy_connect__ZN13QNetworkReply34preSharedKeyAuthenticationRequiredEP29QSslPreSharedKeyAuthenticator(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QNetworkReply)=1 #[derive(Default)] pub struct QNetworkReply { qbase: QIODevice, pub qclsinst: u64 /* *mut c_void*/, pub _preSharedKeyAuthenticationRequired: QNetworkReply_preSharedKeyAuthenticationRequired_signal, pub _metaDataChanged: QNetworkReply_metaDataChanged_signal, pub _encrypted: QNetworkReply_encrypted_signal, pub _sslErrors: QNetworkReply_sslErrors_signal, pub _uploadProgress: QNetworkReply_uploadProgress_signal, pub _downloadProgress: QNetworkReply_downloadProgress_signal, pub _finished: QNetworkReply_finished_signal, pub _error: QNetworkReply_error_signal, } impl /*struct*/ QNetworkReply { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QNetworkReply { return QNetworkReply{qbase: QIODevice::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QNetworkReply { type Target = QIODevice; fn deref(&self) -> &QIODevice { return & self.qbase; } } impl AsRef<QIODevice> for QNetworkReply { fn as_ref(& self) -> & QIODevice { return & self.qbase; } } // proto: void QNetworkReply::ignoreSslErrors(); impl /*struct*/ QNetworkReply { pub fn ignoreSslErrors<RetType, T: QNetworkReply_ignoreSslErrors<RetType>>(& self, overload_args: T) -> RetType { return overload_args.ignoreSslErrors(self); // return 1; } } pub trait QNetworkReply_ignoreSslErrors<RetType> { fn ignoreSslErrors(self , rsthis: & QNetworkReply) -> RetType; } // proto: void QNetworkReply::ignoreSslErrors(); impl<'a> /*trait*/ QNetworkReply_ignoreSslErrors<()> for () { fn ignoreSslErrors(self , rsthis: & QNetworkReply) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QNetworkReply15ignoreSslErrorsEv()}; unsafe {_ZN13QNetworkReply15ignoreSslErrorsEv(rsthis.qclsinst)}; // return 1; } } // proto: bool QNetworkReply::hasRawHeader(const QByteArray & headerName); impl /*struct*/ QNetworkReply { pub fn hasRawHeader<RetType, T: QNetworkReply_hasRawHeader<RetType>>(& self, overload_args: T) -> RetType { return overload_args.hasRawHeader(self); // return 1; } } pub trait QNetworkReply_hasRawHeader<RetType> { fn hasRawHeader(self , rsthis: & QNetworkReply) -> RetType; } // proto: bool QNetworkReply::hasRawHeader(const QByteArray & headerName); impl<'a> /*trait*/ QNetworkReply_hasRawHeader<i8> for (&'a QByteArray) { fn hasRawHeader(self , rsthis: & QNetworkReply) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply12hasRawHeaderERK10QByteArray()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {_ZNK13QNetworkReply12hasRawHeaderERK10QByteArray(rsthis.qclsinst, arg0)}; return ret as i8; // return 1; } } // proto: void QNetworkReply::setReadBufferSize(qint64 size); impl /*struct*/ QNetworkReply { pub fn setReadBufferSize<RetType, T: QNetworkReply_setReadBufferSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setReadBufferSize(self); // return 1; } } pub trait QNetworkReply_setReadBufferSize<RetType> { fn setReadBufferSize(self , rsthis: & QNetworkReply) -> RetType; } // proto: void QNetworkReply::setReadBufferSize(qint64 size); impl<'a> /*trait*/ QNetworkReply_setReadBufferSize<()> for (i64) { fn setReadBufferSize(self , rsthis: & QNetworkReply) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QNetworkReply17setReadBufferSizeEx()}; let arg0 = self as c_longlong; unsafe {_ZN13QNetworkReply17setReadBufferSizeEx(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QNetworkRequest QNetworkReply::request(); impl /*struct*/ QNetworkReply { pub fn request<RetType, T: QNetworkReply_request<RetType>>(& self, overload_args: T) -> RetType { return overload_args.request(self); // return 1; } } pub trait QNetworkReply_request<RetType> { fn request(self , rsthis: & QNetworkReply) -> RetType; } // proto: QNetworkRequest QNetworkReply::request(); impl<'a> /*trait*/ QNetworkReply_request<QNetworkRequest> for () { fn request(self , rsthis: & QNetworkReply) -> QNetworkRequest { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply7requestEv()}; let mut ret = unsafe {_ZNK13QNetworkReply7requestEv(rsthis.qclsinst)}; let mut ret1 = QNetworkRequest::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QNetworkReply::abort(); impl /*struct*/ QNetworkReply { pub fn abort<RetType, T: QNetworkReply_abort<RetType>>(& self, overload_args: T) -> RetType { return overload_args.abort(self); // return 1; } } pub trait QNetworkReply_abort<RetType> { fn abort(self , rsthis: & QNetworkReply) -> RetType; } // proto: void QNetworkReply::abort(); impl<'a> /*trait*/ QNetworkReply_abort<()> for () { fn abort(self , rsthis: & QNetworkReply) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QNetworkReply5abortEv()}; unsafe {_ZN13QNetworkReply5abortEv(rsthis.qclsinst)}; // return 1; } } // proto: bool QNetworkReply::isRunning(); impl /*struct*/ QNetworkReply { pub fn isRunning<RetType, T: QNetworkReply_isRunning<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isRunning(self); // return 1; } } pub trait QNetworkReply_isRunning<RetType> { fn isRunning(self , rsthis: & QNetworkReply) -> RetType; } // proto: bool QNetworkReply::isRunning(); impl<'a> /*trait*/ QNetworkReply_isRunning<i8> for () { fn isRunning(self , rsthis: & QNetworkReply) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply9isRunningEv()}; let mut ret = unsafe {_ZNK13QNetworkReply9isRunningEv(rsthis.qclsinst)}; return ret as i8; // return 1; } } // proto: QList<QByteArray> QNetworkReply::rawHeaderList(); impl /*struct*/ QNetworkReply { pub fn rawHeaderList<RetType, T: QNetworkReply_rawHeaderList<RetType>>(& self, overload_args: T) -> RetType { return overload_args.rawHeaderList(self); // return 1; } } pub trait QNetworkReply_rawHeaderList<RetType> { fn rawHeaderList(self , rsthis: & QNetworkReply) -> RetType; } // proto: QList<QByteArray> QNetworkReply::rawHeaderList(); impl<'a> /*trait*/ QNetworkReply_rawHeaderList<()> for () { fn rawHeaderList(self , rsthis: & QNetworkReply) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply13rawHeaderListEv()}; unsafe {_ZNK13QNetworkReply13rawHeaderListEv(rsthis.qclsinst)}; // return 1; } } // proto: const QList<RawHeaderPair> & QNetworkReply::rawHeaderPairs(); impl /*struct*/ QNetworkReply { pub fn rawHeaderPairs<RetType, T: QNetworkReply_rawHeaderPairs<RetType>>(& self, overload_args: T) -> RetType { return overload_args.rawHeaderPairs(self); // return 1; } } pub trait QNetworkReply_rawHeaderPairs<RetType> { fn rawHeaderPairs(self , rsthis: & QNetworkReply) -> RetType; } // proto: const QList<RawHeaderPair> & QNetworkReply::rawHeaderPairs(); impl<'a> /*trait*/ QNetworkReply_rawHeaderPairs<()> for () { fn rawHeaderPairs(self , rsthis: & QNetworkReply) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply14rawHeaderPairsEv()}; unsafe {_ZNK13QNetworkReply14rawHeaderPairsEv(rsthis.qclsinst)}; // return 1; } } // proto: void QNetworkReply::setSslConfiguration(const QSslConfiguration & configuration); impl /*struct*/ QNetworkReply { pub fn setSslConfiguration<RetType, T: QNetworkReply_setSslConfiguration<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setSslConfiguration(self); // return 1; } } pub trait QNetworkReply_setSslConfiguration<RetType> { fn setSslConfiguration(self , rsthis: & QNetworkReply) -> RetType; } // proto: void QNetworkReply::setSslConfiguration(const QSslConfiguration & configuration); impl<'a> /*trait*/ QNetworkReply_setSslConfiguration<()> for (&'a QSslConfiguration) { fn setSslConfiguration(self , rsthis: & QNetworkReply) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QNetworkReply19setSslConfigurationERK17QSslConfiguration()}; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN13QNetworkReply19setSslConfigurationERK17QSslConfiguration(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QUrl QNetworkReply::url(); impl /*struct*/ QNetworkReply { pub fn url<RetType, T: QNetworkReply_url<RetType>>(& self, overload_args: T) -> RetType { return overload_args.url(self); // return 1; } } pub trait QNetworkReply_url<RetType> { fn url(self , rsthis: & QNetworkReply) -> RetType; } // proto: QUrl QNetworkReply::url(); impl<'a> /*trait*/ QNetworkReply_url<QUrl> for () { fn url(self , rsthis: & QNetworkReply) -> QUrl { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply3urlEv()}; let mut ret = unsafe {_ZNK13QNetworkReply3urlEv(rsthis.qclsinst)}; let mut ret1 = QUrl::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QNetworkReply::isSequential(); impl /*struct*/ QNetworkReply { pub fn isSequential<RetType, T: QNetworkReply_isSequential<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isSequential(self); // return 1; } } pub trait QNetworkReply_isSequential<RetType> { fn isSequential(self , rsthis: & QNetworkReply) -> RetType; } // proto: bool QNetworkReply::isSequential(); impl<'a> /*trait*/ QNetworkReply_isSequential<i8> for () { fn isSequential(self , rsthis: & QNetworkReply) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply12isSequentialEv()}; let mut ret = unsafe {_ZNK13QNetworkReply12isSequentialEv(rsthis.qclsinst)}; return ret as i8; // return 1; } } // proto: QByteArray QNetworkReply::rawHeader(const QByteArray & headerName); impl /*struct*/ QNetworkReply { pub fn rawHeader<RetType, T: QNetworkReply_rawHeader<RetType>>(& self, overload_args: T) -> RetType { return overload_args.rawHeader(self); // return 1; } } pub trait QNetworkReply_rawHeader<RetType> { fn rawHeader(self , rsthis: & QNetworkReply) -> RetType; } // proto: QByteArray QNetworkReply::rawHeader(const QByteArray & headerName); impl<'a> /*trait*/ QNetworkReply_rawHeader<QByteArray> for (&'a QByteArray) { fn rawHeader(self , rsthis: & QNetworkReply) -> QByteArray { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply9rawHeaderERK10QByteArray()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {_ZNK13QNetworkReply9rawHeaderERK10QByteArray(rsthis.qclsinst, arg0)}; let mut ret1 = QByteArray::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QNetworkAccessManager * QNetworkReply::manager(); impl /*struct*/ QNetworkReply { pub fn manager<RetType, T: QNetworkReply_manager<RetType>>(& self, overload_args: T) -> RetType { return overload_args.manager(self); // return 1; } } pub trait QNetworkReply_manager<RetType> { fn manager(self , rsthis: & QNetworkReply) -> RetType; } // proto: QNetworkAccessManager * QNetworkReply::manager(); impl<'a> /*trait*/ QNetworkReply_manager<QNetworkAccessManager> for () { fn manager(self , rsthis: & QNetworkReply) -> QNetworkAccessManager { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply7managerEv()}; let mut ret = unsafe {_ZNK13QNetworkReply7managerEv(rsthis.qclsinst)}; let mut ret1 = QNetworkAccessManager::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QNetworkReply::QNetworkReply(QObject * parent); impl /*struct*/ QNetworkReply { pub fn new<T: QNetworkReply_new>(value: T) -> QNetworkReply { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QNetworkReply_new { fn new(self) -> QNetworkReply; } // proto: void QNetworkReply::QNetworkReply(QObject * parent); impl<'a> /*trait*/ QNetworkReply_new for (&'a QObject) { fn new(self) -> QNetworkReply { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QNetworkReplyC2EP7QObject()}; let ctysz: c_int = unsafe{QNetworkReply_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN13QNetworkReplyC2EP7QObject(qthis_ph, arg0)}; let qthis: u64 = qthis_ph; let rsthis = QNetworkReply{qbase: QIODevice::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QNetworkReply::close(); impl /*struct*/ QNetworkReply { pub fn close<RetType, T: QNetworkReply_close<RetType>>(& self, overload_args: T) -> RetType { return overload_args.close(self); // return 1; } } pub trait QNetworkReply_close<RetType> { fn close(self , rsthis: & QNetworkReply) -> RetType; } // proto: void QNetworkReply::close(); impl<'a> /*trait*/ QNetworkReply_close<()> for () { fn close(self , rsthis: & QNetworkReply) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QNetworkReply5closeEv()}; unsafe {_ZN13QNetworkReply5closeEv(rsthis.qclsinst)}; // return 1; } } // proto: bool QNetworkReply::isFinished(); impl /*struct*/ QNetworkReply { pub fn isFinished<RetType, T: QNetworkReply_isFinished<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isFinished(self); // return 1; } } pub trait QNetworkReply_isFinished<RetType> { fn isFinished(self , rsthis: & QNetworkReply) -> RetType; } // proto: bool QNetworkReply::isFinished(); impl<'a> /*trait*/ QNetworkReply_isFinished<i8> for () { fn isFinished(self , rsthis: & QNetworkReply) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply10isFinishedEv()}; let mut ret = unsafe {_ZNK13QNetworkReply10isFinishedEv(rsthis.qclsinst)}; return ret as i8; // return 1; } } // proto: qint64 QNetworkReply::readBufferSize(); impl /*struct*/ QNetworkReply { pub fn readBufferSize<RetType, T: QNetworkReply_readBufferSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.readBufferSize(self); // return 1; } } pub trait QNetworkReply_readBufferSize<RetType> { fn readBufferSize(self , rsthis: & QNetworkReply) -> RetType; } // proto: qint64 QNetworkReply::readBufferSize(); impl<'a> /*trait*/ QNetworkReply_readBufferSize<i64> for () { fn readBufferSize(self , rsthis: & QNetworkReply) -> i64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply14readBufferSizeEv()}; let mut ret = unsafe {_ZNK13QNetworkReply14readBufferSizeEv(rsthis.qclsinst)}; return ret as i64; // return 1; } } // proto: QSslConfiguration QNetworkReply::sslConfiguration(); impl /*struct*/ QNetworkReply { pub fn sslConfiguration<RetType, T: QNetworkReply_sslConfiguration<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sslConfiguration(self); // return 1; } } pub trait QNetworkReply_sslConfiguration<RetType> { fn sslConfiguration(self , rsthis: & QNetworkReply) -> RetType; } // proto: QSslConfiguration QNetworkReply::sslConfiguration(); impl<'a> /*trait*/ QNetworkReply_sslConfiguration<QSslConfiguration> for () { fn sslConfiguration(self , rsthis: & QNetworkReply) -> QSslConfiguration { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply16sslConfigurationEv()}; let mut ret = unsafe {_ZNK13QNetworkReply16sslConfigurationEv(rsthis.qclsinst)}; let mut ret1 = QSslConfiguration::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QNetworkReply::metaObject(); impl /*struct*/ QNetworkReply { pub fn metaObject<RetType, T: QNetworkReply_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QNetworkReply_metaObject<RetType> { fn metaObject(self , rsthis: & QNetworkReply) -> RetType; } // proto: const QMetaObject * QNetworkReply::metaObject(); impl<'a> /*trait*/ QNetworkReply_metaObject<()> for () { fn metaObject(self , rsthis: & QNetworkReply) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QNetworkReply10metaObjectEv()}; unsafe {_ZNK13QNetworkReply10metaObjectEv(rsthis.qclsinst)}; // return 1; } } // proto: void QNetworkReply::~QNetworkReply(); impl /*struct*/ QNetworkReply { pub fn free<RetType, T: QNetworkReply_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QNetworkReply_free<RetType> { fn free(self , rsthis: & QNetworkReply) -> RetType; } // proto: void QNetworkReply::~QNetworkReply(); impl<'a> /*trait*/ QNetworkReply_free<()> for () { fn free(self , rsthis: & QNetworkReply) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QNetworkReplyD2Ev()}; unsafe {_ZN13QNetworkReplyD2Ev(rsthis.qclsinst)}; // return 1; } } #[derive(Default)] // for QNetworkReply_preSharedKeyAuthenticationRequired pub struct QNetworkReply_preSharedKeyAuthenticationRequired_signal{poi:u64} impl /* struct */ QNetworkReply { pub fn preSharedKeyAuthenticationRequired(&self) -> QNetworkReply_preSharedKeyAuthenticationRequired_signal { return QNetworkReply_preSharedKeyAuthenticationRequired_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkReply_preSharedKeyAuthenticationRequired_signal { pub fn connect<T: QNetworkReply_preSharedKeyAuthenticationRequired_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkReply_preSharedKeyAuthenticationRequired_signal_connect { fn connect(self, sigthis: QNetworkReply_preSharedKeyAuthenticationRequired_signal); } #[derive(Default)] // for QNetworkReply_metaDataChanged pub struct QNetworkReply_metaDataChanged_signal{poi:u64} impl /* struct */ QNetworkReply { pub fn metaDataChanged(&self) -> QNetworkReply_metaDataChanged_signal { return QNetworkReply_metaDataChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkReply_metaDataChanged_signal { pub fn connect<T: QNetworkReply_metaDataChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkReply_metaDataChanged_signal_connect { fn connect(self, sigthis: QNetworkReply_metaDataChanged_signal); } #[derive(Default)] // for QNetworkReply_encrypted pub struct QNetworkReply_encrypted_signal{poi:u64} impl /* struct */ QNetworkReply { pub fn encrypted(&self) -> QNetworkReply_encrypted_signal { return QNetworkReply_encrypted_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkReply_encrypted_signal { pub fn connect<T: QNetworkReply_encrypted_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkReply_encrypted_signal_connect { fn connect(self, sigthis: QNetworkReply_encrypted_signal); } #[derive(Default)] // for QNetworkReply_sslErrors pub struct QNetworkReply_sslErrors_signal{poi:u64} impl /* struct */ QNetworkReply { pub fn sslErrors(&self) -> QNetworkReply_sslErrors_signal { return QNetworkReply_sslErrors_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkReply_sslErrors_signal { pub fn connect<T: QNetworkReply_sslErrors_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkReply_sslErrors_signal_connect { fn connect(self, sigthis: QNetworkReply_sslErrors_signal); } #[derive(Default)] // for QNetworkReply_uploadProgress pub struct QNetworkReply_uploadProgress_signal{poi:u64} impl /* struct */ QNetworkReply { pub fn uploadProgress(&self) -> QNetworkReply_uploadProgress_signal { return QNetworkReply_uploadProgress_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkReply_uploadProgress_signal { pub fn connect<T: QNetworkReply_uploadProgress_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkReply_uploadProgress_signal_connect { fn connect(self, sigthis: QNetworkReply_uploadProgress_signal); } #[derive(Default)] // for QNetworkReply_downloadProgress pub struct QNetworkReply_downloadProgress_signal{poi:u64} impl /* struct */ QNetworkReply { pub fn downloadProgress(&self) -> QNetworkReply_downloadProgress_signal { return QNetworkReply_downloadProgress_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkReply_downloadProgress_signal { pub fn connect<T: QNetworkReply_downloadProgress_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkReply_downloadProgress_signal_connect { fn connect(self, sigthis: QNetworkReply_downloadProgress_signal); } #[derive(Default)] // for QNetworkReply_finished pub struct QNetworkReply_finished_signal{poi:u64} impl /* struct */ QNetworkReply { pub fn finished(&self) -> QNetworkReply_finished_signal { return QNetworkReply_finished_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkReply_finished_signal { pub fn connect<T: QNetworkReply_finished_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkReply_finished_signal_connect { fn connect(self, sigthis: QNetworkReply_finished_signal); } #[derive(Default)] // for QNetworkReply_error pub struct QNetworkReply_error_signal{poi:u64} impl /* struct */ QNetworkReply { pub fn error(&self) -> QNetworkReply_error_signal { return QNetworkReply_error_signal{poi:self.qclsinst}; } } impl /* struct */ QNetworkReply_error_signal { pub fn connect<T: QNetworkReply_error_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QNetworkReply_error_signal_connect { fn connect(self, sigthis: QNetworkReply_error_signal); } // downloadProgress(qint64, qint64) extern fn QNetworkReply_downloadProgress_signal_connect_cb_0(rsfptr:fn(i64, i64), arg0: c_longlong, arg1: c_longlong) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i64; let rsarg1 = arg1 as i64; rsfptr(rsarg0,rsarg1); } extern fn QNetworkReply_downloadProgress_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(i64, i64)>, arg0: c_longlong, arg1: c_longlong) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i64; let rsarg1 = arg1 as i64; // rsfptr(rsarg0,rsarg1); unsafe{(*rsfptr_raw)(rsarg0,rsarg1)}; } impl /* trait */ QNetworkReply_downloadProgress_signal_connect for fn(i64, i64) { fn connect(self, sigthis: QNetworkReply_downloadProgress_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_downloadProgress_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply16downloadProgressExx(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkReply_downloadProgress_signal_connect for Box<Fn(i64, i64)> { fn connect(self, sigthis: QNetworkReply_downloadProgress_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_downloadProgress_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply16downloadProgressExx(arg0, arg1, arg2)}; } } // finished() extern fn QNetworkReply_finished_signal_connect_cb_1(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QNetworkReply_finished_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QNetworkReply_finished_signal_connect for fn() { fn connect(self, sigthis: QNetworkReply_finished_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_finished_signal_connect_cb_1 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply8finishedEv(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkReply_finished_signal_connect for Box<Fn()> { fn connect(self, sigthis: QNetworkReply_finished_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_finished_signal_connect_cb_box_1 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply8finishedEv(arg0, arg1, arg2)}; } } // metaDataChanged() extern fn QNetworkReply_metaDataChanged_signal_connect_cb_2(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QNetworkReply_metaDataChanged_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QNetworkReply_metaDataChanged_signal_connect for fn() { fn connect(self, sigthis: QNetworkReply_metaDataChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_metaDataChanged_signal_connect_cb_2 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply15metaDataChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkReply_metaDataChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QNetworkReply_metaDataChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_metaDataChanged_signal_connect_cb_box_2 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply15metaDataChangedEv(arg0, arg1, arg2)}; } } // uploadProgress(qint64, qint64) extern fn QNetworkReply_uploadProgress_signal_connect_cb_3(rsfptr:fn(i64, i64), arg0: c_longlong, arg1: c_longlong) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i64; let rsarg1 = arg1 as i64; rsfptr(rsarg0,rsarg1); } extern fn QNetworkReply_uploadProgress_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(i64, i64)>, arg0: c_longlong, arg1: c_longlong) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i64; let rsarg1 = arg1 as i64; // rsfptr(rsarg0,rsarg1); unsafe{(*rsfptr_raw)(rsarg0,rsarg1)}; } impl /* trait */ QNetworkReply_uploadProgress_signal_connect for fn(i64, i64) { fn connect(self, sigthis: QNetworkReply_uploadProgress_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_uploadProgress_signal_connect_cb_3 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply14uploadProgressExx(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkReply_uploadProgress_signal_connect for Box<Fn(i64, i64)> { fn connect(self, sigthis: QNetworkReply_uploadProgress_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_uploadProgress_signal_connect_cb_box_3 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply14uploadProgressExx(arg0, arg1, arg2)}; } } // encrypted() extern fn QNetworkReply_encrypted_signal_connect_cb_4(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QNetworkReply_encrypted_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QNetworkReply_encrypted_signal_connect for fn() { fn connect(self, sigthis: QNetworkReply_encrypted_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_encrypted_signal_connect_cb_4 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply9encryptedEv(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkReply_encrypted_signal_connect for Box<Fn()> { fn connect(self, sigthis: QNetworkReply_encrypted_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_encrypted_signal_connect_cb_box_4 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply9encryptedEv(arg0, arg1, arg2)}; } } // preSharedKeyAuthenticationRequired(class QSslPreSharedKeyAuthenticator *) extern fn QNetworkReply_preSharedKeyAuthenticationRequired_signal_connect_cb_5(rsfptr:fn(QSslPreSharedKeyAuthenticator), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QSslPreSharedKeyAuthenticator::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QNetworkReply_preSharedKeyAuthenticationRequired_signal_connect_cb_box_5(rsfptr_raw:*mut Box<Fn(QSslPreSharedKeyAuthenticator)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QSslPreSharedKeyAuthenticator::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QNetworkReply_preSharedKeyAuthenticationRequired_signal_connect for fn(QSslPreSharedKeyAuthenticator) { fn connect(self, sigthis: QNetworkReply_preSharedKeyAuthenticationRequired_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_preSharedKeyAuthenticationRequired_signal_connect_cb_5 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply34preSharedKeyAuthenticationRequiredEP29QSslPreSharedKeyAuthenticator(arg0, arg1, arg2)}; } } impl /* trait */ QNetworkReply_preSharedKeyAuthenticationRequired_signal_connect for Box<Fn(QSslPreSharedKeyAuthenticator)> { fn connect(self, sigthis: QNetworkReply_preSharedKeyAuthenticationRequired_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QNetworkReply_preSharedKeyAuthenticationRequired_signal_connect_cb_box_5 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QNetworkReply_SlotProxy_connect__ZN13QNetworkReply34preSharedKeyAuthenticationRequiredEP29QSslPreSharedKeyAuthenticator(arg0, arg1, arg2)}; } } // <= body block end
use crate::{ caveat::{CaveatBuilder, CaveatType}, error::MacaroonError, serialization::macaroon_builder::MacaroonBuilder, Macaroon, }; use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD}; use std::str; // Version 1 fields const LOCATION: &str = "location"; const IDENTIFIER: &str = "identifier"; const SIGNATURE: &str = "signature"; const CID: &str = "cid"; const VID: &str = "vid"; const CL: &str = "cl"; const HEADER_SIZE: usize = 4; fn serialize_as_packet<'r>(tag: &'r str, value: &'r [u8]) -> Vec<u8> { let mut packet: Vec<u8> = Vec::new(); let size = HEADER_SIZE + 2 + tag.len() + value.len(); packet.extend(packet_header(size)); packet.extend_from_slice(tag.as_bytes()); packet.extend_from_slice(b" "); packet.extend_from_slice(value); packet.extend_from_slice(b"\n"); packet } fn to_hex_char(value: u8) -> u8 { let hex = format!("{:1x}", value); hex.as_bytes()[0] } fn packet_header(size: usize) -> Vec<u8> { let mut header: Vec<u8> = Vec::new(); header.push(to_hex_char(((size >> 12) & 15) as u8)); header.push(to_hex_char(((size >> 8) & 15) as u8)); header.push(to_hex_char(((size >> 4) & 15) as u8)); header.push(to_hex_char((size & 15) as u8)); header } pub fn serialize_v1(macaroon: &Macaroon) -> Result<Vec<u8>, MacaroonError> { let mut serialized: Vec<u8> = Vec::new(); if let Some(ref location) = macaroon.location() { serialized.extend(serialize_as_packet(LOCATION, location.as_bytes())); }; serialized.extend(serialize_as_packet( IDENTIFIER, macaroon.identifier().as_bytes(), )); for caveat in macaroon.caveats() { match caveat.get_type() { CaveatType::FirstParty => { let first_party = caveat.as_first_party().unwrap(); serialized.extend(serialize_as_packet(CID, first_party.predicate().as_bytes())); } CaveatType::ThirdParty => { let third_party = caveat.as_third_party().unwrap(); serialized.extend(serialize_as_packet(CID, third_party.id().as_bytes())); serialized.extend(serialize_as_packet( VID, third_party.verifier_id().as_slice(), )); serialized.extend(serialize_as_packet(CL, third_party.location().as_bytes())) } } } serialized.extend(serialize_as_packet(SIGNATURE, macaroon.signature())); Ok(serialized.to_base64(STANDARD).as_bytes().to_vec()) } fn base64_decode(base64: &str) -> Result<Vec<u8>, MacaroonError> { Ok(base64.from_base64()?) } struct Packet { key: String, value: Vec<u8>, } fn deserialize_as_packets( data: &[u8], mut packets: Vec<Packet>, ) -> Result<Vec<Packet>, MacaroonError> { if data.is_empty() { return Ok(packets); } let hex: &str = str::from_utf8(&data[..4])?; let size: usize = usize::from_str_radix(hex, 16)?; let packet_data = &data[4..size]; let index = split_index(packet_data)?; let (key_slice, value_slice) = packet_data.split_at(index); packets.push(Packet { key: String::from_utf8(key_slice.to_vec())?, // skip beginning space and terminating \n value: value_slice[1..value_slice.len() - 1].to_vec(), }); deserialize_as_packets(&data[size..], packets) } fn split_index(packet: &[u8]) -> Result<usize, MacaroonError> { match packet.iter().position(|&r| r == b' ') { Some(index) => Ok(index), None => Err(MacaroonError::DeserializationError(String::from( "Key/value error", ))), } } pub fn deserialize_v1(base64: &[u8]) -> Result<Macaroon, MacaroonError> { let data = base64_decode(&String::from_utf8(base64.to_vec())?)?; let mut builder: MacaroonBuilder = MacaroonBuilder::new(); let mut caveat_builder: CaveatBuilder = CaveatBuilder::new(); for packet in deserialize_as_packets(data.as_slice(), Vec::new())? { match packet.key.as_str() { LOCATION => { builder.set_location(&String::from_utf8(packet.value)?); } IDENTIFIER => { builder.set_identifier(&String::from_utf8(packet.value)?); } SIGNATURE => { if caveat_builder.has_id() { builder.add_caveat(caveat_builder.build()?); caveat_builder = CaveatBuilder::new(); } if packet.value.len() != 32 { error!( "deserialize_v1: Deserialization error - signature length is {}", packet.value.len() ); return Err(MacaroonError::DeserializationError(String::from( "Illegal signature length in packet", ))); } builder.set_signature(&packet.value); } CID => { if caveat_builder.has_id() { builder.add_caveat(caveat_builder.build()?); caveat_builder = CaveatBuilder::new(); caveat_builder.add_id(String::from_utf8(packet.value)?); } else { caveat_builder.add_id(String::from_utf8(packet.value)?); } } VID => { caveat_builder.add_verifier_id(packet.value); } CL => caveat_builder.add_location(String::from_utf8(packet.value)?), _ => { return Err(MacaroonError::DeserializationError(String::from( "Unknown key", ))) } }; } Ok(builder.build()?) } #[cfg(test)] mod tests { use crate::Macaroon; #[test] fn test_deserialize_v1() { let mut serialized = "MDAyMWxvY2F0aW9uIGh0dHA6Ly9leGFtcGxlLm9yZy8KMDAxNWlkZW50aWZpZXIga2V5aWQKMDAyZnNpZ25hdHVyZSB83ueSURxbxvUoSFgF3-myTnheKOKpkwH51xHGCeOO9wo"; let mut signature: [u8; 32] = [ 124, 222, 231, 146, 81, 28, 91, 198, 245, 40, 72, 88, 5, 223, 233, 178, 78, 120, 94, 40, 226, 169, 147, 1, 249, 215, 17, 198, 9, 227, 142, 247, ]; let macaroon = super::deserialize_v1(&serialized.as_bytes().to_vec()).unwrap(); assert!(macaroon.location().is_some()); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!("keyid", macaroon.identifier()); assert_eq!(signature.to_vec(), macaroon.signature()); serialized = "MDAyMWxvY2F0aW9uIGh0dHA6Ly9leGFtcGxlLm9yZy8KMDAxNWlkZW50aWZpZXIga2V5aWQKMDAxZGNpZCBhY2NvdW50ID0gMzczNTkyODU1OQowMDJmc2lnbmF0dXJlIPVIB_bcbt-Ivw9zBrOCJWKjYlM9v3M5umF2XaS9JZ2HCg"; signature = [ 245, 72, 7, 246, 220, 110, 223, 136, 191, 15, 115, 6, 179, 130, 37, 98, 163, 98, 83, 61, 191, 115, 57, 186, 97, 118, 93, 164, 189, 37, 157, 135, ]; let macaroon = super::deserialize_v1(&serialized.as_bytes().to_vec()).unwrap(); assert!(macaroon.location().is_some()); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!("keyid", macaroon.identifier()); assert_eq!(1, macaroon.caveats().len()); assert_eq!( "account = 3735928559", macaroon.caveats()[0].as_first_party().unwrap().predicate() ); assert_eq!(signature.to_vec(), macaroon.signature()); } #[test] fn test_deserialize_v1_two_caveats() { let serialized = "MDAyMWxvY2F0aW9uIGh0dHA6Ly9leGFtcGxlLm9yZy8KMDAxNWlkZW50aWZpZXIga2V5aWQKMDAxZGNpZCBhY2NvdW50ID0gMzczNTkyODU1OQowMDE1Y2lkIHVzZXIgPSBhbGljZQowMDJmc2lnbmF0dXJlIEvpZ80eoMaya69qSpTumwWxWIbaC6hejEKpPI0OEl78Cg"; let signature = [ 75, 233, 103, 205, 30, 160, 198, 178, 107, 175, 106, 74, 148, 238, 155, 5, 177, 88, 134, 218, 11, 168, 94, 140, 66, 169, 60, 141, 14, 18, 94, 252, ]; let macaroon = super::deserialize_v1(&serialized.as_bytes().to_vec()).unwrap(); assert!(macaroon.location().is_some()); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!("keyid", macaroon.identifier()); assert_eq!(signature.to_vec(), macaroon.signature()); assert_eq!(2, macaroon.caveats().len()); assert_eq!( "account = 3735928559", macaroon.caveats()[0].as_first_party().unwrap().predicate() ); assert_eq!( "user = alice", macaroon.caveats()[1].as_first_party().unwrap().predicate() ); } #[test] fn test_serialize_deserialize_v1() { let mut macaroon: Macaroon = Macaroon::create("http://example.org/", b"my key", "keyid").unwrap(); macaroon.add_first_party_caveat("account = 3735928559"); macaroon.add_first_party_caveat("user = alice"); macaroon.add_third_party_caveat("https://auth.mybank.com", b"caveat key", "caveat"); let serialized = macaroon.serialize(super::super::Format::V1).unwrap(); let deserialized = Macaroon::deserialize(&serialized).unwrap(); assert_eq!(macaroon, deserialized); } }
// Data types that represent things related to discord // Example: User, Guild (server), channel, message, Role, etc use crate::connection::CallbackContext; use core::borrow::Borrow; /// The command and args from a users message starting with <prefix> e.x. !ping /// used for command callbacks pub struct Command<'a> { args: [&'a str], } pub struct CommandIter<'a> { index: usize, data: &'a [Command<'a>], } impl<'a> CommandIter<'a> { fn new(from_data: &[Command]) -> CommandIter<'a> { CommandIter { index: 0, data: from_data } } } impl<'a> Iterator for CommandIter<'a> { type Item = Command<'a>; fn next(&mut self) -> Option<&Command> { // Check to see if we've finished counting or not. let next_item = if self.index < self.data.len() { Some(&self.data[self.index]) } else { None }; self.count += 1; next_item } } /// Represents a text chat room in a discord server or private message pub struct Channel<'a> { uuid: u32, name: &'a str, } impl<'a> Channel<'a> { pub async fn send(&self, message: &str) { // send a message to this channel through the discord api } } /// A Guild is discord's name for servers pub struct Guild<'a> { uuid: u32, name: &'a str, } /// The user that sent the message or command pub struct User<'a> { uuid: u32, name: &'a str, } /// The contents of a message pub struct Message<'a> { sender: User<'a>, content: &'a str, server: Guild<'a>, channel: Channel<'a>, } /// The context data for the help command pub struct HelpContext<T: ?Sized + CallbackContext> { bot_commands: [T], } impl<'a> HelpContext<Command<'a>> { fn commands(&self) -> CommandIter { CommandIter::new(&self.bot_commands) } }
use std::fs::File; use serde_json; use serde::Serialize; pub fn save<T: Serialize>(json: T, filename: &str) { serde_json::to_writer(&File::create(format!("output/{}.json", filename)).expect("Could not create output file"), &json).expect("Failed to serialize output file"); }
//! Handle network connections for a varlink service #![allow(dead_code)] #[cfg(unix)] use libc::{close, dup2, getpid}; use std::io::{Read, Write}; use std::net::{Shutdown, TcpStream}; use std::process::Child; use tempfile::TempDir; #[cfg(unix)] use std::os::unix::io::IntoRawFd; #[cfg(unix)] use std::os::unix::net::UnixStream; #[cfg(windows)] use uds_windows::UnixStream; use crate::error::*; use chainerror::*; pub enum VarlinkStream { TCP(TcpStream), UNIX(UnixStream), } #[cfg(windows)] pub fn varlink_exec<S: ?Sized + AsRef<str>>( _address: &S, ) -> Result<(Child, String, Option<TempDir>)> { return Err(into_cherr!(ErrorKind::MethodNotImplemented( "varlink_exec".into() ))); } #[cfg(unix)] pub fn varlink_exec<S: ?Sized + AsRef<str>>( address: &S, ) -> Result<(Child, String, Option<TempDir>)> { use std::env; use std::os::unix::process::CommandExt; use std::process::Command; use tempfile::tempdir; let executable = String::from("exec ") + address.as_ref(); use unix_socket::UnixListener; let dir = tempdir().map_err(minto_cherr!())?; let file_path = dir.path().join("varlink-socket"); let listener = UnixListener::bind(file_path.clone()).map_err(minto_cherr!())?; let fd = listener.into_raw_fd(); let child = Command::new("sh") .arg("-c") .arg(executable) .before_exec({ let file_path = file_path.clone(); move || { unsafe { if fd != 3 { close(3); dup2(fd, 3); } env::set_var("VARLINK_ADDRESS", format!("unix:{}", file_path.display())); env::set_var("LISTEN_FDS", "1"); env::set_var("LISTEN_FDNAMES", "varlink"); env::set_var("LISTEN_PID", format!("{}", getpid())); } Ok(()) } }) .spawn() .map_err(minto_cherr!())?; Ok((child, format!("unix:{}", file_path.display()), Some(dir))) } #[cfg(windows)] pub fn varlink_bridge<S: ?Sized + AsRef<str>>(address: &S) -> Result<(Child, VarlinkStream)> { use std::io::copy; use std::process::{Command, Stdio}; use std::thread; let (stream0, stream1) = UnixStream::pair().map_err(minto_cherr!())?; let executable = address.as_ref(); let mut child = Command::new("cmd") .arg("/C") .arg(executable) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .map_err(minto_cherr!())?; let mut client_writer = child.stdin.take().unwrap(); let mut client_reader = child.stdout.take().unwrap(); let mut service_writer = stream1.try_clone().map_err(minto_cherr!())?; let mut service_reader = stream1; thread::spawn(move || copy(&mut client_reader, &mut service_writer)); thread::spawn(move || copy(&mut service_reader, &mut client_writer)); Ok((child, VarlinkStream::UNIX(stream0))) } #[cfg(unix)] pub fn varlink_bridge<S: ?Sized + AsRef<str>>(address: &S) -> Result<(Child, VarlinkStream)> { use std::os::unix::io::FromRawFd; use std::process::Command; let executable = address.as_ref(); // use unix_socket::UnixStream; let (stream0, stream1) = UnixStream::pair().map_err(minto_cherr!())?; let fd = stream1.into_raw_fd(); let childin = unsafe { ::std::fs::File::from_raw_fd(fd) }; let childout = unsafe { ::std::fs::File::from_raw_fd(fd) }; let child = Command::new("sh") .arg("-c") .arg(executable) .stdin(childin) .stdout(childout) .spawn() .map_err(minto_cherr!())?; Ok((child, VarlinkStream::UNIX(stream0))) } #[cfg(any(target_os = "linux", target_os = "android"))] fn get_abstract_unixstream(addr: &str) -> Result<UnixStream> { // FIXME: abstract unix domains sockets still not in std // FIXME: https://github.com/rust-lang/rust/issues/14194 use std::os::unix::io::FromRawFd; use unix_socket::UnixStream as AbstractStream; unsafe { Ok(UnixStream::from_raw_fd( AbstractStream::connect(addr) .map_err(minto_cherr!())? .into_raw_fd(), )) } } #[cfg(not(any(target_os = "linux", target_os = "android")))] fn get_abstract_unixstream(_addr: &str) -> Result<UnixStream> { Err(into_cherr!(ErrorKind::InvalidAddress)) } impl<'a> VarlinkStream { pub fn connect<S: ?Sized + AsRef<str>>(address: &S) -> Result<(Self, String)> { let address = address.as_ref(); let new_address: String = address.into(); if new_address.starts_with("tcp:") { Ok(( VarlinkStream::TCP(TcpStream::connect(&new_address[4..]).map_err(minto_cherr!())?), new_address, )) } else if new_address.starts_with("unix:") { let mut addr = String::from(new_address[5..].split(';').next().unwrap()); if addr.starts_with('@') { addr = addr.replacen('@', "\0", 1); return get_abstract_unixstream(&addr) .and_then(|v| Ok((VarlinkStream::UNIX(v), new_address))); } Ok(( VarlinkStream::UNIX(UnixStream::connect(addr).map_err(minto_cherr!())?), new_address, )) } else { Err(into_cherr!(ErrorKind::InvalidAddress))? } } pub fn split(&mut self) -> Result<(Box<Read + Send + Sync>, Box<Write + Send + Sync>)> { match *self { VarlinkStream::TCP(ref mut s) => Ok(( Box::new(s.try_clone().map_err(minto_cherr!())?), Box::new(s.try_clone().map_err(minto_cherr!())?), )), VarlinkStream::UNIX(ref mut s) => Ok(( Box::new(s.try_clone().map_err(minto_cherr!())?), Box::new(s.try_clone().map_err(minto_cherr!())?), )), } } pub fn shutdown(&mut self) -> Result<()> { match *self { VarlinkStream::TCP(ref mut s) => s.shutdown(Shutdown::Both).map_err(minto_cherr!())?, VarlinkStream::UNIX(ref mut s) => s.shutdown(Shutdown::Both).map_err(minto_cherr!())?, } Ok(()) } pub fn set_nonblocking(&self, b: bool) -> Result<()> { match *self { VarlinkStream::TCP(ref l) => l.set_nonblocking(b).map_err(minto_cherr!())?, VarlinkStream::UNIX(ref l) => l.set_nonblocking(b).map_err(minto_cherr!())?, } Ok(()) } } impl Drop for VarlinkStream { fn drop(&mut self) { let _r = self.shutdown(); } }
fn main() { use text_grid::*; let mut g = GridBuilder::new(); g.push(|b| { b.push(cell("name").right()); b.push("type"); b.push("value"); }); g.push_separator(); g.push(|b| { b.push(cell(String::from("X")).right()); b.push("A"); b.push(10); }); g.push(|b| { b.push(cell("Y").right()); b.push_with_colspan(cell("BBB").center(), 2); }); print!("{}", g); }
use serde::{Serialize, Deserialize, de::Error, Deserializer}; use anyhow::{Result, Context}; use rust_decimal::Decimal; use std::collections::HashMap; use url::Url; use tokio_tungstenite::tungstenite::protocol::Message; use actix::Message as ActixMessage; #[derive(Clone, Debug, Deserialize)] pub struct Feed{ pub chain_id: String, #[serde(alias = "type")] pub block_type: String, pub data: FeedData } #[derive(Clone, Debug, Deserialize)] pub struct FeedData{ pub txs: Vec<FeedDataTx>, } #[derive(Clone, Debug, Deserialize)] pub struct FeedDataTx{ pub logs: Vec<FeedDataTxLog>, } #[derive(Clone, Debug, Deserialize)] pub struct FeedDataTxLog{ pub events: Vec<FeedDataTxLogEvent>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FeedDataTxLogEvent{ #[serde(alias = "type")] pub event_type: String, pub attributes: Vec<FeedDataTxLogEventAttribute>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FeedDataTxLogEventAttribute{ pub key: String, pub value: String } /////////////////////////////////////////////////////////Output Data Feed////////////////////////////////////////////////////// pub type Asset = String; pub type ExchangeRate = Decimal; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ActixMessage)] #[rtype(result = "()")] pub struct OutputData{ pub luna_exch_rates: HashMap<Asset, ExchangeRate> } /////////////////////////////////////////////////////////Server Config////////////////////////////////////////////////////// #[derive(Clone, Debug, Deserialize)] pub struct RawConfig{ pub web_socket_url: String, pub web_socket_feed: String, pub server_address: String, pub server_port: u16 } #[derive(Clone, Debug, PartialEq, Eq)] pub struct WebAppConfig{ pub web_socket_url: Url, pub web_socket_feed: Message, pub server_address: String, pub server_port: u16 } impl WebAppConfig { pub fn new(json_str: String) -> Result<Self>{ let config: WebAppConfig = serde_json::from_str(&json_str) .context("JSON was not well-formatted config")?; Ok(config) } } impl<'de> Deserialize<'de> for WebAppConfig { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let raw_config: RawConfig = Deserialize::deserialize(deserializer)?; Ok(WebAppConfig{ web_socket_url: Url::parse(&raw_config.web_socket_url).map_err(D::Error::custom)?, web_socket_feed: Message::text(raw_config.web_socket_feed), server_address: raw_config.server_address, server_port: raw_config.server_port }) } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AdjustWindowRectExForDpi<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(lprect: *mut super::super::Foundation::RECT, dwstyle: u32, bmenu: Param2, dwexstyle: u32, dpi: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AdjustWindowRectExForDpi(lprect: *mut super::super::Foundation::RECT, dwstyle: u32, bmenu: super::super::Foundation::BOOL, dwexstyle: u32, dpi: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(AdjustWindowRectExForDpi(::core::mem::transmute(lprect), ::core::mem::transmute(dwstyle), bmenu.into_param().abi(), ::core::mem::transmute(dwexstyle), ::core::mem::transmute(dpi))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn AreDpiAwarenessContextsEqual<'a, Param0: ::windows::core::IntoParam<'a, DPI_AWARENESS_CONTEXT>, Param1: ::windows::core::IntoParam<'a, DPI_AWARENESS_CONTEXT>>(dpicontexta: Param0, dpicontextb: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn AreDpiAwarenessContextsEqual(dpicontexta: DPI_AWARENESS_CONTEXT, dpicontextb: DPI_AWARENESS_CONTEXT) -> super::super::Foundation::BOOL; } ::core::mem::transmute(AreDpiAwarenessContextsEqual(dpicontexta.into_param().abi(), dpicontextb.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS(pub u32); pub const DCDC_DEFAULT: DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS = DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS(0u32); pub const DCDC_DISABLE_FONT_UPDATE: DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS = DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS(1u32); pub const DCDC_DISABLE_RELAYOUT: DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS = DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS(2u32); impl ::core::convert::From<u32> for DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS { type Abi = Self; } impl ::core::ops::BitOr for DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DIALOG_DPI_CHANGE_BEHAVIORS(pub u32); pub const DDC_DEFAULT: DIALOG_DPI_CHANGE_BEHAVIORS = DIALOG_DPI_CHANGE_BEHAVIORS(0u32); pub const DDC_DISABLE_ALL: DIALOG_DPI_CHANGE_BEHAVIORS = DIALOG_DPI_CHANGE_BEHAVIORS(1u32); pub const DDC_DISABLE_RESIZE: DIALOG_DPI_CHANGE_BEHAVIORS = DIALOG_DPI_CHANGE_BEHAVIORS(2u32); pub const DDC_DISABLE_CONTROL_RELAYOUT: DIALOG_DPI_CHANGE_BEHAVIORS = DIALOG_DPI_CHANGE_BEHAVIORS(4u32); impl ::core::convert::From<u32> for DIALOG_DPI_CHANGE_BEHAVIORS { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DIALOG_DPI_CHANGE_BEHAVIORS { type Abi = Self; } impl ::core::ops::BitOr for DIALOG_DPI_CHANGE_BEHAVIORS { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for DIALOG_DPI_CHANGE_BEHAVIORS { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for DIALOG_DPI_CHANGE_BEHAVIORS { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for DIALOG_DPI_CHANGE_BEHAVIORS { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for DIALOG_DPI_CHANGE_BEHAVIORS { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DPI_AWARENESS(pub i32); pub const DPI_AWARENESS_INVALID: DPI_AWARENESS = DPI_AWARENESS(-1i32); pub const DPI_AWARENESS_UNAWARE: DPI_AWARENESS = DPI_AWARENESS(0i32); pub const DPI_AWARENESS_SYSTEM_AWARE: DPI_AWARENESS = DPI_AWARENESS(1i32); pub const DPI_AWARENESS_PER_MONITOR_AWARE: DPI_AWARENESS = DPI_AWARENESS(2i32); impl ::core::convert::From<i32> for DPI_AWARENESS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DPI_AWARENESS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq)] #[repr(transparent)] pub struct DPI_AWARENESS_CONTEXT(pub isize); impl ::core::default::Default for DPI_AWARENESS_CONTEXT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } unsafe impl ::windows::core::Handle for DPI_AWARENESS_CONTEXT {} unsafe impl ::windows::core::Abi for DPI_AWARENESS_CONTEXT { type Abi = Self; } pub const DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE: DPI_AWARENESS_CONTEXT = DPI_AWARENESS_CONTEXT(-3i32 as _); pub const DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2: DPI_AWARENESS_CONTEXT = DPI_AWARENESS_CONTEXT(-4i32 as _); pub const DPI_AWARENESS_CONTEXT_SYSTEM_AWARE: DPI_AWARENESS_CONTEXT = DPI_AWARENESS_CONTEXT(-2i32 as _); pub const DPI_AWARENESS_CONTEXT_UNAWARE: DPI_AWARENESS_CONTEXT = DPI_AWARENESS_CONTEXT(-1i32 as _); pub const DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED: DPI_AWARENESS_CONTEXT = DPI_AWARENESS_CONTEXT(-5i32 as _); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DPI_HOSTING_BEHAVIOR(pub i32); pub const DPI_HOSTING_BEHAVIOR_INVALID: DPI_HOSTING_BEHAVIOR = DPI_HOSTING_BEHAVIOR(-1i32); pub const DPI_HOSTING_BEHAVIOR_DEFAULT: DPI_HOSTING_BEHAVIOR = DPI_HOSTING_BEHAVIOR(0i32); pub const DPI_HOSTING_BEHAVIOR_MIXED: DPI_HOSTING_BEHAVIOR = DPI_HOSTING_BEHAVIOR(1i32); impl ::core::convert::From<i32> for DPI_HOSTING_BEHAVIOR { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DPI_HOSTING_BEHAVIOR { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn EnableNonClientDpiScaling<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(hwnd: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EnableNonClientDpiScaling(hwnd: super::super::Foundation::HWND) -> super::super::Foundation::BOOL; } ::core::mem::transmute(EnableNonClientDpiScaling(hwnd.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn GetAwarenessFromDpiAwarenessContext<'a, Param0: ::windows::core::IntoParam<'a, DPI_AWARENESS_CONTEXT>>(value: Param0) -> DPI_AWARENESS { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetAwarenessFromDpiAwarenessContext(value: DPI_AWARENESS_CONTEXT) -> DPI_AWARENESS; } ::core::mem::transmute(GetAwarenessFromDpiAwarenessContext(value.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetDialogControlDpiChangeBehavior<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(hwnd: Param0) -> DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetDialogControlDpiChangeBehavior(hwnd: super::super::Foundation::HWND) -> DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS; } ::core::mem::transmute(GetDialogControlDpiChangeBehavior(hwnd.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetDialogDpiChangeBehavior<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(hdlg: Param0) -> DIALOG_DPI_CHANGE_BEHAVIORS { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetDialogDpiChangeBehavior(hdlg: super::super::Foundation::HWND) -> DIALOG_DPI_CHANGE_BEHAVIORS; } ::core::mem::transmute(GetDialogDpiChangeBehavior(hdlg.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetDpiAwarenessContextForProcess<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hprocess: Param0) -> DPI_AWARENESS_CONTEXT { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetDpiAwarenessContextForProcess(hprocess: super::super::Foundation::HANDLE) -> DPI_AWARENESS_CONTEXT; } ::core::mem::transmute(GetDpiAwarenessContextForProcess(hprocess.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Graphics_Gdi")] #[inline] pub unsafe fn GetDpiForMonitor<'a, Param0: ::windows::core::IntoParam<'a, super::super::Graphics::Gdi::HMONITOR>>(hmonitor: Param0, dpitype: MONITOR_DPI_TYPE, dpix: *mut u32, dpiy: *mut u32) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetDpiForMonitor(hmonitor: super::super::Graphics::Gdi::HMONITOR, dpitype: MONITOR_DPI_TYPE, dpix: *mut u32, dpiy: *mut u32) -> ::windows::core::HRESULT; } GetDpiForMonitor(hmonitor.into_param().abi(), ::core::mem::transmute(dpitype), ::core::mem::transmute(dpix), ::core::mem::transmute(dpiy)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn GetDpiForSystem() -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetDpiForSystem() -> u32; } ::core::mem::transmute(GetDpiForSystem()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetDpiForWindow<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(hwnd: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetDpiForWindow(hwnd: super::super::Foundation::HWND) -> u32; } ::core::mem::transmute(GetDpiForWindow(hwnd.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn GetDpiFromDpiAwarenessContext<'a, Param0: ::windows::core::IntoParam<'a, DPI_AWARENESS_CONTEXT>>(value: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetDpiFromDpiAwarenessContext(value: DPI_AWARENESS_CONTEXT) -> u32; } ::core::mem::transmute(GetDpiFromDpiAwarenessContext(value.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetProcessDpiAwareness<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hprocess: Param0) -> ::windows::core::Result<PROCESS_DPI_AWARENESS> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetProcessDpiAwareness(hprocess: super::super::Foundation::HANDLE, value: *mut PROCESS_DPI_AWARENESS) -> ::windows::core::HRESULT; } let mut result__: <PROCESS_DPI_AWARENESS as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); GetProcessDpiAwareness(hprocess.into_param().abi(), &mut result__).from_abi::<PROCESS_DPI_AWARENESS>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetSystemDpiForProcess<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hprocess: Param0) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetSystemDpiForProcess(hprocess: super::super::Foundation::HANDLE) -> u32; } ::core::mem::transmute(GetSystemDpiForProcess(hprocess.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn GetSystemMetricsForDpi(nindex: i32, dpi: u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetSystemMetricsForDpi(nindex: i32, dpi: u32) -> i32; } ::core::mem::transmute(GetSystemMetricsForDpi(::core::mem::transmute(nindex), ::core::mem::transmute(dpi))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn GetThreadDpiAwarenessContext() -> DPI_AWARENESS_CONTEXT { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetThreadDpiAwarenessContext() -> DPI_AWARENESS_CONTEXT; } ::core::mem::transmute(GetThreadDpiAwarenessContext()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn GetThreadDpiHostingBehavior() -> DPI_HOSTING_BEHAVIOR { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetThreadDpiHostingBehavior() -> DPI_HOSTING_BEHAVIOR; } ::core::mem::transmute(GetThreadDpiHostingBehavior()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetWindowDpiAwarenessContext<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(hwnd: Param0) -> DPI_AWARENESS_CONTEXT { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetWindowDpiAwarenessContext(hwnd: super::super::Foundation::HWND) -> DPI_AWARENESS_CONTEXT; } ::core::mem::transmute(GetWindowDpiAwarenessContext(hwnd.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetWindowDpiHostingBehavior<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(hwnd: Param0) -> DPI_HOSTING_BEHAVIOR { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetWindowDpiHostingBehavior(hwnd: super::super::Foundation::HWND) -> DPI_HOSTING_BEHAVIOR; } ::core::mem::transmute(GetWindowDpiHostingBehavior(hwnd.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn IsValidDpiAwarenessContext<'a, Param0: ::windows::core::IntoParam<'a, DPI_AWARENESS_CONTEXT>>(value: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn IsValidDpiAwarenessContext(value: DPI_AWARENESS_CONTEXT) -> super::super::Foundation::BOOL; } ::core::mem::transmute(IsValidDpiAwarenessContext(value.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn LogicalToPhysicalPointForPerMonitorDPI<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(hwnd: Param0, lppoint: *mut super::super::Foundation::POINT) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LogicalToPhysicalPointForPerMonitorDPI(hwnd: super::super::Foundation::HWND, lppoint: *mut super::super::Foundation::POINT) -> super::super::Foundation::BOOL; } ::core::mem::transmute(LogicalToPhysicalPointForPerMonitorDPI(hwnd.into_param().abi(), ::core::mem::transmute(lppoint))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct MONITOR_DPI_TYPE(pub i32); pub const MDT_EFFECTIVE_DPI: MONITOR_DPI_TYPE = MONITOR_DPI_TYPE(0i32); pub const MDT_ANGULAR_DPI: MONITOR_DPI_TYPE = MONITOR_DPI_TYPE(1i32); pub const MDT_RAW_DPI: MONITOR_DPI_TYPE = MONITOR_DPI_TYPE(2i32); pub const MDT_DEFAULT: MONITOR_DPI_TYPE = MONITOR_DPI_TYPE(0i32); impl ::core::convert::From<i32> for MONITOR_DPI_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for MONITOR_DPI_TYPE { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn OpenThemeDataForDpi<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(hwnd: Param0, pszclasslist: Param1, dpi: u32) -> isize { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn OpenThemeDataForDpi(hwnd: super::super::Foundation::HWND, pszclasslist: super::super::Foundation::PWSTR, dpi: u32) -> isize; } ::core::mem::transmute(OpenThemeDataForDpi(hwnd.into_param().abi(), pszclasslist.into_param().abi(), ::core::mem::transmute(dpi))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PROCESS_DPI_AWARENESS(pub i32); pub const PROCESS_DPI_UNAWARE: PROCESS_DPI_AWARENESS = PROCESS_DPI_AWARENESS(0i32); pub const PROCESS_SYSTEM_DPI_AWARE: PROCESS_DPI_AWARENESS = PROCESS_DPI_AWARENESS(1i32); pub const PROCESS_PER_MONITOR_DPI_AWARE: PROCESS_DPI_AWARENESS = PROCESS_DPI_AWARENESS(2i32); impl ::core::convert::From<i32> for PROCESS_DPI_AWARENESS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PROCESS_DPI_AWARENESS { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn PhysicalToLogicalPointForPerMonitorDPI<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(hwnd: Param0, lppoint: *mut super::super::Foundation::POINT) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn PhysicalToLogicalPointForPerMonitorDPI(hwnd: super::super::Foundation::HWND, lppoint: *mut super::super::Foundation::POINT) -> super::super::Foundation::BOOL; } ::core::mem::transmute(PhysicalToLogicalPointForPerMonitorDPI(hwnd.into_param().abi(), ::core::mem::transmute(lppoint))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetDialogControlDpiChangeBehavior<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(hwnd: Param0, mask: DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS, values: DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetDialogControlDpiChangeBehavior(hwnd: super::super::Foundation::HWND, mask: DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS, values: DIALOG_CONTROL_DPI_CHANGE_BEHAVIORS) -> super::super::Foundation::BOOL; } ::core::mem::transmute(SetDialogControlDpiChangeBehavior(hwnd.into_param().abi(), ::core::mem::transmute(mask), ::core::mem::transmute(values))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetDialogDpiChangeBehavior<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HWND>>(hdlg: Param0, mask: DIALOG_DPI_CHANGE_BEHAVIORS, values: DIALOG_DPI_CHANGE_BEHAVIORS) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetDialogDpiChangeBehavior(hdlg: super::super::Foundation::HWND, mask: DIALOG_DPI_CHANGE_BEHAVIORS, values: DIALOG_DPI_CHANGE_BEHAVIORS) -> super::super::Foundation::BOOL; } ::core::mem::transmute(SetDialogDpiChangeBehavior(hdlg.into_param().abi(), ::core::mem::transmute(mask), ::core::mem::transmute(values))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SetProcessDpiAwareness(value: PROCESS_DPI_AWARENESS) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetProcessDpiAwareness(value: PROCESS_DPI_AWARENESS) -> ::windows::core::HRESULT; } SetProcessDpiAwareness(::core::mem::transmute(value)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetProcessDpiAwarenessContext<'a, Param0: ::windows::core::IntoParam<'a, DPI_AWARENESS_CONTEXT>>(value: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetProcessDpiAwarenessContext(value: DPI_AWARENESS_CONTEXT) -> super::super::Foundation::BOOL; } ::core::mem::transmute(SetProcessDpiAwarenessContext(value.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SetThreadDpiAwarenessContext<'a, Param0: ::windows::core::IntoParam<'a, DPI_AWARENESS_CONTEXT>>(dpicontext: Param0) -> DPI_AWARENESS_CONTEXT { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetThreadDpiAwarenessContext(dpicontext: DPI_AWARENESS_CONTEXT) -> DPI_AWARENESS_CONTEXT; } ::core::mem::transmute(SetThreadDpiAwarenessContext(dpicontext.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn SetThreadDpiHostingBehavior(value: DPI_HOSTING_BEHAVIOR) -> DPI_HOSTING_BEHAVIOR { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetThreadDpiHostingBehavior(value: DPI_HOSTING_BEHAVIOR) -> DPI_HOSTING_BEHAVIOR; } ::core::mem::transmute(SetThreadDpiHostingBehavior(::core::mem::transmute(value))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SystemParametersInfoForDpi(uiaction: u32, uiparam: u32, pvparam: *mut ::core::ffi::c_void, fwinini: u32, dpi: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SystemParametersInfoForDpi(uiaction: u32, uiparam: u32, pvparam: *mut ::core::ffi::c_void, fwinini: u32, dpi: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(SystemParametersInfoForDpi(::core::mem::transmute(uiaction), ::core::mem::transmute(uiparam), ::core::mem::transmute(pvparam), ::core::mem::transmute(fwinini), ::core::mem::transmute(dpi))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type HttpCacheDirectiveHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpChallengeHeaderValue = *mut ::core::ffi::c_void; pub type HttpChallengeHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpConnectionOptionHeaderValue = *mut ::core::ffi::c_void; pub type HttpConnectionOptionHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpContentCodingHeaderValue = *mut ::core::ffi::c_void; pub type HttpContentCodingHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpContentCodingWithQualityHeaderValue = *mut ::core::ffi::c_void; pub type HttpContentCodingWithQualityHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpContentDispositionHeaderValue = *mut ::core::ffi::c_void; pub type HttpContentHeaderCollection = *mut ::core::ffi::c_void; pub type HttpContentRangeHeaderValue = *mut ::core::ffi::c_void; pub type HttpCookiePairHeaderValue = *mut ::core::ffi::c_void; pub type HttpCookiePairHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpCredentialsHeaderValue = *mut ::core::ffi::c_void; pub type HttpDateOrDeltaHeaderValue = *mut ::core::ffi::c_void; pub type HttpExpectationHeaderValue = *mut ::core::ffi::c_void; pub type HttpExpectationHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpLanguageHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpLanguageRangeWithQualityHeaderValue = *mut ::core::ffi::c_void; pub type HttpLanguageRangeWithQualityHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpMediaTypeHeaderValue = *mut ::core::ffi::c_void; pub type HttpMediaTypeWithQualityHeaderValue = *mut ::core::ffi::c_void; pub type HttpMediaTypeWithQualityHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpMethodHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpNameValueHeaderValue = *mut ::core::ffi::c_void; pub type HttpProductHeaderValue = *mut ::core::ffi::c_void; pub type HttpProductInfoHeaderValue = *mut ::core::ffi::c_void; pub type HttpProductInfoHeaderValueCollection = *mut ::core::ffi::c_void; pub type HttpRequestHeaderCollection = *mut ::core::ffi::c_void; pub type HttpResponseHeaderCollection = *mut ::core::ffi::c_void; pub type HttpTransferCodingHeaderValue = *mut ::core::ffi::c_void; pub type HttpTransferCodingHeaderValueCollection = *mut ::core::ffi::c_void;
extern crate log; extern crate naia_derive; mod auth_event; mod example_actor; mod example_event; mod manifest_load; mod point_actor; mod shared_config; mod string_event; pub use auth_event::AuthEvent; pub use example_actor::ExampleActor; pub use example_event::ExampleEvent; pub use manifest_load::manifest_load; pub use point_actor::PointActor; pub use shared_config::get_shared_config; pub use string_event::StringEvent;
#[macro_use] extern crate construct; use std::collections::HashMap; fn main() { // Vector construction let v = construct!(Vec<_>, 1,2,3,4); assert_eq!(v, vec![1,2,3,4]); // Hashmap construction let m = construct!(HashMap<_,_>, (1, "hi"), (2, "bye")); let mut manual = HashMap::new(); manual.insert(1, "hi"); manual.insert(2, "bye"); assert_eq!(m, manual); }
use std::rc::Rc; use std::fs::File; use std::io::Read; use std::sync::Mutex; use std::time::{SystemTime, UNIX_EPOCH}; extern crate rustyline; use rustyline::error::ReadlineError; use rustyline::Editor; use types::{MalVal,MalArgs,MalRet,error,func,hash_map,_assoc,_dissoc,atom}; use types::MalVal::{Nil,Bool,Int,Str,Sym,List,Vector,Hash,Func,MalFunc,Atom}; use types::MalErr::{ErrMalVal}; use reader::read_str; use printer::pr_seq; macro_rules! fn_t_int_int { ($ret:ident, $fn:expr) => {{ |a:MalArgs| { match (a[0].clone(), a[1].clone()) { (Int(a0), Int(a1)) => Ok($ret($fn(a0, a1))), _ => error("expecting (int,int) args"), } } }}; } macro_rules! fn_is_type { ($($ps:pat),*) => {{ |a:MalArgs| { Ok(Bool(match a[0] { $($ps => true,)* _ => false})) } }}; ($p:pat if $e:expr) => {{ |a:MalArgs| { Ok(Bool(match a[0] { $p if $e => true, _ => false})) } }}; ($p:pat if $e:expr,$($ps:pat),*) => {{ |a:MalArgs| { Ok(Bool(match a[0] { $p if $e => true, $($ps => true,)* _ => false})) } }}; } macro_rules! fn_str { ($fn:expr) => {{ |a:MalArgs| { match a[0].clone() { Str(a0) => $fn(a0), _ => error("expecting (str) arg"), } } }}; } fn symbol(a: MalArgs) -> MalRet { match a[0] { Str(ref s) => Ok(Sym(s.to_string())), _ => error("illegal symbol call") } } fn readline(a: MalArgs) -> MalRet { lazy_static! { static ref RL: Mutex<Editor<()>> = Mutex::new(Editor::<()>::new()); } //let mut rl = Editor::<()>::new(); match a[0] { Str(ref p) => { //match rl.readline(p) { match RL.lock().unwrap().readline(p) { Ok(line) => Ok(Str(line)), Err(ReadlineError::Eof) => Ok(Nil), Err(e) => error(&format!("{:?}", e)) } }, _ => error("readline: prompt is not Str"), } } fn slurp(f: String) -> MalRet { let mut s = String::new(); match File::open(f).and_then(|mut f| f.read_to_string(&mut s)) { Ok(_) => Ok(Str(s)), Err(e) => error(&e.to_string()), } } fn time_ms(_a: MalArgs) -> MalRet { let ms_e = match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(d) => d, Err(e) => return error(&format!("{:?}", e)), }; Ok(Int(ms_e.as_secs() as i64 * 1000 + ms_e.subsec_nanos() as i64 / 1_000_000)) } fn get(a: MalArgs) -> MalRet { match (a[0].clone(), a[1].clone()) { (Nil, _) => Ok(Nil), (Hash(ref hm,_), Str(ref s)) => { match hm.get(s) { Some(mv) => Ok(mv.clone()), None => Ok(Nil), } }, _ => error("illegal get args") } } fn assoc(a: MalArgs) -> MalRet { match a[0] { Hash(ref hm,_) => _assoc((**hm).clone(), a[1..].to_vec()), _ => error("assoc on non-Hash Map") } } fn dissoc(a: MalArgs) -> MalRet { match a[0] { Hash(ref hm,_) => _dissoc((**hm).clone(), a[1..].to_vec()), _ => error("dissoc on non-Hash Map") } } fn contains_q(a: MalArgs) -> MalRet { match (a[0].clone(), a[1].clone()) { (Hash(ref hm,_), Str(ref s)) => { Ok(Bool(hm.contains_key(s))) }, _ => error("illegal get args") } } fn keys(a: MalArgs) -> MalRet { match a[0] { Hash(ref hm,_) => { Ok(list!(hm.keys().map(|k|{Str(k.to_string())}).collect())) }, _ => error("keys requires Hash Map") } } fn vals(a: MalArgs) -> MalRet { match a[0] { Hash(ref hm,_) => { Ok(list!(hm.values().map(|v|{v.clone()}).collect())) }, _ => error("keys requires Hash Map") } } fn cons(a: MalArgs) -> MalRet { match a[1].clone() { List(v,_) | Vector(v,_) => { let mut new_v = vec![a[0].clone()]; new_v.extend_from_slice(&v); Ok(list!(new_v.to_vec())) }, _ => error("cons expects seq as second arg"), } } fn concat(a: MalArgs) -> MalRet { let mut new_v = vec![]; for seq in a.iter() { match seq { List(v,_) | Vector(v,_) => new_v.extend_from_slice(v), _ => return error("non-seq passed to concat"), } } Ok(list!(new_v.to_vec())) } fn nth(a: MalArgs) -> MalRet { match (a[0].clone(), a[1].clone()) { (List(seq,_), Int(idx)) | (Vector(seq,_), Int(idx)) => { if seq.len() <= idx as usize { return error("nth: index out of range"); } Ok(seq[idx as usize].clone()) } _ => error("invalid args to nth"), } } fn first(a: MalArgs) -> MalRet { match a[0].clone() { List(ref seq,_) | Vector(ref seq,_) if seq.len() == 0 => Ok(Nil), List(ref seq,_) | Vector(ref seq,_) => Ok(seq[0].clone()), Nil => Ok(Nil), _ => error("invalid args to first"), } } fn rest(a: MalArgs) -> MalRet { match a[0].clone() { List(ref seq,_) | Vector(ref seq,_) => { if seq.len() > 1 { Ok(list!(seq[1..].to_vec())) } else { Ok(list![]) } }, Nil => Ok(list![]), _ => error("invalid args to first"), } } fn apply(a: MalArgs) -> MalRet { match a[a.len()-1] { List(ref v,_) | Vector(ref v,_) => { let f = &a[0]; let mut fargs = a[1..a.len()-1].to_vec(); fargs.extend_from_slice(&v); f.apply(fargs) }, _ => error("apply called with non-seq"), } } fn map(a: MalArgs) -> MalRet { match a[1] { List(ref v,_) | Vector(ref v,_) => { let mut res = vec![]; for mv in v.iter() { res.push(a[0].apply(vec![mv.clone()])?) } Ok(list!(res)) }, _ => error("map called with non-seq"), } } fn conj(a: MalArgs) -> MalRet { match a[0] { List(ref v,_) => { let sl = a[1..].iter().rev().map(|a|{a.clone()}).collect::<Vec<MalVal>>(); Ok(list!([&sl[..],v].concat())) }, Vector(ref v,_) => Ok(vector!([v,&a[1..]].concat())), _ => error("conj: called with non-seq"), } } fn seq(a: MalArgs) -> MalRet { match a[0] { List(ref v,_) | Vector(ref v,_) if v.len() == 0 => Ok(Nil), List(ref v,_) | Vector(ref v,_) => Ok(list!(v.to_vec())), Str(ref s) if s.len() == 0 => Ok(Nil), Str(ref s) if !a[0].keyword_q() => { Ok(list!(s.chars().map(|c|{Str(c.to_string())}).collect())) }, Nil => Ok(Nil), _ => error("seq: called with non-seq"), } } pub fn ns() -> Vec<(&'static str, MalVal)> { vec![ ("=", func(|a|{Ok(Bool(a[0] == a[1]))})), ("throw", func(|a|{Err(ErrMalVal(a[0].clone()))})), ("nil?", func(fn_is_type!(Nil))), ("true?", func(fn_is_type!(Bool(true)))), ("false?", func(fn_is_type!(Bool(false)))), ("symbol", func(symbol)), ("symbol?", func(fn_is_type!(Sym(_)))), ("string?", func(fn_is_type!(Str(ref s) if !s.starts_with("\u{29e}")))), ("keyword", func(|a|{a[0].keyword()})), ("keyword?", func(fn_is_type!(Str(ref s) if s.starts_with("\u{29e}")))), ("number?", func(fn_is_type!(Int(_)))), ("fn?", func(fn_is_type!(MalFunc{is_macro,..} if !is_macro,Func(_,_)))), ("macro?", func(fn_is_type!(MalFunc{is_macro,..} if is_macro))), ("pr-str", func(|a|Ok(Str(pr_seq(&a, true, "", "", " "))))), ("str", func(|a|Ok(Str(pr_seq(&a, false, "", "", ""))))), ("prn", func(|a|{println!("{}", pr_seq(&a, true, "", "", " ")); Ok(Nil)})), ("println", func(|a|{println!("{}", pr_seq(&a, false, "", "", " ")); Ok(Nil)})), ("read-string", func(fn_str!(|s|{read_str(s)}))), ("readline", func(readline)), ("slurp", func(fn_str!(|f|{slurp(f)}))), ("<", func(fn_t_int_int!(Bool,|i,j|{i<j}))), ("<=", func(fn_t_int_int!(Bool,|i,j|{i<=j}))), (">", func(fn_t_int_int!(Bool,|i,j|{i>j}))), (">=", func(fn_t_int_int!(Bool,|i,j|{i>=j}))), ("+", func(fn_t_int_int!(Int,|i,j|{i+j}))), ("-", func(fn_t_int_int!(Int,|i,j|{i-j}))), ("*", func(fn_t_int_int!(Int,|i,j|{i*j}))), ("/", func(fn_t_int_int!(Int,|i,j|{i/j}))), ("time-ms", func(time_ms)), ("sequential?", func(fn_is_type!(List(_,_),Vector(_,_)))), ("list", func(|a|{Ok(list!(a))})), ("list?", func(fn_is_type!(List(_,_)))), ("vector", func(|a|{Ok(vector!(a))})), ("vector?", func(fn_is_type!(Vector(_,_)))), ("hash-map", func(|a|{hash_map(a)})), ("map?", func(fn_is_type!(Hash(_,_)))), ("assoc", func(assoc)), ("dissoc", func(dissoc)), ("get", func(get)), ("contains?", func(contains_q)), ("keys", func(keys)), ("vals", func(vals)), ("cons", func(cons)), ("concat", func(concat)), ("empty?", func(|a|{a[0].empty_q()})), ("nth", func(nth)), ("first", func(first)), ("rest", func(rest)), ("count", func(|a|{a[0].count()})), ("apply", func(apply)), ("map", func(map)), ("conj", func(conj)), ("seq", func(seq)), ("meta", func(|a|{a[0].get_meta()})), ("with-meta", func(|a|{a[0].clone().with_meta(&a[1])})), ("atom", func(|a|{Ok(atom(&a[0]))})), ("atom?", func(fn_is_type!(Atom(_)))), ("deref", func(|a|{a[0].deref()})), ("reset!", func(|a|{a[0].reset_bang(&a[1])})), ("swap!", func(|a|{a[0].swap_bang(&a[1..].to_vec())})), ] } // vim: ts=2:sw=2:expandtab
use std::collections::HashMap; use super::hash_session; use super::HashSessionStore; use super::SessionPair; use super::SessionStore; #[test] fn test_generate_id(){ let s = super::generate_id(); println!("{}",s); } #[test] fn test_session() { // let hs: HashSessionStore<String> = HashSessionStore::new(); let session_id = "1".into(); // Create session storage let hs2 = hash_session(); // Insert new session let mut map = HashMap::new(); map.insert("user_id".to_string(), "1".to_string()); let mut map_mut = map.clone(); hs2.set(&session_id, map); // Update existed session map_mut.insert("user_name".to_string(), "jarrysix".to_string()); hs2.set(&session_id, map_mut); // Get session let map: HashMap<String, String> = hs2.get(&session_id).unwrap(); println!("{:#?}", map); assert_eq!(1, 1); }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::PP { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct PWM_PP_GCNTR { bits: u8, } impl PWM_PP_GCNTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _PWM_PP_GCNTW<'a> { w: &'a mut W, } impl<'a> _PWM_PP_GCNTW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 0); self.w.bits |= ((value as u32) & 15) << 0; self.w } } #[doc = r"Value of the field"] pub struct PWM_PP_FCNTR { bits: u8, } impl PWM_PP_FCNTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _PWM_PP_FCNTW<'a> { w: &'a mut W, } impl<'a> _PWM_PP_FCNTW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(15 << 4); self.w.bits |= ((value as u32) & 15) << 4; self.w } } #[doc = r"Value of the field"] pub struct PWM_PP_ESYNCR { bits: bool, } impl PWM_PP_ESYNCR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _PWM_PP_ESYNCW<'a> { w: &'a mut W, } impl<'a> _PWM_PP_ESYNCW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct PWM_PP_EFAULTR { bits: bool, } impl PWM_PP_EFAULTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _PWM_PP_EFAULTW<'a> { w: &'a mut W, } impl<'a> _PWM_PP_EFAULTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 9); self.w.bits |= ((value as u32) & 1) << 9; self.w } } #[doc = r"Value of the field"] pub struct PWM_PP_ONER { bits: bool, } impl PWM_PP_ONER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _PWM_PP_ONEW<'a> { w: &'a mut W, } impl<'a> _PWM_PP_ONEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 10); self.w.bits |= ((value as u32) & 1) << 10; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:3 - Generators"] #[inline(always)] pub fn pwm_pp_gcnt(&self) -> PWM_PP_GCNTR { let bits = ((self.bits >> 0) & 15) as u8; PWM_PP_GCNTR { bits } } #[doc = "Bits 4:7 - Fault Inputs (per PWM unit)"] #[inline(always)] pub fn pwm_pp_fcnt(&self) -> PWM_PP_FCNTR { let bits = ((self.bits >> 4) & 15) as u8; PWM_PP_FCNTR { bits } } #[doc = "Bit 8 - Extended Synchronization"] #[inline(always)] pub fn pwm_pp_esync(&self) -> PWM_PP_ESYNCR { let bits = ((self.bits >> 8) & 1) != 0; PWM_PP_ESYNCR { bits } } #[doc = "Bit 9 - Extended Fault"] #[inline(always)] pub fn pwm_pp_efault(&self) -> PWM_PP_EFAULTR { let bits = ((self.bits >> 9) & 1) != 0; PWM_PP_EFAULTR { bits } } #[doc = "Bit 10 - One-Shot Mode"] #[inline(always)] pub fn pwm_pp_one(&self) -> PWM_PP_ONER { let bits = ((self.bits >> 10) & 1) != 0; PWM_PP_ONER { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:3 - Generators"] #[inline(always)] pub fn pwm_pp_gcnt(&mut self) -> _PWM_PP_GCNTW { _PWM_PP_GCNTW { w: self } } #[doc = "Bits 4:7 - Fault Inputs (per PWM unit)"] #[inline(always)] pub fn pwm_pp_fcnt(&mut self) -> _PWM_PP_FCNTW { _PWM_PP_FCNTW { w: self } } #[doc = "Bit 8 - Extended Synchronization"] #[inline(always)] pub fn pwm_pp_esync(&mut self) -> _PWM_PP_ESYNCW { _PWM_PP_ESYNCW { w: self } } #[doc = "Bit 9 - Extended Fault"] #[inline(always)] pub fn pwm_pp_efault(&mut self) -> _PWM_PP_EFAULTW { _PWM_PP_EFAULTW { w: self } } #[doc = "Bit 10 - One-Shot Mode"] #[inline(always)] pub fn pwm_pp_one(&mut self) -> _PWM_PP_ONEW { _PWM_PP_ONEW { w: self } } }
trait Foo { fn edible(&self) -> bool { false } } struct Bar<T> { value: T } impl Foo for Bar<i64> {} impl Foo for Bar<i32> { fn edible(&self) -> bool { true } } fn main() { let x = Box::new(Bar{value: 42i32}); println!("{}", &x.value); println!("{}", x.edible()); }
use std::thread; use std::net::{TcpListener, TcpStream, Shutdown}; use std::io::{Read, Write}; use std::str::from_utf8; fn handle_client(mut stream: TcpStream) { let mut buffer = [0 as u8; 100]; // using 100 byte buffer while match stream.read(&mut buffer) { Ok(_) => { // echo everything! let data = from_utf8(&buffer).unwrap().trim().replace("\n", ""); println!("Receive data: {} from {} ", data, stream.peer_addr().unwrap()); let sub:String = data.chars().skip(0).take(4).collect(); // if read exit from client, just return if sub == "exit" { println!("exit!"); //stream.shutdown(Shutdown::Read).unwrap(); return; } // flush the stream stream.flush().ok(); true }, Err(_) => { println!("An error occurred, terminating connection with {}", stream.peer_addr().unwrap()); stream.shutdown(Shutdown::Read).unwrap(); false } } {} } fn main() { let listener = TcpListener::bind("0.0.0.0:3333").unwrap(); // accept connections and process them, spawning a new thread for each one let mut thread_vec: Vec<thread::JoinHandle<()>> = Vec::new(); println!("Server listening on port 3333"); for stream in listener.incoming() { match stream { Ok(stream) => { println!("New connection: {}", stream.peer_addr().unwrap()); let handle = thread::spawn(move|| { // connection succeeded handle_client(stream) }); thread_vec.push(handle); } Err(e) => { println!("Error: {}", e); /* connection failed */ } } } // wait for thread finishing task for handle in thread_vec { handle.join().unwrap(); } // close the socket server drop(listener); }
use std::borrow::Borrow; use std::io::Read; use std::mem; use std::sync::Arc; use crossbeam_channel::{bounded, Receiver, Sender, TrySendError}; use crate::common::{CancelSignal, Result}; use crate::runtime::{ splitter::{ batch::{ get_find_indexes, BytesIndexKernel, InputFormat, Offsets, WhitespaceIndexKernel, WhitespaceOffsets, }, Reader, }, str_impl::UniqueBuf, }; // TODO: We probably want a better story here about ChunkProducers propagating error values. pub trait ChunkProducer { type Chunk: Chunk; // Create up to _requested_size additional handles to the ChunkProducer, if possible. Chunk is // Send, so these new producers can be used to read from the same source in parallel. // // NB: what's going on with this gnarly return type? All implementations either return an empty // vector or a vector containing functions returning Box<Self>, but we need this trait to be // object-safe, so it returns a trait object instead. // // Why return a FnOnce rather than a trait object directly? Some ChunkProducer // implementations are not Send, even though the data to initialize a new ChunkProducer reading // from the same source is Send. Passing a FnOnce allows us to handle this, which is the case // for (e.g.) ShardedChunkProducer. fn try_dyn_resize( &self, _requested_size: usize, ) -> Vec<Box<dyn FnOnce() -> Box<dyn ChunkProducer<Chunk = Self::Chunk>> + Send>> { vec![] } fn wait(&self) -> bool { true } fn get_chunk(&mut self, chunk: &mut Self::Chunk) -> Result<bool /*done*/>; fn next_file(&mut self) -> Result<bool /*new file available*/>; } pub trait Chunk: Send + Default { fn get_name(&self) -> &str; } #[derive(Copy, Clone)] enum ChunkState { Init, Main, Done, } pub struct OffsetChunkProducer<R, F> { inner: Reader<R>, cur_file_version: u32, name: Arc<str>, find_indexes: F, record_sep: u8, state: ChunkState, } pub fn new_offset_chunk_producer_csv<R: Read>( r: R, chunk_size: usize, name: &str, ifmt: InputFormat, start_version: u32, check_utf8: bool, ) -> OffsetChunkProducer<R, impl FnMut(&[u8], &mut Offsets)> { let find_indexes = get_find_indexes(ifmt); OffsetChunkProducer { name: name.into(), inner: Reader::new(r, chunk_size, /*padding=*/ 128, check_utf8), find_indexes: move |bs: &[u8], offs: &mut Offsets| { unsafe { find_indexes(bs, offs, 0, 0) }; }, record_sep: b'\n', cur_file_version: start_version, state: ChunkState::Init, } } pub fn new_offset_chunk_producer_bytes<R: Read>( r: R, chunk_size: usize, name: &str, field_sep: u8, record_sep: u8, start_version: u32, check_utf8: bool, find_indexes: BytesIndexKernel, ) -> OffsetChunkProducer<R, impl FnMut(&[u8], &mut Offsets)> { OffsetChunkProducer { name: name.into(), inner: Reader::new(r, chunk_size, /*padding=*/ 128, check_utf8), find_indexes: move |bs: &[u8], offs: &mut Offsets| unsafe { find_indexes(bs, offs, field_sep, record_sep) }, cur_file_version: start_version, record_sep, state: ChunkState::Init, } } pub fn new_offset_chunk_producer_ascii_whitespace<R: Read>( r: R, chunk_size: usize, name: &str, start_version: u32, check_utf8: bool, find_indexes: WhitespaceIndexKernel, ) -> WhitespaceChunkProducer<R, impl FnMut(&[u8], &mut WhitespaceOffsets, u64) -> u64> { WhitespaceChunkProducer( OffsetChunkProducer { name: name.into(), inner: Reader::new(r, chunk_size, /*padding=*/ 128, check_utf8), find_indexes: move |bs: &[u8], offs: &mut WhitespaceOffsets, start: u64| unsafe { find_indexes(bs, offs, start) }, cur_file_version: start_version, record_sep: 0u8, // unused state: ChunkState::Init, }, 1, ) } pub fn new_chained_offset_chunk_producer_csv< 'a, R: Read, N: Borrow<str>, I: Iterator<Item = (R, N)>, >( r: I, chunk_size: usize, ifmt: InputFormat, check_utf8: bool, ) -> ChainedChunkProducer<OffsetChunkProducer<R, impl FnMut(&[u8], &mut Offsets)>> { ChainedChunkProducer::new( r.enumerate() .map(|(i, (r, name))| { new_offset_chunk_producer_csv( r, chunk_size, name.borrow(), ifmt, /*start_version=*/ (i as u32).wrapping_add(1), check_utf8, ) }) .collect(), ) } pub fn new_chained_offset_chunk_producer_bytes< R: Read, N: Borrow<str>, I: Iterator<Item = (R, N)>, >( r: I, chunk_size: usize, field_sep: u8, record_sep: u8, check_utf8: bool, kernel: BytesIndexKernel, ) -> ChainedChunkProducer<OffsetChunkProducer<R, impl FnMut(&[u8], &mut Offsets)>> { ChainedChunkProducer::new( r.enumerate() .map(|(i, (r, name))| { new_offset_chunk_producer_bytes( r, chunk_size, name.borrow(), field_sep, record_sep, /*start_version=*/ (i as u32).wrapping_add(1), check_utf8, kernel, ) }) .collect(), ) } pub fn new_chained_offset_chunk_producer_ascii_whitespace< R: Read, N: Borrow<str>, I: Iterator<Item = (R, N)>, >( r: I, chunk_size: usize, check_utf8: bool, find_indexes: WhitespaceIndexKernel, ) -> ChainedChunkProducer< WhitespaceChunkProducer<R, impl FnMut(&[u8], &mut WhitespaceOffsets, u64) -> u64>, > { ChainedChunkProducer::new( r.enumerate() .map(|(i, (r, name))| { new_offset_chunk_producer_ascii_whitespace( r, chunk_size, name.borrow(), /*start_version=*/ (i as u32).wrapping_add(1), check_utf8, find_indexes, ) }) .collect(), ) } impl<C: Chunk> ChunkProducer for Box<dyn ChunkProducer<Chunk = C>> { type Chunk = C; fn try_dyn_resize( &self, requested_size: usize, ) -> Vec<Box<dyn FnOnce() -> Box<dyn ChunkProducer<Chunk = C>> + Send>> { (&**self).try_dyn_resize(requested_size) } fn wait(&self) -> bool { (&**self).wait() } fn next_file(&mut self) -> Result<bool> { (&mut **self).next_file() } fn get_chunk(&mut self, chunk: &mut C) -> Result<bool> { (&mut **self).get_chunk(chunk) } } pub struct OffsetChunk<Off = Offsets> { pub version: u32, pub name: Arc<str>, pub buf: Option<UniqueBuf>, pub len: usize, pub off: Off, } impl<Off: Default> Default for OffsetChunk<Off> { fn default() -> OffsetChunk<Off> { OffsetChunk { version: 0, name: "".into(), buf: None, len: 0, off: Default::default(), } } } impl<Off: Default + Send> Chunk for OffsetChunk<Off> { fn get_name(&self) -> &str { &*self.name } } impl<R: Read, F: FnMut(&[u8], &mut Offsets)> ChunkProducer for OffsetChunkProducer<R, F> { type Chunk = OffsetChunk; fn next_file(&mut self) -> Result<bool> { self.state = ChunkState::Done; self.inner.force_eof(); Ok(false) } fn get_chunk(&mut self, chunk: &mut OffsetChunk) -> Result<bool> { loop { match self.state { ChunkState::Init => { self.state = if self.inner.reset()? { ChunkState::Done } else { ChunkState::Main }; } ChunkState::Main => { chunk.version = self.cur_file_version; chunk.name = self.name.clone(); let buf = self.inner.buf.clone(); let bs = buf.as_bytes(); (self.find_indexes)(bs, &mut chunk.off); let mut target = None; let mut new_len = chunk.off.rel.fields.len(); let mut always_truncate = new_len; for offset in chunk.off.rel.fields.iter().rev() { let offset = *offset as usize; if offset >= self.inner.end { always_truncate -= 1; new_len -= 1; continue; } if bs[offset] == self.record_sep { target = Some(offset + 1); break; } new_len -= 1; } debug_assert!(new_len <= always_truncate); let is_partial = if let Some(chunk_end) = target { self.inner.start = chunk_end; false } else { debug_assert_eq!(new_len, 0); true }; // chunk.len is a bit tricky. There are two signals that we have to take into // account: // 1) Is this the last buffer? (is_eof) // 2) Does this buffer contain a record separator? (!is_partial) // // If it is the last buffer then we should set chunk.len to self.inner.end, // which is all of the bytes that were returned by the underlying reader. This // is true regardless of whether or not there's a record separator in the // input. // // If this is _not_ the last buffer and we do have a record separator, we need // to adjust the length of the chunk to only encompass the buffer's contents up // through the last record separator (target.unwrap()). // // Lastly, if it is not the last buffer and we do not have a record separator, // we simply repeat this entire loop. chunk.len = self.inner.end; let is_eof = self.inner.reset()?; return match (is_partial, is_eof) { (false, false) => { // Yield buffer, stay in main. chunk.buf = Some(buf.try_unique().unwrap()); chunk.off.rel.fields.truncate(new_len); chunk.len = target.unwrap(); Ok(false) } (false, true) | (true, true) => { // Yield the entire buffer, this was the last piece of data. self.inner.clear_buf(); chunk.buf = Some(buf.try_unique().unwrap()); chunk.off.rel.fields.truncate(always_truncate); self.state = ChunkState::Done; Ok(false) } // We read an entire chunk, but we didn't find a full record. Try again // (note that the call to reset read in a larger chunk and would have kept // a prefix) (true, false) => continue, }; } ChunkState::Done => return Ok(true), } } } } pub struct WhitespaceChunkProducer<R, F>(OffsetChunkProducer<R, F>, u64); impl<R: Read, F: FnMut(&[u8], &mut WhitespaceOffsets, u64) -> u64> ChunkProducer for WhitespaceChunkProducer<R, F> { type Chunk = OffsetChunk<WhitespaceOffsets>; fn next_file(&mut self) -> Result<bool> { self.0.state = ChunkState::Done; self.0.inner.force_eof(); Ok(false) } fn get_chunk(&mut self, chunk: &mut Self::Chunk) -> Result<bool> { loop { match self.0.state { ChunkState::Init => { self.0.state = if self.0.inner.reset()? { ChunkState::Done } else { ChunkState::Main }; } ChunkState::Main => { chunk.version = self.0.cur_file_version; chunk.name = self.0.name.clone(); let buf = self.0.inner.buf.clone(); let bs = buf.as_bytes(); self.1 = (self.0.find_indexes)(bs, &mut chunk.off, self.1); // Find the last newline in the buffer, if there is one. let (is_partial, truncate_to, len_if_not_last) = if let Some(nl_off) = chunk.off.0.nl.fields.last().cloned() { let buf_end = nl_off as usize + 1; self.0.inner.start = buf_end; let mut start = chunk.off.0.rel.fields.len() as isize - 1; while start > 0 { if chunk.off.0.rel.fields[start as usize] > nl_off as u64 { // We are removing trailing fields from the input, but we know // that newlines are whitespace, so we reset the start_ws // variable to 1. self.1 = 1; start -= 1; } else { break; } } (false, start as usize, buf_end) } else { (true, 0, 0) }; // See comments in get_chunk for OffsetChunkProducer<R, F> chunk.len = self.0.inner.end; let is_eof = self.0.inner.reset()?; return match (is_partial, is_eof) { (false, false) => { // Yield buffer, stay in main. chunk.buf = Some(buf.try_unique().unwrap()); chunk.off.0.rel.fields.truncate(truncate_to); chunk.len = len_if_not_last; Ok(false) } (false, true) | (true, true) => { // Yield the entire buffer, this was the last piece of data. self.0.inner.clear_buf(); chunk.buf = Some(buf.try_unique().unwrap()); self.0.state = ChunkState::Done; Ok(false) } // We read an entire chunk, but we didn't find a full record. Try again // (note that the call to reset read in a larger chunk and would have kept // a prefix) (true, false) => continue, }; } ChunkState::Done => return Ok(true), } } } } pub struct ChainedChunkProducer<P>(Vec<P>); impl<P> ChainedChunkProducer<P> { fn new(mut v: Vec<P>) -> ChainedChunkProducer<P> { v.reverse(); ChainedChunkProducer(v) } } impl<P: ChunkProducer> ChunkProducer for ChainedChunkProducer<P> { type Chunk = P::Chunk; fn wait(&self) -> bool { let res = if let Some(cur) = self.0.last() { cur.wait() } else { true }; res } fn next_file(&mut self) -> Result<bool> { if let Some(cur) = self.0.last_mut() { if !cur.next_file()? { let _last = self.0.pop(); debug_assert!(_last.is_some()); } Ok(self.0.len() != 0) } else { Ok(false) } } fn get_chunk(&mut self, chunk: &mut P::Chunk) -> Result<bool> { while let Some(cur) = self.0.last_mut() { if !cur.get_chunk(chunk)? { return Ok(false); } let _last = self.0.pop(); debug_assert!(_last.is_some()); } Ok(true) } } /// ParallelChunkProducer allows for consumption of individual chunks from a ChunkProducer in /// parallel. pub struct ParallelChunkProducer<P: ChunkProducer> { start: Receiver<()>, incoming: Receiver<P::Chunk>, spent: Sender<P::Chunk>, } impl<P: ChunkProducer> Clone for ParallelChunkProducer<P> { fn clone(&self) -> ParallelChunkProducer<P> { ParallelChunkProducer { start: self.start.clone(), incoming: self.incoming.clone(), spent: self.spent.clone(), } } } impl<P: ChunkProducer + 'static> ParallelChunkProducer<P> { pub fn new( p_factory: impl FnOnce() -> P + Send + 'static, chan_size: usize, ) -> ParallelChunkProducer<P> { let (start_sender, start_receiver) = bounded(chan_size); let (in_sender, in_receiver) = bounded(chan_size); let (spent_sender, spent_receiver) = bounded(chan_size); std::thread::spawn(move || { let mut n_workers = 0; let mut p = p_factory(); let mut n_failures = 0; loop { let mut chunk = spent_receiver .try_recv() .ok() .unwrap_or_else(P::Chunk::default); let chunk_res = p.get_chunk(&mut chunk); if chunk_res.is_err() || matches!(chunk_res, Ok(true)) { return; } match in_sender.try_send(chunk) { Ok(()) => { n_failures = 0; continue; } Err(TrySendError::Full(c)) => { n_failures += 1; chunk = c; } Err(TrySendError::Disconnected(_)) => { return; } } // TODO: This heuristic works fairly well when the target is a relatively small // number of workers. The idea here is that we require progressively stronger // signals that we are producing chunks too fast before starting a new worker. // // However, for extremely expensive worker functions, this heuristic will not // learn the optimal number of workers before the 2s timeout in wait() // // One alternative is to keep a running average of the amount of time it takes // to read a chunk, and a running average of the amount of time spent blocking // to send a chunk (perhaps a rolling window, or one that downweights previous // runs). // // The amount of time we spend blocking will give us an idea of the total parallel // throughput of the workers. If the throughput is lower than the speed at which we // read the chunks, that's a signal to up the number of workers (potentially not // just incrementing them, but adding them 'all at once'). if n_failures == (2 << n_workers) { if start_sender.try_send(()).is_ok() { n_workers += 1; } n_failures = 0; } if in_sender.send(chunk).is_err() { return; } } }); ParallelChunkProducer { start: start_receiver, incoming: in_receiver, spent: spent_sender, } } } impl<P: ChunkProducer + 'static> ChunkProducer for ParallelChunkProducer<P> { type Chunk = P::Chunk; fn try_dyn_resize( &self, requested_size: usize, ) -> Vec<Box<dyn FnOnce() -> Box<dyn ChunkProducer<Chunk = Self::Chunk>> + Send>> { let mut res = Vec::with_capacity(requested_size); for _ in 0..requested_size { let p = self.clone(); res.push(Box::new(move || Box::new(p) as Box<dyn ChunkProducer<Chunk = P::Chunk>>) as _) } res } fn next_file(&mut self) -> Result<bool> { err!("nextfile is not supported in record-oriented parallel mode") } fn wait(&self) -> bool { self.start .recv_timeout(std::time::Duration::from_secs(2)) .is_ok() } fn get_chunk(&mut self, chunk: &mut P::Chunk) -> Result<bool> { if let Ok(mut new_chunk) = self.incoming.recv() { mem::swap(chunk, &mut new_chunk); let _ = self.spent.try_send(new_chunk); Ok(false) } else { Ok(true) } } } enum ProducerState<T> { Init, Main(T), Done, } /// ShardedChunkProducer allows consuption of entire chunk producers in parallel pub struct ShardedChunkProducer<P> { incoming: Receiver<Box<dyn FnOnce() -> P + Send>>, state: ProducerState<P>, } impl<P: ChunkProducer + 'static> ShardedChunkProducer<P> { pub fn new<Iter>(ps: Iter) -> ShardedChunkProducer<P> where Iter: Iterator + 'static + Send, Iter::Item: FnOnce() -> P + 'static + Send, { // These are usually individual files, which should be fairly large, so we hard-code a // small buffer. let (sender, receiver) = bounded(1); std::thread::spawn(move || { for p_factory in ps { let to_send: Box<dyn FnOnce() -> P + Send> = Box::new(p_factory); if sender.send(to_send).is_err() { return; } } }); ShardedChunkProducer { incoming: receiver, state: ProducerState::Init, } } fn refresh_producer(&mut self) -> bool { let next = if let Ok(p) = self.incoming.recv() { p } else { self.state = ProducerState::Done; return false; }; self.state = ProducerState::Main(next()); true } } impl<P: ChunkProducer + 'static> ChunkProducer for ShardedChunkProducer<P> { type Chunk = P::Chunk; fn try_dyn_resize( &self, requested_size: usize, ) -> Vec<Box<dyn FnOnce() -> Box<dyn ChunkProducer<Chunk = Self::Chunk>> + Send>> { let mut res = Vec::with_capacity(requested_size); for _ in 0..requested_size { let incoming = self.incoming.clone(); res.push(Box::new(move || { Box::new(ShardedChunkProducer { incoming, state: ProducerState::Init, }) as Box<dyn ChunkProducer<Chunk = P::Chunk>> }) as _) } res } fn next_file(&mut self) -> Result<bool> { match &mut self.state { ProducerState::Init => Ok(self.refresh_producer()), ProducerState::Done => Ok(false), ProducerState::Main(p) => Ok(p.next_file()? || self.refresh_producer()), } } fn get_chunk(&mut self, chunk: &mut Self::Chunk) -> Result<bool> { loop { match &mut self.state { ProducerState::Main(p) => { if !p.get_chunk(chunk)? { return Ok(false); } self.refresh_producer() } ProducerState::Init => self.refresh_producer(), ProducerState::Done => return Ok(true), }; } } } /// A ChunkProducer that stops input early if a [CancelSignal] is triggered. pub struct CancellableChunkProducer<P> { signal: CancelSignal, prod: P, } impl<P: ChunkProducer + 'static> CancellableChunkProducer<P> { pub fn new(signal: CancelSignal, prod: P) -> Self { Self { signal, prod } } } impl<P: ChunkProducer + 'static> ChunkProducer for CancellableChunkProducer<P> { type Chunk = P::Chunk; // TODO this API means we have two layers of virtual dispatch, which isn't great. // It's not the end of the world, but we should think about whether there is a way around this. fn try_dyn_resize( &self, requested_size: usize, ) -> Vec<Box<dyn FnOnce() -> Box<dyn ChunkProducer<Chunk = Self::Chunk>> + Send>> { let children = self.prod.try_dyn_resize(requested_size); let mut res = Vec::with_capacity(children.len()); for factory in children.into_iter() { let signal = self.signal.clone(); res.push(Box::new(move || { Box::new(CancellableChunkProducer { signal, prod: factory(), }) as Box<dyn ChunkProducer<Chunk = P::Chunk>> }) as _) } res } fn wait(&self) -> bool { self.prod.wait() } fn next_file(&mut self) -> Result<bool> { if self.signal.cancelled() { return Ok(false); } self.prod.next_file() } fn get_chunk(&mut self, chunk: &mut P::Chunk) -> Result<bool> { if self.signal.cancelled() { return Ok(true); } self.prod.get_chunk(chunk) } } #[cfg(test)] mod tests { use super::*; // Basic machinery to turn an iterator into a ChunkProducer. This makes it easier to unit test // the "derived ChunkProducers" like ParallelChunkProducer. fn new_iter( low: usize, high: usize, name: &str, ) -> impl FnOnce() -> IterChunkProducer<std::ops::Range<usize>> { let name: Arc<str> = name.into(); move || IterChunkProducer { iter: (low..high), name, } } struct IterChunkProducer<I> { iter: I, name: Arc<str>, } struct ItemChunk<T> { item: T, name: Arc<str>, } impl<T: Default> Default for ItemChunk<T> { fn default() -> ItemChunk<T> { ItemChunk { item: Default::default(), name: "".into(), } } } impl<T: Send + Default> Chunk for ItemChunk<T> { fn get_name(&self) -> &str { &*self.name } } impl<I: Iterator> ChunkProducer for IterChunkProducer<I> where I::Item: Send + Default, { type Chunk = ItemChunk<I::Item>; fn next_file(&mut self) -> Result<bool> { // clear remaining items while let Some(_) = self.iter.next() {} Ok(false) } fn get_chunk(&mut self, chunk: &mut ItemChunk<I::Item>) -> Result<bool> { if let Some(item) = self.iter.next() { chunk.item = item; chunk.name = self.name.clone(); Ok(false) } else { Ok(true) } } } #[test] fn chained_all_elements() { let mut chained_producer = ChainedChunkProducer(vec![ new_iter(20, 30, "file3")(), new_iter(10, 20, "file2")(), new_iter(0, 10, "file1")(), ]); let mut got = Vec::new(); let mut names = Vec::new(); let mut chunk = ItemChunk::default(); let mut i = 0; while !chained_producer .get_chunk(&mut chunk) .expect("get_chunk should succeed") { if i % 10 == 0 { names.push(chunk.name.clone()) } got.push(chunk.item); i += 1; } assert_eq!(got, (0..30).collect::<Vec<_>>()); assert_eq!(names, vec!["file1".into(), "file2".into(), "file3".into()]); } #[test] fn chained_next_file() { let mut chained_producer = ChainedChunkProducer(vec![ new_iter(20, 30, "file3")(), new_iter(10, 20, "file2")(), new_iter(0, 10, "file1")(), ]); let mut got = Vec::new(); let mut names = Vec::new(); let mut chunk = ItemChunk::default(); while !chained_producer .get_chunk(&mut chunk) .expect("get_chunk should succeed") { names.push(chunk.name.clone()); got.push(chunk.item); if !chained_producer .next_file() .expect("next_file should succeed") { break; } } assert_eq!(got, vec![0, 10, 20]); assert_eq!(names, vec!["file1".into(), "file2".into(), "file3".into()]); } #[test] fn sharded_next_file() { let mut sharded_producer = ShardedChunkProducer::new( vec![ new_iter(0, 10, "file1"), new_iter(10, 20, "file2"), new_iter(20, 30, "file3"), ] .into_iter(), ); let mut got = Vec::new(); let mut names = Vec::new(); let mut chunk = ItemChunk::default(); while !sharded_producer .get_chunk(&mut chunk) .expect("get_chunk should succeed") { names.push(chunk.name.clone()); got.push(chunk.item); if !sharded_producer .next_file() .expect("next_file should succeed") { break; } } assert_eq!(got, vec![0, 10, 20]); assert_eq!(names, vec!["file1".into(), "file2".into(), "file3".into()]); } #[test] fn parallel_all_elements() { use std::{sync::Mutex, thread}; let parallel_producer = ParallelChunkProducer::new(new_iter(0, 100, "file1"), /*chan_size=*/ 10); let got = Arc::new(Mutex::new(Vec::new())); let threads = { let _guard = got.lock().unwrap(); let mut threads = Vec::with_capacity(5); for prod in parallel_producer.try_dyn_resize(5) { let got = got.clone(); threads.push(thread::spawn(move || { let mut prod = prod(); let mut chunk = ItemChunk::default(); while !prod .get_chunk(&mut chunk) .expect("get_chunk should succeed") { assert_eq!(chunk.name, "file1".into()); got.lock().unwrap().push(chunk.item); } })); } threads }; for t in threads.into_iter() { t.join().unwrap(); } let mut g = got.lock().unwrap(); g.sort(); assert_eq!(*g, (0..100).collect::<Vec<_>>()); } #[test] fn sharded_all_elements() { use std::{sync::Mutex, thread}; let sharded_producer = ShardedChunkProducer::new( vec![ new_iter(0, 10, "file1"), new_iter(10, 20, "file2"), new_iter(20, 30, "file3"), new_iter(30, 40, "file4"), new_iter(40, 50, "file5"), new_iter(50, 60, "file6"), ] .into_iter(), ); let got = Arc::new(Mutex::new(Vec::new())); let threads = { let _guard = got.lock().unwrap(); let mut threads = Vec::with_capacity(5); for prod in sharded_producer.try_dyn_resize(5) { let got = got.clone(); threads.push(thread::spawn(move || { let mut prod = prod(); let mut chunk = ItemChunk::default(); while !prod .get_chunk(&mut chunk) .expect("get_chunk should succeed") { let expected_name = match chunk.item { 0..=9 => "file1", 10..=19 => "file2", 20..=29 => "file3", 30..=39 => "file4", 40..=49 => "file5", 50..=59 => "file6", x => panic!("unexpected item {} (should be in range [0,59])", x), }; assert_eq!(&*chunk.name, expected_name); got.lock().unwrap().push(chunk.item); } })); } threads }; for t in threads.into_iter() { t.join().unwrap(); } let mut g = got.lock().unwrap(); g.sort(); assert_eq!(*g, (0..60).collect::<Vec<_>>()); } // TODO: test that we get all elements in Chained, Sharded and Parallel chunkproducers. // TODO: test nextfile behavior for Chained and Sharded chunk producer. }
#![allow(dead_code)] use crate::tokens::Token; use crate::tokens::Symbol; use std::fs; pub struct Parser { } impl Parser { pub fn from_string(string: String) { let mut output: String = String::new(); for char in string.chars() { let str_data = &format!("{}", char).to_owned(); output = format!( "{}{}", output, match Symbol::new(str_data) { Ok(t) => format!("{}", char), Err(msg) => panic!(msg) } ); } } pub fn from_file(path: &str) { let data = fs::read_to_string(path).expect(&format!("Error while trying to openg the file {}", path).to_owned()); Parser::from_string(data); } }
use std::fmt; use super::dice::Dice; #[derive(Debug, PartialEq)] pub struct CheckerMove { from: u8, to: u8, hits: bool, } impl CheckerMove { pub fn make(from: u8, to: u8, hits: bool) -> CheckerMove { CheckerMove { from, to, hits } } pub fn src_point(&self) -> u8 { self.from - 1 } pub fn dst_point(&self) -> u8 { self.to - 1 } pub fn is_entering(&self) -> bool { self.from == 25 } pub fn is_bearing_off(&self) -> bool { self.to == 0 } } impl fmt::Display for CheckerMove { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}/{}{}", self.from, self.to, if self.hits {"*"} else {""}) } } #[derive(Debug, PartialEq)] pub struct Move { roll: Dice, checker_moves: Vec<CheckerMove>, } impl Move { pub fn make(roll: Dice, checker_moves: Vec<CheckerMove>) -> Move { Move { roll, checker_moves, } } pub fn moves(&self) -> &Vec<CheckerMove> { &self.checker_moves } } impl fmt::Display for Move { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}:", self.roll)?; for mv in &self.checker_moves { write!(f, " {}", mv)?; } write!(f, "") } }
use gl::types::*; use super::*; use anyhow::{Result, anyhow}; use crate::error::get_program_error; use std::rc::Rc; use crate::get_value; use std::collections::HashMap; pub trait ProgramAttachment { fn id(&self) -> GLuint; } impl<T> ProgramAttachment for Shader<T> where T: ShaderExt { fn id(&self) -> GLuint { self.id() } } pub struct Program { id: GLuint, shaders: Vec<Rc<dyn ProgramAttachment>>, uniform_locations: HashMap<String, GLint>, } impl Program { pub fn new() -> Program { Program { id: unsafe{gl::CreateProgram()}, shaders: Vec::new(), uniform_locations: HashMap::new(), } } pub fn from_shaders(shaders: Vec<Rc<dyn ProgramAttachment>>) -> Result<Program> { let mut program = Program::new(); for shader in shaders { program.attach(shader); } program.link()?; Ok(program) } pub fn id(&self) -> GLuint { self.id } pub fn attach(&mut self, shader: Rc<dyn ProgramAttachment>) { unsafe { gl::AttachShader(self.id, shader.id()) } self.shaders.push(shader); } pub fn link(&mut self) -> Result<()> { unsafe { gl::LinkProgram(self.id); } let success = get_value(1, |success|unsafe { gl::GetProgramiv(self.id, gl::LINK_STATUS, success); }); match success { 1 => Ok(()), _ => { Err(anyhow!( "Failed to link program: {}", get_program_error(self.id) )) } } } pub fn set_uniform<K>(&mut self, name: &str, val: K) where K: Uniform<K> { if let Some(loc) = self.get_uniform_loc(name) { unsafe { val.set(loc); } } } /// Returns the uniform location for the name or none, if it fails. fn get_uniform_loc(&mut self, name: &str) -> Option<GLint> { if let Some(loc) = self.uniform_locations.get(name) { return Some(*loc); } use std::ffi::CString; let c_name = CString::new(name).unwrap(); let loc = unsafe { gl::GetUniformLocation(self.id, c_name.as_ptr()) }; if loc != -1 { self.uniform_locations.insert(name.to_owned(), loc); Some(loc) } else { None } } pub fn set_used(&mut self) { unsafe {gl::UseProgram(self.id)} } } impl Drop for Program { fn drop(&mut self) { unsafe { for shader in &self.shaders { gl::DetachShader(self.id, shader.id()) } gl::DeleteProgram(self.id) } } }
use std::{ convert::TryInto, io::{Read, Write}, mem, }; use serialport::{self, SerialPort, TTYPort}; use crate::ublox::UbloxMsg; #[derive(Debug, Clone)] pub enum Message { Ublox(UbloxMsg), Nmea(String), } #[derive(Debug)] pub struct PortBuffer { port: TTYPort, buf: Vec<u8>, } impl PortBuffer { pub fn new(port: TTYPort) -> PortBuffer { PortBuffer { port, buf: vec![] } } pub fn send(&mut self, msg: Message) { let bytes = match msg { Message::Ublox(ubmsg) => ubmsg.into(), Message::Nmea(nmea) => nmea.into_bytes(), }; self.port.write_all(&bytes).unwrap(); self.port.flush().unwrap(); } pub fn read(&mut self) -> Result<(), String> { let num_bytes = self .port .bytes_to_read() .map_err(|err| format!("{}", err))?; if num_bytes == 0 { return Ok(()); } let mut bytes = vec![0; num_bytes as usize]; self.port.read_exact(&mut bytes).unwrap(); self.buf.extend(bytes); Ok(()) } pub fn sync(&mut self) -> bool { let mut i = 0; if self.buf.len() < 2 { return false; } while i < self.buf.len() - 1 { if &self.buf[i..i + 2] == &[0xb5, 0x62] || (self.buf[i] == b'$' && self.buf[i + 1] >= b'A' && self.buf[i + 1] <= b'Z') { let rest = self.buf.split_off(i); self.buf = rest; return true; } i += 1; } false } pub fn read_msg(&mut self) -> Option<Message> { if !self.sync() { return None; } if self.buf[0] == b'$' && self.buf[1] >= b'A' && self.buf[1] <= b'Z' { let (end, _) = self.buf.iter().enumerate().find(|(_, c)| **c == b'\n')?; let rest = self.buf.split_off(end + 1); let msg = String::from_utf8(mem::replace(&mut self.buf, rest)).unwrap(); return Some(Message::Nmea(msg)); } if &self.buf[0..2] == &[0xb5, 0x62] { if self.buf.len() < 8 { return None; } let length = u16::from_le_bytes(self.buf[4..6].try_into().unwrap()) as usize; if self.buf.len() < 8 + length { return None; } let rest = self.buf.split_off(8 + length); let msg = mem::replace(&mut self.buf, rest); return Some(Message::Ublox(msg.try_into().unwrap())); } None } }
#![feature(plugin, decl_macro, custom_attribute, proc_macro_hygiene)] extern crate libtitan; #[macro_use] extern crate rocket; use rocket::fairing::AdHoc; extern crate rocket_contrib; extern crate diesel; extern crate regex; extern crate bcrypt; extern crate frank_jwt; extern crate rocket_cors; use libtitan::routes; use libtitan::db; use libtitan::config; use libtitan::cors_fairing; use libtitan::accounts; use libtitan::organizations; fn main() { rocket::ignite() .attach(db::TitanPrimary::fairing()) .attach(db::UnksoMainForums::fairing()) .attach(cors_fairing::cors()) .attach(AdHoc::on_attach("Config", |rocket| { let settings = config::AppConfig::from_env(&rocket.config()); match settings { Ok(settings) => Ok(rocket.manage(settings)), Err(_) => Err(rocket), } })) .mount("/auth/pulse", routes![routes::health_check]) .mount("/auth", accounts::get_auth_routes()) .mount("/users", accounts::get_user_routes()) .mount("/organizations", organizations::get_routes()) .launch(); }
//! Checks for following exploit mitigations: //! //! * NX (Non-eXecutable bit) stack //! * NX (Non-eXecutable bit) heap //! * Position-Independent Executable //! * Stack Canaries //! * Restricted segment use goblin::mach::MachO; use serde_json::json; use crate::check::{Analyze, GenericMap}; use crate::errors::BinResult; const MH_PIE: u32 = 0x200000; const MH_ALLOW_STACK_EXECUTION: u32 = 0x20000; const MH_NO_HEAP_EXECUTION: u32 = 0x1000000; impl Analyze for MachO<'_> { fn run_compilation_checks(&self, _bytes: &[u8]) -> BinResult<GenericMap> { todo!() } fn run_mitigation_checks(&self) -> GenericMap { let mut mitigate_map: GenericMap = GenericMap::new(); let nx_stack: bool = matches!(self.header.flags & MH_ALLOW_STACK_EXECUTION, 0); mitigate_map.insert("Executable Stack".to_string(), json!(nx_stack)); let nx_heap: bool = matches!(self.header.flags & MH_NO_HEAP_EXECUTION, 0); mitigate_map.insert("Executable Heap".to_string(), json!(nx_heap)); let aslr: bool = matches!(self.header.flags & MH_PIE, 0); mitigate_map.insert( "Position Independent Executable / ASLR".to_string(), json!(aslr), ); // check for stack canary by finding canary functions in imports let stack_canary: bool = match self.imports() { Ok(imports) => imports .iter() .any(|x| x.name == "__stack_chk_fail" || x.name == "__stack_chk_guard"), Err(_) => false, }; mitigate_map.insert("Stack Canary".to_string(), json!(stack_canary)); // check for __RESTRICT section for stopping dynlib injection let restrict: bool = self .segments .iter() .filter_map(|s| { if let Ok(name) = s.name() { Some(name.to_string()) } else { None } }) .any(|s| s.to_lowercase() == "__restrict"); mitigate_map.insert("__RESTRICT segment".to_string(), json!(restrict)); mitigate_map } }
use byteorder::*; use std::io; use std::io::Read; use std::io::Write; pub fn send_precision<W: Write>(out_stream: &mut W, datum: f64, precision: f64)->io::Result<()>{ out_stream.write_bu16((datum*precision) as u16) } pub fn read_precision<R: Read>(in_stream: &mut R, precision: f64)->io::Result<f64>{ (in_stream.read_bu16()).map(|x|(x as f64)/precision) } pub fn send_as_i16<W: Write>(out_stream: &mut W, datum: f64)->io::Result<()>{ out_stream.write_bi16(datum as i16) } pub fn read_as_i16<R: Read>(in_stream: &mut R)->io::Result<f64>{ in_stream.read_bi16().map(|x|x as f64) } pub trait BigEndianRead{ fn read_bu16(&mut self)->io::Result<u16>; fn read_bu32(&mut self)->io::Result<u32>; fn read_bi16(&mut self)->io::Result<i16>; } impl<T: Read> BigEndianRead for T{ fn read_bu16(&mut self)->io::Result<u16>{ self.read_u16::<BigEndian>() } fn read_bu32(&mut self)->io::Result<u32>{ self.read_u32::<BigEndian>() } fn read_bi16(&mut self)->io::Result<i16>{ self.read_i16::<BigEndian>() } } pub trait BigEndianWrite{ fn write_bu16(&mut self, x: u16)->io::Result<()>; fn write_bu32(&mut self, x: u32)->io::Result<()>; fn write_bi16(&mut self, x: i16)->io::Result<()>; } impl<T: Write> BigEndianWrite for T{ fn write_bu16(&mut self, x: u16)->io::Result<()>{ self.write_u16::<BigEndian>(x) } fn write_bu32(&mut self, x: u32)->io::Result<()>{ self.write_u32::<BigEndian>(x) } fn write_bi16(&mut self, x: i16)->io::Result<()>{ self.write_i16::<BigEndian>(x) } }
use super::*; use proptest::strategy::Strategy; mod with_bit_count; // `without_bit_count` in integration tests // `without_integer_start_without_integer_length_errors_badarg` in integration tests // `without_integer_start_with_integer_length_errors_badarg` in integration tests // `with_non_negative_integer_start_without_integer_length_errors_badarg` in integration tests // `with_negative_start_with_valid_length_errors_badarg` in integration tests // `with_start_greater_than_size_with_non_negative_length_errors_badarg` in integration tests // `with_start_less_than_size_with_negative_length_past_start_errors_badarg` in integration tests // `with_start_less_than_size_with_positive_length_past_end_errors_badarg` in integration tests // `with_positive_start_and_negative_length_returns_subbinary` in integration tests
use std::{ cell::RefCell, collections::VecDeque, io, marker::PhantomData, ops::DerefMut, pin::Pin, rc::Rc, task, task::{Context, Poll}, }; use bitflags::bitflags; use bytes::BytesMut; use futures_sink::Sink; use tokio::io::{AsyncWrite, AsyncWriteExt}; use tokio_util::codec::Encoder; use crate::{ actor::{Actor, ActorContext, AsyncContext, Running, SpawnHandle}, fut::ActorFuture, }; /// A helper trait for write handling. /// /// `WriteHandler` is a helper for `AsyncWrite` types. Implementation /// of this trait is required for `Writer` and `FramedWrite` support. #[allow(unused_variables)] pub trait WriteHandler<E> where Self: Actor, Self::Context: ActorContext, { /// Called when the writer emits error. /// /// If this method returns `ErrorAction::Continue` writer processing /// continues otherwise stream processing stops. fn error(&mut self, err: E, ctx: &mut Self::Context) -> Running { Running::Stop } /// Called when the writer finishes. /// /// By default this method stops actor's `Context`. fn finished(&mut self, ctx: &mut Self::Context) { ctx.stop() } } bitflags! { struct Flags: u8 { const CLOSING = 0b0000_0001; const CLOSED = 0b0000_0010; } } const LOW_WATERMARK: usize = 4 * 1024; const HIGH_WATERMARK: usize = 4 * LOW_WATERMARK; /// A wrapper for `AsyncWrite` types. pub struct Writer<T: AsyncWrite, E: From<io::Error>> { inner: UnsafeWriter<T, E>, } struct UnsafeWriter<T: AsyncWrite, E: From<io::Error>>(Rc<RefCell<InnerWriter<E>>>, Rc<RefCell<T>>); impl<T: AsyncWrite, E: From<io::Error>> Clone for UnsafeWriter<T, E> { fn clone(&self) -> Self { UnsafeWriter(self.0.clone(), self.1.clone()) } } struct InnerWriter<E: From<io::Error>> { flags: Flags, buffer: BytesMut, error: Option<E>, low: usize, high: usize, handle: SpawnHandle, task: Option<task::Waker>, } impl<T: AsyncWrite, E: From<io::Error> + 'static> Writer<T, E> { pub fn new<A, C>(io: T, ctx: &mut C) -> Self where A: Actor<Context = C> + WriteHandler<E>, C: AsyncContext<A>, T: Unpin + 'static, { let inner = UnsafeWriter( Rc::new(RefCell::new(InnerWriter { flags: Flags::empty(), buffer: BytesMut::new(), error: None, low: LOW_WATERMARK, high: HIGH_WATERMARK, handle: SpawnHandle::default(), task: None, })), Rc::new(RefCell::new(io)), ); let h = ctx.spawn(WriterFut { inner: inner.clone(), }); let writer = Self { inner }; writer.inner.0.borrow_mut().handle = h; writer } /// Gracefully closes the sink. /// /// The closing happens asynchronously. pub fn close(&mut self) { self.inner.0.borrow_mut().flags.insert(Flags::CLOSING); } /// Checks if the sink is closed. pub fn closed(&self) -> bool { self.inner.0.borrow().flags.contains(Flags::CLOSED) } /// Sets the write buffer capacity. pub fn set_buffer_capacity(&mut self, low_watermark: usize, high_watermark: usize) { let mut inner = self.inner.0.borrow_mut(); inner.low = low_watermark; inner.high = high_watermark; } /// Sends an item to the sink. pub fn write(&mut self, msg: &[u8]) { let mut inner = self.inner.0.borrow_mut(); inner.buffer.extend_from_slice(msg); if let Some(task) = inner.task.take() { task.wake_by_ref(); } } /// Returns the `SpawnHandle` for this writer. pub fn handle(&self) -> SpawnHandle { self.inner.0.borrow().handle } } struct WriterFut<T, E> where T: AsyncWrite + Unpin, E: From<io::Error>, { inner: UnsafeWriter<T, E>, } impl<T: 'static, E: 'static, A> ActorFuture<A> for WriterFut<T, E> where T: AsyncWrite + Unpin, E: From<io::Error>, A: Actor + WriteHandler<E>, A::Context: AsyncContext<A>, { type Output = (); fn poll( self: Pin<&mut Self>, act: &mut A, ctx: &mut A::Context, task: &mut Context<'_>, ) -> Poll<Self::Output> { let this = self.get_mut(); let mut inner = this.inner.0.borrow_mut(); if let Some(err) = inner.error.take() { if act.error(err, ctx) == Running::Stop { act.finished(ctx); return Poll::Ready(()); } } let mut io = this.inner.1.borrow_mut(); inner.task = None; while !inner.buffer.is_empty() { match Pin::new(io.deref_mut()).poll_write(task, &inner.buffer) { Poll::Ready(Ok(n)) => { if n == 0 && act.error( io::Error::new( io::ErrorKind::WriteZero, "failed to write frame to transport", ) .into(), ctx, ) == Running::Stop { act.finished(ctx); return Poll::Ready(()); } let _ = inner.buffer.split_to(n); } Poll::Ready(Err(ref e)) if e.kind() == io::ErrorKind::WouldBlock => { if inner.buffer.len() > inner.high { ctx.wait(WriterDrain { inner: this.inner.clone(), }); } return Poll::Pending; } Poll::Ready(Err(e)) => { if act.error(e.into(), ctx) == Running::Stop { act.finished(ctx); return Poll::Ready(()); } } Poll::Pending => return Poll::Pending, } } // Try flushing the underlying IO match Pin::new(io.deref_mut()).poll_flush(task) { Poll::Ready(Ok(_)) => (), Poll::Pending => return Poll::Pending, Poll::Ready(Err(ref e)) if e.kind() == io::ErrorKind::WouldBlock => { return Poll::Pending; } Poll::Ready(Err(e)) => { if act.error(e.into(), ctx) == Running::Stop { act.finished(ctx); return Poll::Ready(()); } } } // close if closing and we don't need to flush any data if inner.flags.contains(Flags::CLOSING) { inner.flags |= Flags::CLOSED; act.finished(ctx); Poll::Ready(()) } else { inner.task = Some(task.waker().clone()); Poll::Pending } } } struct WriterDrain<T, E> where T: AsyncWrite + Unpin, E: From<io::Error>, { inner: UnsafeWriter<T, E>, } impl<T, E, A> ActorFuture<A> for WriterDrain<T, E> where T: AsyncWrite + Unpin, E: From<io::Error>, A: Actor, A::Context: AsyncContext<A>, { type Output = (); fn poll( self: Pin<&mut Self>, _: &mut A, _: &mut A::Context, task: &mut Context<'_>, ) -> Poll<Self::Output> { let this = self.get_mut(); let mut inner = this.inner.0.borrow_mut(); if inner.error.is_some() { return Poll::Ready(()); } let mut io = this.inner.1.borrow_mut(); while !inner.buffer.is_empty() { match Pin::new(io.deref_mut()).poll_write(task, &inner.buffer) { Poll::Ready(Ok(n)) => { if n == 0 { inner.error = Some( io::Error::new( io::ErrorKind::WriteZero, "failed to write frame to transport", ) .into(), ); return Poll::Ready(()); } let _ = inner.buffer.split_to(n); } Poll::Ready(Err(ref e)) if e.kind() == io::ErrorKind::WouldBlock => { return if inner.buffer.len() < inner.low { Poll::Ready(()) } else { Poll::Pending }; } Poll::Ready(Err(e)) => { inner.error = Some(e.into()); return Poll::Ready(()); } Poll::Pending => return Poll::Pending, } } Poll::Ready(()) } } /// A wrapper for the `AsyncWrite` and `Encoder` types. The [`AsyncWrite`] will be flushed when this /// struct is dropped. pub struct FramedWrite<I, T: AsyncWrite + Unpin, U: Encoder<I>> { enc: U, inner: UnsafeWriter<T, U::Error>, } impl<I, T: AsyncWrite + Unpin, U: Encoder<I>> FramedWrite<I, T, U> { pub fn new<A, C>(io: T, enc: U, ctx: &mut C) -> Self where A: Actor<Context = C> + WriteHandler<U::Error>, C: AsyncContext<A>, U::Error: 'static, T: Unpin + 'static, { let inner = UnsafeWriter( Rc::new(RefCell::new(InnerWriter { flags: Flags::empty(), buffer: BytesMut::new(), error: None, low: LOW_WATERMARK, high: HIGH_WATERMARK, handle: SpawnHandle::default(), task: None, })), Rc::new(RefCell::new(io)), ); let h = ctx.spawn(WriterFut { inner: inner.clone(), }); let writer = Self { enc, inner }; writer.inner.0.borrow_mut().handle = h; writer } pub fn from_buffer<A, C>(io: T, enc: U, buffer: BytesMut, ctx: &mut C) -> Self where A: Actor<Context = C> + WriteHandler<U::Error>, C: AsyncContext<A>, U::Error: 'static, T: Unpin + 'static, { let inner = UnsafeWriter( Rc::new(RefCell::new(InnerWriter { buffer, flags: Flags::empty(), error: None, low: LOW_WATERMARK, high: HIGH_WATERMARK, handle: SpawnHandle::default(), task: None, })), Rc::new(RefCell::new(io)), ); let h = ctx.spawn(WriterFut { inner: inner.clone(), }); let writer = Self { enc, inner }; writer.inner.0.borrow_mut().handle = h; writer } /// Gracefully closes the sink. /// /// The closing happens asynchronously. pub fn close(&mut self) { self.inner.0.borrow_mut().flags.insert(Flags::CLOSING); } /// Checks if the sink is closed. pub fn closed(&self) -> bool { self.inner.0.borrow().flags.contains(Flags::CLOSED) } /// Sets the write buffer capacity. pub fn set_buffer_capacity(&mut self, low: usize, high: usize) { let mut inner = self.inner.0.borrow_mut(); inner.low = low; inner.high = high; } /// Writes an item to the sink. pub fn write(&mut self, item: I) { let mut inner = self.inner.0.borrow_mut(); let _ = self.enc.encode(item, &mut inner.buffer).map_err(|e| { inner.error = Some(e); }); if let Some(task) = inner.task.take() { task.wake_by_ref(); } } /// Returns the `SpawnHandle` for this writer. pub fn handle(&self) -> SpawnHandle { self.inner.0.borrow().handle } } impl<I, T: AsyncWrite + Unpin, U: Encoder<I>> Drop for FramedWrite<I, T, U> { fn drop(&mut self) { // Attempts to write any remaining bytes to the stream and flush it let mut async_writer = self.inner.1.borrow_mut(); let inner = self.inner.0.borrow_mut(); if !inner.buffer.is_empty() { // Results must be ignored during drop, as the errors cannot be handled meaningfully drop(async_writer.write(&inner.buffer)); drop(async_writer.flush()); } } } /// A wrapper for the `Sink` type. pub struct SinkWrite<I, S: Sink<I> + Unpin> { inner: Rc<RefCell<InnerSinkWrite<I, S>>>, } impl<I: 'static, S: Sink<I> + Unpin + 'static> SinkWrite<I, S> { pub fn new<A, C>(sink: S, ctxt: &mut C) -> Self where A: Actor<Context = C> + WriteHandler<S::Error>, C: AsyncContext<A>, { let inner = Rc::new(RefCell::new(InnerSinkWrite { _i: PhantomData, closing_flag: Flags::empty(), sink, task: None, handle: SpawnHandle::default(), buffer: VecDeque::new(), })); let handle = ctxt.spawn(SinkWriteFuture { inner: inner.clone(), }); inner.borrow_mut().handle = handle; SinkWrite { inner } } /// Queues an item to be sent to the sink. /// /// Returns unsent item if sink is closing or closed. pub fn write(&mut self, item: I) -> Result<(), I> { if self.inner.borrow().closing_flag.is_empty() { self.inner.borrow_mut().buffer.push_back(item); self.notify_task(); Ok(()) } else { Err(item) } } /// Gracefully closes the sink. /// /// The closing happens asynchronously. pub fn close(&mut self) { self.inner.borrow_mut().closing_flag.insert(Flags::CLOSING); self.notify_task(); } /// Checks if the sink is closed. pub fn closed(&self) -> bool { self.inner.borrow_mut().closing_flag.contains(Flags::CLOSED) } fn notify_task(&self) { if let Some(task) = &self.inner.borrow().task { task.wake_by_ref() } } /// Returns the `SpawnHandle` for this writer. pub fn handle(&self) -> SpawnHandle { self.inner.borrow().handle } } struct InnerSinkWrite<I, S: Sink<I>> { _i: PhantomData<I>, closing_flag: Flags, sink: S, task: Option<task::Waker>, handle: SpawnHandle, // buffer of items to be sent so that multiple // calls to start_send don't silently skip items buffer: VecDeque<I>, } struct SinkWriteFuture<I: 'static, S: Sink<I>> { inner: Rc<RefCell<InnerSinkWrite<I, S>>>, } impl<I: 'static, S: Sink<I>, A> ActorFuture<A> for SinkWriteFuture<I, S> where S: Sink<I> + Unpin, A: Actor + WriteHandler<S::Error>, A::Context: AsyncContext<A>, { type Output = (); fn poll( self: Pin<&mut Self>, act: &mut A, ctxt: &mut A::Context, cx: &mut Context<'_>, ) -> Poll<Self::Output> { let this = self.get_mut(); let inner = &mut this.inner.borrow_mut(); // Loop to ensure we either process all items in the buffer, or trigger the inner sink to be pending // and wake this task later. loop { // ensure sink is ready to receive next item match Pin::new(&mut inner.sink).poll_ready(cx) { Poll::Ready(Ok(())) => { if let Some(item) = inner.buffer.pop_front() { // send front of buffer to sink let _ = Pin::new(&mut inner.sink).start_send(item); } else { break; } } Poll::Ready(Err(_err)) => { break; } Poll::Pending => { break; } } } if !inner.closing_flag.contains(Flags::CLOSING) { match Pin::new(&mut inner.sink).poll_flush(cx) { Poll::Ready(Err(e)) => { if act.error(e, ctxt) == Running::Stop { act.finished(ctxt); return Poll::Ready(()); } } Poll::Ready(Ok(())) => {} Poll::Pending => {} } } else { assert!(!inner.closing_flag.contains(Flags::CLOSED)); match Pin::new(&mut inner.sink).poll_close(cx) { Poll::Ready(Err(e)) => { if act.error(e, ctxt) == Running::Stop { act.finished(ctxt); return Poll::Ready(()); } } Poll::Ready(Ok(())) => { // ensure all items in buffer have been sent before closing if inner.buffer.is_empty() { inner.closing_flag |= Flags::CLOSED; act.finished(ctxt); return Poll::Ready(()); } } Poll::Pending => {} } } inner.task.replace(cx.waker().clone()); Poll::Pending } }
//! A collection of different matching strategies provided out-of-the-box by `wiremock`. //! //! If the set of matchers provided out-of-the-box is not enough for your specific testing needs //! you can implement your own thanks to the [`Match`] trait. //! //! Furthermore, `Fn` closures that take an immutable [`Request`] reference as input and return a boolean //! as input automatically implement [`Match`] and can be used where a matcher is expected. //! //! Check [`Match`]'s documentation for examples. use crate::{Match, Request}; use http_types::headers::{HeaderName, HeaderValue, HeaderValues}; use http_types::Method; use log::debug; use regex::Regex; use serde::Serialize; use std::convert::TryInto; use std::str; /// Implement the `Match` trait for all closures, out of the box, /// if their signature is compatible. impl<F> Match for F where F: Fn(&Request) -> bool, F: Send + Sync, { fn matches(&self, request: &Request) -> bool { // Just call the closure itself! self(request) } } #[derive(Debug)] /// Match **exactly** the method of a request. /// /// ### Example: /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::method; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// let response = ResponseTemplate::new(200); /// let mock = Mock::given(method("GET")).respond_with(response); /// /// mock_server.register(mock).await; /// /// // Act /// let status = surf::get(&mock_server.uri()) /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` pub struct MethodExactMatcher(Method); /// Shorthand for [`MethodExactMatcher::new`]. pub fn method<T>(method: T) -> MethodExactMatcher where T: TryInto<Method>, <T as TryInto<Method>>::Error: std::fmt::Debug, { MethodExactMatcher::new(method) } impl MethodExactMatcher { pub fn new<T>(method: T) -> Self where T: TryInto<Method>, <T as TryInto<Method>>::Error: std::fmt::Debug, { let method = method .try_into() .expect("Failed to convert to HTTP method."); Self(method) } } impl Match for MethodExactMatcher { fn matches(&self, request: &Request) -> bool { request.method == self.0 } } #[derive(Debug)] /// Match all incoming requests, regardless of their method, path, headers or body. /// /// You can use it to verify that a request has been fired towards the server, without making /// any other assertion about it. /// /// ### Example: /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::any; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// let response = ResponseTemplate::new(200); /// // Respond with a `200 OK` to all requests hitting /// // the mock server /// let mock = Mock::given(any()).respond_with(response); /// /// mock_server.register(mock).await; /// /// // Act /// let status = surf::get(&mock_server.uri()) /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` pub struct AnyMatcher; /// Shorthand for [`AnyMatcher`]. pub fn any() -> AnyMatcher { AnyMatcher } impl Match for AnyMatcher { fn matches(&self, _request: &Request) -> bool { true } } #[derive(Debug)] /// Match **exactly** the path of a request. /// /// ### Example: /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::path; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// let response = ResponseTemplate::new(200).set_body_string("world"); /// let mock = Mock::given(path("/hello")).respond_with(response); /// /// mock_server.register(mock).await; /// /// // Act /// let status = surf::get(format!("{}/hello", &mock_server.uri())) /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` /// /// ### Example: /// /// The path matcher ignores query parameters: /// /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::path; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// let response = ResponseTemplate::new(200).set_body_string("world"); /// let mock = Mock::given(path("/hello")).respond_with(response); /// /// mock_server.register(mock).await; /// /// // Act /// let status = surf::get(format!("{}/hello?a_parameter=some_value", &mock_server.uri())) /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` pub struct PathExactMatcher(String); /// Shorthand for [`PathExactMatcher::new`]. pub fn path<T>(path: T) -> PathExactMatcher where T: Into<String>, { PathExactMatcher::new(path) } impl PathExactMatcher { pub fn new<T: Into<String>>(path: T) -> Self { let path = path.into(); // Prepend "/" to the path if missing. if path.starts_with('/') { Self(path) } else { Self(format!("/{}", path)) } } } impl Match for PathExactMatcher { fn matches(&self, request: &Request) -> bool { request.url.path() == self.0 } } #[derive(Debug)] /// Match the path of a request against a regular expression. /// /// ### Example: /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::path_regex; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// let response = ResponseTemplate::new(200).set_body_string("world"); /// let mock = Mock::given(path_regex(r"^/hello/\d{3}$")).respond_with(response); /// /// mock_server.register(mock).await; /// /// // Act /// let status = surf::get(format!("{}/hello/123", &mock_server.uri())) /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` /// /// ### Example: /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::path_regex; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// let response = ResponseTemplate::new(200).set_body_string("world"); /// let mock = Mock::given(path_regex(r"^/users/[a-z0-9-~_]{1,}/posts$")).respond_with(response); /// /// mock_server.register(mock).await; /// /// // Act /// let status = surf::get(format!("{}/users/da2854ea-b70f-46e7-babc-2846eff4d33c/posts", &mock_server.uri())) /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` pub struct PathRegexMatcher(Regex); /// Shorthand for [`PathRegexMatcher::new`]. pub fn path_regex<T>(path: T) -> PathRegexMatcher where T: Into<String>, { PathRegexMatcher::new(path) } impl PathRegexMatcher { pub fn new<T: Into<String>>(path: T) -> Self { let path = path.into(); Self(Regex::new(&path).expect("Failed to create regex for path matcher")) } } impl Match for PathRegexMatcher { fn matches(&self, request: &Request) -> bool { self.0.is_match(request.url.path()) } } #[derive(Debug)] /// Match **exactly** the header of a request. /// /// ### Example: /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::{header, headers}; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// Mock::given(header("custom", "header")) /// .and(headers("cache-control", vec!["no-cache", "no-store"])) /// .respond_with(ResponseTemplate::new(200)) /// .mount(&mock_server) /// .await; /// /// // Act /// let status = surf::get(&mock_server.uri()) /// .header("custom", "header") /// .header("cache-control", "no-cache, no-store") /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` pub struct HeaderExactMatcher(HeaderName, HeaderValues); /// Shorthand for [`HeaderExactMatcher::new`]. pub fn header<K, V>(key: K, value: V) -> HeaderExactMatcher where K: TryInto<HeaderName>, <K as TryInto<HeaderName>>::Error: std::fmt::Debug, V: TryInto<HeaderValue>, <V as TryInto<HeaderValue>>::Error: std::fmt::Debug, { HeaderExactMatcher::new(key, value.try_into().map(HeaderValues::from).unwrap()) } /// Shorthand for [`HeaderExactMatcher::new`] supporting multi valued headers. pub fn headers<K, V>(key: K, values: Vec<V>) -> HeaderExactMatcher where K: TryInto<HeaderName>, <K as TryInto<HeaderName>>::Error: std::fmt::Debug, V: TryInto<HeaderValue>, <V as TryInto<HeaderValue>>::Error: std::fmt::Debug, { let values = values .into_iter() .filter_map(|v| v.try_into().ok()) .collect::<HeaderValues>(); HeaderExactMatcher::new(key, values) } impl HeaderExactMatcher { pub fn new<K, V>(key: K, value: V) -> Self where K: TryInto<HeaderName>, <K as TryInto<HeaderName>>::Error: std::fmt::Debug, V: TryInto<HeaderValues>, <V as TryInto<HeaderValues>>::Error: std::fmt::Debug, { let key = key.try_into().expect("Failed to convert to header name."); let value = value .try_into() .expect("Failed to convert to header value."); Self(key, value) } } impl Match for HeaderExactMatcher { fn matches(&self, request: &Request) -> bool { match request.headers.get(&self.0) { None => false, Some(values) => { let headers: Vec<&str> = self.1.iter().map(HeaderValue::as_str).collect(); values.eq(headers.as_slice()) } } } } #[derive(Debug)] /// Match **exactly** the header name of a request. It checks that the /// header is present but does not validate the value. /// /// ### Example: /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::header; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// use wiremock::matchers::header_exists; /// let mock_server = MockServer::start().await; /// /// Mock::given(header_exists("custom")) /// .respond_with(ResponseTemplate::new(200)) /// .mount(&mock_server) /// .await; /// /// // Act /// let status = surf::get(&mock_server.uri()) /// .header("custom", "header") /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` pub struct HeaderExistsMatcher(HeaderName); /// Shorthand for [`HeaderExistsMatcher::new`]. pub fn header_exists<K>(key: K) -> HeaderExistsMatcher where K: TryInto<HeaderName>, <K as TryInto<HeaderName>>::Error: std::fmt::Debug, { HeaderExistsMatcher::new(key) } impl HeaderExistsMatcher { pub fn new<K>(key: K) -> Self where K: TryInto<HeaderName>, <K as TryInto<HeaderName>>::Error: std::fmt::Debug, { let key = key.try_into().expect("Failed to convert to header name."); Self(key) } } impl Match for HeaderExistsMatcher { fn matches(&self, request: &Request) -> bool { request.headers.get(&self.0).is_some() } } #[derive(Debug)] /// Match **exactly** the body of a request. /// /// ### Example (string): /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::body_string; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// Mock::given(body_string("hello world!")) /// .respond_with(ResponseTemplate::new(200)) /// .mount(&mock_server) /// .await; /// /// // Act /// let status = surf::post(&mock_server.uri()) /// .body("hello world!") /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` /// /// ### Example (json): /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::body_json; /// use serde_json::json; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// let expected_body = json!({ /// "hello": "world!" /// }); /// Mock::given(body_json(&expected_body)) /// .respond_with(ResponseTemplate::new(200)) /// .mount(&mock_server) /// .await; /// /// // Act /// let status = surf::post(&mock_server.uri()) /// .body(expected_body) /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` pub struct BodyExactMatcher(Vec<u8>); impl BodyExactMatcher { /// Specify the expected body as a string. pub fn string<T: Into<String>>(body: T) -> Self { let body = body.into(); Self(body.as_bytes().into()) } /// Specify the expected body as a vector of bytes. pub fn bytes<T: Into<Vec<u8>>>(body: T) -> Self { let body = body.into(); Self(body) } /// Specify something JSON-serializable as the expected body. pub fn json<T: Serialize>(body: T) -> Self { let body = serde_json::to_vec(&body).expect("Failed to serialise body"); Self(body) } } /// Shorthand for [`BodyExactMatcher::json`]. pub fn body_json<T>(body: T) -> BodyExactMatcher where T: Serialize, { BodyExactMatcher::json(body) } /// Shorthand for [`BodyExactMatcher::string`]. pub fn body_string<T>(body: T) -> BodyExactMatcher where T: Into<String>, { BodyExactMatcher::string(body) } /// Shorthand for [`BodyExactMatcher::bytes`]. pub fn body_bytes<T>(body: T) -> BodyExactMatcher where T: Into<Vec<u8>>, { BodyExactMatcher::bytes(body) } impl Match for BodyExactMatcher { fn matches(&self, request: &Request) -> bool { request.body == self.0 } } #[derive(Debug)] /// Match part of the body of a request. /// /// ### Example (string): /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::body_string_contains; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// Mock::given(body_string_contains("hello world")) /// .respond_with(ResponseTemplate::new(200)) /// .mount(&mock_server) /// .await; /// /// // Act /// let status = surf::post(&mock_server.uri()) /// .body("this is a hello world example!") /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` pub struct BodyContainsMatcher(Vec<u8>); impl BodyContainsMatcher { /// Specify the part of the body that should be matched as a string. pub fn string<T: Into<String>>(body: T) -> Self { Self(body.into().as_bytes().into()) } } /// Shorthand for [`BodyContainsMatcher::string`]. pub fn body_string_contains<T>(body: T) -> BodyContainsMatcher where T: Into<String>, { BodyContainsMatcher::string(body) } impl Match for BodyContainsMatcher { fn matches(&self, request: &Request) -> bool { let body = match str::from_utf8(&request.body) { Ok(body) => body.to_string(), Err(err) => { debug!("can't convert body from byte slice to string: {}", err); return false; } }; let part = match str::from_utf8(&self.0) { Ok(part) => part, Err(err) => { debug!( "can't convert expected part from byte slice to string: {}", err ); return false; } }; body.contains(part) } } #[derive(Debug)] /// Match **exactly** the query parameter of a request. /// /// ### Example: /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::query_param; /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// Mock::given(query_param("hello", "world")) /// .respond_with(ResponseTemplate::new(200)) /// .mount(&mock_server) /// .await; /// /// // Act /// let status = surf::get(format!("{}?hello=world", &mock_server.uri())) /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// ``` pub struct QueryParamExactMatcher(String, String); impl QueryParamExactMatcher { /// Specify the expected value for a query parameter. pub fn new<K: Into<String>, V: Into<String>>(key: K, value: V) -> Self { let key = key.into(); let value = value.into(); Self(key, value) } } /// Shorthand for [`QueryParamExactMatcher::new`]. pub fn query_param<K, V>(key: K, value: V) -> QueryParamExactMatcher where K: Into<String>, V: Into<String>, { QueryParamExactMatcher::new(key, value) } impl Match for QueryParamExactMatcher { fn matches(&self, request: &Request) -> bool { request .url .query_pairs() .any(|q| q.0 == self.0.as_str() && q.1 == self.1.as_str()) } } /// Match an incoming request if its body is encoded as JSON and can be deserialized /// according to the specified schema. /// /// ### Example: /// ```rust /// use wiremock::{MockServer, Mock, ResponseTemplate}; /// use wiremock::matchers::body_json_schema; /// use serde_json::json; /// use serde::{Deserialize, Serialize}; /// /// // The schema we expect the body to conform to. /// #[derive(Deserialize, Serialize)] /// struct Greeting { /// hello: String, /// } /// /// #[async_std::main] /// async fn main() { /// // Arrange /// let mock_server = MockServer::start().await; /// /// Mock::given(body_json_schema::<Greeting>) /// .respond_with(ResponseTemplate::new(200)) /// .mount(&mock_server) /// .await; /// /// // Both JSON objects have the same fields, /// // therefore they'll match. /// let success_cases = vec![ /// json!({"hello": "world!"}), /// json!({"hello": "everyone!"}), /// ]; /// for case in success_cases.into_iter() { /// let status = surf::post(&mock_server.uri()) /// .body(case) /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 200); /// } /// /// // This JSON object cannot be deserialized as `Greeting` /// // because it does not have the `hello` field. /// // It won't match. /// let failure_case = json!({"world": "hello!"}); /// let status = surf::post(&mock_server.uri()) /// .body(failure_case) /// .await /// .unwrap() /// .status(); /// /// // Assert /// assert_eq!(status, 404); /// } /// ``` pub fn body_json_schema<T>(request: &Request) -> bool where for<'de> T: serde::de::Deserialize<'de>, { serde_json::from_slice::<T>(&request.body).is_ok() }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DIAGNOSTIC_DATA_EVENT_BINARY_STATS { pub moduleName: super::super::Foundation::PWSTR, pub friendlyModuleName: super::super::Foundation::PWSTR, pub eventCount: u32, pub uploadSizeBytes: u64, } #[cfg(feature = "Win32_Foundation")] impl DIAGNOSTIC_DATA_EVENT_BINARY_STATS {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DIAGNOSTIC_DATA_EVENT_BINARY_STATS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DIAGNOSTIC_DATA_EVENT_BINARY_STATS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_DATA_EVENT_BINARY_STATS").field("moduleName", &self.moduleName).field("friendlyModuleName", &self.friendlyModuleName).field("eventCount", &self.eventCount).field("uploadSizeBytes", &self.uploadSizeBytes).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DIAGNOSTIC_DATA_EVENT_BINARY_STATS { fn eq(&self, other: &Self) -> bool { self.moduleName == other.moduleName && self.friendlyModuleName == other.friendlyModuleName && self.eventCount == other.eventCount && self.uploadSizeBytes == other.uploadSizeBytes } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DIAGNOSTIC_DATA_EVENT_BINARY_STATS {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DIAGNOSTIC_DATA_EVENT_BINARY_STATS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION { pub id: i32, pub name: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION").field("id", &self.id).field("name", &self.name).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.name == other.name } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION { pub name: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION").field("name", &self.name).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION { fn eq(&self, other: &Self) -> bool { self.name == other.name } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION { pub privacyTag: i32, pub name: super::super::Foundation::PWSTR, pub description: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION").field("privacyTag", &self.privacyTag).field("name", &self.name).field("description", &self.description).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION { fn eq(&self, other: &Self) -> bool { self.privacyTag == other.privacyTag && self.name == other.name && self.description == other.description } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DIAGNOSTIC_DATA_EVENT_TAG_STATS { pub privacyTag: i32, pub eventCount: u32, } impl DIAGNOSTIC_DATA_EVENT_TAG_STATS {} impl ::core::default::Default for DIAGNOSTIC_DATA_EVENT_TAG_STATS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DIAGNOSTIC_DATA_EVENT_TAG_STATS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_DATA_EVENT_TAG_STATS").field("privacyTag", &self.privacyTag).field("eventCount", &self.eventCount).finish() } } impl ::core::cmp::PartialEq for DIAGNOSTIC_DATA_EVENT_TAG_STATS { fn eq(&self, other: &Self) -> bool { self.privacyTag == other.privacyTag && self.eventCount == other.eventCount } } impl ::core::cmp::Eq for DIAGNOSTIC_DATA_EVENT_TAG_STATS {} unsafe impl ::windows::core::Abi for DIAGNOSTIC_DATA_EVENT_TAG_STATS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION { pub hoursOfHistoryToKeep: u32, pub maxStoreMegabytes: u32, pub requestedMaxStoreMegabytes: u32, } impl DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION {} impl ::core::default::Default for DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION").field("hoursOfHistoryToKeep", &self.hoursOfHistoryToKeep).field("maxStoreMegabytes", &self.maxStoreMegabytes).field("requestedMaxStoreMegabytes", &self.requestedMaxStoreMegabytes).finish() } } impl ::core::cmp::PartialEq for DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION { fn eq(&self, other: &Self) -> bool { self.hoursOfHistoryToKeep == other.hoursOfHistoryToKeep && self.maxStoreMegabytes == other.maxStoreMegabytes && self.requestedMaxStoreMegabytes == other.requestedMaxStoreMegabytes } } impl ::core::cmp::Eq for DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION {} unsafe impl ::windows::core::Abi for DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DIAGNOSTIC_DATA_GENERAL_STATS { pub optInLevel: u32, pub transcriptSizeBytes: u64, pub oldestEventTimestamp: u64, pub totalEventCountLast24Hours: u32, pub averageDailyEvents: f32, } impl DIAGNOSTIC_DATA_GENERAL_STATS {} impl ::core::default::Default for DIAGNOSTIC_DATA_GENERAL_STATS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DIAGNOSTIC_DATA_GENERAL_STATS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_DATA_GENERAL_STATS") .field("optInLevel", &self.optInLevel) .field("transcriptSizeBytes", &self.transcriptSizeBytes) .field("oldestEventTimestamp", &self.oldestEventTimestamp) .field("totalEventCountLast24Hours", &self.totalEventCountLast24Hours) .field("averageDailyEvents", &self.averageDailyEvents) .finish() } } impl ::core::cmp::PartialEq for DIAGNOSTIC_DATA_GENERAL_STATS { fn eq(&self, other: &Self) -> bool { self.optInLevel == other.optInLevel && self.transcriptSizeBytes == other.transcriptSizeBytes && self.oldestEventTimestamp == other.oldestEventTimestamp && self.totalEventCountLast24Hours == other.totalEventCountLast24Hours && self.averageDailyEvents == other.averageDailyEvents } } impl ::core::cmp::Eq for DIAGNOSTIC_DATA_GENERAL_STATS {} unsafe impl ::windows::core::Abi for DIAGNOSTIC_DATA_GENERAL_STATS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DIAGNOSTIC_DATA_RECORD { pub rowId: i64, pub timestamp: u64, pub eventKeywords: u64, pub fullEventName: super::super::Foundation::PWSTR, pub providerGroupGuid: super::super::Foundation::PWSTR, pub producerName: super::super::Foundation::PWSTR, pub privacyTags: *mut i32, pub privacyTagCount: u32, pub categoryIds: *mut i32, pub categoryIdCount: u32, pub isCoreData: super::super::Foundation::BOOL, pub extra1: super::super::Foundation::PWSTR, pub extra2: super::super::Foundation::PWSTR, pub extra3: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DIAGNOSTIC_DATA_RECORD {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DIAGNOSTIC_DATA_RECORD { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DIAGNOSTIC_DATA_RECORD { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_DATA_RECORD") .field("rowId", &self.rowId) .field("timestamp", &self.timestamp) .field("eventKeywords", &self.eventKeywords) .field("fullEventName", &self.fullEventName) .field("providerGroupGuid", &self.providerGroupGuid) .field("producerName", &self.producerName) .field("privacyTags", &self.privacyTags) .field("privacyTagCount", &self.privacyTagCount) .field("categoryIds", &self.categoryIds) .field("categoryIdCount", &self.categoryIdCount) .field("isCoreData", &self.isCoreData) .field("extra1", &self.extra1) .field("extra2", &self.extra2) .field("extra3", &self.extra3) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DIAGNOSTIC_DATA_RECORD { fn eq(&self, other: &Self) -> bool { self.rowId == other.rowId && self.timestamp == other.timestamp && self.eventKeywords == other.eventKeywords && self.fullEventName == other.fullEventName && self.providerGroupGuid == other.providerGroupGuid && self.producerName == other.producerName && self.privacyTags == other.privacyTags && self.privacyTagCount == other.privacyTagCount && self.categoryIds == other.categoryIds && self.categoryIdCount == other.categoryIdCount && self.isCoreData == other.isCoreData && self.extra1 == other.extra1 && self.extra2 == other.extra2 && self.extra3 == other.extra3 } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DIAGNOSTIC_DATA_RECORD {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DIAGNOSTIC_DATA_RECORD { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DIAGNOSTIC_DATA_SEARCH_CRITERIA { pub producerNames: *mut super::super::Foundation::PWSTR, pub producerNameCount: u32, pub textToMatch: super::super::Foundation::PWSTR, pub categoryIds: *mut i32, pub categoryIdCount: u32, pub privacyTags: *mut i32, pub privacyTagCount: u32, pub coreDataOnly: super::super::Foundation::BOOL, } #[cfg(feature = "Win32_Foundation")] impl DIAGNOSTIC_DATA_SEARCH_CRITERIA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DIAGNOSTIC_DATA_SEARCH_CRITERIA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DIAGNOSTIC_DATA_SEARCH_CRITERIA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_DATA_SEARCH_CRITERIA") .field("producerNames", &self.producerNames) .field("producerNameCount", &self.producerNameCount) .field("textToMatch", &self.textToMatch) .field("categoryIds", &self.categoryIds) .field("categoryIdCount", &self.categoryIdCount) .field("privacyTags", &self.privacyTags) .field("privacyTagCount", &self.privacyTagCount) .field("coreDataOnly", &self.coreDataOnly) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DIAGNOSTIC_DATA_SEARCH_CRITERIA { fn eq(&self, other: &Self) -> bool { self.producerNames == other.producerNames && self.producerNameCount == other.producerNameCount && self.textToMatch == other.textToMatch && self.categoryIds == other.categoryIds && self.categoryIdCount == other.categoryIdCount && self.privacyTags == other.privacyTags && self.privacyTagCount == other.privacyTagCount && self.coreDataOnly == other.coreDataOnly } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DIAGNOSTIC_DATA_SEARCH_CRITERIA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DIAGNOSTIC_DATA_SEARCH_CRITERIA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DIAGNOSTIC_REPORT_DATA { pub signature: DIAGNOSTIC_REPORT_SIGNATURE, pub bucketId: ::windows::core::GUID, pub reportId: ::windows::core::GUID, pub creationTime: super::super::Foundation::FILETIME, pub sizeInBytes: u64, pub cabId: super::super::Foundation::PWSTR, pub reportStatus: u32, pub reportIntegratorId: ::windows::core::GUID, pub fileNames: *mut super::super::Foundation::PWSTR, pub fileCount: u32, pub friendlyEventName: super::super::Foundation::PWSTR, pub applicationName: super::super::Foundation::PWSTR, pub applicationPath: super::super::Foundation::PWSTR, pub description: super::super::Foundation::PWSTR, pub bucketIdString: super::super::Foundation::PWSTR, pub legacyBucketId: u64, pub reportKey: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DIAGNOSTIC_REPORT_DATA {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DIAGNOSTIC_REPORT_DATA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DIAGNOSTIC_REPORT_DATA { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_REPORT_DATA") .field("signature", &self.signature) .field("bucketId", &self.bucketId) .field("reportId", &self.reportId) .field("creationTime", &self.creationTime) .field("sizeInBytes", &self.sizeInBytes) .field("cabId", &self.cabId) .field("reportStatus", &self.reportStatus) .field("reportIntegratorId", &self.reportIntegratorId) .field("fileNames", &self.fileNames) .field("fileCount", &self.fileCount) .field("friendlyEventName", &self.friendlyEventName) .field("applicationName", &self.applicationName) .field("applicationPath", &self.applicationPath) .field("description", &self.description) .field("bucketIdString", &self.bucketIdString) .field("legacyBucketId", &self.legacyBucketId) .field("reportKey", &self.reportKey) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DIAGNOSTIC_REPORT_DATA { fn eq(&self, other: &Self) -> bool { self.signature == other.signature && self.bucketId == other.bucketId && self.reportId == other.reportId && self.creationTime == other.creationTime && self.sizeInBytes == other.sizeInBytes && self.cabId == other.cabId && self.reportStatus == other.reportStatus && self.reportIntegratorId == other.reportIntegratorId && self.fileNames == other.fileNames && self.fileCount == other.fileCount && self.friendlyEventName == other.friendlyEventName && self.applicationName == other.applicationName && self.applicationPath == other.applicationPath && self.description == other.description && self.bucketIdString == other.bucketIdString && self.legacyBucketId == other.legacyBucketId && self.reportKey == other.reportKey } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DIAGNOSTIC_REPORT_DATA {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DIAGNOSTIC_REPORT_DATA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DIAGNOSTIC_REPORT_PARAMETER { pub name: [u16; 129], pub value: [u16; 260], } impl DIAGNOSTIC_REPORT_PARAMETER {} impl ::core::default::Default for DIAGNOSTIC_REPORT_PARAMETER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DIAGNOSTIC_REPORT_PARAMETER { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_REPORT_PARAMETER").field("name", &self.name).field("value", &self.value).finish() } } impl ::core::cmp::PartialEq for DIAGNOSTIC_REPORT_PARAMETER { fn eq(&self, other: &Self) -> bool { self.name == other.name && self.value == other.value } } impl ::core::cmp::Eq for DIAGNOSTIC_REPORT_PARAMETER {} unsafe impl ::windows::core::Abi for DIAGNOSTIC_REPORT_PARAMETER { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DIAGNOSTIC_REPORT_SIGNATURE { pub eventName: [u16; 65], pub parameters: [DIAGNOSTIC_REPORT_PARAMETER; 10], } impl DIAGNOSTIC_REPORT_SIGNATURE {} impl ::core::default::Default for DIAGNOSTIC_REPORT_SIGNATURE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DIAGNOSTIC_REPORT_SIGNATURE { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DIAGNOSTIC_REPORT_SIGNATURE").field("eventName", &self.eventName).field("parameters", &self.parameters).finish() } } impl ::core::cmp::PartialEq for DIAGNOSTIC_REPORT_SIGNATURE { fn eq(&self, other: &Self) -> bool { self.eventName == other.eventName && self.parameters == other.parameters } } impl ::core::cmp::Eq for DIAGNOSTIC_REPORT_SIGNATURE {} unsafe impl ::windows::core::Abi for DIAGNOSTIC_REPORT_SIGNATURE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DdqAccessLevel(pub i32); pub const NoData: DdqAccessLevel = DdqAccessLevel(0i32); pub const CurrentUserData: DdqAccessLevel = DdqAccessLevel(1i32); pub const AllUserData: DdqAccessLevel = DdqAccessLevel(2i32); impl ::core::convert::From<i32> for DdqAccessLevel { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DdqAccessLevel { type Abi = Self; } #[inline] pub unsafe fn DdqCancelDiagnosticRecordOperation<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqCancelDiagnosticRecordOperation(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION) -> ::windows::core::HRESULT; } DdqCancelDiagnosticRecordOperation(hsession.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqCloseSession<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqCloseSession(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION) -> ::windows::core::HRESULT; } DdqCloseSession(hsession.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqCreateSession(accesslevel: DdqAccessLevel) -> ::windows::core::Result<super::HDIAGNOSTIC_DATA_QUERY_SESSION> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqCreateSession(accesslevel: DdqAccessLevel, hsession: *mut super::HDIAGNOSTIC_DATA_QUERY_SESSION) -> ::windows::core::HRESULT; } let mut result__: <super::HDIAGNOSTIC_DATA_QUERY_SESSION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqCreateSession(::core::mem::transmute(accesslevel), &mut result__).from_abi::<super::HDIAGNOSTIC_DATA_QUERY_SESSION>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqExtractDiagnosticReport<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(hsession: Param0, reportstoretype: u32, reportkey: Param2, destinationpath: Param3) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqExtractDiagnosticReport(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, reportstoretype: u32, reportkey: super::super::Foundation::PWSTR, destinationpath: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } DdqExtractDiagnosticReport(hsession.into_param().abi(), ::core::mem::transmute(reportstoretype), reportkey.into_param().abi(), destinationpath.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqFreeDiagnosticRecordLocaleTags<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_EVENT_TAG_DESCRIPTION>>(htagdescription: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqFreeDiagnosticRecordLocaleTags(htagdescription: super::HDIAGNOSTIC_EVENT_TAG_DESCRIPTION) -> ::windows::core::HRESULT; } DdqFreeDiagnosticRecordLocaleTags(htagdescription.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqFreeDiagnosticRecordPage<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_RECORD>>(hrecord: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqFreeDiagnosticRecordPage(hrecord: super::HDIAGNOSTIC_RECORD) -> ::windows::core::HRESULT; } DdqFreeDiagnosticRecordPage(hrecord.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqFreeDiagnosticRecordProducerCategories<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION>>(hcategorydescription: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqFreeDiagnosticRecordProducerCategories(hcategorydescription: super::HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION) -> ::windows::core::HRESULT; } DdqFreeDiagnosticRecordProducerCategories(hcategorydescription.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqFreeDiagnosticRecordProducers<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION>>(hproducerdescription: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqFreeDiagnosticRecordProducers(hproducerdescription: super::HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION) -> ::windows::core::HRESULT; } DdqFreeDiagnosticRecordProducers(hproducerdescription.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqFreeDiagnosticReport<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_REPORT>>(hreport: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqFreeDiagnosticReport(hreport: super::HDIAGNOSTIC_REPORT) -> ::windows::core::HRESULT; } DdqFreeDiagnosticReport(hreport.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetDiagnosticDataAccessLevelAllowed() -> ::windows::core::Result<DdqAccessLevel> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticDataAccessLevelAllowed(accesslevel: *mut DdqAccessLevel) -> ::windows::core::HRESULT; } let mut result__: <DdqAccessLevel as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticDataAccessLevelAllowed(&mut result__).from_abi::<DdqAccessLevel>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordAtIndex<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_RECORD>>(hrecord: Param0, index: u32) -> ::windows::core::Result<DIAGNOSTIC_DATA_RECORD> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordAtIndex(hrecord: super::HDIAGNOSTIC_RECORD, index: u32, record: *mut DIAGNOSTIC_DATA_RECORD) -> ::windows::core::HRESULT; } let mut result__: <DIAGNOSTIC_DATA_RECORD as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordAtIndex(hrecord.into_param().abi(), ::core::mem::transmute(index), &mut result__).from_abi::<DIAGNOSTIC_DATA_RECORD>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordBinaryDistribution<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0, producernames: *const super::super::Foundation::PWSTR, producernamecount: u32, topnbinaries: u32, binarystats: *mut *mut DIAGNOSTIC_DATA_EVENT_BINARY_STATS, statcount: *mut u32) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordBinaryDistribution(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, producernames: *const super::super::Foundation::PWSTR, producernamecount: u32, topnbinaries: u32, binarystats: *mut *mut DIAGNOSTIC_DATA_EVENT_BINARY_STATS, statcount: *mut u32) -> ::windows::core::HRESULT; } DdqGetDiagnosticRecordBinaryDistribution(hsession.into_param().abi(), ::core::mem::transmute(producernames), ::core::mem::transmute(producernamecount), ::core::mem::transmute(topnbinaries), ::core::mem::transmute(binarystats), ::core::mem::transmute(statcount)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordCategoryAtIndex<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION>>(hcategorydescription: Param0, index: u32) -> ::windows::core::Result<DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordCategoryAtIndex(hcategorydescription: super::HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION, index: u32, categorydescription: *mut DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION) -> ::windows::core::HRESULT; } let mut result__: <DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordCategoryAtIndex(hcategorydescription.into_param().abi(), ::core::mem::transmute(index), &mut result__).from_abi::<DIAGNOSTIC_DATA_EVENT_CATEGORY_DESCRIPTION>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetDiagnosticRecordCategoryCount<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION>>(hcategorydescription: Param0) -> ::windows::core::Result<u32> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordCategoryCount(hcategorydescription: super::HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION, categorydescriptioncount: *mut u32) -> ::windows::core::HRESULT; } let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordCategoryCount(hcategorydescription.into_param().abi(), &mut result__).from_abi::<u32>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetDiagnosticRecordCount<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_RECORD>>(hrecord: Param0) -> ::windows::core::Result<u32> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordCount(hrecord: super::HDIAGNOSTIC_RECORD, recordcount: *mut u32) -> ::windows::core::HRESULT; } let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordCount(hrecord.into_param().abi(), &mut result__).from_abi::<u32>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordLocaleTagAtIndex<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_EVENT_TAG_DESCRIPTION>>(htagdescription: Param0, index: u32) -> ::windows::core::Result<DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordLocaleTagAtIndex(htagdescription: super::HDIAGNOSTIC_EVENT_TAG_DESCRIPTION, index: u32, tagdescription: *mut DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION) -> ::windows::core::HRESULT; } let mut result__: <DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordLocaleTagAtIndex(htagdescription.into_param().abi(), ::core::mem::transmute(index), &mut result__).from_abi::<DIAGNOSTIC_DATA_EVENT_TAG_DESCRIPTION>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetDiagnosticRecordLocaleTagCount<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_EVENT_TAG_DESCRIPTION>>(htagdescription: Param0) -> ::windows::core::Result<u32> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordLocaleTagCount(htagdescription: super::HDIAGNOSTIC_EVENT_TAG_DESCRIPTION, tagdescriptioncount: *mut u32) -> ::windows::core::HRESULT; } let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordLocaleTagCount(htagdescription.into_param().abi(), &mut result__).from_abi::<u32>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordLocaleTags<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(hsession: Param0, locale: Param1) -> ::windows::core::Result<super::HDIAGNOSTIC_EVENT_TAG_DESCRIPTION> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordLocaleTags(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, locale: super::super::Foundation::PWSTR, htagdescription: *mut super::HDIAGNOSTIC_EVENT_TAG_DESCRIPTION) -> ::windows::core::HRESULT; } let mut result__: <super::HDIAGNOSTIC_EVENT_TAG_DESCRIPTION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordLocaleTags(hsession.into_param().abi(), locale.into_param().abi(), &mut result__).from_abi::<super::HDIAGNOSTIC_EVENT_TAG_DESCRIPTION>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordPage<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0, searchcriteria: *const DIAGNOSTIC_DATA_SEARCH_CRITERIA, offset: u32, pagerecordcount: u32, baserowid: i64) -> ::windows::core::Result<super::HDIAGNOSTIC_RECORD> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordPage(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, searchcriteria: *const DIAGNOSTIC_DATA_SEARCH_CRITERIA, offset: u32, pagerecordcount: u32, baserowid: i64, hrecord: *mut super::HDIAGNOSTIC_RECORD) -> ::windows::core::HRESULT; } let mut result__: <super::HDIAGNOSTIC_RECORD as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordPage(hsession.into_param().abi(), ::core::mem::transmute(searchcriteria), ::core::mem::transmute(offset), ::core::mem::transmute(pagerecordcount), ::core::mem::transmute(baserowid), &mut result__).from_abi::<super::HDIAGNOSTIC_RECORD>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordPayload<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0, rowid: i64) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordPayload(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, rowid: i64, payload: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordPayload(hsession.into_param().abi(), ::core::mem::transmute(rowid), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordProducerAtIndex<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION>>(hproducerdescription: Param0, index: u32) -> ::windows::core::Result<DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordProducerAtIndex(hproducerdescription: super::HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION, index: u32, producerdescription: *mut DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION) -> ::windows::core::HRESULT; } let mut result__: <DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordProducerAtIndex(hproducerdescription.into_param().abi(), ::core::mem::transmute(index), &mut result__).from_abi::<DIAGNOSTIC_DATA_EVENT_PRODUCER_DESCRIPTION>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordProducerCategories<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(hsession: Param0, producername: Param1) -> ::windows::core::Result<super::HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordProducerCategories(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, producername: super::super::Foundation::PWSTR, hcategorydescription: *mut super::HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION) -> ::windows::core::HRESULT; } let mut result__: <super::HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordProducerCategories(hsession.into_param().abi(), producername.into_param().abi(), &mut result__).from_abi::<super::HDIAGNOSTIC_EVENT_CATEGORY_DESCRIPTION>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetDiagnosticRecordProducerCount<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION>>(hproducerdescription: Param0) -> ::windows::core::Result<u32> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordProducerCount(hproducerdescription: super::HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION, producerdescriptioncount: *mut u32) -> ::windows::core::HRESULT; } let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordProducerCount(hproducerdescription.into_param().abi(), &mut result__).from_abi::<u32>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetDiagnosticRecordProducers<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0) -> ::windows::core::Result<super::HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordProducers(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, hproducerdescription: *mut super::HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION) -> ::windows::core::HRESULT; } let mut result__: <super::HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordProducers(hsession.into_param().abi(), &mut result__).from_abi::<super::HDIAGNOSTIC_EVENT_PRODUCER_DESCRIPTION>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordStats<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0, searchcriteria: *const DIAGNOSTIC_DATA_SEARCH_CRITERIA, recordcount: *mut u32, minrowid: *mut i64, maxrowid: *mut i64) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordStats(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, searchcriteria: *const DIAGNOSTIC_DATA_SEARCH_CRITERIA, recordcount: *mut u32, minrowid: *mut i64, maxrowid: *mut i64) -> ::windows::core::HRESULT; } DdqGetDiagnosticRecordStats(hsession.into_param().abi(), ::core::mem::transmute(searchcriteria), ::core::mem::transmute(recordcount), ::core::mem::transmute(minrowid), ::core::mem::transmute(maxrowid)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordSummary<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0, producernames: *const super::super::Foundation::PWSTR, producernamecount: u32) -> ::windows::core::Result<DIAGNOSTIC_DATA_GENERAL_STATS> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordSummary(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, producernames: *const super::super::Foundation::PWSTR, producernamecount: u32, generalstats: *mut DIAGNOSTIC_DATA_GENERAL_STATS) -> ::windows::core::HRESULT; } let mut result__: <DIAGNOSTIC_DATA_GENERAL_STATS as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticRecordSummary(hsession.into_param().abi(), ::core::mem::transmute(producernames), ::core::mem::transmute(producernamecount), &mut result__).from_abi::<DIAGNOSTIC_DATA_GENERAL_STATS>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticRecordTagDistribution<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0, producernames: *const super::super::Foundation::PWSTR, producernamecount: u32, tagstats: *mut *mut DIAGNOSTIC_DATA_EVENT_TAG_STATS, statcount: *mut u32) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticRecordTagDistribution(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, producernames: *const super::super::Foundation::PWSTR, producernamecount: u32, tagstats: *mut *mut DIAGNOSTIC_DATA_EVENT_TAG_STATS, statcount: *mut u32) -> ::windows::core::HRESULT; } DdqGetDiagnosticRecordTagDistribution(hsession.into_param().abi(), ::core::mem::transmute(producernames), ::core::mem::transmute(producernamecount), ::core::mem::transmute(tagstats), ::core::mem::transmute(statcount)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetDiagnosticReport<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0, reportstoretype: u32) -> ::windows::core::Result<super::HDIAGNOSTIC_REPORT> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticReport(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, reportstoretype: u32, hreport: *mut super::HDIAGNOSTIC_REPORT) -> ::windows::core::HRESULT; } let mut result__: <super::HDIAGNOSTIC_REPORT as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticReport(hsession.into_param().abi(), ::core::mem::transmute(reportstoretype), &mut result__).from_abi::<super::HDIAGNOSTIC_REPORT>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqGetDiagnosticReportAtIndex<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_REPORT>>(hreport: Param0, index: u32) -> ::windows::core::Result<DIAGNOSTIC_REPORT_DATA> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticReportAtIndex(hreport: super::HDIAGNOSTIC_REPORT, index: u32, report: *mut DIAGNOSTIC_REPORT_DATA) -> ::windows::core::HRESULT; } let mut result__: <DIAGNOSTIC_REPORT_DATA as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticReportAtIndex(hreport.into_param().abi(), ::core::mem::transmute(index), &mut result__).from_abi::<DIAGNOSTIC_REPORT_DATA>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetDiagnosticReportCount<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_REPORT>>(hreport: Param0) -> ::windows::core::Result<u32> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticReportCount(hreport: super::HDIAGNOSTIC_REPORT, reportcount: *mut u32) -> ::windows::core::HRESULT; } let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticReportCount(hreport.into_param().abi(), &mut result__).from_abi::<u32>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetDiagnosticReportStoreReportCount<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0, reportstoretype: u32) -> ::windows::core::Result<u32> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetDiagnosticReportStoreReportCount(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, reportstoretype: u32, reportcount: *mut u32) -> ::windows::core::HRESULT; } let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetDiagnosticReportStoreReportCount(hsession.into_param().abi(), ::core::mem::transmute(reportstoretype), &mut result__).from_abi::<u32>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetSessionAccessLevel<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0) -> ::windows::core::Result<DdqAccessLevel> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetSessionAccessLevel(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, accesslevel: *mut DdqAccessLevel) -> ::windows::core::HRESULT; } let mut result__: <DdqAccessLevel as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetSessionAccessLevel(hsession.into_param().abi(), &mut result__).from_abi::<DdqAccessLevel>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqGetTranscriptConfiguration<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0) -> ::windows::core::Result<DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqGetTranscriptConfiguration(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, currentconfig: *mut DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION) -> ::windows::core::HRESULT; } let mut result__: <DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqGetTranscriptConfiguration(hsession.into_param().abi(), &mut result__).from_abi::<DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DdqIsDiagnosticRecordSampledIn<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>( hsession: Param0, providergroup: *const ::windows::core::GUID, providerid: *const ::windows::core::GUID, providername: Param3, eventid: *const u32, eventname: Param5, eventversion: *const u32, eventkeywords: *const u64, ) -> ::windows::core::Result<super::super::Foundation::BOOL> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqIsDiagnosticRecordSampledIn(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, providergroup: *const ::windows::core::GUID, providerid: *const ::windows::core::GUID, providername: super::super::Foundation::PWSTR, eventid: *const u32, eventname: super::super::Foundation::PWSTR, eventversion: *const u32, eventkeywords: *const u64, issampledin: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); DdqIsDiagnosticRecordSampledIn(hsession.into_param().abi(), ::core::mem::transmute(providergroup), ::core::mem::transmute(providerid), providername.into_param().abi(), ::core::mem::transmute(eventid), eventname.into_param().abi(), ::core::mem::transmute(eventversion), ::core::mem::transmute(eventkeywords), &mut result__).from_abi::<super::super::Foundation::BOOL>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn DdqSetTranscriptConfiguration<'a, Param0: ::windows::core::IntoParam<'a, super::HDIAGNOSTIC_DATA_QUERY_SESSION>>(hsession: Param0, desiredconfig: *const DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DdqSetTranscriptConfiguration(hsession: super::HDIAGNOSTIC_DATA_QUERY_SESSION, desiredconfig: *const DIAGNOSTIC_DATA_EVENT_TRANSCRIPT_CONFIGURATION) -> ::windows::core::HRESULT; } DdqSetTranscriptConfiguration(hsession.into_param().abi(), ::core::mem::transmute(desiredconfig)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); }