text
stringlengths
8
4.13M
use crate::Player; use game_camera::{CameraConfig, CameraMode, ScaledOrthographicProjection}; use game_input::ActionInput; use game_lib::{ bevy::{prelude::*, render::camera::Camera}, tracing::{self, instrument}, }; use game_physics::{JumpStatus, Velocity}; #[instrument(skip(config, input))] pub fn cycle_camera_mode(mut config: ResMut<CameraConfig>, input: Res<Input<ActionInput>>) { if input.just_released(ActionInput::CycleCameraMode) { config.camera_mode = match config.camera_mode { CameraMode::FollowPlayer => CameraMode::Free, CameraMode::Free => CameraMode::FollowPlayer, } } } #[instrument(skip(config, input, time, player_query, camera_query))] pub fn update_camera( config: Res<CameraConfig>, input: Res<Input<ActionInput>>, time: Res<Time>, player_query: Query<&Transform, (With<Player>, Changed<Transform>)>, mut camera_query: Query< (&mut Transform, &mut ScaledOrthographicProjection), (Without<Player>, With<Camera>), >, ) { match config.camera_mode { CameraMode::FollowPlayer => { if let Ok(player_transform) = player_query.single() { let player_pos = player_transform.translation; for (mut camera, _) in camera_query.iter_mut() { camera.translation = player_pos; } } } CameraMode::Free => { // Get direction to move let mut direction = Vec3::default(); if input.pressed(ActionInput::CameraUp) { direction += Vec3::Y; } if input.pressed(ActionInput::CameraDown) { direction -= Vec3::Y; } if input.pressed(ActionInput::CameraLeft) { direction -= Vec3::X; } if input.pressed(ActionInput::CameraRight) { direction += Vec3::X; } // Get amount to zoom in/out let mut zoom_direction = 0.0; if input.pressed(ActionInput::CameraIn) { zoom_direction += 1.0; } if input.pressed(ActionInput::CameraOut) { zoom_direction -= 1.0; } for (mut camera, mut projection) in camera_query.iter_mut() { // Translate camera if needed let velocity = 1000.0 * time.delta_seconds() / projection.zoom; let offset = direction * velocity; if offset.length_squared() > velocity / 10.0 { camera.translation += offset; } // Adjust camera zoom if needed let zoom_velocity = 32.0 * time.delta_seconds(); let zoom_offset = zoom_direction * zoom_velocity; let new_zoom = (projection.zoom + zoom_offset).max(0.1); if (projection.zoom - new_zoom).abs() > 0.001 { projection.zoom = new_zoom; } } } } } #[instrument(skip(input, query))] pub fn move_player( input: Res<Input<ActionInput>>, mut query: Query<(&mut Velocity, &mut JumpStatus), With<Player>>, ) { // Get direction to move const MOVE_SPEED: f32 = 5.0; const JUMP_SPEED: f32 = 5.0; let mut move_velocity = Vec2::default(); let mut jump_velocity = None; if input.pressed(ActionInput::PlayerLeft) { move_velocity -= Vec2::X * MOVE_SPEED; } if input.pressed(ActionInput::PlayerRight) { move_velocity += Vec2::X * MOVE_SPEED; } if input.pressed(ActionInput::PlayerJump) { jump_velocity = Some(Vec2::Y * JUMP_SPEED); } // Apply force for (mut velocity, mut jump_status) in query.iter_mut() { if move_velocity.length_squared() >= 0.1 { if move_velocity.x > 0.0 && move_velocity.x > velocity.0.x { velocity.0.x = (velocity.0.x + move_velocity.x).min(move_velocity.x); } else if move_velocity.x < 0.0 && move_velocity.x < velocity.0.x { velocity.0.x = (velocity.0.x + move_velocity.x).max(move_velocity.x); } } if *jump_status == JumpStatus::OnGround { if let Some(jump_velocity) = jump_velocity { velocity.0.y = (velocity.0.y + jump_velocity.y).min(jump_velocity.y); *jump_status = JumpStatus::InAir { jumps: 1 }; } } } }
use scihub_scraper::SciHubScraper; use structopt::StructOpt; #[derive(StructOpt, Debug)] #[structopt(name = "basic")] struct Opt { #[structopt(short, long)] paper: String, } #[tokio::main] async fn main() { let opt = Opt::from_args(); println!("Fetching paper: {}", opt.paper); let mut scraper = SciHubScraper::new(); println!("Fetching base urls..."); match scraper.fetch_base_urls().await { Ok(base_urls) => { println!( "Found base urls: {}", base_urls .iter() .map(|e| e.url.as_str()) .collect::<Vec<_>>() .join(", ") ); } Err(error) => { println!("Failed to fetch base urls: {}", error); return; } } println!("Fetching paper..."); match scraper.fetch_paper_by_doi(&opt.paper).await { Ok(paper) => { println!("Found paper:"); println!("{:#?}", paper); } Err(error) => { println!("Failed to fetch paper: {}", error); } } }
use crate::integer::Integer; use core::cmp::Ordering; macro_rules! impl_partial_eq { ($rhs:ty, $func:path) => { impl PartialEq<$rhs> for Integer { fn eq(&self, other: &$rhs) -> bool { $func(&self, other) == Ordering::Equal } } }; ($rhs:ty, $func:path, deref rhs) => { impl PartialEq<$rhs> for Integer { fn eq(&self, other: &$rhs) -> bool { $func(&self, *other) == Ordering::Equal } } impl PartialEq<Integer> for $rhs { fn eq(&self, other: &Integer) -> bool { // This doesn't need to be reversed as it simply checks equality $func(&other, *self) == Ordering::Equal } } }; ($rhs:ty, $func:path, into rhs) => { impl PartialEq<$rhs> for Integer { fn eq(&self, other: &$rhs) -> bool { $func(&self, &Integer::from(other)) == Ordering::Equal } } impl PartialEq<Integer> for $rhs { fn eq(&self, other: &Integer) -> bool { // This doesn't need to be reversed as it simply checks equality $func(&other, &Integer::from(self)) == Ordering::Equal } } }; } impl_partial_eq!(Integer, Integer::compare); impl_partial_eq!(u8, Integer::compare_c_long, deref rhs); impl_partial_eq!(i8, Integer::compare_c_long, deref rhs); impl_partial_eq!(u16, Integer::compare_c_long, deref rhs); impl_partial_eq!(i16, Integer::compare_c_long, deref rhs); impl_partial_eq!(i32, Integer::compare_c_long, deref rhs); cfg_if::cfg_if! { if #[cfg(all(target_pointer_width = "64", not(windows)))] { impl_partial_eq!(u32, Integer::compare_c_long, deref rhs); impl_partial_eq!(i64, Integer::compare_c_long, deref rhs); } else { impl_partial_eq!(u32, Integer::compare, into rhs); impl_partial_eq!(i64, Integer::compare, into rhs); } } impl_partial_eq!(u64, Integer::compare, into rhs); impl_partial_eq!(i128, Integer::compare, into rhs); impl_partial_eq!(u128, Integer::compare, into rhs); impl Eq for Integer {} macro_rules! impl_partial_ord { ($rhs:ty, $func:path) => { impl PartialOrd<$rhs> for Integer { fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> { Some($func(self, other)) } } }; ($rhs:ty, $func:path, deref rhs) => { impl PartialOrd<$rhs> for Integer { fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> { Some($func(self, *other)) } } impl PartialOrd<Integer> for $rhs { fn partial_cmp(&self, other: &Integer) -> Option<Ordering> { // This implies that: // (a cmp b) <=> (b cmp a).reverse() // I don't know if thats always true Some($func(other, *self).reverse()) } } }; ($rhs:ty, $func:path, into rhs) => { impl PartialOrd<$rhs> for Integer { fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> { Some($func(self, &Integer::from(other))) } } impl PartialOrd<Integer> for $rhs { fn partial_cmp(&self, other: &Integer) -> Option<Ordering> { // This implies that: // (a cmp b) <=> (b cmp a).reverse() // I don't know if thats always true Some($func(other, &Integer::from(self)).reverse()) } } }; } impl_partial_ord!(Integer, Integer::compare); impl_partial_ord!(u8, Integer::compare_c_long, deref rhs); impl_partial_ord!(i8, Integer::compare_c_long, deref rhs); impl_partial_ord!(u16, Integer::compare_c_long, deref rhs); impl_partial_ord!(i16, Integer::compare_c_long, deref rhs); impl_partial_ord!(i32, Integer::compare_c_long, deref rhs); cfg_if::cfg_if! { if #[cfg(all(target_pointer_width = "64", not(windows)))] { impl_partial_ord!(u32, Integer::compare_c_long, deref rhs); impl_partial_ord!(i64, Integer::compare_c_long, deref rhs); } else { impl_partial_ord!(u32, Integer::compare, into rhs); impl_partial_ord!(i64, Integer::compare, into rhs); } } impl_partial_ord!(u64, Integer::compare, into rhs); impl_partial_ord!(i128, Integer::compare, into rhs); impl_partial_ord!(u128, Integer::compare, into rhs); impl Ord for Integer { fn cmp(&self, other: &Self) -> Ordering { Integer::compare(self, other) } } #[cfg(test)] mod test { use super::*; #[test] fn compare_integers() { let a = Integer::from_c_long(50505); let b = Integer::from_c_long(5050); assert_eq!(a.cmp(&b), Ordering::Greater); assert_eq!(a.cmp(&a), Ordering::Equal); assert_eq!(b.cmp(&a), Ordering::Less); } #[test] fn compare_integers_with_operands() { let a = Integer::from_c_long(12345); let b = Integer::from_c_long(1234); assert!(a != b); assert!(a > b); assert!(!(a < b)); assert!((&a - &b) > b); assert!(b != a); assert!(b < a); assert!(!(b > a)); assert!((&b - &a) < 0); } #[test] fn compare_big_integers_with_small() { let a = Integer::from_string_repr("1234567890", 10).unwrap(); assert!(a > 0); assert!(a != 987_654_321); assert!(a < 9_999_999_990u128); assert!(9_999_999_990u128 > a); assert!(987_654_321 != a); assert!(0 < a); } }
use crate::Instance; use std::rc::Rc; /// A publisher of messages. /// /// It can be used to route messages back to the [`Application`]. /// /// [`Application`]: trait.Application.html #[allow(missing_debug_implementations)] #[derive(Clone)] pub struct Bus<Message> { publish: Rc<Box<dyn Fn(Message, &mut dyn dodrio::RootRender)>>, } impl<Message> Bus<Message> where Message: 'static + Clone, { pub(crate) fn new() -> Self { Self { publish: Rc::new(Box::new(|message, root| { let app = root.unwrap_mut::<Instance<Message>>(); app.update(message) })), } } /// Publishes a new message for the [`Application`]. /// /// [`Application`]: trait.Application.html pub fn publish(&self, message: Message, root: &mut dyn dodrio::RootRender) { (self.publish)(message, root); } /// Creates a new [`Bus`] that applies the given function to the messages /// before publishing. /// /// [`Bus`]: struct.Bus.html pub fn map<B>(&self, mapper: Rc<Box<dyn Fn(B) -> Message>>) -> Bus<B> where B: 'static, { let publish = self.publish.clone(); Bus { publish: Rc::new(Box::new(move |message, root| { publish(mapper(message), root) })), } } }
#![allow(clippy::type_complexity)] use fuzzcheck::mutators::bool::BoolMutator; use fuzzcheck::mutators::boxed::BoxMutator; use fuzzcheck::mutators::option::OptionMutator; use fuzzcheck::mutators::recursive::{RecurToMutator, RecursiveMutator}; use fuzzcheck::{make_mutator, DefaultMutator, Mutator}; #[derive(Clone, Debug)] struct S { x: bool, y: Option<Box<S>>, } make_mutator! { name: SMutator, recursive: true, default: true, type: struct S { x: bool, #[field_mutator(OptionMutator<Box<S>, BoxMutator<RecurToMutator<SMutator<M0>>>> = { OptionMutator::new(BoxMutator::new(self_.into())) }) ] y: Option<Box<S>>, } } #[derive(Clone)] pub struct R<T> { x: u8, y: Option<Box<R<T>>>, z: Vec<T>, } make_mutator! { name: RMutator, recursive: true, default: true, type: // repeat the declaration of E pub struct R<T> { x: u8, // for recursive mutators, it is necessary to indicate *where* the recursion is // and use a `RecurToMutator` as the recursive field's mutator // M0 is the type parameter for the mutator of the `x` field #[field_mutator(OptionMutator<Box<R<T>>, BoxMutator<RecurToMutator<RMutator<T, M0, M2>>>> = { OptionMutator::new(BoxMutator::new(self_.into())) })] // self_.into() creates the RecurToMutator y: Option<Box<R<T>>>, z: Vec<T> } } mod mutator {} #[test] #[no_coverage] fn test_compile() { let _m = RecursiveMutator::new(|self_| { SMutator::new(<bool as DefaultMutator>::default_mutator(), { OptionMutator::new(BoxMutator::new(self_.into())) }) }); let _m: RecursiveMutator<SMutator<BoolMutator>> = S::default_mutator(); let m = S::default_mutator(); let (x, _) = m.random_arbitrary(10.0); println!("{:?}", x); }
#[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::_2_RIS { #[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_2_RIS_INTCNTZEROR { bits: bool, } impl PWM_2_RIS_INTCNTZEROR { #[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_2_RIS_INTCNTZEROW<'a> { w: &'a mut W, } impl<'a> _PWM_2_RIS_INTCNTZEROW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct PWM_2_RIS_INTCNTLOADR { bits: bool, } impl PWM_2_RIS_INTCNTLOADR { #[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_2_RIS_INTCNTLOADW<'a> { w: &'a mut W, } impl<'a> _PWM_2_RIS_INTCNTLOADW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct PWM_2_RIS_INTCMPAUR { bits: bool, } impl PWM_2_RIS_INTCMPAUR { #[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_2_RIS_INTCMPAUW<'a> { w: &'a mut W, } impl<'a> _PWM_2_RIS_INTCMPAUW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct PWM_2_RIS_INTCMPADR { bits: bool, } impl PWM_2_RIS_INTCMPADR { #[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_2_RIS_INTCMPADW<'a> { w: &'a mut W, } impl<'a> _PWM_2_RIS_INTCMPADW<'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 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct PWM_2_RIS_INTCMPBUR { bits: bool, } impl PWM_2_RIS_INTCMPBUR { #[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_2_RIS_INTCMPBUW<'a> { w: &'a mut W, } impl<'a> _PWM_2_RIS_INTCMPBUW<'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 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct PWM_2_RIS_INTCMPBDR { bits: bool, } impl PWM_2_RIS_INTCMPBDR { #[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_2_RIS_INTCMPBDW<'a> { w: &'a mut W, } impl<'a> _PWM_2_RIS_INTCMPBDW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Counter=0 Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcntzero(&self) -> PWM_2_RIS_INTCNTZEROR { let bits = ((self.bits >> 0) & 1) != 0; PWM_2_RIS_INTCNTZEROR { bits } } #[doc = "Bit 1 - Counter=Load Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcntload(&self) -> PWM_2_RIS_INTCNTLOADR { let bits = ((self.bits >> 1) & 1) != 0; PWM_2_RIS_INTCNTLOADR { bits } } #[doc = "Bit 2 - Comparator A Up Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcmpau(&self) -> PWM_2_RIS_INTCMPAUR { let bits = ((self.bits >> 2) & 1) != 0; PWM_2_RIS_INTCMPAUR { bits } } #[doc = "Bit 3 - Comparator A Down Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcmpad(&self) -> PWM_2_RIS_INTCMPADR { let bits = ((self.bits >> 3) & 1) != 0; PWM_2_RIS_INTCMPADR { bits } } #[doc = "Bit 4 - Comparator B Up Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcmpbu(&self) -> PWM_2_RIS_INTCMPBUR { let bits = ((self.bits >> 4) & 1) != 0; PWM_2_RIS_INTCMPBUR { bits } } #[doc = "Bit 5 - Comparator B Down Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcmpbd(&self) -> PWM_2_RIS_INTCMPBDR { let bits = ((self.bits >> 5) & 1) != 0; PWM_2_RIS_INTCMPBDR { 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 = "Bit 0 - Counter=0 Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcntzero(&mut self) -> _PWM_2_RIS_INTCNTZEROW { _PWM_2_RIS_INTCNTZEROW { w: self } } #[doc = "Bit 1 - Counter=Load Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcntload(&mut self) -> _PWM_2_RIS_INTCNTLOADW { _PWM_2_RIS_INTCNTLOADW { w: self } } #[doc = "Bit 2 - Comparator A Up Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcmpau(&mut self) -> _PWM_2_RIS_INTCMPAUW { _PWM_2_RIS_INTCMPAUW { w: self } } #[doc = "Bit 3 - Comparator A Down Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcmpad(&mut self) -> _PWM_2_RIS_INTCMPADW { _PWM_2_RIS_INTCMPADW { w: self } } #[doc = "Bit 4 - Comparator B Up Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcmpbu(&mut self) -> _PWM_2_RIS_INTCMPBUW { _PWM_2_RIS_INTCMPBUW { w: self } } #[doc = "Bit 5 - Comparator B Down Interrupt Status"] #[inline(always)] pub fn pwm_2_ris_intcmpbd(&mut self) -> _PWM_2_RIS_INTCMPBDW { _PWM_2_RIS_INTCMPBDW { w: self } } }
extern crate naive_gui; use naive_gui::{ Gui, Drawer, Widget::*, }; struct DrawContext { fill_rgba: (f32, f32, f32, f32), stroke_rgba: (f32, f32, f32, f32), font_size: f32, } impl DrawContext { fn new() -> Self{ DrawContext{ fill_rgba: (0., 0., 0., 1.), stroke_rgba: (0., 0., 0., 1.), font_size: 12., } } } impl Drawer for DrawContext{ fn set_fill_style(&mut self, rgba:(f32, f32, f32, f32)){ self.fill_rgba = rgba; } fn set_stroke_style(&mut self, rgba:(f32, f32, f32, f32)){ self.stroke_rgba = rgba; } fn set_font_style(&mut self, size: f32) { self.font_size = size; } fn draw_rect(&self, xywh:(f32, f32, f32, f32)) { println!("draw rect at {:?}", xywh); } fn draw_text(&self, text: &str, xy:(f32, f32)){ println!("draw text({}) at {}, {}", text, xy.0, xy.1); } } fn main(){ let mut drawer = DrawContext::new(); let mut gui = Gui::new(); let id = gui.put(Label{text:"hi".to_string(), size:12., xy:(1., 1.), rgba:(1.,1.,1.,0.)}); let id2 = gui.put(Label{text:"hello".to_string(), size:12., xy:(1., 1.), rgba:(1.,1.,1.,0.)}); gui.draw(&mut drawer); /* let mut t = gui.take(id); t.text = "hmm..".to_string(); gui.put(t); */ if let Label{ref mut text, ..} = gui.get_mut(id) { *text = "mutated".to_string(); } gui.draw(&mut drawer); //if let Label{ref text, ..} = a { // println!("{}?", text); //} }
pub use self::imp::*; #[cfg(all( regex_runtime_teddy_ssse3, target_arch = "x86_64", ))] mod imp; #[cfg(not(all( regex_runtime_teddy_ssse3, target_arch = "x86_64", )))] #[path = "fallback.rs"] mod imp;
//! Watchlists to detect clauses that became unit. //! //! Each (long) clause has always two watches pointing to it. The watches are kept in the watchlists //! of two different literals of the clause. Whenever the watches are moved to different literals //! the litereals of the clause are permuted so the watched literals are in position 0 and 1. //! //! When a clause is not unit under the current assignment, the watched literals point at two //! non-false literals. When a clause is unit and thus propagating, the true literal is watched and //! in position 0, the other watched literal is the one with the largest decision level and kept in //! position 1. When a clause becomes satisfied before becoming unit the watches can be kept as they //! were. //! //! When a literal is assigned false that invariant can be invalidated. This can be detected by //! scanning the watches of the assigned literal. When the assignment is processed the watches are //! moved to restore that invariant. Unless there is a conflict, i.e. a clause with no non-false //! literals, this can always be done. This also finds all clauses that became unit. The new unit //! clauses are exactly those clauses where no two non-false literals can be found. //! //! There is no need to update watchlists on backtracking, as unassigning variables cannot //! invalidate the invariant. //! //! See [Section 4.5.1 of the "Handbook of Satisfiability"][handbook-ch4] for more details and //! references. //! //! As a further optimization we use blocking literals. This means that each watch stores a literal //! of the clause that is different from the watched literal. It can be the other watched literal or //! any unwatched literal. When that literal is true, the clause is already satisfied, meaning that //! no watches need to be updated. This can be detected by just looking at the watch, avoiding //! access of the clause database. This variant was introduced by [Niklas Sörensson and Niklas Eén //! in "MINISAT 2.1 and MINISAT++1.0 — SAT Race 2008 Editions"][minisat-2.1]. //! //! [handbook-ch4]: https://www.satassociation.org/articles/FAIA185-0131.pdf //! [minisat-2.1]: https://www.cril.univ-artois.fr/SAT09/solvers/booklet.pdf use partial_ref::{partial, PartialRef}; use varisat_formula::Lit; use crate::{ clause::{db, ClauseRef}, context::{parts::*, Context}, }; /// A watch on a long clause. #[derive(Copy, Clone)] pub struct Watch { /// Clause which has the referring lit in position 0 or 1. pub cref: ClauseRef, /// A lit of the clause, different from the referring lit. pub blocking: Lit, } /// Watchlists to detect clauses that became unit. pub struct Watchlists { /// Contains only valid data for indices of assigned variables. watches: Vec<Vec<Watch>>, /// Whether watchlists are present enabled: bool, } impl Default for Watchlists { fn default() -> Watchlists { Watchlists { watches: vec![], enabled: true, } } } impl Watchlists { /// Update structures for a new variable count. pub fn set_var_count(&mut self, count: usize) { self.watches.resize(count * 2, vec![]); } /// Start watching a clause. /// /// `lits` have to be the first two literals of the given clause. pub fn watch_clause(&mut self, cref: ClauseRef, lits: [Lit; 2]) { if !self.enabled { return; } for i in 0..2 { let watch = Watch { cref, blocking: lits[i ^ 1], }; self.add_watch(!lits[i], watch); } } /// Return watches for a given literal. pub fn watched_by_mut(&mut self, lit: Lit) -> &mut Vec<Watch> { &mut self.watches[lit.code()] } /// Make a literal watch a clause. pub fn add_watch(&mut self, lit: Lit, watch: Watch) { self.watches[lit.code()].push(watch) } /// Are watchlists enabled. pub fn enabled(&self) -> bool { self.enabled } /// Clear and disable watchlists. /// /// Actual clearing of the watchlists is done on re-enabling of the watchlists. pub fn disable(&mut self) { self.enabled = false; } } /// Enable and rebuild watchlists. pub fn enable_watchlists(mut ctx: partial!(Context, mut WatchlistsP, ClauseAllocP, ClauseDbP)) { let (watchlists, mut ctx) = ctx.split_part_mut(WatchlistsP); if watchlists.enabled { return; } for watchlist in watchlists.watches.iter_mut() { watchlist.clear(); } watchlists.enabled = true; let (alloc, mut ctx) = ctx.split_part(ClauseAllocP); for cref in db::clauses_iter(&ctx.borrow()) { let lits = alloc.clause(cref).lits(); watchlists.watch_clause(cref, [lits[0], lits[1]]); } }
extern crate nbt; use nbt::NBT; #[test] fn test_byte() { let data: ~str = ~"\x0a\x00\x04abcd\x01\x00\x04test\x01\x00"; let bytes = ~std::io::MemReader::new(data.into_bytes()); let mut parser = NBT::Parser::new(bytes as ~Reader); let root: ~NBT::NamedTag = parser.parse(); assert!(root.get_name() == "abcd"); match *root.get_tag() { NBT::CompoundTag(ref vs) => { assert!(vs.len() == 1); let sub_tag : &NBT::NamedTag = vs.get(0); assert!(sub_tag.get_name() == "test"); match *sub_tag.get_tag() { NBT::ByteTag(v) => { assert!(v == 1); } _ => fail!("Unexpected subtag!") } }, _ => fail!("Unexpected tag type!") } } #[test] fn test_short() { let data: ~str = ~"\x0a\x00\x04abcd\x02\x00\x05hello\x12\x34\x00"; let bytes = ~std::io::MemReader::new(data.into_bytes()); let mut parser = NBT::Parser::new(bytes as ~Reader); let root: ~NBT::NamedTag = parser.parse(); assert!(root.get_name() == "abcd"); match *root.get_tag() { NBT::CompoundTag(ref vs) => { assert!(vs.len() == 1); let sub_tag : &NBT::NamedTag = vs.get(0); assert!(sub_tag.get_name() == "hello"); match *sub_tag.get_tag() { NBT::ShortTag(v) => { assert!(v == 4660); } _ => fail!("Unexpected subtag!") } }, _ => fail!("Unexpected tag type!") } } #[test] fn test_int() { let data: ~str = ~"\x0a\x00\x04abcd\x03\x00\x05world\x12\x34\x56\x78\x00"; let bytes = ~std::io::MemReader::new(data.into_bytes()); let mut parser = NBT::Parser::new(bytes as ~Reader); let root: ~NBT::NamedTag = parser.parse(); assert!(root.get_name() == "abcd"); match *root.get_tag() { NBT::CompoundTag(ref vs) => { assert!(vs.len() == 1); let sub_tag : &NBT::NamedTag = vs.get(0); assert!(sub_tag.get_name() == "world"); match *sub_tag.get_tag() { NBT::IntTag(v) => { assert!(v == 305419896); } _ => fail!("Unexpected subtag!") } }, _ => fail!("Unexpected tag type!") } } #[test] fn test_long() { let data: ~str = ~"\x0a\x00\x04abcd\x04\x00\x05world\x12\x34\x56\x78\x12\x34\x56\x78\x00"; let bytes = ~std::io::MemReader::new(data.into_bytes()); let mut parser = NBT::Parser::new(bytes as ~Reader); let root: ~NBT::NamedTag = parser.parse(); assert!(root.get_name() == "abcd"); match *root.get_tag() { NBT::CompoundTag(ref vs) => { assert!(vs.len() == 1); let sub_tag : &NBT::NamedTag = vs.get(0); assert!(sub_tag.get_name() == "world"); match *sub_tag.get_tag() { NBT::LongTag(v) => { assert!(v == 1311768465173141112); } _ => fail!("Unexpected subtag!") } }, _ => fail!("Unexpected tag type!") } } #[test] fn test_bytearray() { let data: ~str = ~"\x0a\x00\x04abcd\x07\x00\x05world\x00\x00\x00\x0a\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x00"; let bytes = ~std::io::MemReader::new(data.into_bytes()); let mut parser = NBT::Parser::new(bytes as ~Reader); let root: ~NBT::NamedTag = parser.parse(); assert!(root.get_name() == "abcd"); match *root.get_tag() { NBT::CompoundTag(ref vs) => { assert!(vs.len() == 1); let sub_tag : &NBT::NamedTag = vs.get(0); assert!(sub_tag.get_name() == "world"); match *sub_tag.get_tag() { NBT::ByteArrayTag(ref v) => { assert!(*v == ~[0,1,2,3,4,5,6,7,8,9]); } _ => fail!("Unexpected subtag!") } }, _ => fail!("Unexpected tag type!") } } #[test] fn test_string() { let data: ~str = ~"\x0a\x00\x04abcd\x08\x00\x05world\x00\x0chello world!\x00"; let bytes = ~std::io::MemReader::new(data.into_bytes()); let mut parser = NBT::Parser::new(bytes as ~Reader); let root: ~NBT::NamedTag = parser.parse(); println!("pasred!"); assert!(root.get_name() == "abcd"); match *root.get_tag() { NBT::CompoundTag(ref vs) => { assert!(vs.len() == 1); let sub_tag : &NBT::NamedTag = vs.get(0); println!("Have subtag!"); assert!(sub_tag.get_name() == "world"); match *sub_tag.get_tag() { NBT::StringTag(ref v) => { assert!(*v == ~"hello world!"); } _ => fail!("Unexpected subtag!") } }, _ => fail!("Unexpected tag type!") } } #[test] fn test_e_dat() { let levelp = std::path::Path::new("e.dat"); let level: std::io::File = std::io::File::open(&levelp).unwrap(); let mut parser = NBT::Parser::new(~level as ~Reader); let root: ~NBT::NamedTag = parser.parse(); assert!(root.get_type() == NBT::TAGCompound); //let n: &u8 = iter.next().unwrap(); //println(format!("byte 1 is {}\n", n.to_str())); //NBT::parse(iter); //let l: uint = bytes.len(); //println(format!("byte 1 is {}\n", bytes[0])); } #[test] fn test_print_e_data() { let levelp = std::path::Path::new("e.dat"); let level: std::io::File = std::io::File::open(&levelp).unwrap(); let mut parser = NBT::Parser::new(~level as ~Reader); let root: ~NBT::NamedTag = parser.parse(); assert!(root.get_type() == NBT::TAGCompound); let s = root.pretty_print(); // if you actually want to see the pretty-printed tree, set the NBT_PRETTYPRINT envvar let xx : std::c_str::CString = "NBT_PRETTYPRINT".to_c_str(); unsafe { if ! std::libc::funcs::c95::stdlib::getenv(xx.unwrap()).is_null() { println!("{}", s); } } }
#[macro_use] extern crate slog; #[macro_use] extern crate clap; use clap::Arg; use daemonize::Daemonize; use sloggers::Config; use std::error::Error; use std::fs::File; use std::io::Read; use std::process::exit; use shaft::db::SqliteDatabase; use shaft::rest::{ format_pence_as_pounds_helper, register_servlets, AppConfig, AppState, AuthenticateUser, MiddlewareLogger, }; use shaft::settings::Settings; /// Attempts to load and build the handlebars template file. macro_rules! load_template { ($logger:expr, $hb:expr, $root:expr, $name:expr) => { if let Err(e) = load_template_impl(&mut $hb, $root, $name) { crit!($logger, "Failed to load resources/{}.hbs: {}", $name, e); exit(1); } }; } /// App Entry point. fn main() { // Load settings, first by looking at command line options for config files // to look in. let matches = clap::app_from_crate!() .arg( Arg::with_name("config") .short("c") .multiple(true) .long("config") .value_name("FILE") .help("Sets a custom config file") .takes_value(true) .required(false), ) .get_matches(); let mut c = config::Config::new(); // We can have multiple config files which get merged together for file in matches.values_of("config").unwrap_or_default() { if let Err(err) = c.merge(config::File::with_name(file)) { // We don't have a logger yet, so print to stderr eprintln!("{}", err); exit(1) } } // Also load config from environment c.merge(config::Environment::with_prefix("SHAFT")).unwrap(); let settings: Settings = match c.try_into() { Ok(s) => s, Err(err) => { // We don't have a logger yet, so print to stderr eprintln!("Config error: {}", err); exit(1); } }; // Set up logging immediately. let logger = settings.log.build_logger().unwrap(); // Load and build the templates. let mut hb = handlebars::Handlebars::new(); load_template!(logger, hb, &settings.resource_dir, "index"); load_template!(logger, hb, &settings.resource_dir, "login"); load_template!(logger, hb, &settings.resource_dir, "transactions"); load_template!(logger, hb, &settings.resource_dir, "base"); hb.register_helper("pence-as-pounds", Box::new(format_pence_as_pounds_helper)); // Set up the database let database = SqliteDatabase::with_path(settings.database_file); // Sanitize the webroot to not end in a trailing slash. let web_root = settings.web_root.trim_end_matches('/').to_string(); // This is the read only config for the app. let app_config = AppConfig { github_client_id: settings.github.client_id.clone(), github_client_secret: settings.github.client_secret.clone(), github_state: settings.github.state.clone(), web_root, required_org: settings.github.required_org.clone(), resource_dir: settings.resource_dir.clone(), }; // Holds the state for the shared state of the app. Gets cloned to each thread. let app_state = AppState::new(app_config, hb, database); // Set up HTTP server let mut sys = actix_rt::System::new("shaft"); // Need to set up an actix system first. let logger_middleware = MiddlewareLogger::new(logger.clone()); let http_server = actix_web::HttpServer::new(move || { // This gets called in each thread to set up the HTTP handlers let logger_middleware = logger_middleware.clone(); actix_web::App::new() .data(app_state.clone()) .app_data(app_state.clone()) .wrap(AuthenticateUser::new(app_state.database.clone())) .wrap_fn(move |req, srv| logger_middleware.wrap(req, srv)) .configure(|config| register_servlets(config, &app_state)) }) .bind(&settings.bind) .unwrap(); // If we need to daemonize do so *just* before starting the event loop if let Some(daemonize_settings) = settings.daemonize { Daemonize::new() .pid_file(daemonize_settings.pid_file) .start() .expect("be able to daemonize"); } // Start the event loop. info!(logger, "Started server on http://{}", settings.bind); let _ = sys.block_on(async move { http_server.run().await }); } /// Attempts to load the template into handlebars instance. fn load_template_impl( hb: &mut handlebars::Handlebars, root: &str, name: &str, ) -> Result<(), Box<dyn Error>> { let mut index_file = File::open(format!("{}/{}.hbs", root, name))?; let mut source = String::new(); index_file.read_to_string(&mut source)?; hb.register_template_string(name, source)?; Ok(()) }
use std::os::unix::io::FromRawFd; use std::pin::Pin; use std::task::{Context, Poll}; use std::thread; use anyhow::Error; use bytes::{Buf, BytesMut}; use futures::Stream; use lazy_static::lazy_static; use libc::STDIN_FILENO; use log::*; use nix::sys::termios::{self, ControlFlags, InputFlags, LocalFlags, OutputFlags, SetArg, Termios}; use pin_project::{pin_project, pinned_drop}; use qp_trie::Trie; use tokio::fs::File; use tokio::io; use tokio_util::codec::{Decoder, FramedRead}; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Key { ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Char(char), Ctrl(char), Backspace, Return, Esc, } lazy_static! { /// Trie mapping all known escape sequences to a pair of the Key that the represent and the /// length of the sequence. static ref ESCAPE_SEQUENCES: Trie<&'static [u8], Key> = { use Key::*; macro_rules! init_trie { ( $( $seq:literal => $key:expr ),* $(,)? ) => { { let mut trie = Trie::new(); $( trie.insert(&$seq[..], $key); )* trie } } } init_trie! { b"A" => ArrowUp, b"B" => ArrowDown, b"C" => ArrowRight, b"D" => ArrowLeft, } }; } /// Codec to decode keys from buffers containing ANSI escape sequences from stdin. Doing this is /// notoriously ambiguous. The strategy employed by this codec relies on a few facts: /// /// - All escape sequences start with `\x1b[`. /// - User input is slow compared to the speed of processing, so individual inputs will /// generally arrive in their own buffers. /// - There are a finite number of known escape sequences, so try to parse from a subset if /// there's ambiguity. struct KeyCodec; impl KeyCodec { fn parse_byte(byte: u8) -> Key { #[allow(clippy::match_overlapping_arm)] // rust-lang/rust-clippy#6603 match byte { b'\x0D' => Key::Return, b'\x01'..=b'\x1A' => Key::Ctrl((byte | 0x60) as char), b'\x1b' => Key::Esc, b'\x7f' => Key::Backspace, _ => Key::Char(byte as char), } } /// Attempts to parse a key from a byte slice that starts with an escape sequence. /// /// The sequence should have its `\x1b[` prefix already removed, but trailing bytes are /// allowed. If the slice contains a known escape sequence, then this function returns a pair /// of the parsed key and how many bytes should be consumed. If no known sequence was found, /// `None` is returned. fn parse_escape_sequence(seq: &[u8]) -> Option<(Key, usize)> { let common_prefix = ESCAPE_SEQUENCES.longest_common_prefix(seq); let key = ESCAPE_SEQUENCES.get(common_prefix)?; Some((*key, common_prefix.len())) } } impl Decoder for KeyCodec { type Item = Key; type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { let key = match buf.as_ref() { [] => return Ok(None), [b'\x1b', b'[', seq @ ..] => { let pos = seq .iter() .position(|&b| b == b'\x1b') .unwrap_or_else(|| seq.len()); if let Some((key, len)) = Self::parse_escape_sequence(&seq[..pos]) { buf.advance(2 + len); key } else { warn!( "encountered unknown escape sequence: \\x1b[{}", String::from_utf8_lossy(seq) ); buf.advance(2 + pos); return Ok(None); } } _ => { let byte = buf.split_to(1)[0]; Self::parse_byte(byte) } }; Ok(Some(key)) } } #[pin_project(PinnedDrop)] pub struct Stdin { #[pin] stdin: FramedRead<File, KeyCodec>, /// The terminal settings when the program started. pub old_termios: Termios, } impl Stdin { /// Creates a new Stdin instance. This function also handles entering raw mode, and the /// destructor will restore the original terminal settings. pub fn new() -> Result<Self, Error> { let stdin = File::from_std(unsafe { std::fs::File::from_raw_fd(STDIN_FILENO) }); let old_termios = termios::tcgetattr(STDIN_FILENO)?; let mut raw = old_termios.clone(); raw.input_flags.remove( InputFlags::BRKINT | InputFlags::ICRNL | InputFlags::INPCK | InputFlags::ISTRIP | InputFlags::IXON, ); raw.output_flags.remove(OutputFlags::OPOST); raw.control_flags.insert(ControlFlags::CS8); raw.local_flags .remove(LocalFlags::ECHO | LocalFlags::ICANON | LocalFlags::IEXTEN | LocalFlags::ISIG); termios::tcsetattr(STDIN_FILENO, SetArg::TCSAFLUSH, &raw)?; Ok(Stdin { stdin: FramedRead::new(stdin, KeyCodec), old_termios, }) } } impl Stream for Stdin { type Item = io::Result<Key>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { self.project().stdin.poll_next(cx) } } #[pinned_drop] impl PinnedDrop for Stdin { fn drop(self: Pin<&mut Self>) { if !thread::panicking() { let _ = termios::tcsetattr(STDIN_FILENO, SetArg::TCSAFLUSH, &self.old_termios); } } } #[cfg(test)] mod tests { use std::io::Cursor; use futures::TryStreamExt; use tokio_util::codec::FramedRead; use super::{Key, KeyCodec}; #[tokio::test] async fn decode_char() { let keys: Vec<Key> = FramedRead::new(Cursor::new(b"a"), KeyCodec) .try_collect() .await .unwrap(); assert_eq!(keys, vec![Key::Char('a')]); } #[tokio::test] async fn decode_ctrl() { let keys: Vec<Key> = FramedRead::new(Cursor::new(b"\x01"), KeyCodec) .try_collect() .await .unwrap(); assert_eq!(keys, vec![Key::Ctrl('a')]); } #[tokio::test] async fn decode_escape() { let keys: Vec<Key> = FramedRead::new(Cursor::new(b"\x1b"), KeyCodec) .try_collect() .await .unwrap(); assert_eq!(keys, vec![Key::Esc]); } #[tokio::test] async fn decode_escape_seq() { let keys: Vec<Key> = FramedRead::new(Cursor::new(b"\x1b[A"), KeyCodec) .try_collect() .await .unwrap(); assert_eq!(keys, vec![Key::ArrowUp]); } #[tokio::test] async fn decode_multi_char() { let keys: Vec<Key> = FramedRead::new(Cursor::new(b"TeSt"), KeyCodec) .try_collect() .await .unwrap(); assert_eq!( keys, vec![ Key::Char('T'), Key::Char('e'), Key::Char('S'), Key::Char('t') ] ); } #[tokio::test] async fn decode_multi_escape_seq() { let keys: Vec<Key> = FramedRead::new(Cursor::new(b"\x1b[B\x1b[A"), KeyCodec) .try_collect() .await .unwrap(); assert_eq!(keys, vec![Key::ArrowDown, Key::ArrowUp]); } #[tokio::test] async fn decode_escape_then_char() { // This case is actually pretty hard to reproduce, but it is possible. let keys: Vec<Key> = FramedRead::new(Cursor::new(b"\x1b[Bf"), KeyCodec) .try_collect() .await .unwrap(); assert_eq!(keys, vec![Key::ArrowDown, Key::Char('f')]) } #[tokio::test] async fn unknown_escape_sequence() { let keys: Vec<Key> = FramedRead::new(Cursor::new(b"\x1b[1337"), KeyCodec) .try_collect() .await .unwrap(); assert_eq!(keys, vec![]); } }
//! Holds a stream that ensures chunks have the same (uniform) schema use std::{collections::HashMap, sync::Arc}; use snafu::Snafu; use std::task::{Context, Poll}; use arrow::{ array::new_null_array, datatypes::{DataType, SchemaRef}, record_batch::RecordBatch, }; use datafusion::physical_plan::{ metrics::BaselineMetrics, RecordBatchStream, SendableRecordBatchStream, }; use datafusion::{error::DataFusionError, scalar::ScalarValue}; use futures::Stream; /// Schema creation / validation errors. #[allow(clippy::enum_variant_names)] #[derive(Debug, Snafu)] pub enum Error { #[snafu(display( "Internal error creating SchemaAdapterStream: field '{}' does not appear in the output schema, known fields are: {:?}", field_name, known_fields, ))] InternalLostInputField { field_name: String, known_fields: Vec<String>, }, #[snafu(display("Internal error creating SchemaAdapterStream: input field '{}' had type '{:?}' which is different than output field '{}' which had type '{:?}'", input_field_name, input_field_type, output_field_name, output_field_type,))] InternalDataTypeMismatch { input_field_name: String, input_field_type: DataType, output_field_name: String, output_field_type: DataType, }, #[snafu(display("Internal error creating SchemaAdapterStream: creating virtual value of type '{:?}' which is different than output field '{}' which had type '{:?}'", field_type, output_field_name, output_field_type,))] InternalDataTypeMismatchForVirtual { field_type: DataType, output_field_name: String, output_field_type: DataType, }, #[snafu(display("Internal error creating SchemaAdapterStream: the field '{}' is specified within the input and as a virtual column, don't know which one to choose", field_name))] InternalColumnBothInInputAndVirtual { field_name: String }, #[snafu(display("Internal error creating SchemaAdapterStream: field '{}' had output type '{:?}' and should be a NULL column but the field is flagged as 'not null'", field_name, output_field_type,))] InternalColumnNotNullable { field_name: String, output_field_type: DataType, }, } pub type Result<T, E = Error> = std::result::Result<T, E>; /// This stream wraps another underlying stream to ensure it produces /// the specified schema. If the underlying stream produces a subset /// of the columns specified in desired schema, this stream creates /// arrays with NULLs to pad out the missing columns or creates "virtual" columns which contain a fixed given value. /// /// For example: /// /// If a table had schema with Cols A, B, C, and D, but the chunk (input) /// stream only produced record batches with columns A and C. For D we provided a virtual value of "foo". This /// stream would append a column of B / nulls to each record batch /// that flowed through it and create a constant column D. /// /// ```text /// /// ┌────────────────┐ ┌───────────────────────────────┐ /// │ ┌─────┐┌─────┐ │ │ ┌─────┐┌──────┐┌─────┐┌─────┐ │ /// │ │ A ││ C │ │ │ │ A ││ B ││ C ││ D │ │ /// │ │ - ││ - │ │ │ │ - ││ - ││ - ││ - │ │ /// ┌──────────────┐ │ │ 1 ││ 10 │ │ ┌──────────────┐ │ │ 1 ││ NULL ││ 10 ││ foo │ │ /// │ Input │ │ │ 2 ││ 20 │ │ │ Adapter │ │ │ 2 ││ NULL ││ 20 ││ foo │ │ /// │ Stream ├────▶ │ │ 3 ││ 30 │ │────▶│ Stream ├───▶│ │ 3 ││ NULL ││ 30 ││ foo │ │ /// └──────────────┘ │ │ 4 ││ 40 │ │ └──────────────┘ │ │ 4 ││ NULL ││ 40 ││ foo │ │ /// │ └─────┘└─────┘ │ │ └─────┘└──────┘└─────┘└─────┘ │ /// │ │ │ │ /// │ Record Batch │ │ Record Batch │ /// └────────────────┘ └───────────────────────────────┘ /// ``` pub(crate) struct SchemaAdapterStream { input: SendableRecordBatchStream, /// Output schema of this stream /// The schema of `input` is always a subset of output_schema output_schema: SchemaRef, mappings: Vec<ColumnMapping>, /// metrics to record execution baseline_metrics: BaselineMetrics, } impl std::fmt::Debug for SchemaAdapterStream { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SchemaAdapterStream") .field("input", &"(OPAQUE STREAM)") .field("output_schema", &self.output_schema) .field("mappings", &self.mappings) .finish() } } impl SchemaAdapterStream { /// Try to create a new adapter stream that produces batches with /// the specified output schema. /// /// Virtual columns that contain constant values may be added via `virtual_columns`. Note that these columns MUST /// NOT appear in underlying stream, other wise this method will fail. /// /// Columns that appear neither within the underlying stream nor a specified as virtual are created as pure NULL /// columns. Note that the column must be nullable for this to work. /// /// If the underlying stream produces columns that DO NOT appear /// in the output schema, or are different types than the output /// schema, an error will be produced. pub(crate) fn try_new( input: SendableRecordBatchStream, output_schema: SchemaRef, virtual_columns: &HashMap<&str, ScalarValue>, baseline_metrics: BaselineMetrics, ) -> Result<Self> { // record this setup time let timer = baseline_metrics.elapsed_compute().timer(); let input_schema = input.schema(); // Figure out how to compute each column in the output let mappings = output_schema .fields() .iter() .map(|output_field| { let input_field_index = input_schema .fields() .iter() .enumerate() .find(|(_, input_field)| output_field.name() == input_field.name()) .map(|(idx, _)| idx); if let Some(input_field_index) = input_field_index { ColumnMapping::FromInput(input_field_index) } else if let Some(value) = virtual_columns.get(output_field.name().as_str()) { ColumnMapping::Virtual(value.clone()) } else { ColumnMapping::MakeNull(output_field.data_type().clone()) } }) .collect::<Vec<_>>(); // sanity logic checks for input_field in input_schema.fields().iter() { // that there are no fields in the input schema that are // not present in the desired output schema (otherwise we // are dropping fields -- theys should have been selected // out with projection push down) if !output_schema .fields() .iter() .any(|output_field| input_field.name() == output_field.name()) { return InternalLostInputFieldSnafu { field_name: input_field.name(), known_fields: output_schema .fields() .iter() .map(|f| f.name().clone()) .collect::<Vec<String>>(), } .fail(); } } // Verify the mappings match the output type for (output_index, mapping) in mappings.iter().enumerate() { let output_field = output_schema.field(output_index); match mapping { ColumnMapping::FromInput(input_index) => { let input_field = input_schema.field(*input_index); if input_field.data_type() != output_field.data_type() { return InternalDataTypeMismatchSnafu { input_field_name: input_field.name(), input_field_type: input_field.data_type().clone(), output_field_name: output_field.name(), output_field_type: output_field.data_type().clone(), } .fail(); } if virtual_columns.contains_key(input_field.name().as_str()) { return InternalColumnBothInInputAndVirtualSnafu { field_name: input_field.name().clone(), } .fail(); } } ColumnMapping::MakeNull(_) => { if !output_field.is_nullable() { return InternalColumnNotNullableSnafu { field_name: output_field.name().clone(), output_field_type: output_field.data_type().clone(), } .fail(); } } ColumnMapping::Virtual(value) => { let data_type = value.get_datatype(); if &data_type != output_field.data_type() { return InternalDataTypeMismatchForVirtualSnafu { field_type: data_type, output_field_name: output_field.name(), output_field_type: output_field.data_type().clone(), } .fail(); } } } } timer.done(); Ok(Self { input, output_schema, mappings, baseline_metrics, }) } /// Extends the record batch, if needed, so that it matches the schema fn extend_batch(&self, batch: RecordBatch) -> Result<RecordBatch, DataFusionError> { let output_columns = self .mappings .iter() .map(|mapping| match mapping { ColumnMapping::FromInput(input_index) => Arc::clone(batch.column(*input_index)), ColumnMapping::MakeNull(data_type) => new_null_array(data_type, batch.num_rows()), ColumnMapping::Virtual(value) => value.to_array_of_size(batch.num_rows()), }) .collect::<Vec<_>>(); Ok(RecordBatch::try_new( Arc::clone(&self.output_schema), output_columns, )?) } } impl RecordBatchStream for SchemaAdapterStream { fn schema(&self) -> SchemaRef { Arc::clone(&self.output_schema) } } impl Stream for SchemaAdapterStream { type Item = Result<RecordBatch, DataFusionError>; fn poll_next( mut self: std::pin::Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll<Option<Self::Item>> { // the Poll result is an Opton<Result<Batch>> so we need a few // layers of maps to get at the actual batch, if any let poll = self.input.as_mut().poll_next(ctx).map(|maybe_result| { maybe_result.map(|batch| batch.and_then(|batch| self.extend_batch(batch))) }); self.baseline_metrics.record_poll(poll) } // TODO is there a useful size_hint to pass? } /// Describes how to create column in the output. #[derive(Debug)] enum ColumnMapping { /// Output column is found at `<index>` column of the input schema FromInput(usize), /// Output colum should be synthesized with nulls of the specified type MakeNull(DataType), /// Create virtual chunk column Virtual(ScalarValue), } #[cfg(test)] mod tests { use std::sync::Arc; use super::*; use arrow::{ array::{ArrayRef, Int32Array, StringArray}, datatypes::{Field, Schema}, record_batch::RecordBatch, }; use arrow_util::assert_batches_eq; use datafusion::physical_plan::{common::collect, metrics::ExecutionPlanMetricsSet}; use datafusion_util::stream_from_batch; use test_helpers::assert_contains; #[tokio::test] async fn same_input_and_output() { let batch = make_batch(); let output_schema = batch.schema(); let input_stream = stream_from_batch(batch.schema(), batch); let adapter_stream = SchemaAdapterStream::try_new( input_stream, output_schema, &Default::default(), baseline_metrics(), ) .unwrap(); let output = collect(Box::pin(adapter_stream)) .await .expect("Running plan"); let expected = vec![ "+---+---+-----+", "| a | b | c |", "+---+---+-----+", "| 1 | 4 | foo |", "| 2 | 5 | bar |", "| 3 | 6 | baz |", "+---+---+-----+", ]; assert_batches_eq!(&expected, &output); } #[tokio::test] async fn input_different_order_than_output() { let batch = make_batch(); // input has columns in different order than desired output let output_schema = Arc::new(Schema::new(vec![ Field::new("b", DataType::Int32, false), Field::new("c", DataType::Utf8, false), Field::new("a", DataType::Int32, false), ])); let input_stream = stream_from_batch(batch.schema(), batch); let adapter_stream = SchemaAdapterStream::try_new( input_stream, output_schema, &Default::default(), baseline_metrics(), ) .unwrap(); let output = collect(Box::pin(adapter_stream)) .await .expect("Running plan"); let expected = vec![ "+---+-----+---+", "| b | c | a |", "+---+-----+---+", "| 4 | foo | 1 |", "| 5 | bar | 2 |", "| 6 | baz | 3 |", "+---+-----+---+", ]; assert_batches_eq!(&expected, &output); } #[tokio::test] async fn input_subset_of_output() { let batch = make_batch(); // input has subset of columns of the desired otuput. d and e are not present let output_schema = Arc::new(Schema::new(vec![ Field::new("c", DataType::Utf8, false), Field::new("e", DataType::Float64, true), Field::new("b", DataType::Int32, false), Field::new("d", DataType::Float32, true), Field::new("f", DataType::Utf8, true), Field::new("g", DataType::Int32, false), Field::new("h", DataType::Int32, false), Field::new("a", DataType::Int32, false), ])); let input_stream = stream_from_batch(batch.schema(), batch); let adapter_stream = SchemaAdapterStream::try_new( input_stream, output_schema, &HashMap::from([ ("f", ScalarValue::from("xxx")), ("g", ScalarValue::from(1i32)), ("h", ScalarValue::from(1i32)), ]), baseline_metrics(), ) .unwrap(); let output = collect(Box::pin(adapter_stream)) .await .expect("Running plan"); let expected = vec![ "+-----+---+---+---+-----+---+---+---+", "| c | e | b | d | f | g | h | a |", "+-----+---+---+---+-----+---+---+---+", "| foo | | 4 | | xxx | 1 | 1 | 1 |", "| bar | | 5 | | xxx | 1 | 1 | 2 |", "| baz | | 6 | | xxx | 1 | 1 | 3 |", "+-----+---+---+---+-----+---+---+---+", ]; assert_batches_eq!(&expected, &output); } #[tokio::test] async fn input_superset_of_columns() { let batch = make_batch(); // No such column "b" in output -- column would be lost let output_schema = Arc::new(Schema::new(vec![ Field::new("c", DataType::Utf8, false), Field::new("a", DataType::Int32, false), ])); let input_stream = stream_from_batch(batch.schema(), batch); let res = SchemaAdapterStream::try_new( input_stream, output_schema, &Default::default(), baseline_metrics(), ); assert_contains!( res.unwrap_err().to_string(), "field 'b' does not appear in the output schema" ); } #[tokio::test] async fn input_has_different_type() { let batch = make_batch(); // column c has string type in input, output asks float32 let output_schema = Arc::new(Schema::new(vec![ Field::new("c", DataType::Float32, false), Field::new("b", DataType::Int32, false), Field::new("a", DataType::Int32, false), ])); let input_stream = stream_from_batch(batch.schema(), batch); let res = SchemaAdapterStream::try_new( input_stream, output_schema, &Default::default(), baseline_metrics(), ); assert_contains!(res.unwrap_err().to_string(), "input field 'c' had type 'Utf8' which is different than output field 'c' which had type 'Float32'"); } #[tokio::test] async fn virtual_col_has_wrong_type() { let batch = make_batch(); let output_schema = Arc::new(Schema::new(vec![ Field::new("c", DataType::Utf8, false), Field::new("b", DataType::Int32, false), Field::new("d", DataType::UInt8, false), Field::new("a", DataType::Int32, false), ])); let input_stream = stream_from_batch(batch.schema(), batch); let res = SchemaAdapterStream::try_new( input_stream, output_schema, &HashMap::from([("d", ScalarValue::from(1u32))]), baseline_metrics(), ); assert_contains!(res.unwrap_err().to_string(), "creating virtual value of type 'UInt32' which is different than output field 'd' which had type 'UInt8'"); } #[tokio::test] async fn virtual_col_also_in_input() { let batch = make_batch(); let output_schema = Arc::new(Schema::new(vec![ Field::new("c", DataType::Utf8, false), Field::new("b", DataType::Int32, false), Field::new("d", DataType::Utf8, false), Field::new("a", DataType::Int32, false), ])); let input_stream = stream_from_batch(batch.schema(), batch); let res = SchemaAdapterStream::try_new( input_stream, output_schema, &HashMap::from([ ("a", ScalarValue::from(1i32)), ("d", ScalarValue::from("foo")), ]), baseline_metrics(), ); assert_contains!(res.unwrap_err().to_string(), "the field 'a' is specified within the input and as a virtual column, don't know which one to choose"); } #[tokio::test] async fn null_non_nullable_column() { let batch = make_batch(); let output_schema = Arc::new(Schema::new(vec![ Field::new("c", DataType::Utf8, false), Field::new("b", DataType::Int32, false), Field::new("a", DataType::Int32, false), Field::new("d", DataType::Utf8, false), ])); let input_stream = stream_from_batch(batch.schema(), batch); let res = SchemaAdapterStream::try_new( input_stream, output_schema, &Default::default(), baseline_metrics(), ); assert_contains!(res.unwrap_err().to_string(), "field 'd' had output type 'Utf8' and should be a NULL column but the field is flagged as 'not null'"); } // input has different column types than desired output fn make_batch() -> RecordBatch { let col_a = Arc::new(Int32Array::from(vec![1, 2, 3])); let col_b = Arc::new(Int32Array::from(vec![4, 5, 6])); let col_c = Arc::new(StringArray::from(vec!["foo", "bar", "baz"])); RecordBatch::try_from_iter(vec![("a", col_a as ArrayRef), ("b", col_b), ("c", col_c)]) .unwrap() } /// Create a BaselineMetrics object for testing fn baseline_metrics() -> BaselineMetrics { BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0) } }
use crate::enums::{Algorithm, CentersInit, Checks, LogLevel}; use crate::raw; use std::os::raw::c_long; const DEFAULT_REBUILD_THRESHOLD: f32 = 2.0; #[derive(Debug, Clone)] pub struct Parameters { pub algorithm: Algorithm, pub checks: Checks, pub eps: f32, pub sorted: i32, pub max_neighbors: i32, pub cores: i32, pub trees: i32, pub leaf_max_size: i32, pub branching: i32, pub iterations: i32, pub centers_init: CentersInit, pub cb_index: f32, pub target_precision: f32, pub build_weight: f32, pub memory_weight: f32, pub sample_fraction: f32, pub table_number: u32, pub key_size: u32, pub multi_probe_level: u32, pub log_level: LogLevel, pub random_seed: c_long, pub rebuild_threshold: f32, } impl Default for Parameters { fn default() -> Parameters { Parameters::from_raw(unsafe { raw::DEFAULT_FLANN_PARAMETERS }) .expect("Illegal default FLANN parameters in C bindings") } } impl Parameters { pub fn from_raw(v: raw::FLANNParameters) -> Result<Parameters, String> { Ok(Parameters { algorithm: Algorithm::from_raw(v.algorithm) .ok_or_else(|| format!("Illegal algorithm enum value: {}", v.algorithm))?, checks: Checks::from_raw(v.checks), eps: v.eps, sorted: v.sorted, max_neighbors: v.max_neighbors, cores: v.cores, trees: v.trees, leaf_max_size: v.leaf_max_size, branching: v.branching, iterations: v.iterations, centers_init: CentersInit::from_raw(v.centers_init) .ok_or_else(|| format!("Illegal centers init enum value: {}", v.centers_init))?, cb_index: v.cb_index, target_precision: v.target_precision, build_weight: v.build_weight, memory_weight: v.memory_weight, sample_fraction: v.sample_fraction, table_number: v.table_number_, key_size: v.key_size_, multi_probe_level: v.multi_probe_level_, log_level: LogLevel::from_raw(v.log_level) .ok_or_else(|| format!("Illegal log level enum value: {}", v.log_level))?, random_seed: v.random_seed, rebuild_threshold: DEFAULT_REBUILD_THRESHOLD, }) } } impl<'a> Into<raw::FLANNParameters> for &'a Parameters { fn into(self) -> raw::FLANNParameters { raw::FLANNParameters { algorithm: self.algorithm.as_raw(), checks: self.checks.as_raw(), eps: self.eps, sorted: self.sorted, max_neighbors: self.max_neighbors, cores: self.cores, trees: self.trees, leaf_max_size: self.leaf_max_size, branching: self.branching, iterations: self.iterations, centers_init: self.centers_init.as_raw(), cb_index: self.cb_index, target_precision: self.target_precision, build_weight: self.build_weight, memory_weight: self.memory_weight, sample_fraction: self.sample_fraction, table_number_: self.table_number, key_size_: self.key_size, multi_probe_level_: self.multi_probe_level, log_level: self.log_level.as_raw(), random_seed: self.random_seed, } } } impl Into<raw::FLANNParameters> for Parameters { fn into(self) -> raw::FLANNParameters { (&self).into() } }
use super::vm::Inst; use std::collections::BTreeMap; #[derive(Debug, Clone)] pub struct Block { pub code: Vec<Inst::Code>, pub start: usize, pub kind: BrKind, pub generated: bool, } #[derive(Clone, Debug, PartialEq)] pub enum BrKind { ConditionalJmp { destinations: Vec<usize> }, UnconditionalJmp { destination: usize }, JmpRequired { destination: usize }, BlockStart, } impl BrKind { pub fn get_conditional_jump_destinations(&self) -> &Vec<usize> { match self { BrKind::ConditionalJmp { destinations } => destinations, _ => panic!(), } } pub fn get_unconditional_jump_destination(&self) -> usize { match self { BrKind::UnconditionalJmp { destination } => *destination, BrKind::JmpRequired { destination } => *destination, _ => panic!(), } } } impl Block { pub fn code_end_position(&self) -> usize { self.start + self.code.len() } } #[derive(Debug, Clone)] pub struct CFGMaker {} impl CFGMaker { pub fn new() -> Self { CFGMaker {} } } impl CFGMaker { pub fn make(&mut self, code: &Vec<Inst::Code>, start: usize, end: usize) -> Vec<Block> { let mut map = BTreeMap::new(); let mut pc = start; while pc < end { let cur_code = code[pc]; match cur_code { // TODO: Add instructions Inst::if_icmpne | Inst::if_icmpge | Inst::if_icmpgt | Inst::if_icmpeq | Inst::ifne | Inst::ifeq | Inst::ifle | Inst::ifge => { let branch = ((code[pc + 1] as i16) << 8) + code[pc + 2] as i16; let dst = (pc as isize + branch as isize) as usize; map.insert( pc + 3 - 1, BrKind::ConditionalJmp { destinations: vec![dst, pc + 3], }, ); map.insert(dst, BrKind::BlockStart); map.insert(pc + 3, BrKind::BlockStart); } Inst::goto => { let branch = ((code[pc + 1] as i16) << 8) + code[pc + 2] as i16; let dst = (pc as isize + branch as isize) as usize; map.insert(pc + 3 - 1, BrKind::UnconditionalJmp { destination: dst }); map.insert(dst, BrKind::BlockStart); } _ => {} } pc += Inst::get_inst_size(cur_code); } let mut start = Some(start); let mut blocks = vec![]; for (key, kind) in map { match kind { BrKind::BlockStart => { if start.is_some() && start.unwrap() < end && start.unwrap() < key { dprintln!("cfg: range: [{}, {}]", start.unwrap(), key - 1); blocks.push(Block { code: code[start.unwrap()..key].to_vec(), start: start.unwrap(), kind: BrKind::JmpRequired { destination: key }, generated: false, }); } start = Some(key); } BrKind::ConditionalJmp { .. } | BrKind::UnconditionalJmp { .. } if start.is_some() && start.unwrap() < end && start.unwrap() < key => { dprintln!( "cfg: range: {}[{}, {}]", match kind { BrKind::ConditionalJmp { ref destinations } => { format!("IF({:?}) ", destinations) } _ => "".to_string(), }, start.unwrap(), key ); blocks.push(Block { code: code[start.unwrap()..key + 1].to_vec(), start: start.unwrap(), kind, generated: false, }); start = None; } _ => {} } } if start.is_some() && start.unwrap() < end { dprintln!("cfg: range: [{}, {}]", start.unwrap(), end - 1); blocks.push(Block { code: code[start.unwrap()..end].to_vec(), start: start.unwrap(), kind: BrKind::BlockStart, generated: false, }); } blocks } }
#[doc = "Reader of register PLLFREQ0"] pub type R = crate::R<u32, super::PLLFREQ0>; #[doc = "Writer for register PLLFREQ0"] pub type W = crate::W<u32, super::PLLFREQ0>; #[doc = "Register PLLFREQ0 `reset()`'s with value 0"] impl crate::ResetValue for super::PLLFREQ0 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `MINT`"] pub type MINT_R = crate::R<u16, u16>; #[doc = "Write proxy for field `MINT`"] pub struct MINT_W<'a> { w: &'a mut W, } impl<'a> MINT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0x03ff) | ((value as u32) & 0x03ff); self.w } } #[doc = "Reader of field `MFRAC`"] pub type MFRAC_R = crate::R<u16, u16>; #[doc = "Write proxy for field `MFRAC`"] pub struct MFRAC_W<'a> { w: &'a mut W, } impl<'a> MFRAC_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03ff << 10)) | (((value as u32) & 0x03ff) << 10); self.w } } #[doc = "Reader of field `PLLPWR`"] pub type PLLPWR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLLPWR`"] pub struct PLLPWR_W<'a> { w: &'a mut W, } impl<'a> PLLPWR_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 << 23)) | (((value as u32) & 0x01) << 23); self.w } } impl R { #[doc = "Bits 0:9 - PLL M Integer Value"] #[inline(always)] pub fn mint(&self) -> MINT_R { MINT_R::new((self.bits & 0x03ff) as u16) } #[doc = "Bits 10:19 - PLL M Fractional Value"] #[inline(always)] pub fn mfrac(&self) -> MFRAC_R { MFRAC_R::new(((self.bits >> 10) & 0x03ff) as u16) } #[doc = "Bit 23 - PLL Power"] #[inline(always)] pub fn pllpwr(&self) -> PLLPWR_R { PLLPWR_R::new(((self.bits >> 23) & 0x01) != 0) } } impl W { #[doc = "Bits 0:9 - PLL M Integer Value"] #[inline(always)] pub fn mint(&mut self) -> MINT_W { MINT_W { w: self } } #[doc = "Bits 10:19 - PLL M Fractional Value"] #[inline(always)] pub fn mfrac(&mut self) -> MFRAC_W { MFRAC_W { w: self } } #[doc = "Bit 23 - PLL Power"] #[inline(always)] pub fn pllpwr(&mut self) -> PLLPWR_W { PLLPWR_W { w: self } } }
use futures::{future::BoxFuture, prelude::*, ready}; use log::*; use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, ops::DerefMut, pin::Pin, sync::{Arc, RwLock}, task::{Context, Poll}, }; use tokio::{ runtime::Builder, sync::{mpsc, oneshot}, task::JoinHandle, task_local, }; type Sender = mpsc::UnboundedSender<BoxFuture<'static, ()>>; type Receiver = mpsc::UnboundedReceiver<BoxFuture<'static, ()>>; type CactchResult<T> = std::result::Result<T, Box<dyn std::any::Any + 'static + Send>>; task_local! { pub static ID: u64; } /// Helper to return the current worker id pub fn current() -> u64 { ID.get() } lazy_static::lazy_static! { static ref GLOBAL_ROUTER: RwLock<Option<Router>> = RwLock::new(None); } #[derive(Clone)] pub struct Router { tx: Arc<Vec<Sender>>, } pub struct Via<T>(oneshot::Receiver<CactchResult<T>>); impl<T> Via<T> { fn new<F, R>(tx: &Sender, f: F) -> Self where T: Send + 'static, F: FnOnce() -> R, R: Future<Output = T> + Send + 'static, { let (otx, orx) = oneshot::channel(); let fut = std::panic::AssertUnwindSafe(f()) .catch_unwind() .then(move |r| async move { let _ = otx.send(r); }) .boxed(); if tx.send(fut).is_err() { panic!("Couldn't send future to router; the future will never be resolved"); } Self(orx) } } impl<T> Future for Via<T> { type Output = T; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { match ready!(self.0.poll_unpin(cx)) { Ok(output) => Poll::Ready(output.expect("panic in the future in the ert router")), Err(_) => panic!("the future in ert was cancelled"), } } } fn open(workers: usize) -> (Vec<Sender>, Vec<Receiver>) { (0..workers).map(|_| mpsc::unbounded_channel()).unzip() } fn run(rxs: Vec<Receiver>) -> Vec<JoinHandle<()>> { rxs.into_iter() .enumerate() .map(|(i, rx)| { tokio::spawn(rx.for_each(move |t| ID.scope(i as u64, async move { t.await }))) }) .collect() } impl Router { pub fn new(workers: usize) -> Self { if workers == 0 { panic!("Invalid number of workers: {}", workers); } let (txs, rxs) = open(workers); run(rxs); Self { tx: Arc::new(txs) } } pub fn run_on_thread(workers: usize) -> Self { let (txs, rxs) = open(workers); std::thread::spawn(move || { let mut rt = Builder::new() .threaded_scheduler() .enable_all() .build() .unwrap(); rt.block_on(async move { if let Err(e) = futures::future::try_join_all(run(rxs)).await { error!("Couldn't join router worker thread successfully: {}", e); } }); }); Self { tx: Arc::new(txs) } } pub fn set_as_global(self) { *GLOBAL_ROUTER.write().unwrap() = Some(self); } pub fn with_global<F, R>(f: F) -> R where F: FnOnce(Option<&Router>) -> R, { f(GLOBAL_ROUTER.read().unwrap().as_ref()) } pub fn with_global_mut<F, R>(f: F) -> R where F: FnOnce(&mut Option<Router>) -> R, { f(GLOBAL_ROUTER.write().unwrap().deref_mut()) } pub fn via<K, F, T, R>(&self, key: K, f: F) -> Via<T> where K: Hash, T: Send + 'static, F: FnOnce() -> R, R: Future<Output = T> + Send + 'static, { let h = { let mut hasher = DefaultHasher::new(); key.hash(&mut hasher); hasher.finish() as usize }; Via::new(&self.tx[h % self.tx.len()], f) } }
use super::state_prelude::*; #[derive(Default)] pub struct Startup; impl<'a, 'b> State<CustomGameData<'a, 'b, CustomData>, StateEvent> for Startup { fn on_start(&mut self, data: StateData<CustomGameData<CustomData>>) { insert_resources(data.world); initialize_music(data.world); initialize_savefile_data(data.world); } fn update( &mut self, data: StateData<CustomGameData<CustomData>>, ) -> Trans<CustomGameData<'a, 'b, CustomData>, StateEvent> { data.data.update(data.world, "startup").unwrap(); Trans::Push(Box::new(DifficultySelect::default())) } }
tonic::include_proto!("youlearn.headpose.v1");
use std::borrow::Cow; use rust_embed::RustEmbed; #[derive(RustEmbed)] #[folder = "assets"] struct AssetImpl; /// The RustEmbed wrapper for completion. pub struct Asset; impl Asset { pub fn get(file_path: &str) -> Option<Cow<'static, [u8]>> { AssetImpl::get(file_path) } pub fn iter() -> impl Iterator<Item = Cow<'static, str>> { AssetImpl::iter() } }
use std::collections::HashMap; use std::fmt::Debug; use std::marker::PhantomData; use cgmath::prelude::*; use cgmath::BaseFloat; use collision::dbvt::{DynamicBoundingVolumeTree, TreeValue}; use collision::prelude::*; use specs::prelude::{ BitSet, Component, ComponentEvent, Entities, Entity, Join, ReadStorage, ReaderId, World, System, Tracked, Write, WriteStorage, }; use core::{CollisionShape, NextFrame, Primitive}; /// Spatial sorting [system](https://docs.rs/specs/0.9.5/specs/trait.System.html) for use with /// [`specs`](https://docs.rs/specs/0.9.5/specs/). /// /// Will perform spatial sorting of the collision world. Uses a Dynamic Bounding Volume Tree for /// sorting. Will update entries in the tree where the pose is dirty. /// /// Can handle any transform component type, as long as the type implements /// [`Transform`](https://docs.rs/cgmath/0.15.0/cgmath/trait.Transform.html), and as long as the /// storage is wrapped in /// [`FlaggedStorage`](https://docs.rs/specs/0.9.5/specs/struct.FlaggedStorage.html) /// /// ## Type parameters: /// /// - `P`: Primitive type, needs to implement `Primitive`. /// - `T`: Transform type, needs to implement `Transform` and have `FlaggedStorage`. /// - `D`: Type of values stored in the DBVT, needs to implement `TreeValue` and /// `From<(Entity, CollisionShape)>` /// - `B`: Bounding volume /// - `Y`: Shape type, see `Collider` /// /// ### System Function: /// /// `fn(Entities, T, NextFrame<T>, CollisionShape) -> (CollisionShape, DynamicBoundingVolumeTree<D>)` #[derive(Debug)] pub struct SpatialSortingSystem<P, T, D, B, Y = ()> { entities: HashMap<Entity, usize>, dead: Vec<Entity>, updated: BitSet, removed: BitSet, pose_reader: Option<ReaderId<ComponentEvent>>, next_pose_reader: Option<ReaderId<ComponentEvent>>, marker: PhantomData<(P, T, Y, B, D)>, } impl<P, T, D, B, Y> SpatialSortingSystem<P, T, D, B, Y> { /// Create a new sorting system. pub fn new() -> Self { SpatialSortingSystem { entities: HashMap::default(), marker: PhantomData, updated: BitSet::default(), removed: BitSet::default(), pose_reader: None, next_pose_reader: None, dead: Vec::default(), } } } impl<'a, P, T, Y, D, B> System<'a> for SpatialSortingSystem<P, T, D, B, Y> where P: Primitive + ComputeBound<B> + Send + Sync + 'static, B: Clone + Debug + Send + Sync + Union<B, Output = B> + Bound<Point = P::Point> + Contains<B> + SurfaceArea<Scalar = <P::Point as EuclideanSpace>::Scalar> + Send + Sync + 'static, P::Point: Debug, <P::Point as EuclideanSpace>::Scalar: BaseFloat + Send + Sync + 'static, <P::Point as EuclideanSpace>::Diff: Debug + Send + Sync, T: Component + Clone + Debug + Transform<P::Point> + Send + Sync, T::Storage: Tracked, Y: Default + Send + Sync + 'static, D: Send + Sync + 'static + TreeValue<Bound = B> + From<(Entity, B)>, { type SystemData = ( Entities<'a>, ReadStorage<'a, T>, ReadStorage<'a, NextFrame<T>>, WriteStorage<'a, CollisionShape<P, T, B, Y>>, Write<'a, DynamicBoundingVolumeTree<D>>, ); fn run(&mut self, (entities, poses, next_poses, mut shapes, mut tree): Self::SystemData) { self.updated.clear(); self.removed.clear(); for event in poses.channel().read(self.pose_reader.as_mut().unwrap()) { match event { ComponentEvent::Inserted(index) => { self.updated.add(*index); } ComponentEvent::Modified(index) => { self.updated.add(*index); } ComponentEvent::Removed(index) => { self.updated.remove(*index); self.removed.add(*index); } } } // remove entities that are missing from the tree self.dead.clear(); for (entity, node_index) in &self.entities { if self.removed.contains(entity.id()) { tree.remove(*node_index); self.dead.push(*entity); } } for entity in &self.dead { self.entities.remove(entity); } // Check for updated poses // Uses FlaggedStorage for (entity, pose, shape, _) in (&*entities, &poses, &mut shapes, &self.updated).join() { shape.update(pose, None); // Update the wrapper in the tree for the shape match self.entities.get(&entity).cloned() { // Update existing Some(node_index) => { tree.update_node(node_index, (entity, shape.bound().clone()).into()); } // Insert new None => { let node_index = tree.insert((entity, shape.bound().clone()).into()); self.entities.insert(entity, node_index); } } } self.updated.clear(); for event in next_poses .channel() .read(self.next_pose_reader.as_mut().unwrap()) { match event { ComponentEvent::Inserted(index) => { self.updated.add(*index); } ComponentEvent::Modified(index) => { self.updated.add(*index); } ComponentEvent::Removed(index) => { self.updated.remove(*index); } } } // Check for updated next frame poses // Uses FlaggedStorage for (entity, pose, next_pose, shape, _) in (&*entities, &poses, &next_poses, &mut shapes, &self.updated).join() { shape.update(pose, Some(&next_pose.value)); // Update the wrapper in the tree for the shape if let Some(node_index) = self.entities.get(&entity).cloned() { tree.update_node(node_index, (entity, shape.bound().clone()).into()); } } // process possibly updated values tree.update(); // do refitting tree.do_refit(); } fn setup(&mut self, res: &mut World) { use specs::prelude::SystemData; Self::SystemData::setup(res); let mut poses = WriteStorage::<T>::fetch(res); self.pose_reader = Some(poses.register_reader()); let mut next_poses = WriteStorage::<NextFrame<T>>::fetch(res); self.next_pose_reader = Some(next_poses.register_reader()); } }
use super::*; /// All COM interfaces (and thus WinRT classes and interfaces) implement /// [IUnknown](https://docs.microsoft.com/en-us/windows/win32/api/unknwn/nn-unknwn-iunknown) /// under the hood to provide reference-counted lifetime management as well as the ability /// to query for additional interfaces that the object may implement. #[repr(transparent)] pub struct IUnknown(core::ptr::NonNull<core::ffi::c_void>); #[doc(hidden)] #[repr(C)] pub struct IUnknown_abi(pub unsafe extern "system" fn(this: RawPtr, iid: *const GUID, interface: *mut RawPtr) -> HRESULT, pub unsafe extern "system" fn(this: RawPtr) -> u32, pub unsafe extern "system" fn(this: RawPtr) -> u32); unsafe impl Interface for IUnknown { type Vtable = IUnknown_abi; const IID: GUID = GUID::from_u128(0x00000000_0000_0000_c000_000000000046); } impl Clone for IUnknown { fn clone(&self) -> Self { unsafe { (self.vtable().1)(core::mem::transmute_copy(self)); // AddRef } Self(self.0) } } impl Drop for IUnknown { fn drop(&mut self) { unsafe { (self.vtable().2)(core::mem::transmute_copy(self)); // Release } } } impl PartialEq for IUnknown { fn eq(&self, other: &Self) -> bool { // Since COM objects may implement multiple interfaces, COM identity can only // be determined by querying for `IUnknown` explicitly and then comparing the // pointer values. This works since `QueryInterface` is required to return // the same pointer value for queries for `IUnknown`. self.cast::<IUnknown>().unwrap().0 == other.cast::<IUnknown>().unwrap().0 } } impl Eq for IUnknown {} impl core::fmt::Debug for IUnknown { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{:?}", self.0) } }
use num::Num; use std::ops::{BitAnd, BitOr, Not}; pub trait FlagSet<T>: std::default::Default where T: Clone + Num + BitAnd<Output = T> + BitOr<Output = T> + Not<Output = T>, { fn value(&self) -> T; fn new() -> Self { Self::default() } fn from(v: T) -> Self { let mut f = Self::default(); f.set(v); f } fn set(&mut self, v: T); fn enable(&mut self, f: T) { self.set(self.value() | f); } fn disable(&mut self, f: T) { self.set(self.value() & !f); } fn toggle(&mut self, f: T) { let v = if self.value() & f.clone() != T::zero() { self.value() & !f } else { self.value() | f }; self.set(v); } fn is_enabled(&self, f: T) -> bool { self.value() & f != T::zero() } } #[cfg(test)] mod tests { use super::*; #[derive(Debug, Default)] pub struct Flags { value: u8, } impl FlagSet<u8> for Flags { fn value(&self) -> u8 { self.value } fn set(&mut self, v: u8) { self.value = v } } const FLAG_ONE: u8 = 0b00000001; #[test] fn can_enable_a_flag() { let mut f = Flags::new(); assert!(!f.is_enabled(FLAG_ONE)); f.enable(FLAG_ONE); assert!(f.is_enabled(FLAG_ONE)); } #[test] fn can_disable_a_flag() { let mut f: Flags = FlagSet::from(1); assert!(f.is_enabled(FLAG_ONE)); f.disable(FLAG_ONE); assert!(!f.is_enabled(FLAG_ONE)); } #[test] fn can_toggle_a_flag() { let mut f = Flags::new(); assert!(!f.is_enabled(FLAG_ONE)); f.toggle(FLAG_ONE); assert!(f.is_enabled(FLAG_ONE)); f.toggle(FLAG_ONE); assert!(!f.is_enabled(FLAG_ONE)); } }
use std::convert::TryFrom; use blake2b_simd::{Params as Blake2bParams, State as Blake2b}; use blake2s_simd::{Params as Blake2sParams, State as Blake2s}; use digest::Digest; use crate::digests::{wrap, Multihash, MultihashDigest, Multihasher}; use crate::errors::DecodeError; #[doc(hidden)] #[macro_export(local_inner_macros)] macro_rules! impl_code { ($( #[$doc:meta] $name:ident => $code:expr, )*) => { /// The code of Multihash. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Code { $( #[$doc] $name, )* } impl Code { /// Hash some input and return the raw binary digest. pub fn digest(&self, data: &[u8]) -> Multihash { match self { $(Self::$name => $name::digest(data),)* } } } impl From<Code> for Box<dyn MultihashDigest<Code>> { fn from(code: Code) -> Self { match code { $(Code::$name => Box::new($name::default()),)* } } } impl From<Code> for u64 { /// Return the code as integer value. fn from(code: Code) -> Self { match code { $(Code::$name => $code,)* } } } impl TryFrom<u64> for Code { type Error = DecodeError; /// Return the `Code` based on the integer value. Error if no matching code exists. fn try_from(raw: u64) -> Result<Self, Self::Error> { match raw { $($code => Ok(Self::$name),)* _ => Err(DecodeError::UnknownCode), } } } }; } #[doc(hidden)] #[macro_export(local_inner_macros)] macro_rules! derive_digest { ($( #[$doc:meta] @sha $type:ty as $name:ident; @code_doc $code_doc:literal, )*) => { $( #[$doc] #[derive(Clone, Debug, Default)] pub struct $name($type); impl $name { #[doc = $code_doc] pub const CODE: Code = Code::$name; /// Hash some input and return the Multihash digest. #[inline] pub fn digest(data: &[u8]) -> Multihash { let digest = <$type>::digest(&data); wrap(Self::CODE, &digest) } } impl Multihasher<Code> for $name { const CODE: Code = Code::$name; #[inline] fn digest(data: &[u8]) -> Multihash { Self::digest(data) } } impl MultihashDigest<Code> for $name { #[inline] fn code(&self) -> Code { Self::CODE } #[inline] fn digest(&self, data: &[u8]) -> Multihash { Self::digest(data) } #[inline] fn input(&mut self, data: &[u8]) { self.0.input(data) } #[inline] fn result(self) -> Multihash { wrap(Self::CODE, self.0.result().as_slice()) } #[inline] fn result_reset(&mut self) -> Multihash { wrap(Self::CODE, self.0.result_reset().as_slice()) } #[inline] fn reset(&mut self) { self.0.reset() } } impl ::std::io::Write for $name { #[inline] fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> { <$name as MultihashDigest<Code>>::input(self, buf); Ok(buf.len()) } #[inline] fn flush(&mut self) -> ::std::io::Result<()> { Ok(()) } } )* }; ($( #[$doc:meta] @blake $type:ty | $params:ty as $name:ident $len:expr; @code_doc $code_doc:literal, )*) => { $( #[$doc] #[derive(Clone, Debug)] pub struct $name($type); impl $name { #[doc = $code_doc] pub const CODE: Code = Code::$name; /// Hash some input and return the Multihash digest. pub fn digest(data: &[u8]) -> Multihash { let digest = <$params>::new().hash_length($len).hash(data); wrap(Self::CODE, &digest.as_bytes()) } } impl Default for $name { fn default() -> Self { $name(<$params>::new().hash_length($len).to_state()) } } impl Multihasher<Code> for $name { const CODE: Code = Code::$name; #[inline] fn digest(data: &[u8]) -> Multihash { Self::digest(data) } } impl MultihashDigest<Code> for $name { #[inline] fn code(&self) -> Code { Self::CODE } #[inline] fn digest(&self, data: &[u8]) -> Multihash { Self::digest(data) } #[inline] fn input(&mut self, data: &[u8]) { self.0.update(data); } #[inline] fn result(self) -> Multihash { let digest = self.0.finalize(); wrap(Self::CODE, digest.as_bytes()) } #[inline] fn result_reset(&mut self) -> Multihash { let digest = self.0.finalize(); let hash = wrap(Self::CODE, digest.as_bytes()); self.reset(); hash } #[inline] fn reset(&mut self) { self.0 = Self::default().0; } } impl ::std::io::Write for $name { #[inline] fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> { <$name as MultihashDigest<Code>>::input(self, buf); Ok(buf.len()) } #[inline] fn flush(&mut self) -> ::std::io::Result<()> { self.0.finalize(); Ok(()) } } )* }; } impl_code! { /// Identity (Raw binary) Identity => 0x00, /// SHA-1 (20-byte hash size) Sha1 => 0x11, /// SHA-256 (32-byte hash size) Sha2_256 => 0x12, /// SHA-512 (64-byte hash size) Sha2_512 => 0x13, /// SHA3-224 (28-byte hash size) Sha3_224 => 0x17, /// SHA3-256 (32-byte hash size) Sha3_256 => 0x16, /// SHA3-384 (48-byte hash size) Sha3_384 => 0x15, /// SHA3-512 (64-byte hash size) Sha3_512 => 0x14, /// Keccak-224 (28-byte hash size) Keccak224 => 0x1a, /// Keccak-256 (32-byte hash size) Keccak256 => 0x1b, /// Keccak-384 (48-byte hash size) Keccak384 => 0x1c, /// Keccak-512 (64-byte hash size) Keccak512 => 0x1d, /// BLAKE2b-256 (32-byte hash size) Blake2b256 => 0xb220, /// BLAKE2b-512 (64-byte hash size) Blake2b512 => 0xb240, /// BLAKE2s-128 (16-byte hash size) Blake2s128 => 0xb250, /// BLAKE2s-256 (32-byte hash size) Blake2s256 => 0xb260, } /// The Identity hasher. #[derive(Clone, Debug, Default)] pub struct Identity(Vec<u8>); impl Multihasher<Code> for Identity { const CODE: Code = Code::Identity; #[inline] fn digest(data: &[u8]) -> Multihash { Self::digest(data) } } impl MultihashDigest<Code> for Identity { #[inline] fn code(&self) -> Code { Self::CODE } #[inline] fn digest(&self, data: &[u8]) -> Multihash { Self::digest(data) } #[inline] fn input(&mut self, data: &[u8]) { if ((self.0.len() as u64) + (data.len() as u64)) >= u64::from(std::u32::MAX) { panic!("Input data for identity hash is too large, it needs to be less than 2^32.") } self.0.extend_from_slice(data) } #[inline] fn result(self) -> Multihash { wrap(Self::CODE, &self.0) } #[inline] fn result_reset(&mut self) -> Multihash { let hash = wrap(Self::CODE, &self.0); self.reset(); hash } #[inline] fn reset(&mut self) { self.0.clear() } } impl Identity { /// The code of the Identity hasher, 0x00. pub const CODE: Code = Code::Identity; /// Hash some input and return the raw binary digest. pub fn digest(data: &[u8]) -> Multihash { if (data.len() as u64) >= u64::from(std::u32::MAX) { panic!("Input data for identity hash is too large, it needs to be less than 2^32.") } wrap(Self::CODE, data) } } derive_digest! { /// The SHA-1 hasher. @sha ::sha1::Sha1 as Sha1; @code_doc "The code of the SHA-1 hasher, 0x11.", /// The SHA2-256 hasher. @sha ::sha2::Sha256 as Sha2_256; @code_doc "The code of the SHA2-256 hasher, 0x12.", /// The SHA2-512 hasher. @sha ::sha2::Sha512 as Sha2_512; @code_doc "The code of the SHA2-512 hasher, 0x13.", /// The SHA3-224 hasher. @sha ::sha3::Sha3_224 as Sha3_224; @code_doc "The code of the SHA3-224 hasher, 0x17.", /// The SHA3-256 hasher. @sha ::sha3::Sha3_256 as Sha3_256; @code_doc "The code of the SHA3-256 hasher, 0x16.", /// The SHA3-384 hasher. @sha ::sha3::Sha3_384 as Sha3_384; @code_doc "The code of the SHA3-384 hasher, 0x15.", /// The SHA3-512 hasher. @sha ::sha3::Sha3_512 as Sha3_512; @code_doc "The code of the SHA3-512 hasher, 0x14.", /// The Keccak-224 hasher. @sha ::sha3::Keccak224 as Keccak224; @code_doc "The code of the Keccak-224 hasher, 0x1a.", /// The Keccak-256 hasher. @sha ::sha3::Keccak256 as Keccak256; @code_doc "The code of the Keccak-256 hasher, 0x1b.", /// The Keccak-384 hasher. @sha ::sha3::Keccak384 as Keccak384; @code_doc "The code of the Keccak-384 hasher, 0x1c.", /// The Keccak-512 hasher. @sha ::sha3::Keccak512 as Keccak512; @code_doc "The code of the Keccak-512 hasher, 0x1d.", } derive_digest! { /// The Blake2b-256 hasher. @blake Blake2b | Blake2bParams as Blake2b256 32; @code_doc "The code of the Blake2-256 hasher, 0xb220.", /// The Blake2b-512 hasher. @blake Blake2b | Blake2bParams as Blake2b512 64; @code_doc "The code of the Blake2-512 hasher, 0xb240.", /// The Blake2s-128 hasher. @blake Blake2s | Blake2sParams as Blake2s128 16; @code_doc "The code of the Blake2-128 hasher, 0xb250.", /// The Blake2s-256 hasher. @blake Blake2s | Blake2sParams as Blake2s256 32; @code_doc "The code of the Blake2-256 hasher, 0xb260.", }
//! Types and operators to work with external data sources. use std::cell::RefCell; use std::rc::{Rc, Weak}; use std::time::{Duration, Instant}; use timely::dataflow::operators::capture::event::link::EventLink; use timely::dataflow::{ProbeHandle, Scope, Stream}; use timely::logging::TimelyEvent; use timely::progress::Timestamp; use differential_dataflow::lattice::Lattice; use differential_dataflow::logging::DifferentialEvent; use crate::scheduling::Scheduler; use crate::AttributeConfig; use crate::{AsAid, Value}; #[cfg(feature = "csv-source")] pub mod csv_file; // pub mod declarative_logging; pub mod differential_logging; // pub mod json_file; pub mod timely_logging; #[cfg(feature = "csv-source")] pub use self::csv_file::CsvFile; // pub use self::json_file::JsonFile; /// A struct encapsulating any state required to create sources. pub struct SourcingContext<T: Timestamp> { /// The logical start of the computation, used by sources to /// compute their relative progress. pub t0: Instant, /// A handle to the timely probe of the domain this source is created in. pub domain_probe: ProbeHandle<T>, /// A weak handle to a scheduler, used by sources to defer their /// next activation when polling. pub scheduler: Weak<RefCell<Scheduler<T>>>, /// A weak handle to a Timely event link. pub timely_events: Rc<EventLink<Duration, (Duration, usize, TimelyEvent)>>, /// A weak handle to Differential event link. pub differential_events: Rc<EventLink<Duration, (Duration, usize, DifferentialEvent)>>, } /// An external data source that can provide Datoms. pub trait Sourceable<A, S> where A: AsAid, S: Scope, S::Timestamp: Timestamp + Lattice, { /// Conjures from thin air (or from wherever the source lives) one /// or more timely streams feeding directly into attributes. fn source( &self, scope: &mut S, context: SourcingContext<S::Timestamp>, ) -> Vec<( A, AttributeConfig, Stream<S, ((Value, Value), S::Timestamp, isize)>, )>; } /// Supported external data sources. #[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)] pub enum Source<A: AsAid + From<&'static str>> { /// Timely logging streams TimelyLogging(timely_logging::TimelyLogging<A>), /// Differential logging streams DifferentialLogging(differential_logging::DifferentialLogging<A>), // /// Declarative logging streams // DeclarativeLogging(declarative_logging::DeclarativeLogging), /// CSV files #[cfg(feature = "csv-source")] CsvFile(CsvFile<A>), // /// Files containing json objects // JsonFile(JsonFile<A>), } #[cfg(feature = "real-time")] impl<A, S> Sourceable<A, S> for Source<A> where A: AsAid + From<&'static str>, S: Scope<Timestamp = Duration>, { fn source( &self, scope: &mut S, context: SourcingContext<S::Timestamp>, ) -> Vec<( A, AttributeConfig, Stream<S, ((Value, Value), Duration, isize)>, )> { match *self { Source::TimelyLogging(ref source) => source.source(scope, context), Source::DifferentialLogging(ref source) => source.source(scope, context), // Source::DeclarativeLogging(ref source) => source.source(scope, context), #[cfg(feature = "csv-source")] Source::CsvFile(ref source) => source.source(scope, context), _ => unimplemented!(), } } } #[cfg(not(feature = "real-time"))] impl<A, S> Sourceable<A, S> for Source<A> where A: AsAid + From<&'static str>, S: Scope, S::Timestamp: Timestamp + Lattice, { fn source( &self, _scope: &mut S, _context: SourcingContext<S::Timestamp>, ) -> Vec<( A, AttributeConfig, Stream<S, ((Value, Value), S::Timestamp, isize)>, )> { unimplemented!(); } }
//! The component module provides all the different components available. A //! Component allows querying different kinds of information from a Timer. This //! information is provided as state objects in a way that can easily be //! visualized by any kind of User Interface. pub mod blank_space; pub mod current_comparison; pub mod current_pace; pub mod delta; pub mod detailed_timer; pub mod graph; pub mod possible_time_save; pub mod previous_segment; pub mod separator; pub mod splits; pub mod sum_of_best; pub mod text; pub mod timer; pub mod title; pub mod total_playtime; use palette::rgb::Rgb; use palette::Alpha; use settings::{Color, Gradient}; use std::marker::PhantomData; const DEFAULT_INFO_TEXT_GRADIENT: Gradient = Gradient::Vertical( Color { rgba: Alpha { alpha: 0.06, color: Rgb { red: 1.0, green: 1.0, blue: 1.0, standard: PhantomData, }, }, }, Color { rgba: Alpha { alpha: 0.005, color: Rgb { red: 1.0, green: 1.0, blue: 1.0, standard: PhantomData, }, }, }, );
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::term::prelude::Term; use crate::erlang::is_record; #[native_implemented::function(erlang:is_record/3)] pub fn result(term: Term, record_tag: Term, size: Term) -> exception::Result<Term> { is_record(term, record_tag, Some(size)) }
use std::io; #[derive(Clone, PartialEq)] enum Seat { Floor, Empty, Occupied, } fn read_seats() -> (Vec<Seat>, i32, i32) { let mut seats = Vec::new(); let mut width = 0; let mut height = 0; loop { let mut line = String::new(); match io::stdin().read_line(&mut line) { Err(error) => panic!("error: {}", error), Ok(0) => break, Ok(_) => { width = line.trim().len() as i32; for c in line.trim().chars() { match c { 'L' => seats.push(Seat::Empty), '.' => seats.push(Seat::Floor), _ => panic!("got unexpected input `{}`", c), } } } } height += 1; } (seats, width, height) } fn count_occupied(seats: &Vec<Seat>) -> i32 { seats .into_iter() .map(|seat| match seat { Seat::Occupied => 1, _ => 0, }) .sum() } fn step_adj(seats: &Vec<Seat>, width: i32, height: i32) -> Vec<usize> { // return the indexes to change let mut changes = Vec::new(); let offsets = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ]; for (idx, seat) in seats.iter().enumerate() { let row = (idx as i32) / width; let col = (idx as i32) % width; let mut adj_occupied = 0; if *seat == Seat::Floor { continue; } for (row_offset, col_offset) in offsets.iter() { let new_row = row + row_offset; let new_col = col + col_offset; if new_row < 0 || new_col < 0 || new_row >= height || new_col >= width { continue; } if seats[(new_row * width + new_col) as usize] == Seat::Occupied { adj_occupied += 1; } } if *seat == Seat::Empty && adj_occupied == 0 { changes.push(idx); } else if *seat == Seat::Occupied && adj_occupied >= 4 { changes.push(idx); } } changes } fn step_visible(seats: &Vec<Seat>, width: i32, height: i32) -> Vec<usize> { // return the indexes to change let mut changes = Vec::new(); let offsets = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ]; for (idx, seat) in seats.iter().enumerate() { let row = (idx as i32) / width; let col = (idx as i32) % width; let mut adj_occupied = 0; if *seat == Seat::Floor { continue; } for (row_offset, col_offset) in offsets.iter() { let mut new_row = row + row_offset; let mut new_col = col + col_offset; // add offset until we reach a seat or go out of bounds while new_row >= 0 && new_col >= 0 && new_row < height && new_col < width && seats[(new_row * width + new_col) as usize] == Seat::Floor { new_row += row_offset; new_col += col_offset; } if new_row < 0 || new_col < 0 || new_row >= height || new_col >= width { continue; } if seats[(new_row * width + new_col) as usize] == Seat::Occupied { adj_occupied += 1; } } if *seat == Seat::Empty && adj_occupied == 0 { changes.push(idx); } else if *seat == Seat::Occupied && adj_occupied >= 5 { changes.push(idx); } } changes } pub fn day11(part_a: bool) { let (mut seats, width, height) = read_seats(); let step_fn = if part_a { step_adj } else { step_visible }; let mut n_rounds = 0; loop { n_rounds += 1; let new_seats = step_fn(&seats, width, height); if new_seats.len() == 0 { break; } for i in new_seats { match seats[i] { Seat::Floor => panic!("want to toggle floor"), Seat::Occupied => seats[i] = Seat::Empty, Seat::Empty => seats[i] = Seat::Occupied, } } println!("ran for {} rounds", n_rounds); println!("Number of occupied seats: {}", count_occupied(&seats)); } println!("ran for {} rounds", n_rounds); println!("Number of occupied seats: {}", count_occupied(&seats)); }
fn main() { for x in vec![1, 2, 3].into_iter().map(|y| y + 1) { println!("{}", x); } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #[cfg(test)] macro_rules! assert_match { ($actual:expr, $expected:pat) => { match $actual { $expected => {} _ => panic!( "assertion match failed (actual: `{:?}`, expected: `{}`)", $actual, stringify!($expected) ), } }; }
use std::fs::File; use std::io::{Error, Read, Write}; use std::path::Path; /* NOTE: Remove any bricks and also the fuse mountpoint from updatedb */ // Ported from host.py in charmhelpers.core.host pub fn add_to_prunepath(path: &String, updatedb_path: &Path) -> Result<(), Error> { let mut f = File::open(updatedb_path)?; let mut buff = String::new(); f.read_to_string(&mut buff)?; let output = updatedb(buff, path); // Truncate the file let mut f = File::create(updatedb_path)?; f.write_all(&output.as_bytes())?; Ok(()) } #[test] fn test_updatedb() { let expected_result = r#"PRUNE_BIND_MOUNTS="yes" # PRUNENAMES=".git .bzr .hg .svn" PRUNEPATHS="/tmp /var/spool /media /home/.ecryptfs /var/lib/schroot /mnt/xvdb" PRUNEFS="NFS nfs nfs4 rpc_pipefs afs binfmt_misc proc smbfs autofs" "#; let update_conf = r#"PRUNE_BIND_MOUNTS="yes" # PRUNENAMES=".git .bzr .hg .svn" PRUNEPATHS="/tmp /var/spool /media /home/.ecryptfs /var/lib/schroot" PRUNEFS="NFS nfs nfs4 rpc_pipefs afs binfmt_misc proc smbfs autofs" "#; let new_path = "/mnt/xvdb"; let result = updatedb(update_conf.to_string(), &new_path.to_string()); println!("Result: {}", result); assert_eq!(result, expected_result); // Test that it isn't added again let new_path = "/mnt/xvdb"; let result = updatedb(expected_result.to_string(), &new_path.to_string()); assert_eq!(result, expected_result); } // Ported from host.py in charmhelpers.core.host fn updatedb(updatedb: String, new_path: &String) -> String { // PRUNEPATHS="/tmp /var/spool /media /home/.ecryptfs /var/lib/schroot" let mut output = String::new(); for line in updatedb.lines() { if line.starts_with("PRUNEPATHS=") { let mut paths: Vec<String> = line.replace("\"", "") .replace("PRUNEPATHS=", "") .split(" ") .map(|e| e.to_string()) .collect(); if !paths.contains(&new_path) { paths.push(new_path.clone()); } output.push_str(&format!("PRUNEPATHS=\"{}\"\n", paths.join(" "))); } else { output.push_str(&format!("{}\n", line)); } } output }
use crate::data::schema::{Allocation, Resource, Route, SchemaData}; use crate::engine::constants::*; use crate::engine::travel::{distance_between_points, distance_in_time}; use std::collections::HashMap; pub fn calculate_plan_value(sd: &SchemaData) -> (f64, f64, f64) { let mut sum: f64 = 0.0; let mut value: f64 = 0.0; let mut travel_time: f64 = 0.0; for route in sd.route.iter() { let (new_sum, new_value, new_travel_time) = calculate_route_value(sd, &route, &sd.allocation); sum += new_sum; value += new_value; travel_time += new_travel_time; } (sum, value, travel_time) } pub fn calculate_route_value(sd: &SchemaData, route: &Route, allocations: &HashMap<String, Allocation>) -> (f64, f64, f64) { let mut sum: f64 = 0.0; let mut value: f64 = 0.0; let mut travel_time: f64 = 0.0; // Get resource and start locations let resource: &Resource = &sd.resource[&route.resource_id]; let mut lat = resource.lat; let mut lon = resource.lon; // Loop through all allocations for allocation_id in route.allocation.iter() { // Get allocation let all = &allocations[allocation_id]; // Get activity let activity = &sd.activity[allocation_id]; sum += all.dist; let this_total_travel = all.travel_to + all.travel_from; travel_time += this_total_travel; value += ACTIVITY_VALUE - (ACTIVITY_DURATION * HOURLY_WAGE / 360.0) - (this_total_travel * HOURLY_WAGE / 360.0); // Update position to this activity lat = activity.lat; lon = activity.lon; } // We also need to consider the cost of travelling home let travel = distance_between_points(lat, lon, resource.lat, resource.lon); value -= distance_in_time(travel) * HOURLY_WAGE / 360.0; (sum, value, travel_time) }
/* * Author: Dave Eddy <dave@daveeddy.com> * Date: January 25, 2022 * License: MIT */ /*! * A rust port of `vsv` * * Original: <https://github.com/bahamas10/vsv> */ #![allow(clippy::uninlined_format_args)] use anyhow::{Context, Result}; use yansi::{Color, Paint}; mod arguments; mod commands; mod config; mod die; mod runit; mod service; mod utils; use config::{Config, ProgramMode}; use die::die; use utils::verbose; fn do_main() -> Result<()> { // disable color until we absolutely know we want it Paint::disable(); // parse CLI options + env vars let args = arguments::parse(); let cfg = Config::from_args(&args).context("failed to parse args into config")?; // toggle color if the user wants it or the env dictates if cfg.colorize { Paint::enable(); } verbose!( cfg, "program_mode={} num_threads={} color_output={}", cfg.mode, rayon::current_num_threads(), cfg.colorize ); // figure out subcommand to run match cfg.mode { ProgramMode::Status => commands::status::do_status(&cfg), ProgramMode::Enable => commands::enable_disable::do_enable(&cfg), ProgramMode::Disable => commands::enable_disable::do_disable(&cfg), ProgramMode::External => commands::external::do_external(&cfg), } } fn main() { let ret = do_main(); if let Err(err) = ret { die!(1, "{}: {:?}", Color::Red.paint("error"), err); } }
//! This example uses no board support crate yet, but is the developer's base line for testing, //! derived from the cortex-m-quickstart examples. //! //! It does nothing, just idles in an infinite loop. #![no_main] #![no_std] #![feature(lang_items)] #[macro_use(entry, exception)] extern crate cortex_m_rt as rt; use rt::ExceptionFrame; entry!(main); fn main() -> ! { loop {} } // define the hard fault handler exception!(HardFault, hard_fault); fn hard_fault(ef: &ExceptionFrame) -> ! { panic!("HardFault at {:#?}", ef); } // define the default exception handler exception!(*, default_handler); fn default_handler(irqn: i16) { panic!("Unhandled exception (IRQn = {})", irqn); } // For any non-minimal demo, and especially during development, you'll likely rather use this // crate and remove everything below here and the lang_items feature. // // extern crate panic_semihosting; #[lang="panic_fmt"] extern fn panic_fmt() -> ! { loop {} } #[no_mangle] pub fn rust_begin_unwind() -> ! { loop {} }
// 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. //! Utilities for implementing PPP control protocols. //! //! Provides a generic implementation of an LCP-like protocol state machine, and implementations of //! LCP, IPCP and IPV6CP using this generic implementation. #![deny(missing_docs)] pub mod ppp; pub mod ipv4; pub mod ipv6; pub mod link; mod test;
use proconio::input; use topological_sort::topological_sort; fn main() { input! { n: usize, st: [(String, String); n], }; let mut names = Vec::new(); for (s, t) in &st { names.push(s); names.push(t); } names.sort(); names.dedup(); let n = names.len(); let mut edges = Vec::new(); for (s, t) in &st { let s = names.binary_search(&s).unwrap(); let t = names.binary_search(&t).unwrap(); edges.push((s, t)); } if let Some(_) = topological_sort(n, &edges) { println!("Yes"); } else { println!("No"); } }
// 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. //! A channel bounded with the sum of sizes associate with items instead of count of items. //! //! other features: //! 1. it is SPSC, enough for now. //! 2. receive can check status of channel with fn is_empty(). use std::collections::VecDeque; use std::sync::Arc; use std::sync::Mutex; use common_base::base::tokio::sync::Notify; struct SizedChannelInner<T> { max_size: usize, values: VecDeque<(T, usize)>, is_recv_stopped: bool, is_send_stopped: bool, } struct Stopped {} pub fn sized_spsc<T>(max_size: usize) -> (SizedChannelSender<T>, SizedChannelReceiver<T>) { let chan = Arc::new(SizedChannel::create(max_size)); let cloned = chan.clone(); (SizedChannelSender { chan }, SizedChannelReceiver { chan: cloned, }) } impl<T> SizedChannelInner<T> { pub fn create(max_size: usize) -> Self { SizedChannelInner { max_size, values: Default::default(), is_recv_stopped: false, is_send_stopped: false, } } pub fn size(&self) -> usize { self.values.iter().map(|x| x.1).sum::<usize>() } pub fn try_send(&mut self, value: T, size: usize) -> Result<Option<T>, Stopped> { let current_size = self.size(); if self.is_recv_stopped || self.is_send_stopped { Err(Stopped {}) } else if current_size + size <= self.max_size || current_size == 0 { self.values.push_back((value, size)); Ok(None) } else { Ok(Some(value)) } } pub fn try_recv(&mut self) -> Result<Option<T>, Stopped> { let v = self.values.pop_front().map(|x| x.0); if v.is_none() && self.is_send_stopped { Err(Stopped {}) } else { Ok(v) } } pub fn is_empty(&self) -> bool { self.values.is_empty() && self.is_send_stopped } pub fn stop_send(&mut self) { self.is_send_stopped = true } pub fn stop_recv(&mut self) { self.is_recv_stopped = true } } struct SizedChannel<T> { inner: Mutex<SizedChannelInner<T>>, notify_on_sent: Notify, notify_on_recv: Notify, } impl<T> SizedChannel<T> { fn create(max_size: usize) -> Self { SizedChannel { inner: Mutex::new(SizedChannelInner::create(max_size)), notify_on_sent: Default::default(), notify_on_recv: Default::default(), } } fn try_send(&self, value: T, size: usize) -> Result<Option<T>, Stopped> { let mut guard = self.inner.lock().unwrap(); guard.try_send(value, size) } pub fn try_recv(&self) -> Result<Option<T>, Stopped> { let mut guard = self.inner.lock().unwrap(); guard.try_recv() } pub async fn send(&self, value: T, size: usize) -> bool { let mut to_send = value; loop { match self.try_send(to_send, size) { Ok(Some(v)) => { to_send = v; self.notify_on_recv.notified().await; } Ok(None) => { self.notify_on_sent.notify_one(); return true; } Err(_) => return false, } } } pub async fn recv(&self) -> Option<T> { loop { match self.try_recv() { Ok(Some(v)) => { self.notify_on_recv.notify_one(); return Some(v); } Ok(None) => { self.notify_on_sent.notified().await; } Err(_) => return None, } } } pub fn is_empty(&self) -> bool { let guard = self.inner.lock().unwrap(); guard.is_empty() } pub fn stop_send(&self) { { let mut guard = self.inner.lock().unwrap(); guard.stop_send() } self.notify_on_sent.notify_one(); } pub fn stop_recv(&self) { { let mut guard = self.inner.lock().unwrap(); guard.stop_recv() } self.notify_on_recv.notify_one(); } } pub struct SizedChannelReceiver<T> { chan: Arc<SizedChannel<T>>, } impl<T> SizedChannelReceiver<T> { pub async fn recv(&self) -> Option<T> { self.chan.recv().await } pub fn try_recv(&self) -> Option<T> { self.chan.try_recv().unwrap_or_default() } pub fn close(&self) { self.chan.stop_recv() } pub fn is_empty(&self) -> bool { self.chan.is_empty() } } pub struct SizedChannelSender<T> { chan: Arc<SizedChannel<T>>, } impl<T> SizedChannelSender<T> { pub async fn send(&self, value: T, size: usize) -> bool { self.chan.send(value, size).await } pub fn close(&self) { self.chan.stop_send() } pub fn closer(&self) -> SizedChannelSenderCloser<T> { SizedChannelSenderCloser { chan: self.chan.clone(), } } } pub struct SizedChannelSenderCloser<T> { chan: Arc<SizedChannel<T>>, } impl<T> SizedChannelSenderCloser<T> { pub fn close(&self) { self.chan.stop_send() } }
#![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; extern crate dotenv; #[macro_use] extern crate rocket_contrib; #[macro_use] extern crate serde_derive; #[macro_use] extern crate diesel; #[macro_use] extern crate diesel_codegen; use rocket_contrib::{Json, Value}; use rocket::response::status::{Created, NoContent}; use diesel::prelude::*; use diesel::pg::PgConnection; use dotenv::dotenv; use std::env; use models::*; use schema::movies; pub mod schema; pub mod models; pub fn establish_connection() -> PgConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL") .expect("DATABASE URL must be set"); PgConnection::establish(&database_url) .expect(&format!("Error connecting to {}.", database_url)) } #[get("/movie/<id>", format = "application/json")] fn get(id: i32) -> Result<Json<Movie>, diesel::result::Error> { let conn: PgConnection = establish_connection(); let movie = movies::table .find(id) .first::<Movie>(&conn)?; Ok(Json(movie)) } #[get("/", format = "application/json")] fn get_all() -> Result<Json<Vec<Movie>>, diesel::result::Error> { let conn: PgConnection = establish_connection(); let movies = movies::table .load::<Movie>(&conn)?; Ok(Json(movies)) } #[post("/", format = "application/json", data = "<movie>")] fn new(movie: Json<NewMovie>) -> Result<Created<Json<Movie>>, diesel::result::Error> { let conn = establish_connection(); let new_movie = NewMovie { title: movie.0.title, director: movie.0.director, rating: movie.0.rating }; let movie: Movie = diesel::insert(&new_movie) .into(movies::table) .get_result(&conn)?; let url = format!("/movie/{}", movie.id); Ok(Created(url, Some(Json(movie)))) } #[delete("/movie/<id>")] fn movie_delete(id: i32) -> Result<NoContent, diesel::result::Error> { let conn = establish_connection(); diesel::delete(movies::table.find(id)) .execute(&conn)?; Ok(NoContent) } #[patch("/movie/<id>", format = "application/json", data = "<movie>")] fn movie_edit(id: i32, movie: Json<Movie>) -> Result<Json<Movie>, diesel::result::Error> { let conn = establish_connection(); let movie = diesel::update(movies::table.find(id)) .set(&movie.0) .get_result::<Movie>(&conn)?; Ok(Json(movie)) } #[error(404)] fn not_found() -> Json<Value> { Json(json!({ "status": "error", "reason": "Resource not found" })) } fn rocket() -> rocket::Rocket { rocket::ignite() .mount("/", routes![get_all, get, new, movie_delete, movie_edit]) .catch(errors![not_found]) } fn main() { rocket().launch(); }
use crate::libbb::ptr_to_globals::bb_errno; use libc; pub unsafe fn cp_mv_stat2( fn_0: *const libc::c_char, fn_stat: *mut libc::stat, sf: unsafe extern "C" fn(_: *const libc::c_char, _: *mut libc::stat) -> libc::c_int, ) -> libc::c_int { if sf(fn_0, fn_stat) < 0 { if *bb_errno != 2 { crate::libbb::perror_msg::bb_perror_msg( b"can\'t stat \'%s\'\x00" as *const u8 as *const libc::c_char, fn_0, ); return -1; } return 0; } if (*fn_stat).st_mode & 0o170000 as libc::c_uint == 0o40000 as libc::c_uint { return 3; } return 1; } pub unsafe fn cp_mv_stat(fn_0: *const libc::c_char, fn_stat: *mut libc::stat) -> libc::c_int { return cp_mv_stat2(fn_0, fn_stat, libc::stat); }
//! A cumulative sum. use super::*; use crate::algebra::{Group, Monoid}; use std::iter::FromIterator; use std::ops::{Range, RangeTo}; /// A cumulative sum. /// /// # Space complexity /// O(n log σ) #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub struct CumulativeSum<T> { vec: Vec<T>, } impl<M: Monoid> CumulativeSum<M> { /// Returns the length of the sequence. /// /// # Time complexity /// O(1) pub fn len(&self) -> usize { self.vec.len() - 1 } /// Folds elements in the given prefix range with a monoid's binary operation. /// /// # Panics /// Panics if `index` is out of bounds. /// /// # Time complexity /// O(1) pub fn prefix_fold(&self, index: RangeTo<usize>) -> &M { assert_index_range_to(index, self.len()); &self.vec[index.end] } } impl<G: Group> CumulativeSum<G> { /// Returns an element at the given index. /// /// # Panics /// Panics if `index` is out of bounds. /// /// # Time complexity /// O(1) pub fn get(&self, index: usize) -> G { assert_index(index, self.len()); self.fold(index..index + 1) } /// Folds elements in the given range with a group's binary operation. /// /// # Panics /// Panics if `index` is out of bounds. /// /// # Time complexity /// O(1) pub fn fold(&self, index: Range<usize>) -> G { assert_index_range(&index, self.len()); // [s, e) = [s, e - 1] = [0, s - 1] ^ -1 * [0, e - 1] = [0, s) ^ -1 * [0, e) let l = self.prefix_fold(..index.start).invert(); let r = self.prefix_fold(..index.end); l.op(r) } } impl<M: Monoid> FromIterator<M> for CumulativeSum<M> { /// Creates a new `CumulativeSum` from an iterator. /// /// # Time complexity /// O(n) fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = M>, { let iter = iter.into_iter(); let mut vec = Vec::with_capacity(iter.size_hint().0); vec.push(M::identity()); for (i, value) in iter.enumerate() { let sum = vec[i].op(&value); vec.push(sum); } vec.shrink_to_fit(); CumulativeSum { vec: vec } } }
#[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::CTL { #[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 TIMER_CTL_TAENR { bits: bool, } impl TIMER_CTL_TAENR { #[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 _TIMER_CTL_TAENW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_TAENW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct TIMER_CTL_TASTALLR { bits: bool, } impl TIMER_CTL_TASTALLR { #[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 _TIMER_CTL_TASTALLW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_TASTALLW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = "Possible values of the field `TIMER_CTL_TAEVENT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIMER_CTL_TAEVENTR { #[doc = "Positive edge"] TIMER_CTL_TAEVENT_POS, #[doc = "Negative edge"] TIMER_CTL_TAEVENT_NEG, #[doc = "Both edges"] TIMER_CTL_TAEVENT_BOTH, #[doc = r"Reserved"] _Reserved(u8), } impl TIMER_CTL_TAEVENTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { TIMER_CTL_TAEVENTR::TIMER_CTL_TAEVENT_POS => 0, TIMER_CTL_TAEVENTR::TIMER_CTL_TAEVENT_NEG => 1, TIMER_CTL_TAEVENTR::TIMER_CTL_TAEVENT_BOTH => 3, TIMER_CTL_TAEVENTR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> TIMER_CTL_TAEVENTR { match value { 0 => TIMER_CTL_TAEVENTR::TIMER_CTL_TAEVENT_POS, 1 => TIMER_CTL_TAEVENTR::TIMER_CTL_TAEVENT_NEG, 3 => TIMER_CTL_TAEVENTR::TIMER_CTL_TAEVENT_BOTH, i => TIMER_CTL_TAEVENTR::_Reserved(i), } } #[doc = "Checks if the value of the field is `TIMER_CTL_TAEVENT_POS`"] #[inline(always)] pub fn is_timer_ctl_taevent_pos(&self) -> bool { *self == TIMER_CTL_TAEVENTR::TIMER_CTL_TAEVENT_POS } #[doc = "Checks if the value of the field is `TIMER_CTL_TAEVENT_NEG`"] #[inline(always)] pub fn is_timer_ctl_taevent_neg(&self) -> bool { *self == TIMER_CTL_TAEVENTR::TIMER_CTL_TAEVENT_NEG } #[doc = "Checks if the value of the field is `TIMER_CTL_TAEVENT_BOTH`"] #[inline(always)] pub fn is_timer_ctl_taevent_both(&self) -> bool { *self == TIMER_CTL_TAEVENTR::TIMER_CTL_TAEVENT_BOTH } } #[doc = "Values that can be written to the field `TIMER_CTL_TAEVENT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIMER_CTL_TAEVENTW { #[doc = "Positive edge"] TIMER_CTL_TAEVENT_POS, #[doc = "Negative edge"] TIMER_CTL_TAEVENT_NEG, #[doc = "Both edges"] TIMER_CTL_TAEVENT_BOTH, } impl TIMER_CTL_TAEVENTW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { TIMER_CTL_TAEVENTW::TIMER_CTL_TAEVENT_POS => 0, TIMER_CTL_TAEVENTW::TIMER_CTL_TAEVENT_NEG => 1, TIMER_CTL_TAEVENTW::TIMER_CTL_TAEVENT_BOTH => 3, } } } #[doc = r"Proxy"] pub struct _TIMER_CTL_TAEVENTW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_TAEVENTW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMER_CTL_TAEVENTW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Positive edge"] #[inline(always)] pub fn timer_ctl_taevent_pos(self) -> &'a mut W { self.variant(TIMER_CTL_TAEVENTW::TIMER_CTL_TAEVENT_POS) } #[doc = "Negative edge"] #[inline(always)] pub fn timer_ctl_taevent_neg(self) -> &'a mut W { self.variant(TIMER_CTL_TAEVENTW::TIMER_CTL_TAEVENT_NEG) } #[doc = "Both edges"] #[inline(always)] pub fn timer_ctl_taevent_both(self) -> &'a mut W { self.variant(TIMER_CTL_TAEVENTW::TIMER_CTL_TAEVENT_BOTH) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 2); self.w.bits |= ((value as u32) & 3) << 2; self.w } } #[doc = r"Value of the field"] pub struct TIMER_CTL_RTCENR { bits: bool, } impl TIMER_CTL_RTCENR { #[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 _TIMER_CTL_RTCENW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_RTCENW<'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 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct TIMER_CTL_TAOTER { bits: bool, } impl TIMER_CTL_TAOTER { #[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 _TIMER_CTL_TAOTEW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_TAOTEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct TIMER_CTL_TAPWMLR { bits: bool, } impl TIMER_CTL_TAPWMLR { #[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 _TIMER_CTL_TAPWMLW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_TAPWMLW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u32) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct TIMER_CTL_TBENR { bits: bool, } impl TIMER_CTL_TBENR { #[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 _TIMER_CTL_TBENW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_TBENW<'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 TIMER_CTL_TBSTALLR { bits: bool, } impl TIMER_CTL_TBSTALLR { #[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 _TIMER_CTL_TBSTALLW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_TBSTALLW<'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 = "Possible values of the field `TIMER_CTL_TBEVENT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIMER_CTL_TBEVENTR { #[doc = "Positive edge"] TIMER_CTL_TBEVENT_POS, #[doc = "Negative edge"] TIMER_CTL_TBEVENT_NEG, #[doc = "Both edges"] TIMER_CTL_TBEVENT_BOTH, #[doc = r"Reserved"] _Reserved(u8), } impl TIMER_CTL_TBEVENTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { TIMER_CTL_TBEVENTR::TIMER_CTL_TBEVENT_POS => 0, TIMER_CTL_TBEVENTR::TIMER_CTL_TBEVENT_NEG => 1, TIMER_CTL_TBEVENTR::TIMER_CTL_TBEVENT_BOTH => 3, TIMER_CTL_TBEVENTR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> TIMER_CTL_TBEVENTR { match value { 0 => TIMER_CTL_TBEVENTR::TIMER_CTL_TBEVENT_POS, 1 => TIMER_CTL_TBEVENTR::TIMER_CTL_TBEVENT_NEG, 3 => TIMER_CTL_TBEVENTR::TIMER_CTL_TBEVENT_BOTH, i => TIMER_CTL_TBEVENTR::_Reserved(i), } } #[doc = "Checks if the value of the field is `TIMER_CTL_TBEVENT_POS`"] #[inline(always)] pub fn is_timer_ctl_tbevent_pos(&self) -> bool { *self == TIMER_CTL_TBEVENTR::TIMER_CTL_TBEVENT_POS } #[doc = "Checks if the value of the field is `TIMER_CTL_TBEVENT_NEG`"] #[inline(always)] pub fn is_timer_ctl_tbevent_neg(&self) -> bool { *self == TIMER_CTL_TBEVENTR::TIMER_CTL_TBEVENT_NEG } #[doc = "Checks if the value of the field is `TIMER_CTL_TBEVENT_BOTH`"] #[inline(always)] pub fn is_timer_ctl_tbevent_both(&self) -> bool { *self == TIMER_CTL_TBEVENTR::TIMER_CTL_TBEVENT_BOTH } } #[doc = "Values that can be written to the field `TIMER_CTL_TBEVENT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIMER_CTL_TBEVENTW { #[doc = "Positive edge"] TIMER_CTL_TBEVENT_POS, #[doc = "Negative edge"] TIMER_CTL_TBEVENT_NEG, #[doc = "Both edges"] TIMER_CTL_TBEVENT_BOTH, } impl TIMER_CTL_TBEVENTW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { TIMER_CTL_TBEVENTW::TIMER_CTL_TBEVENT_POS => 0, TIMER_CTL_TBEVENTW::TIMER_CTL_TBEVENT_NEG => 1, TIMER_CTL_TBEVENTW::TIMER_CTL_TBEVENT_BOTH => 3, } } } #[doc = r"Proxy"] pub struct _TIMER_CTL_TBEVENTW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_TBEVENTW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMER_CTL_TBEVENTW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Positive edge"] #[inline(always)] pub fn timer_ctl_tbevent_pos(self) -> &'a mut W { self.variant(TIMER_CTL_TBEVENTW::TIMER_CTL_TBEVENT_POS) } #[doc = "Negative edge"] #[inline(always)] pub fn timer_ctl_tbevent_neg(self) -> &'a mut W { self.variant(TIMER_CTL_TBEVENTW::TIMER_CTL_TBEVENT_NEG) } #[doc = "Both edges"] #[inline(always)] pub fn timer_ctl_tbevent_both(self) -> &'a mut W { self.variant(TIMER_CTL_TBEVENTW::TIMER_CTL_TBEVENT_BOTH) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 10); self.w.bits |= ((value as u32) & 3) << 10; self.w } } #[doc = r"Value of the field"] pub struct TIMER_CTL_TBOTER { bits: bool, } impl TIMER_CTL_TBOTER { #[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 _TIMER_CTL_TBOTEW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_TBOTEW<'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 << 13); self.w.bits |= ((value as u32) & 1) << 13; self.w } } #[doc = r"Value of the field"] pub struct TIMER_CTL_TBPWMLR { bits: bool, } impl TIMER_CTL_TBPWMLR { #[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 _TIMER_CTL_TBPWMLW<'a> { w: &'a mut W, } impl<'a> _TIMER_CTL_TBPWMLW<'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 << 14); self.w.bits |= ((value as u32) & 1) << 14; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - GPTM Timer A Enable"] #[inline(always)] pub fn timer_ctl_taen(&self) -> TIMER_CTL_TAENR { let bits = ((self.bits >> 0) & 1) != 0; TIMER_CTL_TAENR { bits } } #[doc = "Bit 1 - GPTM Timer A Stall Enable"] #[inline(always)] pub fn timer_ctl_tastall(&self) -> TIMER_CTL_TASTALLR { let bits = ((self.bits >> 1) & 1) != 0; TIMER_CTL_TASTALLR { bits } } #[doc = "Bits 2:3 - GPTM Timer A Event Mode"] #[inline(always)] pub fn timer_ctl_taevent(&self) -> TIMER_CTL_TAEVENTR { TIMER_CTL_TAEVENTR::_from(((self.bits >> 2) & 3) as u8) } #[doc = "Bit 4 - GPTM RTC Stall Enable"] #[inline(always)] pub fn timer_ctl_rtcen(&self) -> TIMER_CTL_RTCENR { let bits = ((self.bits >> 4) & 1) != 0; TIMER_CTL_RTCENR { bits } } #[doc = "Bit 5 - GPTM Timer A Output Trigger Enable"] #[inline(always)] pub fn timer_ctl_taote(&self) -> TIMER_CTL_TAOTER { let bits = ((self.bits >> 5) & 1) != 0; TIMER_CTL_TAOTER { bits } } #[doc = "Bit 6 - GPTM Timer A PWM Output Level"] #[inline(always)] pub fn timer_ctl_tapwml(&self) -> TIMER_CTL_TAPWMLR { let bits = ((self.bits >> 6) & 1) != 0; TIMER_CTL_TAPWMLR { bits } } #[doc = "Bit 8 - GPTM Timer B Enable"] #[inline(always)] pub fn timer_ctl_tben(&self) -> TIMER_CTL_TBENR { let bits = ((self.bits >> 8) & 1) != 0; TIMER_CTL_TBENR { bits } } #[doc = "Bit 9 - GPTM Timer B Stall Enable"] #[inline(always)] pub fn timer_ctl_tbstall(&self) -> TIMER_CTL_TBSTALLR { let bits = ((self.bits >> 9) & 1) != 0; TIMER_CTL_TBSTALLR { bits } } #[doc = "Bits 10:11 - GPTM Timer B Event Mode"] #[inline(always)] pub fn timer_ctl_tbevent(&self) -> TIMER_CTL_TBEVENTR { TIMER_CTL_TBEVENTR::_from(((self.bits >> 10) & 3) as u8) } #[doc = "Bit 13 - GPTM Timer B Output Trigger Enable"] #[inline(always)] pub fn timer_ctl_tbote(&self) -> TIMER_CTL_TBOTER { let bits = ((self.bits >> 13) & 1) != 0; TIMER_CTL_TBOTER { bits } } #[doc = "Bit 14 - GPTM Timer B PWM Output Level"] #[inline(always)] pub fn timer_ctl_tbpwml(&self) -> TIMER_CTL_TBPWMLR { let bits = ((self.bits >> 14) & 1) != 0; TIMER_CTL_TBPWMLR { 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 = "Bit 0 - GPTM Timer A Enable"] #[inline(always)] pub fn timer_ctl_taen(&mut self) -> _TIMER_CTL_TAENW { _TIMER_CTL_TAENW { w: self } } #[doc = "Bit 1 - GPTM Timer A Stall Enable"] #[inline(always)] pub fn timer_ctl_tastall(&mut self) -> _TIMER_CTL_TASTALLW { _TIMER_CTL_TASTALLW { w: self } } #[doc = "Bits 2:3 - GPTM Timer A Event Mode"] #[inline(always)] pub fn timer_ctl_taevent(&mut self) -> _TIMER_CTL_TAEVENTW { _TIMER_CTL_TAEVENTW { w: self } } #[doc = "Bit 4 - GPTM RTC Stall Enable"] #[inline(always)] pub fn timer_ctl_rtcen(&mut self) -> _TIMER_CTL_RTCENW { _TIMER_CTL_RTCENW { w: self } } #[doc = "Bit 5 - GPTM Timer A Output Trigger Enable"] #[inline(always)] pub fn timer_ctl_taote(&mut self) -> _TIMER_CTL_TAOTEW { _TIMER_CTL_TAOTEW { w: self } } #[doc = "Bit 6 - GPTM Timer A PWM Output Level"] #[inline(always)] pub fn timer_ctl_tapwml(&mut self) -> _TIMER_CTL_TAPWMLW { _TIMER_CTL_TAPWMLW { w: self } } #[doc = "Bit 8 - GPTM Timer B Enable"] #[inline(always)] pub fn timer_ctl_tben(&mut self) -> _TIMER_CTL_TBENW { _TIMER_CTL_TBENW { w: self } } #[doc = "Bit 9 - GPTM Timer B Stall Enable"] #[inline(always)] pub fn timer_ctl_tbstall(&mut self) -> _TIMER_CTL_TBSTALLW { _TIMER_CTL_TBSTALLW { w: self } } #[doc = "Bits 10:11 - GPTM Timer B Event Mode"] #[inline(always)] pub fn timer_ctl_tbevent(&mut self) -> _TIMER_CTL_TBEVENTW { _TIMER_CTL_TBEVENTW { w: self } } #[doc = "Bit 13 - GPTM Timer B Output Trigger Enable"] #[inline(always)] pub fn timer_ctl_tbote(&mut self) -> _TIMER_CTL_TBOTEW { _TIMER_CTL_TBOTEW { w: self } } #[doc = "Bit 14 - GPTM Timer B PWM Output Level"] #[inline(always)] pub fn timer_ctl_tbpwml(&mut self) -> _TIMER_CTL_TBPWMLW { _TIMER_CTL_TBPWMLW { w: self } } }
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use crate::output_manager_service::{ error::OutputManagerStorageError, storage::database::{ DbKey, DbKeyValuePair, DbValue, KeyManagerState, OutputManagerBackend, PendingTransactionOutputs, WriteOperation, }, TxId, }; use chrono::{Duration as ChronoDuration, Utc}; use std::{ collections::HashMap, sync::{Arc, RwLock}, time::Duration, }; use tari_core::transactions::transaction::UnblindedOutput; /// This structure is an In-Memory database backend that implements the `OutputManagerBackend` trait and provides all /// the functionality required by the trait. #[derive(Default)] pub struct InnerDatabase { unspent_outputs: Vec<UnblindedOutput>, spent_outputs: Vec<UnblindedOutput>, invalid_outputs: Vec<UnblindedOutput>, pending_transactions: HashMap<TxId, PendingTransactionOutputs>, short_term_pending_transactions: HashMap<TxId, PendingTransactionOutputs>, key_manager_state: Option<KeyManagerState>, } impl InnerDatabase { pub fn new() -> Self { Self { unspent_outputs: Vec::new(), spent_outputs: Vec::new(), invalid_outputs: Vec::new(), pending_transactions: HashMap::new(), short_term_pending_transactions: Default::default(), key_manager_state: None, } } } #[derive(Clone, Default)] pub struct OutputManagerMemoryDatabase { db: Arc<RwLock<InnerDatabase>>, } impl OutputManagerMemoryDatabase { pub fn new() -> Self { Self { db: Arc::new(RwLock::new(InnerDatabase::new())), } } } impl OutputManagerBackend for OutputManagerMemoryDatabase { fn fetch(&self, key: &DbKey) -> Result<Option<DbValue>, OutputManagerStorageError> { let db = acquire_read_lock!(self.db); let result = match key { DbKey::SpentOutput(k) => db .spent_outputs .iter() .find(|v| &v.spending_key == k) .map(|v| DbValue::SpentOutput(Box::new(v.clone()))), DbKey::UnspentOutput(k) => db .unspent_outputs .iter() .find(|v| &v.spending_key == k) .map(|v| DbValue::UnspentOutput(Box::new(v.clone()))), DbKey::PendingTransactionOutputs(tx_id) => { let mut result = db.pending_transactions.get(tx_id); if result.is_none() { result = db.short_term_pending_transactions.get(&tx_id); } result.map(|v| DbValue::PendingTransactionOutputs(Box::new(v.clone()))) }, DbKey::UnspentOutputs => Some(DbValue::UnspentOutputs(db.unspent_outputs.clone())), DbKey::SpentOutputs => Some(DbValue::SpentOutputs(db.spent_outputs.clone())), DbKey::AllPendingTransactionOutputs => { let mut pending_tx_outputs = db.pending_transactions.clone(); for (k, v) in db.short_term_pending_transactions.iter() { pending_tx_outputs.insert(k.clone(), v.clone()); } Some(DbValue::AllPendingTransactionOutputs(pending_tx_outputs)) }, DbKey::KeyManagerState => db .key_manager_state .as_ref() .map(|km| DbValue::KeyManagerState(km.clone())), DbKey::InvalidOutputs => Some(DbValue::InvalidOutputs(db.invalid_outputs.clone())), }; Ok(result) } fn write(&self, op: WriteOperation) -> Result<Option<DbValue>, OutputManagerStorageError> { let mut db = acquire_write_lock!(self.db); match op { WriteOperation::Insert(kvp) => match kvp { DbKeyValuePair::SpentOutput(k, o) => { if db.spent_outputs.iter().any(|v| v.spending_key == k) || db.unspent_outputs.iter().any(|v| v.spending_key == k) { return Err(OutputManagerStorageError::DuplicateOutput); } db.spent_outputs.push(*o); }, DbKeyValuePair::UnspentOutput(k, o) => { if db.unspent_outputs.iter().any(|v| v.spending_key == k) || db.spent_outputs.iter().any(|v| v.spending_key == k) { return Err(OutputManagerStorageError::DuplicateOutput); } db.unspent_outputs.push(*o); }, DbKeyValuePair::PendingTransactionOutputs(t, p) => { db.short_term_pending_transactions.insert(t, *p); }, DbKeyValuePair::KeyManagerState(km) => db.key_manager_state = Some(km), }, WriteOperation::Remove(k) => match k { DbKey::SpentOutput(k) => match db.spent_outputs.iter().position(|v| v.spending_key == k) { None => return Err(OutputManagerStorageError::ValueNotFound(DbKey::SpentOutput(k))), Some(pos) => { return Ok(Some(DbValue::SpentOutput(Box::new(db.spent_outputs.remove(pos))))); }, }, DbKey::UnspentOutput(k) => match db.unspent_outputs.iter().position(|v| v.spending_key == k) { None => return Err(OutputManagerStorageError::ValueNotFound(DbKey::UnspentOutput(k))), Some(pos) => { return Ok(Some(DbValue::UnspentOutput(Box::new(db.unspent_outputs.remove(pos))))); }, }, DbKey::PendingTransactionOutputs(tx_id) => { if let Some(p) = db.pending_transactions.remove(&tx_id) { return Ok(Some(DbValue::PendingTransactionOutputs(Box::new(p)))); } else { return Err(OutputManagerStorageError::ValueNotFound( DbKey::PendingTransactionOutputs(tx_id), )); } }, DbKey::UnspentOutputs => return Err(OutputManagerStorageError::OperationNotSupported), DbKey::SpentOutputs => return Err(OutputManagerStorageError::OperationNotSupported), DbKey::AllPendingTransactionOutputs => return Err(OutputManagerStorageError::OperationNotSupported), DbKey::KeyManagerState => return Err(OutputManagerStorageError::OperationNotSupported), DbKey::InvalidOutputs => return Err(OutputManagerStorageError::OperationNotSupported), }, } Ok(None) } fn confirm_transaction(&self, tx_id: TxId) -> Result<(), OutputManagerStorageError> { let mut db = acquire_write_lock!(self.db); let mut pending_tx = db.pending_transactions.remove(&tx_id); if pending_tx.is_none() { pending_tx = db.short_term_pending_transactions.remove(&tx_id); } let mut pending_tx = pending_tx .ok_or_else(|| OutputManagerStorageError::ValueNotFound(DbKey::PendingTransactionOutputs(tx_id)))?; // Add Spent outputs for o in pending_tx.outputs_to_be_spent.drain(..) { db.spent_outputs.push(o) } // Add Unspent outputs for o in pending_tx.outputs_to_be_received.drain(..) { db.unspent_outputs.push(o); } Ok(()) } fn short_term_encumber_outputs( &self, tx_id: TxId, outputs_to_send: &[UnblindedOutput], outputs_to_receive: &[UnblindedOutput], ) -> Result<(), OutputManagerStorageError> { let mut db = acquire_write_lock!(self.db); let mut outputs_to_be_spent = Vec::new(); for i in outputs_to_send { if let Some(pos) = db.unspent_outputs.iter().position(|v| v.spending_key == i.spending_key) { outputs_to_be_spent.push(db.unspent_outputs.remove(pos)); } else { return Err(OutputManagerStorageError::ValuesNotFound); } } let mut pending_transaction = PendingTransactionOutputs { tx_id, outputs_to_be_spent, outputs_to_be_received: Vec::new(), timestamp: Utc::now().naive_utc(), }; for co in outputs_to_receive { pending_transaction.outputs_to_be_received.push(co.clone()); } db.short_term_pending_transactions.insert(tx_id, pending_transaction); Ok(()) } fn confirm_encumbered_outputs(&self, tx_id: u64) -> Result<(), OutputManagerStorageError> { let mut db = acquire_write_lock!(self.db); let pending_tx = db .short_term_pending_transactions .remove(&tx_id) .ok_or_else(|| OutputManagerStorageError::ValueNotFound(DbKey::PendingTransactionOutputs(tx_id)))?; let _ = db.pending_transactions.insert(pending_tx.tx_id, pending_tx); Ok(()) } fn clear_short_term_encumberances(&self) -> Result<(), OutputManagerStorageError> { let db = acquire_write_lock!(self.db); let short_term_encumberances = db.short_term_pending_transactions.clone(); drop(db); for tx_id in short_term_encumberances.keys() { self.cancel_pending_transaction(tx_id.clone())?; } Ok(()) } fn cancel_pending_transaction(&self, tx_id: TxId) -> Result<(), OutputManagerStorageError> { let mut db = acquire_write_lock!(self.db); let mut pending_tx = db.pending_transactions.remove(&tx_id); if pending_tx.is_none() { pending_tx = db.short_term_pending_transactions.remove(&tx_id); } let mut pending_tx = pending_tx .ok_or_else(|| OutputManagerStorageError::ValueNotFound(DbKey::PendingTransactionOutputs(tx_id)))?; for o in pending_tx.outputs_to_be_spent.drain(..) { db.unspent_outputs.push(o); } Ok(()) } fn timeout_pending_transactions(&self, period: Duration) -> Result<(), OutputManagerStorageError> { let db = acquire_write_lock!(self.db); let mut transactions_to_be_cancelled = Vec::new(); for (tx_id, pt) in db.pending_transactions.iter() { if pt.timestamp + ChronoDuration::from_std(period)? < Utc::now().naive_utc() { transactions_to_be_cancelled.push(tx_id.clone()); } } for (tx_id, pt) in db.short_term_pending_transactions.iter() { if pt.timestamp + ChronoDuration::from_std(period)? < Utc::now().naive_utc() { transactions_to_be_cancelled.push(tx_id.clone()); } } drop(db); for t in transactions_to_be_cancelled { self.cancel_pending_transaction(t.clone())?; } Ok(()) } fn invalidate_unspent_output(&self, output: &UnblindedOutput) -> Result<(), OutputManagerStorageError> { let mut db = acquire_write_lock!(self.db); match db .unspent_outputs .iter() .position(|v| v.spending_key == output.spending_key) { Some(pos) => { let output = db.unspent_outputs.remove(pos); db.invalid_outputs.push(output); }, None => return Err(OutputManagerStorageError::ValuesNotFound), } Ok(()) } fn increment_key_index(&self) -> Result<(), OutputManagerStorageError> { let mut db = acquire_write_lock!(self.db); if db.key_manager_state.is_none() { return Err(OutputManagerStorageError::KeyManagerNotInitialized); } db.key_manager_state = db.key_manager_state.clone().map(|mut state| { state.primary_key_index += 1; state }); Ok(()) } }
#[doc = "Reader of register CR"] pub type R = crate::R<u32, super::CR>; #[doc = "Writer for register CR"] pub type W = crate::W<u32, super::CR>; #[doc = "Register CR `reset()`'s with value 0"] impl crate::ResetValue for super::CR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Volatile data execution\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum VDE_A { #[doc = "0: Volatile data segment cannot be executed if VDS = 0"] NOTEXECUTABLE = 0, #[doc = "1: Volatile data segment is declared executable whatever VDS bit value"] EXECUTABLE = 1, } impl From<VDE_A> for bool { #[inline(always)] fn from(variant: VDE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `VDE`"] pub type VDE_R = crate::R<bool, VDE_A>; impl VDE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> VDE_A { match self.bits { false => VDE_A::NOTEXECUTABLE, true => VDE_A::EXECUTABLE, } } #[doc = "Checks if the value of the field is `NOTEXECUTABLE`"] #[inline(always)] pub fn is_not_executable(&self) -> bool { *self == VDE_A::NOTEXECUTABLE } #[doc = "Checks if the value of the field is `EXECUTABLE`"] #[inline(always)] pub fn is_executable(&self) -> bool { *self == VDE_A::EXECUTABLE } } #[doc = "Volatile data execution\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum VDE_AW { #[doc = "0: Resets volatile data execution bit"] RESET = 0, } impl From<VDE_AW> for bool { #[inline(always)] fn from(variant: VDE_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `VDE`"] pub struct VDE_W<'a> { w: &'a mut W, } impl<'a> VDE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: VDE_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Resets volatile data execution bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(VDE_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Volatile data shared\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum VDS_A { #[doc = "0: Volatile data segment is not shared and cannot be hit by a non protected executable code when the Firewall is closed"] NOTSHARED = 0, #[doc = "1: Volatile data segment is shared with non protected application code"] SHARED = 1, } impl From<VDS_A> for bool { #[inline(always)] fn from(variant: VDS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `VDS`"] pub type VDS_R = crate::R<bool, VDS_A>; impl VDS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> VDS_A { match self.bits { false => VDS_A::NOTSHARED, true => VDS_A::SHARED, } } #[doc = "Checks if the value of the field is `NOTSHARED`"] #[inline(always)] pub fn is_not_shared(&self) -> bool { *self == VDS_A::NOTSHARED } #[doc = "Checks if the value of the field is `SHARED`"] #[inline(always)] pub fn is_shared(&self) -> bool { *self == VDS_A::SHARED } } #[doc = "Volatile data shared\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum VDS_AW { #[doc = "0: Resets volatile data shared bit"] RESET = 0, } impl From<VDS_AW> for bool { #[inline(always)] fn from(variant: VDS_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `VDS`"] pub struct VDS_W<'a> { w: &'a mut W, } impl<'a> VDS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: VDS_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Resets volatile data shared bit"] #[inline(always)] pub fn reset(self) -> &'a mut W { self.variant(VDS_AW::RESET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Firewall pre alarm\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FPA_A { #[doc = "0: Any code executed outside the protected segment when the Firewall is opened will generate a system reset"] PREARMRESET = 0, #[doc = "1: Any code executed outside the protected segment will close the Firewall"] PREARMSET = 1, } impl From<FPA_A> for bool { #[inline(always)] fn from(variant: FPA_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `FPA`"] pub type FPA_R = crate::R<bool, FPA_A>; impl FPA_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FPA_A { match self.bits { false => FPA_A::PREARMRESET, true => FPA_A::PREARMSET, } } #[doc = "Checks if the value of the field is `PREARMRESET`"] #[inline(always)] pub fn is_pre_arm_reset(&self) -> bool { *self == FPA_A::PREARMRESET } #[doc = "Checks if the value of the field is `PREARMSET`"] #[inline(always)] pub fn is_pre_arm_set(&self) -> bool { *self == FPA_A::PREARMSET } } #[doc = "Write proxy for field `FPA`"] pub struct FPA_W<'a> { w: &'a mut W, } impl<'a> FPA_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FPA_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Any code executed outside the protected segment when the Firewall is opened will generate a system reset"] #[inline(always)] pub fn pre_arm_reset(self) -> &'a mut W { self.variant(FPA_A::PREARMRESET) } #[doc = "Any code executed outside the protected segment will close the Firewall"] #[inline(always)] pub fn pre_arm_set(self) -> &'a mut W { self.variant(FPA_A::PREARMSET) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 2 - Volatile data execution"] #[inline(always)] pub fn vde(&self) -> VDE_R { VDE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - Volatile data shared"] #[inline(always)] pub fn vds(&self) -> VDS_R { VDS_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Firewall pre alarm"] #[inline(always)] pub fn fpa(&self) -> FPA_R { FPA_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 2 - Volatile data execution"] #[inline(always)] pub fn vde(&mut self) -> VDE_W { VDE_W { w: self } } #[doc = "Bit 1 - Volatile data shared"] #[inline(always)] pub fn vds(&mut self) -> VDS_W { VDS_W { w: self } } #[doc = "Bit 0 - Firewall pre alarm"] #[inline(always)] pub fn fpa(&mut self) -> FPA_W { FPA_W { w: self } } }
#[macro_use] extern crate serde_derive; use libstd; use std::env; use scrypt::{scrypt, ScryptParams}; fn main() { /* let str = "0xFFFFFFFFFFFFf"; let args: Vec<String> = env::args().collect(); println!("{:?}",args); if args.len()!=1 { //读取命令行参数 match args[1].as_str() { "-c"=>{ println!("{:?}", args[2]); }, _=>println!("parameter {} is not support",args[1]), } } println!("{}",str.to_lowercase());*/ //scrypt_demo(); trait_test(); } use std::mem::size_of; trait T{} fn trait_test(){ A::x{name:"sss".to_string()}; assert_eq!(size_of::<&bool>(),size_of::<&u128>()); assert_eq!(size_of::<&bool>(),size_of::<usize>()); assert_eq!(size_of::<&dyn T>(),size_of::<usize>()*2); } mod A{ pub struct x{ name:String, } } ///定义输入keystore文件格式,用于转换json格式文件 #[derive(Serialize, Deserialize)] struct KeyStore{ version:u8, id:String, address:String, crypto:Crypto, } #[derive(Serialize,Debug,Deserialize)] struct Crypto{ ciphertext:String, cipher:String, cipherparams:CipherParams, kdf:String, kdfparams:KdfParams, mac:String, } #[derive(Serialize,Debug,Deserialize)] struct CipherParams{ iv:String, } #[derive(Serialize,Debug,Deserialize)] struct KdfParams{ dklen:u8, salt:String, n:f32, r:u32, p:u32, } fn scrypt_demo(){ let keystore = r#"{ "version": 3, "id": "80d7b778-e617-4b35-bb09-f4b224984ed6", "address": "d280b60c38bc8db9d309fa5a540ffec499f0a3e8", "crypto": { "ciphertext": "58ac20c29dd3029f4d374839508ba83fc84628ae9c3f7e4cc36b05e892bf150d", "cipherparams": { "iv": "9ab7a5f9bcc9df7d796b5022023e2d14" }, "cipher": "aes-128-ctr", "kdf": "scrypt", "kdfparams": { "dklen": 32, "salt": "63a364b8a64928843708b5e9665a79fa00890002b32833b3a9ff99eec78dbf81", "n": 262144, "r": 8, "p": 1 }, "mac": "3a38f91234b52dd95d8438172bca4b7ac1f32e6425387be4296c08d8bddb2098" } } "#; let store :KeyStore= serde_json::from_str(keystore).unwrap(); println!("{},{}",store.address,store.version); println!("{:?}",store.crypto); let password = "12345"; //对称加密密钥 // let mut key = vec![0u8; 32]; let mut key = [0u8; 32]; let crypto = store.crypto; let kdfparams = crypto.kdfparams; let log_n = kdfparams.n.log2() as u8; println!("log_n is:{}",log_n); let p = kdfparams.p; let r = kdfparams.r; let params = ScryptParams::new(18, r, p).unwrap(); //let params = ScryptParams::new(19, r, p); let hex_salt = kdfparams.salt; let salt = hex::decode(hex_salt).unwrap(); scrypt(password.as_bytes(), salt.as_slice(), &params, &mut key).expect("32 bytes always satisfy output length requirements"); //rust_scrypt::scrypt(password.as_bytes(), salt.as_slice(), &params, &mut key); println!("scrypt data is {}",hex::encode(key)); }
extern crate serde; mod test_utils; use flexi_logger::LoggerHandle; use hdbconnect_async::{ConnectParams, Connection, HdbResult, IntoConnectParams}; use log::*; use serde::{Deserialize, Serialize}; use std::env; use std::time::Instant; #[tokio::test] async fn test_010_connect() -> HdbResult<()> { let mut log_handle = test_utils::init_logger(); let start = Instant::now(); connect_successfully(&mut log_handle).await.unwrap(); reconnect(&mut log_handle).await.unwrap(); connect_options(&mut log_handle).await.unwrap(); client_info(&mut log_handle).await.unwrap(); connect_wrong_credentials(&mut log_handle).await; connect_and_select_with_explicit_clientlocale(&mut log_handle) .await .unwrap(); connect_and_select_with_clientlocale_from_env(&mut log_handle) .await .unwrap(); command_info(&mut log_handle).await.unwrap(); info!("Elapsed time: {:?}", Instant::now().duration_since(start)); Ok(()) } async fn connect_successfully(_log_handle: &mut LoggerHandle) -> HdbResult<()> { info!("test a successful connection"); test_utils::get_authenticated_connection().await?; Ok(()) } async fn reconnect(_log_handle: &mut LoggerHandle) -> HdbResult<()> { info!("test reconnect"); _log_handle .parse_and_push_temp_spec("info, hdbconnect::conn= debug, test=debug") .unwrap(); let cpb = test_utils::get_std_redirect_cp_builder()?; debug!("Attempting connect to {}", cpb.to_url()?); let _conn = Connection::new(cpb).await?; _log_handle.pop_temp_spec(); Ok(()) } async fn connect_options(_log_handle: &mut LoggerHandle) -> HdbResult<()> { info!("test connect options"); let connection = test_utils::get_authenticated_connection().await?; debug!( "Connection options:\n{}", connection.dump_connect_options().await? ); Ok(()) } async fn client_info(_log_handle: &mut LoggerHandle) -> HdbResult<()> { info!("client info"); _log_handle .parse_and_push_temp_spec("info, test = debug") .unwrap(); let connection = test_utils::get_authenticated_connection().await.unwrap(); let connection_id: i32 = connection.id().await?; debug!("verify original client info appears in session context"); let mut prep_stmt = connection .prepare( "\ SELECT KEY, VALUE \ FROM M_SESSION_CONTEXT \ WHERE CONNECTION_ID = ? \ AND (\ KEY = 'APPLICATION' \ OR KEY = 'APPLICATIONSOURCE' \ OR KEY = 'APPLICATIONUSER' \ OR KEY = 'APPLICATIONVERSION') \ ORDER BY KEY", ) .await?; let result: Vec<SessCtx> = prep_stmt .execute(&connection_id) .await? .into_resultset()? .try_into() .await?; check_session_context(true, &result); debug!("overwrite the client info, check that it appears in session context"); connection.set_application("TEST 1 - 2 - 3").await?; connection.set_application_user("OTTO").await?; connection.set_application_version("0.8.15").await?; connection.set_application_source("dummy.rs").await?; let result: Vec<SessCtx> = prep_stmt .execute(&connection_id) .await? .into_resultset()? .try_into() .await?; check_session_context(false, &result); debug!("verify that the updated client info remains set"); let _result: Vec<SessCtx> = prep_stmt .execute(&connection_id) .await? .into_resultset()? .try_into() .await?; let _result: Vec<SessCtx> = prep_stmt .execute(&connection_id) .await? .into_resultset()? .try_into() .await?; let result: Vec<SessCtx> = prep_stmt .execute(&connection_id) .await? .into_resultset()? .try_into() .await?; check_session_context(false, &result); _log_handle.pop_temp_spec(); Ok(()) } fn check_session_context(orig: bool, result: &[SessCtx]) { if orig { assert_eq!(result.len(), 1); assert!(result[0].value.starts_with("test_010_connect")); } else { assert_eq!(result.len(), 4); assert_eq!(result[0], SessCtx::new("APPLICATION", "TEST 1 - 2 - 3")); assert_eq!(result[1], SessCtx::new("APPLICATIONSOURCE", "dummy.rs")); assert_eq!(result[2], SessCtx::new("APPLICATIONUSER", "OTTO")); assert_eq!(result[3], SessCtx::new("APPLICATIONVERSION", "0.8.15")); } } async fn connect_wrong_credentials(_log_handle: &mut LoggerHandle) { info!("test connect failure on wrong credentials"); let start = Instant::now(); let mut cp_builder = test_utils::get_std_cp_builder().unwrap(); cp_builder.dbuser("didi").password("blabla"); let conn_params: ConnectParams = cp_builder.into_connect_params().unwrap(); assert_eq!(conn_params.password().unsecure(), "blabla"); let err = Connection::new(conn_params).await.err().unwrap(); info!( "connect with wrong credentials failed as expected, after {} µs with {}.", Instant::now().duration_since(start).as_micros(), err ); } async fn connect_and_select_with_explicit_clientlocale( _log_handle: &mut LoggerHandle, ) -> HdbResult<()> { info!("connect and do some simple select with explicit clientlocale"); let mut cp_builder = test_utils::get_std_cp_builder()?; cp_builder.clientlocale("en_US"); let conn_params: ConnectParams = cp_builder.build()?; assert_eq!(conn_params.clientlocale().unwrap(), "en_US"); let mut connection = Connection::new(conn_params).await?; select_version_and_user(&mut connection).await?; Ok(()) } async fn connect_and_select_with_clientlocale_from_env( _log_handle: &mut LoggerHandle, ) -> HdbResult<()> { info!("connect and do some simple select with clientlocale from env"); if env::var("LANG").is_err() { env::set_var("LANG", "en_US.UTF-8"); } let mut cp_builder = test_utils::get_std_cp_builder()?; cp_builder.clientlocale_from_env_lang(); let conn_params: ConnectParams = cp_builder.build()?; assert!(conn_params.clientlocale().is_some()); let mut connection = Connection::new(conn_params).await?; select_version_and_user(&mut connection).await?; Ok(()) } async fn select_version_and_user(connection: &mut Connection) -> HdbResult<()> { #[derive(Serialize, Deserialize, Debug)] struct VersionAndUser { version: Option<String>, current_user: String, } let stmt = r#"SELECT VERSION as "version", CURRENT_USER as "current_user" FROM SYS.M_DATABASE"#; debug!("calling connection.query(SELECT VERSION as ...)"); let resultset = connection.query(stmt).await?; let version_and_user: VersionAndUser = resultset.try_into().await?; let conn_params: ConnectParams = test_utils::get_std_cp_builder()?.into_connect_params()?; assert_eq!( version_and_user.current_user, conn_params.dbuser().to_uppercase() ); debug!("VersionAndUser: {:?}", version_and_user); Ok(()) } #[derive(Eq, PartialEq, Serialize, Deserialize, Debug)] #[serde(rename_all = "UPPERCASE")] struct SessCtx { key: String, value: String, } impl SessCtx { fn new(key: &str, value: &str) -> SessCtx { SessCtx { key: key.to_string(), value: value.to_string(), } } } async fn command_info(_log_handle: &mut LoggerHandle) -> HdbResult<()> { info!("command info"); let mut connection = test_utils::get_authenticated_connection().await.unwrap(); let stmt = r#"SELECT KEY, VALUE FROM M_SESSION_CONTEXT ORDER BY KEY"#; let _result: Vec<SessCtx> = connection .execute_with_debuginfo(stmt, "BLABLA", 4711) .await? .into_resultset()? .try_into() .await?; let stmt = r#"SELECT KEY, NONSENSE FROM M_SESSION_CONTEXT ORDER BY KEY"#; assert!(connection .execute_with_debuginfo(stmt, "BLABLA", 4711) .await .is_err()); Ok(()) }
//! This file contains an implementation of Vec that can't be empty. use crate::*; use std::vec::Drain; use std::vec::Splice; use std::ops::Bound; // =================== // === NonEmptyVec === // =================== /// A version of [`std::vec::Vec`] that can't be empty. #[allow(missing_docs)] #[derive(Clone,Debug,PartialEq)] pub struct NonEmptyVec<T> { elems: Vec<T> } impl<T> Deref for NonEmptyVec<T> { type Target = Vec<T>; fn deref(&self) -> &Self::Target { &self.elems } } impl<T> NonEmptyVec<T> { /// Construct a new non-empty vector. /// /// The vector will not allocate more than the space required to contain `first` and `rest`. /// /// # Examples /// /// ``` /// #![allow(unused_mut)] /// use enso_prelude::NonEmptyVec; /// let mut vec: NonEmptyVec<usize> = NonEmptyVec::new(0,vec![]); /// ``` pub fn new(first:T, rest:Vec<T>) -> NonEmptyVec<T> { let mut elems = vec![first]; elems.extend(rest); NonEmptyVec{elems} } /// Construct a `NonEmptyVec` containing a single element. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let vec = NonEmptyVec::singleton(0); /// assert_eq!(vec.get(0),Some(&0)); /// assert_eq!(vec.len(),1); /// ``` pub fn singleton(first:T) -> NonEmptyVec<T> { NonEmptyVec::new(first,vec![]) } /// Construct a new, `NonEmptyVec<T>` containing the provided element and with the provided /// `capacity`. /// /// If `capacity` is 0, then the vector will be allocated with capacity for the provided `first` /// element. The vector will be able to hold exactly `capacity` elements without reallocating. /// /// It is important to note that although the returned vector has the *capacity* specified, the /// vector will have a length of 1. /// /// # Panics /// /// Panics if `capacity` is not > 0. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let mut vec = NonEmptyVec::with_capacity(0, 10); /// /// // The vector contains one item, even though it has capacity for more /// assert_eq!(vec.len(), 1); /// /// // These are all done without reallocating... /// for i in 1..10 { /// vec.push(i); /// } /// /// // ...but this may make the vector reallocate /// vec.push(11); /// ``` pub fn with_capacity(first:T, capacity:usize) -> NonEmptyVec<T> { if capacity == 0 { panic!("Capacity must be greater than zero for a NonEmptyVec."); } let mut elems = Vec::with_capacity(capacity); elems.push(first); NonEmptyVec{elems} } /// Reserve capacity for at least `additional` more elements to be inserted in the given /// `Vec<T>`. /// /// The collection may reserve more space to avoid frequent reallocations. After calling /// `reserve`, capacity will be greater than or equal to `self.len() + additional`. Does nothing /// if capacity is already sufficient. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let mut vec = NonEmptyVec::new(0,vec![]); /// vec.reserve(10); /// assert!(vec.capacity() >= 11); /// ``` pub fn reserve(&mut self, additional:usize) { self.elems.reserve(additional); } /// Shrinks the capacity of the `NonEmotyVec` as much as possible. /// /// It will drop down as close as possible to the length, but the allocator may still inform the /// vector that there is space for a few more elements. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let mut vec = NonEmptyVec::with_capacity(0, 10); /// assert_eq!(vec.capacity(),10); /// vec.shrink_to_fit(); /// assert!(vec.capacity() < 10); /// ``` pub fn shrink_to_fit(&mut self) { self.elems.shrink_to_fit(); } /// Append an element to the back of a collection. /// /// # Panics /// /// Panics if the number of elements in the vector overflows a `usize`. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let mut vec = NonEmptyVec::new(0,vec![1,2]); /// vec.push(3); /// assert_eq!(vec.len(),4); /// ``` pub fn push(&mut self, value:T) { self.elems.push(value) } /// Remove an element from the back of the collection, returning it. /// /// Will not pop any item if there is only one item left in the vector. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let mut vec = NonEmptyVec::new(0,vec![1]); /// assert!(vec.pop().is_some()); /// assert!(vec.pop().is_none()); /// assert_eq!(vec.len(),1); /// ``` pub fn pop(&mut self) -> Option<T> { (self.len() > 1).and_option_from(||self.elems.pop()) } /// Obtain a mutable reference to teh element in the vector at the specified `index`. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let mut vec = NonEmptyVec::new(0,vec![1,2]); /// let reference = vec.get_mut(0); /// assert!(reference.is_some()); /// assert_eq!(*reference.unwrap(),0); /// ``` pub fn get_mut(&mut self, index:usize) -> Option<&mut T> { self.elems.get_mut(index) } /// Obtain an immutable reference to the head of the `NonEmptyVec`. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let vec = NonEmptyVec::new(0,vec![1,2]); /// assert_eq!(*vec.first(), 0); /// ``` pub fn first(&self) -> &T { &self.elems.first().expect("The NonEmptyVec always has an item in it.") } /// Obtain a mutable reference to the head of the `NonEmptyVec`. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let mut vec = NonEmptyVec::new(0,vec![1,2]); /// assert_eq!(*vec.first_mut(), 0); /// ``` pub fn first_mut(&mut self) -> &mut T { self.elems.first_mut().expect("The NonEmptyVec always has an item in it.") } /// Obtain an immutable reference to the last element in the `NonEmptyVec`. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let vec = NonEmptyVec::new(0,vec![1,2]); /// assert_eq!(*vec.last(),2) /// ``` pub fn last(&self) -> &T { self.get(self.len() - 1).expect("There is always one element in a NonEmptyVec.") } /// Obtain a mutable reference to the last element in the `NonEmptyVec`. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let mut vec = NonEmptyVec::new(0,vec![1,2]); /// assert_eq!(*vec.last_mut(),2) /// ``` pub fn last_mut(&mut self) -> &mut T { self.get_mut(self.len() - 1).expect("There is always one element in a NonEmptyVec.") } /// Create a draining iterator that removes the specified range in the vector and yields the /// removed items. /// /// It will never remove the root element of the vector. /// /// # Panics /// /// Panics if the starting point is greater than the end point or if the end point is greater /// than the length of the vector. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let mut vec = NonEmptyVec::new(0,vec![1,2,3,4,5]); /// let drained:Vec<i32> = vec.drain(1..=5).collect(); /// assert_eq!(drained,[1,2,3,4,5]) /// ``` pub fn drain<R>(&mut self, range:R) -> Drain<T> where R:RangeBounds<usize> { if range.contains(&0) { match range.end_bound() { Bound::Included(n) => self.elems.drain(1..=*n), Bound::Excluded(n) => self.elems.drain(1..*n), Bound::Unbounded => self.elems.drain(1..) } } else { self.elems.drain(range) } } /// Creates a splicing iterator that replaces the specified range in the vector with the given 4 /// `replace_with` iterator and yields the removed items. /// /// `replace_with` does not need to be the same length as range. The element range is removed /// even if the iterator is not consumed until the end. /// /// It is unspecified how many elements are removed from the vector if the Splice value is leaked. /// /// The input iterator replace_with is only consumed when the Splice value is dropped. /// /// # Panics /// /// Panics if the starting point is greater than the end point or if the end point is greater /// than the length of the vector. /// /// # Examples /// /// ``` /// use enso_prelude::NonEmptyVec; /// let mut vec = NonEmptyVec::new(0,vec![1,2,3,4,5]); /// let replacements = [10,20,30,40]; /// let yielded:Vec<_> = vec.splice(..2,replacements.iter().cloned()).collect(); /// assert_eq!(vec.as_slice(),&[10,20,30,40,2,3,4,5]); /// assert_eq!(yielded,&[0,1]) /// ``` pub fn splice<R,I>(&mut self, range:R, replace_with:I) -> Splice<<I as IntoIterator>::IntoIter> where I: IntoIterator<Item = T>, R: RangeBounds<usize> { self.elems.splice(range,replace_with) } } // === Trait Impls === impl<T:Default> Default for NonEmptyVec<T> { fn default() -> Self { Self::singleton(default()) } }
#[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::PINASSIGN2 { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct U1_CTS_IR { bits: u8, } impl U1_CTS_IR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct U1_SCLK_IOR { bits: u8, } impl U1_SCLK_IOR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct U2_TXD_OR { bits: u8, } impl U2_TXD_OR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct U2_RXD_IR { bits: u8, } impl U2_RXD_IR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Proxy"] pub struct _U1_CTS_IW<'a> { w: &'a mut W, } impl<'a> _U1_CTS_IW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _U1_SCLK_IOW<'a> { w: &'a mut W, } impl<'a> _U1_SCLK_IOW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _U2_TXD_OW<'a> { w: &'a mut W, } impl<'a> _U2_TXD_OW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _U2_RXD_IW<'a> { w: &'a mut W, } impl<'a> _U2_RXD_IW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:7 - U1_CTS function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn u1_cts_i(&self) -> U1_CTS_IR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; U1_CTS_IR { bits } } #[doc = "Bits 8:15 - U1_SCLK function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn u1_sclk_io(&self) -> U1_SCLK_IOR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 }; U1_SCLK_IOR { bits } } #[doc = "Bits 16:23 - U2_TXD function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn u2_txd_o(&self) -> U2_TXD_OR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }; U2_TXD_OR { bits } } #[doc = "Bits 24:31 - U2_RXD function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn u2_rxd_i(&self) -> U2_RXD_IR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 }; U2_RXD_IR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 4294967295 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:7 - U1_CTS function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn u1_cts_i(&mut self) -> _U1_CTS_IW { _U1_CTS_IW { w: self } } #[doc = "Bits 8:15 - U1_SCLK function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn u1_sclk_io(&mut self) -> _U1_SCLK_IOW { _U1_SCLK_IOW { w: self } } #[doc = "Bits 16:23 - U2_TXD function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn u2_txd_o(&mut self) -> _U2_TXD_OW { _U2_TXD_OW { w: self } } #[doc = "Bits 24:31 - U2_RXD function assignment. The value is the pin number to be assigned to this function. The following pins are available: PIO0_0 (= 0) to PIO0_17 (= 0x11)."] #[inline] pub fn u2_rxd_i(&mut self) -> _U2_RXD_IW { _U2_RXD_IW { w: self } } }
use noak::descriptor::{BaseType, TypeDescriptor}; use noak::reader::cpool; pub mod javastd; pub mod pubapi; pub mod refer; fn get_type_name(t: &TypeDescriptor) -> String { match t.base() { BaseType::Boolean => "java/lang/Boolean".to_string(), BaseType::Byte => "java/lang/Byte".to_string(), BaseType::Short => "java/lang/Short".to_string(), BaseType::Integer => "java/lang/Integer".to_string(), BaseType::Long => "java/lang/Long".to_string(), BaseType::Float => "java/lang/Float".to_string(), BaseType::Double => "java/lang/Double".to_string(), BaseType::Char => "java/lang/Char".to_string(), BaseType::Object(name) => String::from_utf8_lossy(name.as_bytes()).to_string(), } } fn to_real_string(utf8: &cpool::Utf8) -> String { String::from_utf8_lossy(utf8.content.as_bytes()).to_string() }
#[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::SSTSH0 { #[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 ADC_SSTSH0_TSH0R { bits: u8, } impl ADC_SSTSH0_TSH0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _ADC_SSTSH0_TSH0W<'a> { w: &'a mut W, } impl<'a> _ADC_SSTSH0_TSH0W<'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 ADC_SSTSH0_TSH1R { bits: u8, } impl ADC_SSTSH0_TSH1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _ADC_SSTSH0_TSH1W<'a> { w: &'a mut W, } impl<'a> _ADC_SSTSH0_TSH1W<'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 ADC_SSTSH0_TSH2R { bits: u8, } impl ADC_SSTSH0_TSH2R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _ADC_SSTSH0_TSH2W<'a> { w: &'a mut W, } impl<'a> _ADC_SSTSH0_TSH2W<'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 << 8); self.w.bits |= ((value as u32) & 15) << 8; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSTSH0_TSH3R { bits: u8, } impl ADC_SSTSH0_TSH3R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _ADC_SSTSH0_TSH3W<'a> { w: &'a mut W, } impl<'a> _ADC_SSTSH0_TSH3W<'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 << 12); self.w.bits |= ((value as u32) & 15) << 12; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSTSH0_TSH4R { bits: u8, } impl ADC_SSTSH0_TSH4R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _ADC_SSTSH0_TSH4W<'a> { w: &'a mut W, } impl<'a> _ADC_SSTSH0_TSH4W<'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 << 16); self.w.bits |= ((value as u32) & 15) << 16; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSTSH0_TSH5R { bits: u8, } impl ADC_SSTSH0_TSH5R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _ADC_SSTSH0_TSH5W<'a> { w: &'a mut W, } impl<'a> _ADC_SSTSH0_TSH5W<'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 << 20); self.w.bits |= ((value as u32) & 15) << 20; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSTSH0_TSH6R { bits: u8, } impl ADC_SSTSH0_TSH6R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _ADC_SSTSH0_TSH6W<'a> { w: &'a mut W, } impl<'a> _ADC_SSTSH0_TSH6W<'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 << 24); self.w.bits |= ((value as u32) & 15) << 24; self.w } } #[doc = r"Value of the field"] pub struct ADC_SSTSH0_TSH7R { bits: u8, } impl ADC_SSTSH0_TSH7R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _ADC_SSTSH0_TSH7W<'a> { w: &'a mut W, } impl<'a> _ADC_SSTSH0_TSH7W<'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 << 28); self.w.bits |= ((value as u32) & 15) << 28; 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 - 1st Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh0(&self) -> ADC_SSTSH0_TSH0R { let bits = ((self.bits >> 0) & 15) as u8; ADC_SSTSH0_TSH0R { bits } } #[doc = "Bits 4:7 - 2nd Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh1(&self) -> ADC_SSTSH0_TSH1R { let bits = ((self.bits >> 4) & 15) as u8; ADC_SSTSH0_TSH1R { bits } } #[doc = "Bits 8:11 - 3rd Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh2(&self) -> ADC_SSTSH0_TSH2R { let bits = ((self.bits >> 8) & 15) as u8; ADC_SSTSH0_TSH2R { bits } } #[doc = "Bits 12:15 - 4th Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh3(&self) -> ADC_SSTSH0_TSH3R { let bits = ((self.bits >> 12) & 15) as u8; ADC_SSTSH0_TSH3R { bits } } #[doc = "Bits 16:19 - 5th Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh4(&self) -> ADC_SSTSH0_TSH4R { let bits = ((self.bits >> 16) & 15) as u8; ADC_SSTSH0_TSH4R { bits } } #[doc = "Bits 20:23 - 6th Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh5(&self) -> ADC_SSTSH0_TSH5R { let bits = ((self.bits >> 20) & 15) as u8; ADC_SSTSH0_TSH5R { bits } } #[doc = "Bits 24:27 - 7th Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh6(&self) -> ADC_SSTSH0_TSH6R { let bits = ((self.bits >> 24) & 15) as u8; ADC_SSTSH0_TSH6R { bits } } #[doc = "Bits 28:31 - 8th Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh7(&self) -> ADC_SSTSH0_TSH7R { let bits = ((self.bits >> 28) & 15) as u8; ADC_SSTSH0_TSH7R { 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 - 1st Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh0(&mut self) -> _ADC_SSTSH0_TSH0W { _ADC_SSTSH0_TSH0W { w: self } } #[doc = "Bits 4:7 - 2nd Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh1(&mut self) -> _ADC_SSTSH0_TSH1W { _ADC_SSTSH0_TSH1W { w: self } } #[doc = "Bits 8:11 - 3rd Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh2(&mut self) -> _ADC_SSTSH0_TSH2W { _ADC_SSTSH0_TSH2W { w: self } } #[doc = "Bits 12:15 - 4th Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh3(&mut self) -> _ADC_SSTSH0_TSH3W { _ADC_SSTSH0_TSH3W { w: self } } #[doc = "Bits 16:19 - 5th Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh4(&mut self) -> _ADC_SSTSH0_TSH4W { _ADC_SSTSH0_TSH4W { w: self } } #[doc = "Bits 20:23 - 6th Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh5(&mut self) -> _ADC_SSTSH0_TSH5W { _ADC_SSTSH0_TSH5W { w: self } } #[doc = "Bits 24:27 - 7th Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh6(&mut self) -> _ADC_SSTSH0_TSH6W { _ADC_SSTSH0_TSH6W { w: self } } #[doc = "Bits 28:31 - 8th Sample and Hold Period Select"] #[inline(always)] pub fn adc_sstsh0_tsh7(&mut self) -> _ADC_SSTSH0_TSH7W { _ADC_SSTSH0_TSH7W { w: self } } }
// Copyright 2021 rust-ipfs-api Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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. // use crate::{ header::{TRAILER, X_STREAM_ERROR_KEY}, read::{JsonLineDecoder, StreamReader}, ApiError, ApiRequest, }; use async_trait::async_trait; use bytes::Bytes; use common_multipart_rfc7578::client::multipart; use futures::{future, FutureExt, Stream, StreamExt, TryStreamExt}; use http::{ header::{HeaderName, HeaderValue}, StatusCode, }; use serde::{Deserialize, Serialize}; use std::fmt::Display; use tokio_util::codec::{Decoder, FramedRead}; #[async_trait(?Send)] pub trait Backend { /// HTTP request type. /// type HttpRequest; /// HTTP response type. /// type HttpResponse; /// Error type for Result. /// type Error: Display + From<ApiError> + From<crate::Error> + 'static; /// Builds the url for an api call. /// fn build_base_request<Req>( &self, req: &Req, form: Option<multipart::Form<'static>>, ) -> Result<Self::HttpRequest, Self::Error> where Req: ApiRequest; /// Get the value of a header from an HTTP response. /// fn get_header(res: &Self::HttpResponse, key: HeaderName) -> Option<&HeaderValue>; /// Generates a request, and returns the unprocessed response future. /// async fn request_raw<Req>( &self, req: Req, form: Option<multipart::Form<'static>>, ) -> Result<(StatusCode, Bytes), Self::Error> where Req: ApiRequest + Serialize; fn response_to_byte_stream( res: Self::HttpResponse, ) -> Box<dyn Stream<Item = Result<Bytes, Self::Error>> + Unpin>; /// Generic method for making a request that expects back a streaming /// response. /// fn request_stream<Res, F, OutStream>( &self, req: Self::HttpRequest, process: F, ) -> Box<dyn Stream<Item = Result<Res, Self::Error>> + Unpin> where OutStream: Stream<Item = Result<Res, Self::Error>> + Unpin, F: 'static + Fn(Self::HttpResponse) -> OutStream; /// Builds an Api error from a response body. /// #[inline] fn process_error_from_body(body: Bytes) -> Self::Error { match serde_json::from_slice::<ApiError>(&body) { Ok(e) => e.into(), Err(_) => { let err = match String::from_utf8(body.to_vec()) { Ok(s) => crate::Error::UnrecognizedApiError(s), Err(e) => crate::Error::from(e), }; err.into() } } } /// Processes a response that expects a json encoded body, returning an /// error or a deserialized json response. /// fn process_json_response<Res>(status: StatusCode, body: Bytes) -> Result<Res, Self::Error> where for<'de> Res: 'static + Deserialize<'de>, { match status { StatusCode::OK => serde_json::from_slice(&body) .map_err(crate::Error::from) .map_err(Self::Error::from), _ => Err(Self::process_error_from_body(body)), } } /// Processes a response that returns a stream of json deserializable /// results. /// fn process_stream_response<D, Res>( res: Self::HttpResponse, decoder: D, ) -> FramedRead<StreamReader<Box<dyn Stream<Item = Result<Bytes, Self::Error>> + Unpin>>, D> where D: Decoder<Item = Res, Error = crate::Error>, { FramedRead::new( StreamReader::new(Self::response_to_byte_stream(res)), decoder, ) } /// Generic method for making a request to the Ipfs server, and getting /// a deserializable response. /// async fn request<Req, Res>( &self, req: Req, form: Option<multipart::Form<'static>>, ) -> Result<Res, Self::Error> where Req: ApiRequest + Serialize, for<'de> Res: 'static + Deserialize<'de>, { let (status, chunk) = self.request_raw(req, form).await?; Self::process_json_response(status, chunk) } /// Generic method for making a request to the Ipfs server, and getting /// back a response with no body. /// async fn request_empty<Req>( &self, req: Req, form: Option<multipart::Form<'static>>, ) -> Result<(), Self::Error> where Req: ApiRequest + Serialize, { let (status, chunk) = self.request_raw(req, form).await?; match status { StatusCode::OK => Ok(()), _ => Err(Self::process_error_from_body(chunk)), } } /// Generic method for making a request to the Ipfs server, and getting /// back a raw String response. /// async fn request_string<Req>( &self, req: Req, form: Option<multipart::Form<'static>>, ) -> Result<String, Self::Error> where Req: ApiRequest + Serialize, { let (status, chunk) = self.request_raw(req, form).await?; match status { StatusCode::OK => String::from_utf8(chunk.to_vec()) .map_err(crate::Error::from) .map_err(Self::Error::from), _ => Err(Self::process_error_from_body(chunk)), } } /// Generic method for making a request to the Ipfs server, and getting /// back a raw stream of bytes. /// fn request_stream_bytes( &self, req: Self::HttpRequest, ) -> Box<dyn Stream<Item = Result<Bytes, Self::Error>> + Unpin> { self.request_stream(req, |res| Self::response_to_byte_stream(res)) } /// Generic method to return a streaming response of deserialized json /// objects delineated by new line separators. /// fn request_stream_json<Res>( &self, req: Self::HttpRequest, ) -> Box<dyn Stream<Item = Result<Res, Self::Error>> + Unpin> where for<'de> Res: 'static + Deserialize<'de>, { self.request_stream(req, |res| { let parse_stream_error = if let Some(trailer) = Self::get_header(&res, TRAILER) { // Response has the Trailer header set. The StreamError trailer // is used to indicate that there was an error while streaming // data with Ipfs. // if trailer == X_STREAM_ERROR_KEY { true } else { let err = crate::Error::UnrecognizedTrailerHeader( String::from_utf8_lossy(trailer.as_ref()).into(), ); // There was an unrecognized trailer value. If that is the case, // create a stream that immediately errors. // return future::err(err).into_stream().err_into().left_stream(); } } else { false }; Self::process_stream_response(res, JsonLineDecoder::new(parse_stream_error)) .err_into() .right_stream() }) } }
#![allow(unused_assignments)] use types::*; /* * From opensource.apple.com/source/xnu/xnu-1699.26.8/osfmk/mach/i386/syscall_sw.h: * Syscall classes for 64-bit system call entry. * For 64-bit users, the 32-bit syscall number is partitioned * with the high-order bits representing the class and low-order * bits being the syscall number within that class. * The high-order 32-bits of the 64-bit syscall number are unused. * All system classes enter the kernel via the syscall instruction. * * These are not #ifdef'd for x86-64 because they might be used for * 32-bit someday and so the 64-bit comm page in a 32-bit kernel * can use them. * * shift = 24 * none: 0 * mach: 1 * unix: 2 * mdep: 3 * diag: 4 * ipc: 5 * class_mask = 0xFF << 24 * call = class << 24 & class_mask | id & !class_mask */ const CLASS_SHIFT: usize = 24; const CLASS_MASK: int_t = 0xFF << CLASS_SHIFT; const NUMBER_MASK: int_t = !CLASS_MASK; macro_rules! syscall { ($class:expr, $id:expr, $name:ident) => { #[inline(always)] #[no_mangle] pub unsafe extern fn $name() -> int_t { let mut ret: int_t = $class << CLASS_SHIFT | NUMBER_MASK & $id; asm!("syscall" : "+{rax}"(ret) : : "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" : "volatile"); ret } }; ($class:expr, $id:expr, $name:ident, $a:ty) => { #[inline(always)] #[no_mangle] pub unsafe extern fn $name(a: $a) -> int_t { let mut ret: int_t = $class << CLASS_SHIFT | NUMBER_MASK & $id; asm!("syscall" : "+{rax}"(ret) : "{rdi}"(a) : "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" : "volatile"); ret } }; ($class:expr, $id:expr, $name:ident, $a:ty, $b:ty) => { #[inline(always)] #[no_mangle] pub unsafe extern fn $name(a: $a, b: $b) -> int_t { let mut ret: int_t = $class << CLASS_SHIFT | NUMBER_MASK & $id; asm!("syscall" : "+{rax}"(ret) : "{rdi}"(a), "{rsi}"(b) : "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" : "volatile"); ret } }; ($class:expr, $id:expr, $name:ident, $a:ty, $b:ty, $c:ty) => { #[inline(always)] #[no_mangle] pub unsafe extern fn $name(a: $a, b: $b, c: $c) -> int_t { let mut ret: int_t = $class << CLASS_SHIFT | NUMBER_MASK & $id; asm!("syscall" : "+{rax}"(ret) : "{rdi}"(a), "{rsi}"(b), "{rdx}"(c) : "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" : "volatile"); ret } }; ($class:expr, $id:expr, $name:ident, $a:ty, $b:ty, $c:ty, $d:ty) => { #[inline(always)] #[no_mangle] pub unsafe extern fn $name(a: $a, b: $b, c: $c, d: $d) -> int_t { let mut ret: int_t = $class << CLASS_SHIFT | NUMBER_MASK & $id; asm!("syscall" : "+{rax}"(ret) : "{rdi}"(a), "{rsi}"(b), "{rdx}"(c), "{r10}"(d) : "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" : "volatile"); ret } }; ($class:expr, $id:expr, $name:ident, $a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => { #[inline(always)] #[no_mangle] pub unsafe extern fn $name(a: $a, b: $b, c: $c, d: $d, e: $e) -> int_t { let mut ret: int_t = $class << CLASS_SHIFT | NUMBER_MASK & $id; asm!("syscall" : "+{rax}"(ret) : "{rdi}"(a), "{rsi}"(b), "{rdx}"(c), "{r10}"(d) "{r8}"(e) : "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" : "volatile"); ret } }; ($class:expr, $id:expr, $name:ident, $a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => { #[inline(always)] #[no_mangle] pub unsafe extern fn $name(a: $a, b: $b, c: $c, d: $d, e: $e, f:$f) -> int_t { let mut ret: int_t = $class << CLASS_SHIFT | NUMBER_MASK & $id; asm!("syscall" : "+{rax}"(ret) : "{rdi}"(a), "{rsi}"(b), "{rdx}"(c), "{r10}"(d) "{r8}"(e), "{r9}"(f) : "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "memory" : "volatile"); ret } }; } // UNIX / BSD system calls: // assert sizeof(*mut) == user_addr_t syscall!(2, 000, sys_nosys); syscall!(2, 001, sys_exit, int_t); // -> void syscall!(2, 002, sys_fork); syscall!(2, 003, sys_read, uint_t, *mut char_t, size_t); syscall!(2, 004, sys_write, uint_t, *const char_t, size_t); // uint_t/int_t ??? syscall!(2, 005, sys_open, *const char_t, int_t, int_t); syscall!(2, 006, sys_close, uint_t); syscall!(2, 010, sys_unlink, *const char_t); syscall!(2, 020, sys_getpid); syscall!(2, 023, sys_setuid, uid_t); syscall!(2, 024, sys_getuid); syscall!(2, 025, sys_geteuid); syscall!(2, 037, sys_kill, int_t, int_t, int_t); syscall!(2, 073, sys_munmap, caddr_t, size_t); syscall!(2, 116, sys_gettimeofday, *mut timeval, *mut timezone); syscall!(2, 128, sys_rename, *const char_t, *const char_t); syscall!(2, 137, sys_rmdir, *const char_t); syscall!(2, 138, sys_utimes, *const char_t, *mut timeval); // WARNING *mut char_t syscall!(2, 147, sys_setsid); syscall!(2, 153, sys_pread, int_t, *mut char_t, size_t, off_t); syscall!(2, 154, sys_pwrite, int_t, *const char_t, size_t, off_t); syscall!(2, 181, sys_setgid, gid_t); syscall!(2, 193, sys_getrlimit, uint_t, *mut rlimit); syscall!(2, 194, sys_setrlimit, uint_t, *mut rlimit); syscall!(2, 197, sys_mmap, caddr_t, size_t, int_t, int_t, int_t, off_t); syscall!(2, 199, sys_lseek, int_t, off_t, int_t);
extern crate rustc_version; use rustc_version::{version_meta, Channel}; pub fn main() { let meta = version_meta().unwrap(); let channel = match meta.channel { Channel::Dev | Channel::Nightly => "nightly", Channel::Beta | Channel::Stable => "stable", }; println!("cargo:rustc-cfg={}_channel", channel); }
use core::{cell::RefCell, ops::DerefMut}; use cortex_m::interrupt::{free, CriticalSection, Mutex}; // Struct for easing the usage of mutexes and refcells to contain global variables pub struct GlobalCell<T> { cell: Mutex<RefCell<Option<T>>>, } impl<T> GlobalCell<T> { pub const fn new(value: Option<T>) -> Self { GlobalCell { cell: Mutex::new(RefCell::new(value)), } } pub fn put(&self, value: T) { free(|cs| self.put_cs(cs, value)); } pub fn put_cs(&self, cs: &CriticalSection, value: T) { // *self.cell.borrow(cs).borrow_mut() = Some(value); self.cell.borrow(cs).replace(Some(value)); // } pub fn try_borrow_mut<F, A>(&self, cs: &CriticalSection, mut f: F) -> Option<A> where F: FnMut(&mut T) -> Option<A>, { if let Some(ref mut value) = self.cell.borrow(cs).borrow_mut().deref_mut() { f(value) } else { None } } // pub fn borrow_mut<'cs>(&'cs self, cs: &'cs CriticalSection) -> &'cs mut Option<T>{ // &mut self.cell.borrow(cs).borrow_mut() // } // pub fn borrow_mut(&self, cs: &CriticalSection) -> & mut Option<T>{ // self.cell.borrow(cs).borrow_mut().deref_mut() // } }
// 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. #![allow(warnings)] use std::marker::PhantomData; use std::option::IntoIter; use zerocopy::AsBytes; struct IsAsBytes<T: AsBytes>(T); // Fail compilation if `$ty: !AsBytes`. macro_rules! is_as_bytes { ($ty:ty) => { const _: () = { let _: IsAsBytes<$ty>; }; }; } // A struct is AsBytes if: // - all fields are AsBytes // - repr(C) or repr(transparent) and // - no padding (size of struct equals sum of size of field types) // - repr(packed) #[derive(AsBytes)] #[repr(C)] struct CZst; is_as_bytes!(CZst); #[derive(AsBytes)] #[repr(C)] struct C { a: u8, b: u8, c: u16, } is_as_bytes!(C); #[derive(AsBytes)] #[repr(transparent)] struct Transparent { a: u8, b: CZst, } is_as_bytes!(Transparent); #[derive(AsBytes)] #[repr(C, packed)] struct CZstPacked; is_as_bytes!(CZstPacked); #[derive(AsBytes)] #[repr(C, packed)] struct CPacked { a: u8, b: u16, } is_as_bytes!(CPacked);
use crate::bgp::packet::MutableBgpHeaderPacket; use crate::bgp::packet::MutableBgpOpenPacket; use crate::bgp::packet::{BgpHeaderPacket, BgpOpenOptPacket, BgpOpenPacket, BgpTypes}; use crate::bgp::{Capabilities, Capability, Family, AFI_IP, BGP_HEADER_LEN, SAFI_MPLS_VPN}; use bytes::BytesMut; use pnet::packet::Packet; use std::io::{Error, ErrorKind}; use std::net::{Ipv4Addr, SocketAddr}; use tokio::net::TcpStream; use tokio_util::codec::{Decoder, Encoder}; pub struct Client {} #[derive(Debug)] pub enum Event { Accept((TcpStream, SocketAddr)), Connect(SocketAddr), TimerExpired, Packet(Message), } #[derive(Debug)] pub enum Message { Open(MessageOpen), RouteRefresh, OpenMessage, } #[derive(Debug)] pub struct MessageOpen { len: u16, version: u8, asn: u16, hold_time: u16, router_id: Ipv4Addr, caps: Capabilities, } impl MessageOpen { pub fn len(&self) -> usize { self.len as usize } pub fn from_bytes(buf: &[u8], len: u16) -> Result<Self, failure::Error> { let open = BgpOpenPacket::new(buf).ok_or(Error::from(ErrorKind::UnexpectedEof))?; let opt_param_len = open.get_opt_param_len() as usize; if opt_param_len < open.payload().len() { return Err(Error::from(ErrorKind::UnexpectedEof).into()); } let mut caps = Capabilities::new(); // Open message. if opt_param_len > 0 { let opt = BgpOpenOptPacket::new(open.payload()) .ok_or(Error::from(ErrorKind::UnexpectedEof))?; // When Open opt message is not capability(2) return here. if opt.get_typ() != 2 { return Err(Error::from(ErrorKind::UnexpectedEof).into()); } let mut len = opt.get_length() as usize; if len < opt.payload().len() { return Err(Error::from(ErrorKind::UnexpectedEof).into()); } // Parse Open capability message. let mut c = std::io::Cursor::new(opt.payload()); while len > 0 { let pos = c.position(); match Capability::from_bytes(&mut c) { Ok(cap) => caps.push(cap), Err(e) => { println!("XXX error {}", e); return Err(e); } } let diff = (c.position() - pos) as usize; if diff > len { return Err(Error::from(ErrorKind::UnexpectedEof).into()); } len -= diff; } println!("XXX caps {:?}", caps) } Ok(MessageOpen { len: len, version: open.get_version(), asn: open.get_asn(), hold_time: open.get_hold_time(), router_id: open.get_router_id(), caps: caps, }) } } // struct MessageUpdate {} // struct MessageKeepAlive {} // struct MessageRouteRefresh {} // struct MessageNotification {} impl Client { pub fn new(_stream: TcpStream, _saddr: SocketAddr) -> Self { Client { //stream: stream, //saddr: saddr, } } pub async fn keepalive_send(&mut self) { // Prepare BGP buffer with marker. let mut buf = [0u8; 4096]; for i in 0..16 { buf[i] = 0xff; } let mut packet = crate::bgp::packet::MutableBgpHeaderPacket::new(&mut buf[0..19]).unwrap(); packet.set_bgp_type(BgpTypes::KEEPALIVE); packet.set_length(19u16); // Open length. let buf = &buf[..19]; println!("Write {:?}", buf); //let _ = self.stream.write(buf).await; } } pub struct Bgp {} pub fn from_bytes(buf: &[u8]) -> Result<Event, failure::Error> { println!("XXX from_bytes len {}", buf.len()); let n = buf.len(); if n == 0 { println!("XXX read length is zero"); std::process::exit(1); } if n < 19 { // Need to read more. println!("BGP packet length is smaller than minimum length (19)."); return Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe).into()); } println!("Read num: {}", n); let packet = BgpHeaderPacket::new(&buf).unwrap(); let typ = packet.get_bgp_type(); let len = packet.get_length(); println!("Type {:?}", typ); println!("Length {:?}", len); match typ { BgpTypes::OPEN => { let msg = MessageOpen::from_bytes(packet.payload(), len)?; println!("MessageOpen {:?}", msg); return Ok(Event::Packet(Message::Open(msg))); } BgpTypes::UPDATE => { println!("Update message!"); } BgpTypes::NOTIFICATION => { println!("Notification message!"); } BgpTypes::KEEPALIVE => { println!("Keepalive message!"); } unknown => { println!("Unknown message type {:?}", unknown); } } println!("Length {:?}", len); return Ok(Event::TimerExpired); } impl Decoder for Bgp { type Item = Event; type Error = std::io::Error; fn decode(&mut self, src: &mut BytesMut) -> std::io::Result<Option<Event>> { match from_bytes(src) { Ok(Event::Packet(m)) => { let _ = src.split_to(m.len()); Ok(Some(Event::Packet(m))) } Ok(_) => { println!("unexpected Ok"); Ok(None) } Err(_) => Ok(None), } } } pub struct PeerConfig { asn: u32, hold_time: u16, } pub fn open_packet( config: &PeerConfig, caps: &Capabilities, buf: &mut [u8], ) -> Result<usize, failure::Error> { // Open. let len = MutableBgpOpenPacket::minimum_packet_size(); //let opt_len = open_option_packet(caps, &mut buf[len..])?; let opt_len = caps.to_bytes(&mut buf[len..])?; let mut open = MutableBgpOpenPacket::new(buf).unwrap(); open.set_version(4); open.set_asn(config.asn as u16); open.set_hold_time(config.hold_time); let router_id: std::net::Ipv4Addr = "10.0.0.1".parse().unwrap(); open.set_router_id(router_id); open.set_opt_param_len(opt_len as u8); Ok(len + opt_len) } impl Message { // Used by decode. pub fn len(&self) -> usize { match self { Message::Open(m) => m.len(), Message::RouteRefresh => 0, Message::OpenMessage => 0, } } // Called from encode(). pub fn to_bytes(self) -> Result<Vec<u8>, failure::Error> { let mut buf = [0u8; 4096]; let mut len: usize = BGP_HEADER_LEN; // Open Specific. { // Capability. let mut caps = Capabilities::new(); let cap_afi = Capability::MultiProtocol(Family { afi: AFI_IP, safi: SAFI_MPLS_VPN, }); caps.push(cap_afi); // Open Parameters. let config = PeerConfig { asn: 1, hold_time: 90, }; // Open encode. len += open_packet(&config, &caps, &mut buf[len..])?; } // BGP Header. for i in 0..16 { buf[i] = 0xff; } let mut header = MutableBgpHeaderPacket::new(&mut buf[..len]).unwrap(); header.set_bgp_type(BgpTypes::OPEN); header.set_length(len as u16); Ok((&buf[..len]).to_vec()) } } impl Encoder for Bgp { type Item = Message; type Error = failure::Error; fn encode(&mut self, msg: Message, dst: &mut BytesMut) -> Result<(), failure::Error> { let buf = msg.to_bytes()?; dst.extend_from_slice(&buf); Ok(()) } }
//! The setups available for any `TestCase` to use by specifying the test name in a comment at the //! start of the `.sql` file in the form of: //! //! ```text //! -- IOX_SETUP: [test name] //! ``` use futures_util::FutureExt; use influxdb_iox_client::table::generated_types::{Part, PartitionTemplate, TemplatePart}; use iox_time::{SystemProvider, Time, TimeProvider}; use once_cell::sync::Lazy; use std::collections::HashMap; use test_helpers_end_to_end::{Step, StepTestState}; /// The string value that will appear in `.sql` files. pub type SetupName = &'static str; /// The steps that should be run when this setup is chosen. pub type SetupSteps = Vec<Step>; /// timestamps for the retention test static RETENTION_SETUP: Lazy<RetentionSetup> = Lazy::new(RetentionSetup::new); /// All possible setups for the [`TestCase`][crate::TestCase]s to use, indexed by name pub static SETUPS: Lazy<HashMap<SetupName, SetupSteps>> = Lazy::new(|| { HashMap::from([ ( "Bugs", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ r#"checks,id=1,method=POST,name=Writes,url="https://example.com",user_id=1 elapsed=66909i,status=204i 1678578528255989730"#, r#"checks,id=1,method=POST,name=Writes,url="https://example.com",user_id=1 elapsed=112928i,status=204i 1678578532192972168"#, r#"checks,id=1,method=POST,name=Writes,url="https://example.com",user_id=1 elapsed=147683i,status=204i 1678578588416052133"#, r#"checks,id=1,method=POST,name=Writes,url="https://example.com",user_id=1 elapsed=78000i,status=204i 1678578592147893402"#, ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwoMeasurements", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "cpu,region=west user=23.2 100", "cpu,region=west user=21.0 150", "disk,region=east bytes=99i 200", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 2, }, ], ), ( "TwoChunksDedupWeirdnessParquet", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol("table,tag=A foo=1,bar=1 0".into()), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol(["table,tag=A bar=2 0", "table,tag=B foo=1 0"].join("\n")), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwoChunksDedupWeirdnessParquetIngester", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol("table,tag=A foo=1,bar=1 0".into()), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::WriteLineProtocol(["table,tag=A bar=2 0", "table,tag=B foo=1 0"].join("\n")), ], ), ( "OneMeasurementFourChunksWithDuplicatesWithIngester", vec![ Step::RecordNumParquetFiles, // Chunk 1: // . time range: 50-250 // . no duplicates in its own chunk Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston min_temp=70.4 50", "h2o,state=MA,city=Bedford min_temp=71.59 150", "h2o,state=MA,city=Boston max_temp=75.4 250", "h2o,state=MA,city=Andover max_temp=69.2, 250", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, // Chunk 2: overlaps with chunk 1 // . time range: 150 - 300 // . no duplicates in its own chunk Step::WriteLineProtocol( [ // new field (area) and update available NULL (max_temp) "h2o,state=MA,city=Bedford max_temp=78.75,area=742u 150", "h2o,state=MA,city=Boston min_temp=65.4 250", // update min_temp from NULL "h2o,state=MA,city=Reading min_temp=53.4, 250", "h2o,state=CA,city=SF min_temp=79.0,max_temp=87.2,area=500u 300", "h2o,state=CA,city=SJ min_temp=78.5,max_temp=88.0 300", "h2o,state=CA,city=SJ min_temp=75.5,max_temp=84.08 350", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, // Chunk 3: no overlap // . time range: 400 - 500 // . duplicates in its own chunk Step::WriteLineProtocol( [ "h2o,state=MA,city=Bedford max_temp=80.75,area=742u 400", "h2o,state=MA,city=Boston min_temp=68.4 400", "h2o,state=MA,city=Bedford min_temp=65.22,area=750u 400", // duplicate "h2o,state=MA,city=Boston min_temp=65.40,max_temp=82.67 400", // duplicate "h2o,state=CA,city=SJ min_temp=77.0,max_temp=90.7 450", "h2o,state=CA,city=SJ min_temp=69.5,max_temp=88.2 500", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, // Chunk 4: no overlap // . time range: 600 - 700 // . no duplicates Step::WriteLineProtocol( [ "h2o,state=MA,city=Bedford max_temp=88.75,area=742u 600", "h2o,state=MA,city=Boston min_temp=67.4 600", "h2o,state=MA,city=Reading min_temp=60.4, 600", "h2o,state=CA,city=SF min_temp=68.4,max_temp=85.7,area=500u 650", "h2o,state=CA,city=SJ min_temp=69.5,max_temp=89.2 650", "h2o,state=CA,city=SJ min_temp=75.5,max_temp=84.08 700", ] .join("\n"), ), ], ), ( "OneMeasurementFourChunksWithDuplicatesParquetOnly", vec![ Step::RecordNumParquetFiles, // Chunk 1: // . time range: 50-250 // . no duplicates in its own chunk Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston min_temp=70.4 50", "h2o,state=MA,city=Bedford min_temp=71.59 150", "h2o,state=MA,city=Boston max_temp=75.4 250", "h2o,state=MA,city=Andover max_temp=69.2, 250", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, // Chunk 2: overlaps with chunk 1 // . time range: 150 - 300 // . no duplicates in its own chunk Step::WriteLineProtocol( [ // new field (area) and update available NULL (max_temp) "h2o,state=MA,city=Bedford max_temp=78.75,area=742u 150", "h2o,state=MA,city=Boston min_temp=65.4 250", // update min_temp from NULL "h2o,state=MA,city=Reading min_temp=53.4, 250", "h2o,state=CA,city=SF min_temp=79.0,max_temp=87.2,area=500u 300", "h2o,state=CA,city=SJ min_temp=78.5,max_temp=88.0 300", "h2o,state=CA,city=SJ min_temp=75.5,max_temp=84.08 350", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, // Chunk 3: no overlap // . time range: 400 - 500 // . duplicates in its own chunk Step::WriteLineProtocol( [ "h2o,state=MA,city=Bedford max_temp=80.75,area=742u 400", "h2o,state=MA,city=Boston min_temp=68.4 400", "h2o,state=MA,city=Bedford min_temp=65.22,area=750u 400", // duplicate "h2o,state=MA,city=Boston min_temp=65.40,max_temp=82.67 400", // duplicate "h2o,state=CA,city=SJ min_temp=77.0,max_temp=90.7 450", "h2o,state=CA,city=SJ min_temp=69.5,max_temp=88.2 500", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, // Chunk 4: no overlap // . time range: 600 - 700 // . no duplicates Step::WriteLineProtocol( [ "h2o,state=MA,city=Bedford max_temp=88.75,area=742u 600", "h2o,state=MA,city=Boston min_temp=67.4 600", "h2o,state=MA,city=Reading min_temp=60.4, 600", "h2o,state=CA,city=SF min_temp=68.4,max_temp=85.7,area=500u 650", "h2o,state=CA,city=SJ min_temp=69.5,max_temp=89.2 650", "h2o,state=CA,city=SJ min_temp=75.5,max_temp=84.08 700", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwentySortedParquetFiles", (0..20) .flat_map(|i| { let write = if i % 2 == 0 { Step::WriteLineProtocol(format!( "m,tag=A f=1 {}\nm,tab=B f=2 {}", 1000 - i, // unique in this chunk 1000 - i, // unique in this chunk (not plus i!) )) } else { Step::WriteLineProtocol( "m,tag=A f=3 2001".into(), // duplicated across all chunks ) }; [ Step::RecordNumParquetFiles, write, Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ] .into_iter() }) .collect::<Vec<_>>(), ), ( "TwentySortedParquetFilesAndIngester", (0..20) .flat_map(|i| { let write = if i % 2 == 0 { Step::WriteLineProtocol(format!( "m,tag=A f=1 {}\nm,tab=B f=2 {}", 1000 - i, // unique in this chunk 1000 - i, // unique in this chunk (not plus i!) )) } else { Step::WriteLineProtocol( "m,tag=A f=3 2001".into(), // duplicated across all chunks ) }; [ Step::RecordNumParquetFiles, write, Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ] .into_iter() }).chain([ Step::WriteLineProtocol( "m,tag=A f=3 2001".into(), // duplicated across all chunks ) ]) .collect::<Vec<_>>(), ), ( "FiftySortedSameParquetFiles", (0..50) .flat_map(|_i| { let write = Step::WriteLineProtocol( "m,tag1=A,tag2=B,tag3=C,tag4=D f1=1,f2=2 2001".into(), // duplicated across all chunks ); [ Step::RecordNumParquetFiles, write, Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ] .into_iter() }) .collect::<Vec<_>>(), ), ( "OneMeasurementManyFields", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,tag1=foo,tag2=bar field1=70.6,field3=2 100", "h2o,tag1=foo,tag2=bar field1=70.4,field2=\"ss\" 100", "h2o,tag1=foo,tag2=bar field1=70.5,field2=\"ss\" 100", "h2o,tag1=foo,tag2=bar field1=70.6,field4=true 1000", "h2o,tag1=foo,tag2=bar field1=70.3,field5=false 3000", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwoMeasurementsManyFields", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=70.4 50", "h2o,state=MA,city=Boston other_temp=70.4 250", "h2o,state=CA,city=Boston other_temp=72.4 350", "o2,state=MA,city=Boston temp=53.4,reading=51 50", "o2,state=CA temp=79.0 300", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 2, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( "h2o,state=MA,city=Boston temp=70.4,moisture=43.0 100000".into(), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwoMeasurementsManyFieldsTwoChunks", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=70.4 50", "h2o,state=MA,city=Boston other_temp=70.4 250", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::WriteLineProtocol( [ "h2o,state=CA,city=Boston other_temp=72.4 150", "o2,state=MA,city=Boston temp=53.4,reading=51 50", "o2,state=CA temp=79.0 300", ] .join("\n"), ), // The system tables test looks for queries, so the setup needs to run this query. Step::Query { sql: "SELECT 1;".into(), expected: vec![ "+----------+", "| Int64(1) |", "+----------+", "| 1 |", "+----------+", ], }, ], ), ( "TwoMeasurementsManyNulls", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=CA,city=LA,county=LA temp=70.4 100", "h2o,state=MA,city=Boston,county=Suffolk temp=72.4 250", "o2,state=MA,city=Boston temp=50.4 200", "o2,state=CA temp=79.0 300", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 2, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "o2,state=NY temp=60.8 400", "o2,state=NY,city=NYC temp=61.0 500", "o2,state=NY,city=NYC,borough=Brooklyn temp=61.0 600", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "OneMeasurementWithTags", vec![Step::WriteLineProtocol( [ "cpu,foo=me bar=1 10", "cpu,foo=you bar=2 20", "cpu,foo=me bar=1 30", "cpu,foo=me bar=1 40", ] .join("\n"), )], ), ( "EqualInMeasurements", vec![Step::WriteLineProtocol( [ "measurement=one,tag=value field=1.0 \ 1609459201000000001", "measurement=one,tag=value2 field=1.0 \ 1609459201000000002", ] .join("\n"), )], ), ( "PeriodsInNames", vec![Step::WriteLineProtocol( [ "measurement.one,tag.one=value,tag.two=other field.one=1.0,field.two=t \ 1609459201000000001", "measurement.one,tag.one=value2,tag.two=other2 field.one=1.0,field.two=f \ 1609459201000000002", ] .join("\n"), )], ), ( "TwoMeasurementsPredicatePushDown", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "restaurant,town=andover count=40000u,system=5.0 100", "restaurant,town=reading count=632u,system=5.0 120", "restaurant,town=bedford count=189u,system=7.0 110", "restaurant,town=tewsbury count=471u,system=6.0 110", "restaurant,town=lexington count=372u,system=5.0 100", "restaurant,town=lawrence count=872u,system=6.0 110", "restaurant,town=reading count=632u,system=6.0 130", ] .join("\n"), ), Step::WriteLineProtocol( [ "school,town=reading count=17u,system=6.0 150", "school,town=andover count=25u,system=6.0 160", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 2, }, ], ), ( "AllTypes", vec![Step::WriteLineProtocol( [ "m,tag=row1 float_field=64.0 450", "m,tag=row1 int_field=64 550", "m,tag=row1 \ float_field=61.0,int_field=22,uint_field=25u,\ string_field=\"foo\",bool_field=t 500", "m,tag=row1 \ float_field=62.0,int_field=21,uint_field=30u,\ string_field=\"ba\",bool_field=f 200", "m,tag=row1 \ float_field=63.0,int_field=20,uint_field=35u,\ string_field=\"baz\",bool_field=f 300", "m,tag=row1 \ float_field=64.0,int_field=19,uint_field=20u,\ string_field=\"bar\",bool_field=t 400", "m,tag=row1 \ float_field=65.0,int_field=18,uint_field=40u,\ string_field=\"fruz\",bool_field=f 100", "m,tag=row1 \ float_field=66.0,int_field=17,uint_field=10u,\ string_field=\"faa\",bool_field=t 600", ] .join("\n"), )], ), ( "ManyFieldsSeveralChunks", vec![ Step::RecordNumParquetFiles, // c1: parquet stage Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=70.4 50", // duplicate with a row in c4 and will be removed "h2o,state=MA,city=Boston other_temp=70.4 250", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, // c2: parquet stage & overlaps with c1 Step::WriteLineProtocol("h2o,state=CA,city=Andover other_temp=72.4 150".into()), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, // c3: parquet stage & doesn't overlap with any Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=80.7 350", "h2o,state=MA,city=Boston other_temp=68.2 450", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, // c4: parquet stage & overlap with c1 Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=88.6 230", // duplicate with a row in c1 but more // recent => this row is kept "h2o,state=MA,city=Boston other_temp=80 250", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, // c5: ingester stage & doesn't overlap with any Step::WriteLineProtocol("h2o,state=CA,city=Andover temp=67.3 500".into()), ], ), ( "MeasurementWithMaxTime", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol(format!( "cpu,host=server01 value=100 {}", // This is the maximum timestamp that can be represented in the InfluxDB data // model: // <https://github.com/influxdata/influxdb/blob/540bb66e1381a48a6d1ede4fc3e49c75a7d9f4af/models/time.go#L12-L34> i64::MAX - 1, // 9223372036854775806 )), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "OneMeasurementRealisticTimes", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "cpu,region=west user=23.2 1626809330000000000", "cpu,region=west user=21.0 1626809430000000000", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "OneMeasurementTwoSeries", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "cpu,region=a user=23.2,idle=70.0 957529200000000000", // 2000-05-05T12:20:00Z "cpu,region=b user=25.2 957529860000000000", // 2000-05-05T12:31:00Z "cpu,region=b user=28.9,idle=60.0 957530340000000000", // 2000-05-05T12:39:00Z "cpu,region=a user=21.0 957530400000000000", // 2000-05-05T12:40:00Z ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwoChunksMissingColumns", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol("table,tag1=a,tag2=b field1=10,field2=11 100".into()), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol("table,tag1=a,tag3=c field1=20,field3=22 200".into()), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwoMeasurementsMultiSeries", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ // Data is deliberately not in series order. "h2o,state=CA,city=LA temp=90.0 200", "h2o,state=MA,city=Boston temp=72.4 250", "h2o,state=MA,city=Boston temp=70.4 100", "h2o,state=CA,city=LA temp=90.0 350", "o2,state=MA,city=Boston temp=53.4,reading=51 250", "o2,state=MA,city=Boston temp=50.4,reading=50 100", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 2, }, ], ), ( // This recreates the test case for <https://github.com/influxdata/idpe/issues/16238>. "StringFieldWithNumericValue", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( ["m,tag0=foo fld=\"200\" 1000", "m,tag0=foo fld=\"404\" 1050"].join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "MeasurementStatusCode", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "status_code,url=http://www.example.com value=404 1527018806000000000", "status_code,url=https://influxdb.com value=418 1527018816000000000", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwoMeasurementsMultiTagValue", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=70.4 100", "h2o,state=MA,city=Lowell temp=75.4 100", "h2o,state=CA,city=LA temp=90.0 200", "o2,state=MA,city=Boston temp=50.4,reading=50 100", "o2,state=KS,city=Topeka temp=60.4,reading=60 100", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 2, }, ], ), ( "MeasurementsSortableTags", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,zz_tag=A,state=MA,city=Kingston temp=70.1 800", "h2o,state=MA,city=Kingston,zz_tag=B temp=70.2 100", "h2o,state=CA,city=Boston temp=70.3 250", "h2o,state=MA,city=Boston,zz_tag=A temp=70.4 1000", "h2o,state=MA,city=Boston temp=70.5,other=5.0 250", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( // See issue: https://github.com/influxdata/influxdb_iox/issues/2845 "MeasurementsForDefect2845", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "system,host=host.local load1=1.83 1527018806000000000", "system,host=host.local load1=1.63 1527018816000000000", "system,host=host.local load3=1.72 1527018806000000000", "system,host=host.local load4=1.77 1527018806000000000", "system,host=host.local load4=1.78 1527018816000000000", "system,host=host.local load4=1.77 1527018826000000000", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "EndToEndTest", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "cpu_load_short,host=server01,region=us-west value=0.64 0000", "cpu_load_short,host=server01 value=27.99 1000", "cpu_load_short,host=server02,region=us-west value=3.89 2000", "cpu_load_short,host=server01,region=us-east value=1234567.891011 3000", "cpu_load_short,host=server01,region=us-west value=0.000003 4000", "system,host=server03 uptime=1303385 5000", "swap,host=server01,name=disk0 in=3,out=4 6000", "status active=t 7000", "attributes color=\"blue\" 8000", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 5, }, ], ), ( "OneMeasurementNoTags", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o temp=70.4 100", "h2o temp=72.4 250", "h2o temp=50.4 200", "h2o level=200.0 300", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "OneMeasurementNoTags2", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol(["m0 foo=1.0 1", "m0 foo=2.0 2"].join("\n")), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "OneMeasurementForAggs", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=70.4 100", "h2o,state=MA,city=Boston temp=72.4 250", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=CA,city=LA temp=90.0 200", "h2o,state=CA,city=LA temp=90.0 350", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwoMeasurementForAggs", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=70.4 100", "h2o,state=MA,city=Boston temp=72.4 250", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "o2,state=CA,city=LA temp=90.0 200", "o2,state=CA,city=LA temp=90.0 350", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "AnotherMeasurementForAggs", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Cambridge temp=80 50", "h2o,state=MA,city=Cambridge temp=81 100", "h2o,state=MA,city=Cambridge temp=82 200", "h2o,state=MA,city=Boston temp=70 300", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=71 400", "h2o,state=CA,city=LA temp=90,humidity=10 500", "h2o,state=CA,city=LA temp=91,humidity=11 600", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "MeasurementForSelectors", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( ["h2o,state=MA,city=Cambridge f=8.0,i=8i,b=true,s=\"d\" 1000"].join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Cambridge f=7.0,i=7i,b=true,s=\"c\" 2000", "h2o,state=MA,city=Cambridge f=6.0,i=6i,b=false,s=\"b\" 3000", "h2o,state=MA,city=Cambridge f=5.0,i=5i,b=false,s=\"a\" 4000", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "MeasurementForMin", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Cambridge f=8.0,i=8i,b=false,s=\"c\" 1000", "h2o,state=MA,city=Cambridge f=7.0,i=7i,b=true,s=\"a\" 2000", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Cambridge f=6.0,i=6i,b=true,s=\"z\" 3000", "h2o,state=MA,city=Cambridge f=5.0,i=5i,b=false,s=\"c\" 4000", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "MeasurementForMax", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Cambridge f=8.0,i=8i,b=true,s=\"c\" 1000", "h2o,state=MA,city=Cambridge f=7.0,i=7i,b=false,s=\"d\" 2000", "h2o,state=MA,city=Cambridge f=6.0,i=6i,b=true,s=\"a\" 3000", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( ["h2o,state=MA,city=Cambridge f=5.0,i=5i,b=false,s=\"z\" 4000"].join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "MeasurementForGroupKeys", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Cambridge temp=80 50", "h2o,state=MA,city=Cambridge temp=81 100", "h2o,state=MA,city=Cambridge temp=82 200", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=70 300", "h2o,state=MA,city=Boston temp=71 400", "h2o,state=CA,city=LA temp=90,humidity=10 500", "h2o,state=CA,city=LA temp=91,humidity=11 600", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "MeasurementForGroupByField", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "system,host=local,region=A load1=1.1,load2=2.1 100", "system,host=local,region=A load1=1.2,load2=2.2 200", "system,host=remote,region=B load1=10.1,load2=2.1 100", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "system,host=remote,region=B load1=10.2,load2=20.2 200", "system,host=local,region=C load1=100.1,load2=200.1 100", "aa_system,host=local,region=C load1=100.1,load2=200.1 100", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwoMeasurementsManyFieldsOneChunk", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=70.4 50", "h2o,state=MA,city=Boston other_temp=70.4 250", "h2o,state=CA,city=Boston other_temp=72.4 350", "o2,state=MA,city=Boston temp=53.4,reading=51 50", "o2,state=CA temp=79.0 300", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 2, }, ], ), ( "MeasurementForDefect2691", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "system,host=host.local load1=1.83 1527018806000000000", "system,host=host.local load1=1.63 1527018816000000000", "system,host=host.local load3=1.72 1527018806000000000", "system,host=host.local load4=1.77 1527018806000000000", "system,host=host.local load4=1.78 1527018816000000000", "system,host=host.local load4=1.77 1527018826000000000", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "MeasurementForWindowAggregate", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Boston temp=70.0 100", "h2o,state=MA,city=Boston temp=71.0 200", "h2o,state=MA,city=Boston temp=72.0 300", "h2o,state=MA,city=Boston temp=73.0 400", "h2o,state=MA,city=Boston temp=74.0 500", "h2o,state=MA,city=Cambridge temp=80.0 100", "h2o,state=MA,city=Cambridge temp=81.0 200", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "h2o,state=MA,city=Cambridge temp=82.0 300", "h2o,state=MA,city=Cambridge temp=83.0 400", "h2o,state=MA,city=Cambridge temp=84.0 500", "h2o,state=CA,city=LA temp=90.0 100", "h2o,state=CA,city=LA temp=91.0 200", "h2o,state=CA,city=LA temp=92.0 300", "h2o,state=CA,city=LA temp=93.0 400", "h2o,state=CA,city=LA temp=94.0 500", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( // Test data to validate fix for // <https://github.com/influxdata/influxdb_iox/issues/2697> "MeasurementForDefect2697", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "mm,section=1a bar=5.0 1609459201000000011", "mm,section=1a bar=0.28 1609459201000000031", "mm,section=2b bar=4.0 1609459201000000009", "mm,section=2b bar=6.0 1609459201000000015", "mm,section=2b bar=1.2 1609459201000000022", "mm,section=1a foo=1.0 1609459201000000001", "mm,section=1a foo=3.0 1609459201000000005", "mm,section=1a foo=11.24 1609459201000000024", "mm,section=2b foo=2.0 1609459201000000002", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "ThreeChunksWithRetention", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol(RETENTION_SETUP.lp_partially_inside_1.clone()), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol(RETENTION_SETUP.lp_fully_inside.clone()), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol(RETENTION_SETUP.lp_fully_outside.clone()), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::WriteLineProtocol(RETENTION_SETUP.lp_partially_inside_2.clone()), Step::SetRetention(Some(RETENTION_SETUP.retention_period_ns)), ], ), ( // Test data to validate fix for // <https://github.com/influxdata/influxdb_iox/issues/2890> "MeasurementForDefect2890", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "mm foo=2.0 1609459201000000001", "mm foo=2.0 1609459201000000002", "mm foo=3.0 1609459201000000005", "mm foo=11.24 1609459201000000024", "mm bar=4.0 1609459201000000009", "mm bar=5.0 1609459201000000011", "mm bar=6.0 1609459201000000015", "mm bar=1.2 1609459201000000022", "mm bar=2.8 1609459201000000031", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( // Single measurement that has several different chunks with different (but // compatible) schemas "MultiChunkSchemaMerge", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "cpu,region=west user=23.2,system=5.0 100", "cpu,region=west user=21.0,system=6.0 150", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "cpu,region=east,host=foo user=23.2 100", "cpu,region=west,host=bar user=21.0 250", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "TwoMeasurementsUnsignedType", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ "restaurant,town=andover count=40000u 100", "restaurant,town=reading count=632u 120", "school,town=reading count=17u 150", "school,town=andover count=25u 160", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( // This has two chunks with different tag/key sets for queries whose columns do not // include keys "OneMeasurementTwoChunksDifferentTagSet", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ // tag: state "h2o,state=MA temp=70.4 50", "h2o,state=MA other_temp=70.4 250", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ // tag: city "h2o,city=Boston other_temp=72.4 350", "h2o,city=Boston temp=53.4,reading=51 50", ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( // This is the dataset defined by https://github.com/influxdata/influxdb_iox/issues/6112 "InfluxQLSelectSupport", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( r#" m0,tag0=val00 f64=10.1,i64=101i,str="hi" 1667181600000000000 m0,tag0=val00 f64=21.2,i64=211i,str="hi" 1667181610000000000 m0,tag0=val00 f64=11.2,i64=191i,str="lo" 1667181620000000000 m0,tag0=val00 f64=19.2,i64=392i,str="lo" 1667181630000000000 m0,tag0=val01 f64=11.3,i64=211i,str="lo" 1667181600000000000 m0,tag0=val02 f64=10.4,i64=101i,str="lo" 1667181600000000000 m0,tag0=val00,tag1=val10 f64=18.9,i64=211i,str="lo" 1667181610000000000 m1,tag0=val00 f64=100.5,i64=1001i,str="hi" 1667181600000000000 m1,tag0=val00 f64=200.6,i64=2001i,str="lo" 1667181610000000000 m1,tag0=val01 f64=101.7,i64=1011i,str="lo" 1667181600000000000 cpu,host=host1,cpu=cpu-total usage_idle=2.98,usage_system=2.2 1667181600000000000 cpu,host=host1,cpu=cpu-total usage_idle=2.99,usage_system=2.1 1667181610000000000 cpu,host=host1,cpu=cpu0 usage_idle=0.98,usage_system=0.2 1667181600000000000 cpu,host=host1,cpu=cpu0 usage_idle=0.99,usage_system=0.1 1667181610000000000 cpu,host=host1,cpu=cpu1 usage_idle=1.98,usage_system=1.2 1667181600000000000 cpu,host=host1,cpu=cpu1 usage_idle=1.99,usage_system=1.1 1667181610000000000 disk,host=host1,device=disk1s1 bytes_free=1234i,bytes_used=219838i 1667181600000000000 disk,host=host1,device=disk1s1 bytes_free=1239i,bytes_used=219833i 1667181610000000000 disk,host=host1,device=disk1s2 bytes_free=2234i,bytes_used=319838i 1667181600000000000 disk,host=host1,device=disk1s2 bytes_free=2239i,bytes_used=319833i 1667181610000000000 disk,host=host1,device=disk1s5 bytes_free=3234i,bytes_used=419838i 1667181600000000000 disk,host=host1,device=disk1s5 bytes_free=3239i,bytes_used=419833i 1667181610000000000 m2,tag0=val00 f64=0.98 1667181600000000000 m2,tag0=val02 f64=1.98 1667181600000000000 m2,tag0=val01 f64=2.98 1667181600000000000 m2,tag0=val05 f64=3.98 1667181600000000000 m2,tag0=val03 f64=4.98 1667181600000000000 m2,tag0=val09 f64=5.98 1667181600000000000 m2,tag0=val10 f64=6.98 1667181600000000000 m2,tag0=val08 f64=7.98 1667181600000000000 m2,tag0=val07 f64=8.98 1667181600000000000 m2,tag0=val04 f64=9.98 1667181600000000000 m3,tag0=a,tag1=b,tag2=c,tag3=d u64=1u 1667181600000000000 m4,tag.one=foo field.one=1 1667181600000000000 time_test,tt_tag=before_default_cutoff,tt_tag_before_default_cutoff=a tt_field="before_default_cutoff",tt_field_before_default_cutoff=1 631151999999999999 time_test,tt_tag=at_default_cutoff,tt_tag_at_default_cutoff=a tt_field="at_default_cutoff",tt_field_at_default_cutoff=1 631152000000000000 time_test,tt_tag=late,tt_tag_late=1 tt_field="late",tt_field_late=1 1667181600000000000 select_test,tag0=a,tag1=a,st_tag=aa,st_tag_aa=x st_field="aa",st_field_aa=1 1667181600000000000 select_test,tag0=a,tag1=b,st_tag=ab,st_tag_ab=x st_field="ab",st_field_ab=1 1667181600000000000 select_test,tag0=b,tag1=a,st_tag=ba,st_tag_ba=x st_field="ba",st_field_ba=1 1667181600000000000 select_test,tag0=b,tag1=b,st_tag=bb,st_tag_bb=x st_field="bb",st_field_bb=1 1667181600000000000 selector_test_1,tag1=a field1=1 1 selector_test_1,tag2=b field2=2 2 selector_test_1,tag3=c field3=3 3 selector_test_2,first=a f=1 1 "# .to_string(), ), Step::Persist, Step::WaitForPersisted { expected_increase: 2, }, ], ), ( // Used for window-like function tests for InfluxQL "window_like", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( include_str!("data/window_like.lp").to_string() ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( // Used for top/bottom function tests for InfluxQL "top_bottom", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( include_str!("data/top_bottom.lp").to_string() ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( // Used for percentile function tests for InfluxQL "percentile", vec![ Step::RecordNumParquetFiles, Step::WriteLineProtocol( include_str!("data/percentile.lp").to_string() ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ], ), ( "DuplicateDifferentDomains", (0..2) .flat_map(|_| { [ Step::RecordNumParquetFiles, Step::WriteLineProtocol( r#" m,tag=A f=1 0 m,tag=A f=2 86400000000000 "#.into(), ), Step::Persist, Step::WaitForPersisted { expected_increase: 2, }, Step::RecordNumParquetFiles, Step::WriteLineProtocol( r#" m,tag=A f=3 1 "#.into(), ), Step::Persist, Step::WaitForPersisted { expected_increase: 1, }, ] .into_iter() }) .collect::<Vec<_>>(), ), ( "CustomPartitioning", [ Step::Custom(Box::new(move |state: &mut StepTestState| { async move { let namespace_name = state.cluster().namespace(); let mut namespace_client = influxdb_iox_client::namespace::Client::new( state.cluster().router().router_grpc_connection(), ); namespace_client .create_namespace(namespace_name, None, None, Some(PartitionTemplate{ parts: vec![ TemplatePart{ part: Some(Part::TagValue("tag1".into())), }, TemplatePart{ part: Some(Part::TagValue("tag3".into())), }, ], })) .await .unwrap(); let mut table_client = influxdb_iox_client::table::Client::new( state.cluster().router().router_grpc_connection(), ); // table1: create implicitly by writing to it // table2: do not override partition template => use namespace template table_client.create_table( namespace_name, "table2", None, ).await.unwrap(); // table3: overide namespace template table_client.create_table( namespace_name, "table3", Some(PartitionTemplate{ parts: vec![ TemplatePart{ part: Some(Part::TagValue("tag2".into())), }, ], }), ).await.unwrap(); } .boxed() })), ].into_iter() .chain( (1..=3).flat_map(|tid| { [ Step::RecordNumParquetFiles, Step::WriteLineProtocol( [ format!("table{tid},tag1=v1a,tag2=v2a,tag3=v3a f=1 11"), format!("table{tid},tag1=v1b,tag2=v2a,tag3=v3a f=1 11"), format!("table{tid},tag1=v1a,tag2=v2b,tag3=v3a f=1 11"), format!("table{tid},tag1=v1b,tag2=v2b,tag3=v3a f=1 11"), format!("table{tid},tag1=v1a,tag2=v2a,tag3=v3b f=1 11"), format!("table{tid},tag1=v1b,tag2=v2a,tag3=v3b f=1 11"), format!("table{tid},tag1=v1a,tag2=v2b,tag3=v3b f=1 11"), format!("table{tid},tag1=v1b,tag2=v2b,tag3=v3b f=1 11"), ] .join("\n"), ), Step::Persist, Step::WaitForPersisted { expected_increase: match tid { 1 => 4, 2 => 4, 3 => 2, _ => unreachable!(), }, }, ].into_iter() }) ) .collect(), ), ]) }); /// Holds parameters for retention period. Tests based on this need to /// be run within the hour of being created. /// /// ```text (cut off) (now) /// time: -----------------------|--------------------------|> /// /// partially_inside: |-----------------| /// /// fully_inside: +1h |-----------| /// /// fully_outside: |---------| /// ``` /// /// Note this setup is only good for 1 hour after it was created. struct RetentionSetup { /// the retention period, relative to now() that the three data /// chunks fall inside/outside retention_period_ns: i64, /// lineprotocol data partially inside retention lp_partially_inside_1: String, /// lineprotocol data partially inside retention lp_partially_inside_2: String, /// lineprotocol data fully inside (included in query) lp_fully_inside: String, /// lineprotocol data fully outside (excluded from query) lp_fully_outside: String, } impl RetentionSetup { fn new() -> Self { let retention_period_1_hour_ns = 3600 * 1_000_000_000; // Data is relative to this particular time stamp // // Use a cutoff date that is NOT at the start of the partition so that `lp_partially_inside` only spans a single // partition, not two. This is important because otherwise this will result in two chunks / files, not one. // However a partial inside/outside chunk is important for the query tests so that we can proof that it is not // sufficient to prune the chunks solely on statistics but that there needs to be an actual row-wise filter. let cutoff = Time::from_rfc3339("2022-01-01T10:00:00+00:00") .unwrap() .timestamp_nanos(); // Timestamp 1 hour later than the cutoff, so the data will be retained for 1 hour let inside_retention = cutoff + retention_period_1_hour_ns; let outside_retention = cutoff - 10; // before retention let lp_partially_inside_1 = format!( "cpu,host=a load=1 {inside_retention}\n\ cpu,host=aa load=11 {outside_retention}" ); let lp_fully_inside = format!( "cpu,host=b load=2 {inside_retention}\n\ cpu,host=bb load=21 {inside_retention}" ); let lp_fully_outside = format!( "cpu,host=c load=3 {outside_retention}\n\ cpu,host=cc load=31 {outside_retention}" ); let lp_partially_inside_2 = format!( "cpu,host=d load=4 {inside_retention}\n\ cpu,host=dd load=41 {outside_retention}" ); // Set retention period to be at the cutoff date. Note that // since real world time advances, after 1 hour of real world // time the data that is inside the retention interval will // move outside (and thus not appear in queries). // // Thus this setup is only valid for 1 hour. let retention_period_ns = SystemProvider::new().now().timestamp_nanos() - cutoff; Self { // translate the retention period to be relative to now retention_period_ns, lp_partially_inside_1, lp_partially_inside_2, lp_fully_inside, lp_fully_outside, } } }
//! An implementation of the SHA-2 cryptographic hash algorithms. //! //! There are 6 standard algorithms specified in the SHA-2 standard: //! //! * `Sha224`, which is the 32-bit `Sha256` algorithm with the result truncated //! to 224 bits. //! * `Sha256`, which is the 32-bit `Sha256` algorithm. //! * `Sha384`, which is the 64-bit `Sha512` algorithm with the result truncated //! to 384 bits. //! * `Sha512`, which is the 64-bit `Sha512` algorithm. //! * `Sha512Trunc224`, which is the 64-bit `Sha512` algorithm with the result //! truncated to 224 bits. //! * `Sha512Trunc256`, which is the 64-bit `Sha512` algorithm with the result //! truncated to 256 bits. //! //! Algorithmically, there are only 2 core algorithms: `Sha256` and `Sha512`. //! All other algorithms are just applications of these with different initial //! hash values, and truncated to different digest bit lengths. //! //! # Usage //! //! An example of using `Sha256` is: //! //! ```rust //! use sha2::{Sha256, Digest}; //! //! // create a Sha256 object //! let mut hasher = Sha256::default(); //! //! // write input message //! hasher.input(b"hello world"); //! //! // read hash digest and consume hasher //! let output = hasher.result(); //! //! assert_eq!(output[..], [0xb9, 0x4d, 0x27, 0xb9, 0x93, 0x4d, 0x3e, 0x08, //! 0xa5, 0x2e, 0x52, 0xd7, 0xda, 0x7d, 0xab, 0xfa, //! 0xc4, 0x84, 0xef, 0xe3, 0x7a, 0x53, 0x80, 0xee, //! 0x90, 0x88, 0xf7, 0xac, 0xe2, 0xef, 0xcd, 0xe9]); //! ``` //! //! An example of using `Sha512` is: //! //! ```rust //! use sha2::{Sha512, Digest}; //! //! // create a Sha512 object //! let mut hasher = Sha512::default(); //! //! // write input message //! hasher.input(b"hello world"); //! //! // read hash digest and consume hasher //! let output = hasher.result(); //! //! assert_eq!(output[..], [0x30, 0x9e, 0xcc, 0x48, 0x9c, 0x12, 0xd6, 0xeb, //! 0x4c, 0xc4, 0x0f, 0x50, 0xc9, 0x02, 0xf2, 0xb4, //! 0xd0, 0xed, 0x77, 0xee, 0x51, 0x1a, 0x7c, 0x7a, //! 0x9b, 0xcd, 0x3c, 0xa8, 0x6d, 0x4c, 0xd8, 0x6f, //! 0x98, 0x9d, 0xd3, 0x5b, 0xc5, 0xff, 0x49, 0x96, //! 0x70, 0xda, 0x34, 0x25, 0x5b, 0x45, 0xb0, 0xcf, //! 0xd8, 0x30, 0xe8, 0x1f, 0x60, 0x5d, 0xcf, 0x7d, //! 0xc5, 0x54, 0x2e, 0x93, 0xae, 0x9c, 0xd7, 0x6f][..]); //! ``` #![no_std] extern crate byte_tools; #[macro_use] extern crate digest; extern crate block_buffer; extern crate fake_simd as simd; #[cfg(feature = "asm")] extern crate sha2_asm; mod consts; #[cfg(not(feature = "asm"))] mod sha256_utils; #[cfg(not(feature = "asm"))] mod sha512_utils; mod sha256; mod sha512; pub use digest::Digest; pub use sha256::{Sha256, Sha224}; pub use sha512::{Sha512, Sha384, Sha512Trunc224, Sha512Trunc256};
use anyhow::Result; use crate::Parser; use log::debug; pub struct XMLParser {} impl Parser for XMLParser { fn parse_tokens_str<'a>(&self, input: &'a str) -> Result<()> { // After testing, there's no difference in out examples between `from` and `from_fragment` let tk = xmlparser::Tokenizer::from_fragment( input, std::ops::Range { start: 0, end: input.len(), }, ); let mut count = 0; for out in tk { let _token = out?; count += 1; } debug!("total xmlparser events {}", count); Ok(()) } fn name(&self) -> String { "xml-parser".to_string() } fn parse_tokens_string(&self, input: String) -> Result<()> { let tk = xmlparser::Tokenizer::from(input.as_str()); let mut count = 0; for out in tk { let _token = out?; count += 1; } debug!("total xmlparser events {}", count); Ok(()) } fn parse_tokens_reader<'a>(&self, input: &'a mut dyn std::io::BufRead) -> Result<()> { let mut mem = String::new(); input.read_to_string(&mut mem)?; let tk = xmlparser::Tokenizer::from(mem.as_str()); let mut count = 0; for out in tk { let _token = out?; count += 1; } debug!("total xmlparser events {}", count); Ok(()) } } pub struct QuickXML {} use quick_xml::events::Event; use quick_xml::Reader; impl Parser for QuickXML { fn parse_tokens_str<'a>(&self, input: &'a str) -> Result<()> { let mut reader = Reader::from_str(input); reader.trim_text(true); let mut count = 0; let mut buf = Vec::new(); // The `Reader` does not implement `Iterator` because it outputs borrowed data (`Cow`s) loop { match reader.read_event(&mut buf) { Ok(Event::Eof) => break, // exits the loop when reaching end of file Err(e) => { return Err(anyhow::anyhow!( "Error at position {}: {:?}", reader.buffer_position(), e )) } _ => { count += 1; } } // if we don't keep a borrow elsewhere, we can clear the buffer to keep memory usage low buf.clear(); } debug!("total quick-xml events {}", count); Ok(()) } fn name(&self) -> String { "quick-xml".to_string() } fn parse_tokens_string(&self, input: String) -> Result<()> { let mut reader = Reader::from_str(input.as_str()); reader.trim_text(true); let mut count = 0; let mut buf = Vec::new(); // The `Reader` does not implement `Iterator` because it outputs borrowed data (`Cow`s) loop { match reader.read_event(&mut buf) { Ok(Event::Eof) => break, // exits the loop when reaching end of file Err(e) => { return Err(anyhow::anyhow!( "Error at position {}: {:?}", reader.buffer_position(), e )) } _ => { count += 1; } } // if we don't keep a borrow elsewhere, we can clear the buffer to keep memory usage low buf.clear(); } debug!("total quick-xml events {}", count); Ok(()) } fn parse_tokens_reader<'a>(&self, input: &'a mut dyn std::io::BufRead) -> Result<()> { let mut reader = Reader::from_reader(input); reader.trim_text(true); let mut count = 0; let mut buf = Vec::new(); // The `Reader` does not implement `Iterator` because it outputs borrowed data (`Cow`s) loop { match reader.read_event(&mut buf) { Ok(Event::Eof) => break, // exits the loop when reaching end of file Err(e) => { return Err(anyhow::anyhow!( "Error at position {}: {:?}", reader.buffer_position(), e )) } _ => { count += 1; } } // if we don't keep a borrow elsewhere, we can clear the buffer to keep memory usage low buf.clear(); } debug!("total quick-xml events {}", count); Ok(()) } } pub struct XmlRs {} use xml::reader::EventReader; impl Parser for XmlRs { fn parse_tokens_str<'a>(&self, input: &'a str) -> Result<()> { let parser = EventReader::new(input.as_bytes()); let mut count = 0; for e in parser { let _token = e?; count += 1; } debug!("total xml-rs events {}", count); Ok(()) } fn name(&self) -> String { "xml-rs".to_string() } fn parse_tokens_string(&self, input: String) -> Result<()> { let parser = EventReader::new(input.as_bytes()); let mut count = 0; for e in parser { let _token = e?; count += 1; } debug!("total xml-rs events {}", count); Ok(()) } fn parse_tokens_reader<'a>(&self, input: &'a mut dyn std::io::BufRead) -> Result<()> { let parser = EventReader::new(input); let mut count = 0; for e in parser { let _token = e?; count += 1; } debug!("total xml-rs events {}", count); Ok(()) } } pub struct Html5Ever {} use html5ever::driver::ParseOpts; use html5ever::parse_document; use html5ever::tendril::TendrilSink; use html5ever::tree_builder::TreeBuilderOpts; use markup5ever_rcdom::RcDom; impl Parser for Html5Ever { fn name(&self) -> String { "html5ever".to_string() } fn parse_tokens_str<'a>(&self, input: &'a str) -> Result<()> { let opts = ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }; let mut inp = input.as_bytes(); let _dom = parse_document(RcDom::default(), opts) .from_utf8() .read_from(&mut inp)?; Ok(()) } fn parse_tokens_string(&self, input: String) -> Result<()> { let opts = ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }; let mut inp = input.as_bytes(); let _dom = parse_document(RcDom::default(), opts) .from_utf8() .read_from(&mut inp)?; Ok(()) } fn parse_tokens_reader<'a>(&self, input: &'a mut dyn std::io::BufRead) -> Result<()> { let opts = ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }; // let mut inp = input; let _dom = parse_document(RcDom::default(), opts) .from_utf8() .read_from(Box::new(input).as_mut())?; Ok(()) } } pub struct HtmlParser {} use html_parser::Dom; // TODO: wrap all tests in panic catch_unwind at the call site, rather than just on this code impl Parser for HtmlParser { fn name(&self) -> String { "html-parser".to_string() } fn parse_tokens_str<'a>(&self, input: &'a str) -> Result<()> { let result = std::panic::catch_unwind(|| Dom::parse(input)); match result { Err(_) => Err(anyhow::anyhow!("unexpected panic from parser")), Ok(r) => { r?; Ok(()) } } } fn parse_tokens_string(&self, input: String) -> Result<()> { let result = std::panic::catch_unwind(|| Dom::parse(input.as_str())); match result { Err(_) => Err(anyhow::anyhow!("unexpected panic from parser")), Ok(r) => { r?; Ok(()) } } } fn parse_tokens_reader<'a>(&self, input: &'a mut dyn std::io::BufRead) -> Result<()> { let mut intermediate = String::new(); input.read_to_string(&mut intermediate)?; let result = std::panic::catch_unwind(|| Dom::parse(intermediate.as_str())); match result { Err(_) => Err(anyhow::anyhow!("unexpected panic from parser")), Ok(r) => { r?; Ok(()) } } } } pub type Parsers = Vec<Box<dyn Parser>>; pub fn get_parsers() -> Parsers { let t: Parsers = vec![ Box::new(XmlRs {}), Box::new(XMLParser {}), Box::new(QuickXML {}), Box::new(Html5Ever {}), Box::new(HtmlParser {}), ]; t }
use piston::input::{RenderArgs, UpdateArgs, Button}; use opengl_graphics::GlyphCache; use super::states::State; use super::gamedata::GameData; use opengl_graphics::GlGraphics; use graphics::Context; pub trait GameState { fn render(&mut self, ctx: &Context, gl: &mut GlGraphics, glyphs: &mut GlyphCache); fn update(&mut self, args: &UpdateArgs) -> State<GameData>; fn key_press(&mut self, args: &Button); fn key_release(&mut self, args: &Button); }
mod rdf { pub fn parse_rdf() { unimplemented!(); } pub fn read_rdf() { let unimplemented!(); } pub fn write_rdf() { unimplemented!(); } }
use std::fs::File; use std::io::prelude::*; fn main() -> std::io::Result<()> { let mut file = File::create("/tmp/file.txt")?; let buffer = "Hello Linux Journal!\n"; file.write_all(buffer.as_bytes())?; println!("Finish writing..."); let mut input = File::open("/tmp/file.txt")?; let mut input_buffer = String::new(); input.read_to_string(&mut input_buffer)?; print!("Read: {}", input_buffer); Ok(()) }
#[cfg(all(not(target_arch = "wasm32"), feature = "svg"))] mod svg; #[cfg(all(not(target_arch = "wasm32"), feature = "svg"))] pub use self::svg::SVGBackend; #[cfg(all(not(target_arch = "wasm32"), feature = "image"))] mod bitmap; #[cfg(all(not(target_arch = "wasm32"), feature = "image"))] pub use bitmap::BitMapBackend; #[cfg(target_arch = "wasm32")] mod canvas; #[cfg(target_arch = "wasm32")] pub use canvas::CanvasBackend;
use std::{ collections::{HashMap, VecDeque}, rc::Rc, }; use crate::{client_actor_manager::ClientActorManager, naia_client::LocalActorKey}; use naia_shared::{wrapping_diff, ActorType, Event, EventType, SequenceBuffer, SequenceIterator}; const COMMAND_HISTORY_SIZE: u16 = 64; /// Handles incoming, local, predicted Commands #[derive(Debug)] pub struct CommandReceiver<T: EventType> { queued_incoming_commands: VecDeque<(u16, LocalActorKey, Rc<Box<dyn Event<T>>>)>, command_history: HashMap<LocalActorKey, SequenceBuffer<Rc<Box<dyn Event<T>>>>>, queued_command_replays: VecDeque<(u16, LocalActorKey, Rc<Box<dyn Event<T>>>)>, replay_trigger: HashMap<LocalActorKey, u16>, } impl<T: EventType> CommandReceiver<T> { /// Creates a new CommandSender pub fn new() -> Self { CommandReceiver { queued_incoming_commands: VecDeque::new(), command_history: HashMap::new(), queued_command_replays: VecDeque::new(), replay_trigger: HashMap::new(), } } /// Gets the next queued Command pub fn pop_command(&mut self) -> Option<(u16, LocalActorKey, Rc<Box<dyn Event<T>>>)> { self.queued_incoming_commands.pop_front() } /// Gets the next queued Replayed Command pub fn pop_command_replay<U: ActorType>( &mut self, actor_manager: &mut ClientActorManager<U>, ) -> Option<(u16, LocalActorKey, Rc<Box<dyn Event<T>>>)> { for (pawn_key, history_tick) in self.replay_trigger.iter() { // set pawn to server authoritative state actor_manager.pawn_reset(pawn_key); // clear all actor_manager.pawn_clear_history(pawn_key); // trigger replay of historical commands if let Some(command_buffer) = self.command_history.get_mut(&pawn_key) { self.queued_incoming_commands.clear(); self.queued_command_replays.clear(); let current_tick = command_buffer.sequence_num(); for tick in *history_tick..=current_tick { if let Some(command) = command_buffer.get_mut(tick) { self.queued_command_replays .push_back((tick, *pawn_key, command.clone())); } } } } self.replay_trigger.clear(); self.queued_command_replays.pop_front() } /// Queues an Command to be ran locally on the Client pub fn queue_command( &mut self, host_tick: u16, pawn_key: LocalActorKey, command: &Rc<Box<dyn Event<T>>>, ) { self.queued_incoming_commands .push_back((host_tick, pawn_key, command.clone())); if let Some(command_buffer) = self.command_history.get_mut(&pawn_key) { command_buffer.insert(host_tick, command.clone()); } } /// Get number of Commands in the command history for a given Pawn pub fn command_history_count(&self, pawn_key: LocalActorKey) -> u8 { if let Some(command_buffer) = self.command_history.get(&pawn_key) { return command_buffer.get_entries_count(); } return 0; } /// Get an iterator of Commands in the command history for a given Pawn pub fn command_history_iter( &self, pawn_key: LocalActorKey, reverse: bool, ) -> Option<SequenceIterator<Rc<Box<dyn Event<T>>>>> { if let Some(command_buffer) = self.command_history.get(&pawn_key) { return Some(command_buffer.iter(reverse)); } return None; } /// Queues commands to be replayed from a given tick pub fn replay_commands(&mut self, history_tick: u16, pawn_key: LocalActorKey) { if let Some(tick) = self.replay_trigger.get_mut(&pawn_key) { if wrapping_diff(*tick, history_tick) > 0 { *tick = history_tick; } } else { self.replay_trigger.insert(pawn_key, history_tick); } } /// Removes command history for a given pawn until a specific tick pub fn remove_history_until(&mut self, history_tick: u16, pawn_key: LocalActorKey) { if let Some(command_buffer) = self.command_history.get_mut(&pawn_key) { command_buffer.remove_until(history_tick); } } /// Perform initialization on pawn creation pub fn pawn_init(&mut self, pawn_key: &LocalActorKey) { self.command_history.insert( *pawn_key, SequenceBuffer::with_capacity(COMMAND_HISTORY_SIZE), ); } /// Perform cleanup on pawn deletion pub fn pawn_cleanup(&mut self, pawn_key: &LocalActorKey) { self.command_history.remove(pawn_key); } }
use std::collections::HashMap; use std::io::{Cursor, Read}; use std::{error, thread}; use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; use dbus::arg::RefArg; use serde::export::Formatter; use dbus_common::org_bluez_device1::OrgBluezDevice1; use dbus_common::org_bluez_gatt_characteristic1::OrgBluezGattCharacteristic1; use crate::dbus_bluez::{ BluezManager, DBusPath, TypedDbusError, BLUEZ_GATT_CHARACTERISTIC_INTERFACE, BLUEZ_SERVICE, }; use std::time::Duration; pub(crate) const XIAOMI_MIFLORA_SERVICE_UUID: &str = "0000fe95-0000-1000-8000-00805f9b34fb"; #[derive(Debug)] pub(crate) enum Error { GATTAttributeNotFound { name: String, uuid: String, }, InvalidData { cause: std::io::Error, }, ErrorConnecting { cause: TypedDbusError, }, ErrorDisconnecting { cause: TypedDbusError, }, ErrorReadingData { name: String, uuid: String, path: String, cause: TypedDbusError, }, ErrorWritingData { name: String, uuid: String, path: String, cause: TypedDbusError, }, DBusError { cause: TypedDbusError, }, ThisShouldNeverHappend, } impl std::error::Error for Error {} impl std::fmt::Display for Error { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { write!(f, "{:?}", self) } } #[derive(Debug)] pub(crate) struct Miflora<'a> { manager: &'a mut BluezManager, device: DBusPath, firmware: Option<DBusPath>, firmware_raw: Option<Vec<u8>>, device_mode: Option<DBusPath>, device_data: Option<DBusPath>, device_time: Option<DBusPath>, history_mode: Option<DBusPath>, history_data: Option<DBusPath>, } enum MifloraDeviceMode { Realtime, Blink, } enum MifloraDeviceHistoryMode { Init, Clear, ReadRecord(u16), } pub(crate) struct RealtimeReadings { pub temperature: f32, pub lux: u32, pub moisture: u8, pub conductivity: u16, } pub(crate) struct HistoryReadings { pub record_number: u16, pub epoch: u32, pub temperature: f32, pub lux: u32, pub moisture: u8, pub conductivity: u16, } impl<'a> Miflora<'a> { const FIRMWARE_CHARACTERISTIC_UUID: &'static str = "00001a02-0000-1000-8000-00805f9b34fb"; const DEVICE_MODE_CHARACTERISTIC_UUID: &'static str = "00001a00-0000-1000-8000-00805f9b34fb"; const DEVICE_DATA_CHARACTERISTIC_UUID: &'static str = "00001a01-0000-1000-8000-00805f9b34fb"; const DEVICE_TIME_CHARACTERISTIC_UUID: &'static str = "00001a12-0000-1000-8000-00805f9b34fb"; const HISTORY_MODE_CHARACTERISTIC_UUID: &'static str = "00001a10-0000-1000-8000-00805f9b34fb"; const HISTORY_DATA_CHARACTERISTIC_UUID: &'static str = "00001a11-0000-1000-8000-00805f9b34fb"; pub fn new( device: DBusPath, manager: &'a mut BluezManager, ) -> Result<Miflora, Box<dyn error::Error>> { Ok(Miflora { manager, device, firmware: None, firmware_raw: None, device_mode: None, device_data: None, device_time: None, history_mode: None, history_data: None, }) } pub fn connect(&mut self) -> Result<(), Box<dyn error::Error>> { info!("{:} connect()", self.device.path); self.device.connect()?; if !self.device.get_connected()? { error!("Can't connect to device"); return Ok(()); // FIXME } self.find_gatt_attributes(); // debug!("DMP DEBUG DeviceMode={:?}, HistoryMode={:?}", // self.read_attr( // &self.device_mode, // "device mode", // Self::DEVICE_MODE_CHARACTERISTIC_UUID, // |v| Ok(v.get_ref().clone()) // ), // self.read_attr( // &self.history_mode, // "history mode", // Self::HISTORY_MODE_CHARACTERISTIC_UUID, // |v| Ok(v.get_ref().clone()) // ) // ); debug!("connected - looking up UUIDs"); thread::sleep(Duration::from_millis(200)); debug!("connected"); Ok(()) } pub fn disconnect(&mut self) -> Result<(), Error> { debug!("disconnect: {:?}", self.device.path); self.device.disconnect().map_err(|err| Error::DBusError { cause: TypedDbusError::from(err), }) } pub fn get_address(&self) -> Result<String, Error> { OrgBluezDevice1::get_address(&self.device).map_err(|err| Error::DBusError { cause: TypedDbusError::from(err), }) } pub fn get_rssi(&self) -> Result<i16, Error> { OrgBluezDevice1::get_rssi(&self.device).map_err(|err| Error::DBusError { cause: TypedDbusError::from(err), }) } pub fn get_name(&self) -> Result<String, Error> { OrgBluezDevice1::get_name(&self.device).map_err(|err| Error::DBusError { cause: TypedDbusError::from(err), }) } pub fn get_alias(&self) -> Result<String, Error> { OrgBluezDevice1::get_alias(&self.device).map_err(|err| Error::DBusError { cause: TypedDbusError::from(err), }) } pub fn get_firmware_version(&self) -> Result<String, Error> { // TODO: Don't reread the same info twice self.read_attr( &self.firmware, "Firmware info", Self::FIRMWARE_CHARACTERISTIC_UUID, |v| { String::from_utf8(v.get_ref()[2..7].to_vec()) .map_err(|_| panic!("Cannot convert to utf8")) }, ) } pub fn get_battery_pct(&self) -> Result<u8, Error> { // TODO: Don't reread the same info twice self.read_attr( &self.firmware, "Firmware info", Self::FIRMWARE_CHARACTERISTIC_UUID, |v| Ok(v.get_ref()[0]), ) } pub fn get_realtime_reading(&self) -> Result<RealtimeReadings, Error> { self.set_device_mode(MifloraDeviceMode::Realtime)?; self.read_attr( &self.device_data, "Device Realtime readout", Self::DEVICE_DATA_CHARACTERISTIC_UUID, |v| self.decode_realtime_data(&mut v.clone()), ) } pub fn blink(&self) -> Result<(), Error> { self.set_device_mode(MifloraDeviceMode::Blink)?; thread::sleep(Duration::from_millis(1000)); Ok(()) } pub fn get_device_time(&self) -> Result<u32, Error> { self.read_attr( &self.device_time, "Device time", Self::DEVICE_TIME_CHARACTERISTIC_UUID, |mut v| v.read_u32::<LittleEndian>(), ) } pub fn get_history_record_count(&self) -> Result<u16, Error> { debug!("get_connected: {:?}", self.device.get_connected()); debug!( "get_services_resolved: {:?}", self.device.get_services_resolved() ); self.set_device_history_mode(MifloraDeviceHistoryMode::Init)?; // byte 0-1 is history record count self.read_attr( &self.history_data, "history date", Self::HISTORY_DATA_CHARACTERISTIC_UUID, |mut v| v.read_u16::<LittleEndian>(), ) } pub fn get_history_records(&self, from: u16, to: u16) -> Result<Vec<HistoryReadings>, Error> { let mut result = Vec::new(); self.set_device_history_mode(MifloraDeviceHistoryMode::Init)?; for idx in from..to { let record = self.read_history_record(idx)?; if let Some(mut record) = record { record.record_number = idx; result.push(record); } } Ok(result) } pub fn clear_history(&self) -> Result<(), Error> { self.set_device_history_mode(MifloraDeviceHistoryMode::Init)?; self.set_device_history_mode(MifloraDeviceHistoryMode::Clear)?; Ok(()) } fn read_history_record(&self, idx: u16) -> Result<Option<HistoryReadings>, Error> { debug!("Reading history record #{:?}", idx); self.set_device_history_mode(MifloraDeviceHistoryMode::ReadRecord(idx))?; self.read_attr( &self.history_data, "history record", Self::HISTORY_DATA_CHARACTERISTIC_UUID, |v| self.decode_history_data(&mut v.clone()), ) } fn decode_history_data( &self, data: &mut Cursor<Vec<u8>>, ) -> Result<Option<HistoryReadings>, std::io::Error> { debug!("read: {:?}", data); // Lets check if its invalid data { let mut raw: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; data.clone().read(&mut raw)?; if raw == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] { debug!("Zero record, ignoring"); return Ok(None); } if raw == [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255] { debug!("0xFF record, ignoring"); return Ok(None); } } // byte 0-3 let history_epoch_time = data.read_u32::<LittleEndian>()?; // byte 4-5 temperature in 0.1 degree celcius let temperature = data.read_u16::<LittleEndian>()? as f32 * 0.1; // byte 6 - unknown let _unknown = data.read_u8()?; // byte 7-9 brightness in lux let lux1: u32 = data.read_u8()?.into(); let lux2: u32 = data.read_u8()?.into(); let lux3: u32 = data.read_u8()?.into(); let mut lux = lux3; lux = lux << 8; lux = lux + lux2; lux = lux << 8; lux = lux + lux1; lux = u32::from_le(lux); // byte 10 - unknown let _unknown2 = data.read_u8()?; // byte 11 - moisture in procent let moisture = data.read_u8()?; // byte 12-13 - conductivity µS/cm let conductivity = data.read_u16::<LittleEndian>()?; // byte 14-15 - unknown let _unknown3 = data.read_u16::<LittleEndian>()?; Ok(Some(HistoryReadings { record_number: 0, // will be populated later epoch: history_epoch_time, temperature, lux, moisture, conductivity, })) } fn decode_realtime_data( &self, data: &mut Cursor<Vec<u8>>, ) -> Result<RealtimeReadings, std::io::Error> { // byte 0-1 let temperature = data.read_u16::<LittleEndian>()? as f32 * 0.1; // byte 2 let _unknown = data.read_u8()?; // byte 3-6 let lux = data.read_u32::<LittleEndian>()?; // byte 7 let moisture = data.read_u8()?; // byte 8-9 let conductivity = data.read_u16::<LittleEndian>()?; // byte 10-15 unknown Ok(RealtimeReadings { temperature, lux, moisture, conductivity, }) } fn set_device_mode(&self, mode: MifloraDeviceMode) -> Result<(), Error> { let (value, name) = match mode { MifloraDeviceMode::Realtime => ([0xa0, 0x1f], "device mode -> realtime"), MifloraDeviceMode::Blink => ([0xfd, 0xff], "device mode -> blink"), }; self.write_attr( &self.device_mode, value, name, Self::DEVICE_MODE_CHARACTERISTIC_UUID, |w| w.to_vec(), )?; Ok(()) } fn set_device_history_mode(&self, mode: MifloraDeviceHistoryMode) -> Result<(), Error> { let (value, name) = match mode { MifloraDeviceHistoryMode::Init => ([0xa0, 0x00, 0x00], "history mode -> init".to_string()), MifloraDeviceHistoryMode::Clear => ([0xa2, 0x00, 0x00], "history mode -> clear".to_string()), MifloraDeviceHistoryMode::ReadRecord(idx) => { let mut cmd = [0; 3]; cmd[0] = 0xa1; LittleEndian::write_u16(&mut cmd[1..3], idx); (cmd, format!("history mode -> read record {:?}", idx)) } }; self.write_attr( &self.history_mode, value, &name, Self::HISTORY_MODE_CHARACTERISTIC_UUID, |w| w.to_vec(), )?; Ok(()) } fn read_attr<T, F>( &self, attr: &Option<DBusPath>, name: &str, uuid: &str, parser: F, ) -> Result<T, Error> where F: FnOnce(Cursor<Vec<u8>>) -> Result<T, std::io::Error>, { debug!("read_attr attr={:?} name={:?} uuid={:?}", attr.as_ref().map(|f| f.path.clone()), name, uuid); let mut result = Err(Error::ThisShouldNeverHappend); for retry in 0..2 { debug!(" - try {:?}", retry); if retry > 0 { debug!(" disconnect"); self.device.disconnect().map_err(|error| { Error::ErrorDisconnecting { cause: TypedDbusError::from(error), } })?; let duration = Duration::from_millis(retry * 30_000); debug!(" sleeping for {:} s", duration.as_secs()); thread::sleep(duration); debug!(" connect"); self.device.connect().map_err(|error| { Error::ErrorConnecting { cause: TypedDbusError::from(error), } })?; thread::sleep(Duration::from_millis(200)); debug!(" sleeping for {:} ms", 200); } result = attr.as_ref() .ok_or(Error::GATTAttributeNotFound { name: name.to_string(), uuid: uuid.to_string(), }) .and_then(|c| { OrgBluezGattCharacteristic1::read_value(c, HashMap::new()).map_err(|error| { Error::ErrorReadingData { name: name.to_string(), uuid: uuid.to_string(), path: c.path.to_string(), cause: TypedDbusError::from(error), } }) }); match result { Ok(_) => { debug!(" - read_attr success!"); break }, Err(ref err) => { debug!(" - read_attr errored with: {:?}", err); } } } result.map(Cursor::new) .and_then(|v| parser(v).map_err(|err| Error::InvalidData { cause: err })) } fn write_attr<T, F>( &self, attr: &Option<DBusPath>, value: T, name: &str, uuid: &str, writer: F, ) -> Result<(), Error> where F: FnOnce(T) -> Vec<u8>, { attr.as_ref() .ok_or(Error::GATTAttributeNotFound { name: name.to_string(), uuid: uuid.to_string(), }) .and_then(|c| { OrgBluezGattCharacteristic1::write_value(c, writer(value), HashMap::new()).map_err( |err| Error::ErrorWritingData { name: name.to_string(), uuid: uuid.to_string(), path: c.path.to_string(), cause: TypedDbusError::from(err), }, ) }) } fn find_gatt_attributes(&mut self) { let mut firmware: Option<DBusPath> = None; let mut device_mode: Option<DBusPath> = None; let mut device_data: Option<DBusPath> = None; let mut device_time: Option<DBusPath> = None; let mut history_mode: Option<DBusPath> = None; let mut history_data: Option<DBusPath> = None; let conn = self.device.conn.clone(); self.manager.find_objects( |path, obj| { if let Some(props) = obj.get(BLUEZ_GATT_CHARACTERISTIC_INTERFACE.into()) { props .get("UUID") .and_then(dbus::arg::Variant::as_str) .and_then(|uuid| match uuid { Self::FIRMWARE_CHARACTERISTIC_UUID => Some(&mut firmware), Self::DEVICE_MODE_CHARACTERISTIC_UUID => Some(&mut device_mode), Self::DEVICE_DATA_CHARACTERISTIC_UUID => Some(&mut device_data), Self::DEVICE_TIME_CHARACTERISTIC_UUID => Some(&mut device_time), Self::HISTORY_MODE_CHARACTERISTIC_UUID => Some(&mut history_mode), Self::HISTORY_DATA_CHARACTERISTIC_UUID => Some(&mut history_data), _ => None, }) .map(|char| { *char = Some(dbus::ConnPath { conn: conn.clone(), dest: dbus::BusName::from(BLUEZ_SERVICE), path: path.clone().into_static(), timeout: 30_000, }) }); } firmware.is_some() && device_mode.is_some() && device_data.is_some() && device_time.is_some() && history_mode.is_some() && history_data.is_some() }, Some(30_000), ); debug!("firmware: {:?}", firmware); debug!("device_mode: {:?}", device_mode); debug!("device_data: {:?}", device_data); debug!("device_time: {:?}", device_time); debug!("history_mode: {:?}", history_mode); debug!("history_data: {:?}", history_data); self.firmware = firmware; self.device_mode = device_mode; self.device_data = device_data; self.device_time = device_time; self.history_mode = history_mode; self.history_data = history_data; } } impl<'a> Drop for Miflora<'a> { fn drop(&mut self) { self.disconnect().ok(); } }
use std::collections::{HashMap}; use template::{ComponentTemplate, Style, TemplateValue}; use {Error, Context}; /// A generated attribute bundle for a component, used by the component and its class to receive /// data from templates and styles. pub struct Attributes { attributes: HashMap<String, TemplateValue>, component_class: String, component_line: usize, } impl Attributes { /// Resolves the final attributes of the current component from its template and the style. pub fn resolve( template: &ComponentTemplate, style: &Style, context: &Context, ) -> Result<Self, Error> { let mut attributes = HashMap::new(); // Attributes should always be added, and thus overwritten, in the sequence they were in in // the template // Add any styles from the stylesheet for component in &style.components { if component.class == template.class { for attribute in &component.attributes { if attribute.check_conditional(&context.runtime)? { attributes.insert(attribute.key.clone(), attribute.value.clone()); } } } } // Overwrite any style resolved attributes with this component's set attributes for attribute in &template.attributes { if attribute.check_conditional(&context.runtime)? { attributes.insert(attribute.key.clone(), attribute.value.clone()); } } Ok(Attributes { component_class: template.class.clone(), component_line: template.line, attributes, }) } pub fn attribute<O, F: FnOnce(&TemplateValue) -> Result<O, Error>>( &self, key: &str, map: F, default: O ) -> Result<O, Error> { self.attributes.get(key) .map(map) .unwrap_or(Ok(default)) // Error reporting here is done by what component is being resolved, rather than // where the attribute came from, for example a style file. Both of these are relevant // information for resolving the error, so this needs to be changed to both. .map_err(|error| Error::Attribute { component: self.component_class.clone(), line: self.component_line, field: key.into(), inner: Box::new(error), }) } pub fn attribute_optional<O, F: FnOnce(&TemplateValue) -> Result<O, Error>>( &self, key: &str, map: F, ) -> Result<Option<O>, Error> { self.attributes.get(key) .map(|value| { if *value == TemplateValue::Default { Ok(None) } else { map(value).map(|v| Some(v)) } }) .unwrap_or(Ok(None)) // Error reporting here is done by what component is being resolved, rather than // where the attribute came from, for example a style file. Both of these are relevant // information for resolving the error, so this needs to be changed to both. .map_err(|error| Error::Attribute { component: self.component_class.clone(), line: self.component_line, field: key.into(), inner: Box::new(error), }) } }
use crate::common::CommonState; use crate::game::{State, Transition, WizardState}; use crate::helpers::ID; use crate::ui::UI; use ezgui::{Choice, EventCtx, GfxCtx, Key, ModalMenu, Text, WarpingItemSlider}; use geom::Pt2D; use map_model::{BusRoute, BusRouteID, BusStopID, Map}; pub struct BusRouteExplorer { slider: WarpingItemSlider<BusStopID>, } impl BusRouteExplorer { pub fn new(ctx: &mut EventCtx, ui: &UI) -> Option<Box<dyn State>> { let map = &ui.primary.map; let routes = match ui.primary.current_selection { Some(ID::BusStop(bs)) => map.get_routes_serving_stop(bs), _ => { return None; } }; if routes.is_empty() { return None; } if !ctx.input.contextual_action(Key::E, "explore bus route") { return None; } if routes.len() == 1 { Some(Box::new(BusRouteExplorer::for_route( routes[0], &ui.primary.map, ctx, ))) } else { Some(make_bus_route_picker( routes.into_iter().map(|r| r.id).collect(), )) } } fn for_route(route: &BusRoute, map: &Map, ctx: &mut EventCtx) -> BusRouteExplorer { let stops: Vec<(Pt2D, BusStopID, Text)> = route .stops .iter() .map(|bs| { let stop = map.get_bs(*bs); (stop.sidewalk_pos.pt(map), stop.id, Text::new()) }) .collect(); BusRouteExplorer { slider: WarpingItemSlider::new( stops, &format!("Bus Route Explorer for {}", route.name), "stop", ctx, ), } } } impl State for BusRouteExplorer { fn event(&mut self, ctx: &mut EventCtx, ui: &mut UI) -> Transition { if ctx.redo_mouseover() { // TODO Or use what debug mode is showing? ui.recalculate_current_selection(ctx); } ctx.canvas.handle_event(ctx.input); if let Some((evmode, done_warping)) = self.slider.event(ctx) { if done_warping { ui.primary.current_selection = Some(ID::BusStop(*self.slider.get().1)); } Transition::KeepWithMode(evmode) } else { Transition::Pop } } fn draw(&self, g: &mut GfxCtx, ui: &UI) { self.slider.draw(g); CommonState::draw_osd(g, ui, &ui.primary.current_selection); } } pub struct BusRoutePicker; impl BusRoutePicker { pub fn new(ui: &UI, menu: &mut ModalMenu) -> Option<Box<dyn State>> { if !menu.action("explore a bus route") { return None; } Some(make_bus_route_picker( ui.primary .map .get_all_bus_routes() .iter() .map(|r| r.id) .collect(), )) } } fn make_bus_route_picker(choices: Vec<BusRouteID>) -> Box<dyn State> { WizardState::new(Box::new(move |wiz, ctx, ui| { let (_, id) = wiz.wrap(ctx).choose("Explore which bus route?", || { choices .iter() .map(|id| Choice::new(&ui.primary.map.get_br(*id).name, *id)) .collect() })?; Some(Transition::Replace(Box::new(BusRouteExplorer::for_route( ui.primary.map.get_br(id), &ui.primary.map, ctx, )))) })) }
mod builder; mod html; mod wu; use builder::build_htmldiff; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::{stdout, BufReader, BufWriter}; use std::process; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 3 { eprintln!("Usage: htmldiff FILE1 FILE2"); process::exit(1); } let html1 = read_html(&args[1]).expect("failed to read html file"); let html2 = read_html(&args[2]).expect("failed to read html file"); let stdout = stdout(); let mut w = BufWriter::new(stdout.lock()); build_htmldiff(&html1, &html2, |s: &str| { w.write(s.as_bytes()).expect("failed to write result"); }); } fn read_html(path: &str) -> io::Result<String> { let mut file = BufReader::new(File::open(path)?); let mut html = String::new(); file.read_to_string(&mut html)?; Ok(html) }
use futures::{Async, Future, Stream}; use inotify::{EventMask, Inotify, WatchMask}; use log::Level; use tokio::timer::Interval; use std::collections::HashMap; use std::env; use std::path::Path; use std::rc::{Rc, Weak}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Mutex, Once}; use std::thread; use std::time::{Duration, Instant}; use crate::com::*; use crate::proxy::standalone::{Cluster, Request}; pub struct FileWatcher { watchfile: String, current: AtomicUsize, versions: Mutex<HashMap<usize, Config>>, reload: bool, } impl FileWatcher { fn new(watchfile: String, config: Config, reload: bool) -> Self { let init_version = 0; let mut init_map = HashMap::new(); init_map.insert(init_version, config); FileWatcher { watchfile, current: AtomicUsize::new(init_version), versions: Mutex::new(init_map), reload, } } pub fn enable_reload(&self) -> bool { self.reload } pub fn get_config(&self, version: usize) -> Option<Config> { let handle = self.versions.lock().unwrap(); handle.get(&version).cloned() } pub fn current_version(&self) -> Version { let current = self.current.load(Ordering::SeqCst); Version(current) } fn current_config(&self) -> Config { let current = self.current.load(Ordering::SeqCst); let handle = self.versions.lock().unwrap(); handle .get(&current) .cloned() .expect("current version must be exists") } fn reload(&self) -> Result<(), AsError> { thread::sleep(Duration::from_millis(200)); debug!("reload from file {:p}", &self.watchfile); let config = Config::load(&self.watchfile)?; config.valid()?; let current_config = self.current_config(); if current_config.reload_equals(&config) { info!("skip due to no change in configuration"); return Ok(()); } info!("load new config content as {:?}", config); let current = self.current.load(Ordering::SeqCst); let mut handle = self.versions.lock().unwrap(); handle.insert(current + 1, config); self.current.fetch_add(1, Ordering::SeqCst); Ok(()) } fn watch_dir(&self) -> String { let pth = Path::new(&self.watchfile); let pb = if pth.is_absolute() { pth.to_path_buf() } else { let current = env::current_dir().expect("must get current dir"); current.join(pth) }; let watch_dir = pb.parent().expect("not valid path for config"); let ret = watch_dir.to_str().expect("not valid path").to_string(); info!("watch file address is {:p}", &self.watchfile); ret } pub fn watch(&self) -> Result<(), AsError> { let mut inotify = Inotify::init()?; let watch_dir = self.watch_dir(); info!("start to watch dir {:?}", watch_dir); inotify.add_watch( watch_dir, WatchMask::MODIFY | WatchMask::CREATE | WatchMask::MOVE, )?; let mut buf = [0u8; 1024]; loop { let events = inotify.read_events_blocking(&mut buf)?; for event in events { let if_changed = event.mask.contains(EventMask::MODIFY) || event.mask.contains(EventMask::MOVED_TO) || event.mask.contains(EventMask::MOVED_FROM); if !if_changed { debug!("skip reload for no change"); continue; } info!( "start reload version from {}", self.current.load(Ordering::SeqCst) ); if let Err(err) = self.reload() { error!("reload fail due to {:?}", err); } else { info!("success reload config"); } break; } } } } static G_FW_ONCE: Once = Once::new(); static mut G_FW: *const FileWatcher = std::ptr::null(); pub fn init(watchfile: &str, config: Config, reload: bool) -> Result<(), AsError> { G_FW_ONCE.call_once(|| { let fw = FileWatcher::new(watchfile.to_string(), config, reload); let fw = Box::new(fw); unsafe { G_FW = Box::into_raw(fw) as *const _; }; }); if reload { info!("starting file watcher"); thread::spawn(move || { let fw = unsafe { G_FW.as_ref().unwrap() }; if let Err(err) = fw.watch() { error!("fail to watch file due to {:?}", err); } else { info!("success start file watcher"); } }); thread::sleep(Duration::from_millis(100)); } Ok(()) } fn current_version() -> Version { let fw = unsafe { G_FW.as_ref().unwrap() }; fw.current_version() } fn get_config(version: usize) -> Option<Config> { let fw = unsafe { G_FW.as_ref().unwrap() }; fw.get_config(version) } fn enable_reload() -> bool { let fw = unsafe { G_FW.as_ref().unwrap() }; fw.enable_reload() } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Version(usize); impl Version { fn config(&self) -> Option<Config> { get_config(self.0) } } pub struct Reloader<T> { name: String, cluster: Weak<Cluster<T>>, current: Version, interval: Interval, enable: bool, } impl<T: Request + 'static> Reloader<T> { pub fn new(cluster: Rc<Cluster<T>>) -> Self { let enable = enable_reload(); let name = cluster.cc.borrow().name.clone(); let weak = Rc::downgrade(&cluster); Reloader { name, enable, cluster: weak, current: Version(0), interval: Interval::new( Instant::now() + Duration::from_secs(10), Duration::from_secs(1), ), } } } impl<T> Future for Reloader<T> where T: Request + 'static, { type Item = (); type Error = (); fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> { if !self.enable { debug!("success reload exists due reload not allow by cli arguments"); return Ok(Async::Ready(())); } loop { match self.interval.poll() { Ok(Async::Ready(_)) => {} Ok(Async::NotReady) => { return Ok(Async::NotReady); } Err(err) => { error!("fail to poll from timer {:?}", err); return Err(()); } } let current = current_version(); if current == self.current { continue; } info!( "start change config version from {:?} to {:?}", self.current, current ); if log_enabled!(Level::Debug) { let current_cfg = current.config(); debug!("start to change config content as {:?}", current_cfg); } let config = match current.config() { Some(ccs) => ccs, None => { debug!("fail to reload, config maybe uninited"); continue; } }; let cc = match config.cluster(&self.name) { Some(cc) => cc, None => { debug!("fail to reload, config absents cluster {}", self.name); continue; } }; if let Some(cluster) = self.cluster.upgrade() { if let Err(err) = cluster.reinit(cc) { error!("fail to reload due to {:?}", err); continue; } info!("success reload for cluster {}", cluster.cc.borrow().name); self.current = current; } else { error!("fail to reload due cluster has been destroyed"); } } } }
use clippy_utils::diagnostics::span_lint_and_help; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_hir::{Expr, ExprKind, PathSegment}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{source_map::Spanned, symbol::sym, Span}; declare_clippy_lint! { /// ### What it does /// Checks for calls to `ends_with` with possible file extensions /// and suggests to use a case-insensitive approach instead. /// /// ### Why is this bad? /// `ends_with` is case-sensitive and may not detect files with a valid extension. /// /// ### Example /// ```rust /// fn is_rust_file(filename: &str) -> bool { /// filename.ends_with(".rs") /// } /// ``` /// Use instead: /// ```rust /// fn is_rust_file(filename: &str) -> bool { /// filename.rsplit('.').next().map(|ext| ext.eq_ignore_ascii_case("rs")) == Some(true) /// } /// ``` #[clippy::version = "1.51.0"] pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS, pedantic, "Checks for calls to ends_with with case-sensitive file extensions" } declare_lint_pass!(CaseSensitiveFileExtensionComparisons => [CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS]); fn check_case_sensitive_file_extension_comparison(ctx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Span> { if_chain! { if let ExprKind::MethodCall(PathSegment { ident, .. }, _, [obj, extension, ..], span) = expr.kind; if ident.as_str() == "ends_with"; if let ExprKind::Lit(Spanned { node: LitKind::Str(ext_literal, ..), ..}) = extension.kind; if (2..=6).contains(&ext_literal.as_str().len()); if ext_literal.as_str().starts_with('.'); if ext_literal.as_str().chars().skip(1).all(|c| c.is_uppercase() || c.is_digit(10)) || ext_literal.as_str().chars().skip(1).all(|c| c.is_lowercase() || c.is_digit(10)); then { let mut ty = ctx.typeck_results().expr_ty(obj); ty = match ty.kind() { ty::Ref(_, ty, ..) => ty, _ => ty }; match ty.kind() { ty::Str => { return Some(span); }, ty::Adt(&ty::AdtDef { did, .. }, _) => { if ctx.tcx.is_diagnostic_item(sym::String, did) { return Some(span); } }, _ => { return None; } } } } None } impl LateLintPass<'tcx> for CaseSensitiveFileExtensionComparisons { fn check_expr(&mut self, ctx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { if let Some(span) = check_case_sensitive_file_extension_comparison(ctx, expr) { span_lint_and_help( ctx, CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS, span, "case-sensitive file extension comparison", None, "consider using a case-insensitive comparison instead", ); } } }
//! The `system_transaction` module provides functionality for creating system transactions. use crate::hash::Hash; use crate::pubkey::Pubkey; use crate::signature::{Keypair, KeypairUtil}; use crate::system_instruction; use crate::system_program; use crate::transaction::Transaction; /// Create and sign new SystemInstruction::CreateAccount transaction pub fn create_account( from_keypair: &Keypair, to: &Pubkey, recent_blockhash: Hash, difs: u64, space: u64, program_id: &Pubkey, ) -> Transaction { let from_pubkey = from_keypair.pubkey(); let create_instruction = system_instruction::create_account(&from_pubkey, to, difs, space, program_id); let instructions = vec![create_instruction]; Transaction::new_signed_instructions(&[from_keypair], instructions, recent_blockhash) } /// Create and sign a transaction to create a system account pub fn create_user_account( from_keypair: &Keypair, to: &Pubkey, difs: u64, recent_blockhash: Hash, ) -> Transaction { let program_id = system_program::id(); create_account(from_keypair, to, recent_blockhash, difs, 0, &program_id) } /// Create and sign new system_instruction::Assign transaction pub fn assign(from_keypair: &Keypair, recent_blockhash: Hash, program_id: &Pubkey) -> Transaction { let from_pubkey = from_keypair.pubkey(); let assign_instruction = system_instruction::assign(&from_pubkey, program_id); let instructions = vec![assign_instruction]; Transaction::new_signed_instructions(&[from_keypair], instructions, recent_blockhash) } /// Create and sign new system_instruction::Transfer transaction pub fn transfer( from_keypair: &Keypair, to: &Pubkey, difs: u64, recent_blockhash: Hash, ) -> Transaction { let from_pubkey = from_keypair.pubkey(); let transfer_instruction = system_instruction::transfer(&from_pubkey, to, difs); let instructions = vec![transfer_instruction]; Transaction::new_signed_instructions(&[from_keypair], instructions, recent_blockhash) }
use amethyst::assets::ProgressCounter; use amethyst::core::Parent; use amethyst::ecs::{Join, Read, ReadExpect, ReadStorage, WriteStorage}; use amethyst::prelude::Builder; use amethyst::ui::{Anchor, UiImage, UiText, UiTransform}; use std::convert::TryFrom; use super::state_prelude::*; const UI_RON_PATH: &str = "ui/difficulty_select.ron"; #[derive(Default)] pub struct DifficultySelect { ui_data: UiData, ui_loading_progress: Option<ProgressCounter>, } impl<'a, 'b> State<CustomGameData<'a, 'b, CustomData>, StateEvent> for DifficultySelect { fn on_start(&mut self, mut data: StateData<CustomGameData<CustomData>>) { self.create_uis(&mut data); } fn on_stop(&mut self, mut data: StateData<CustomGameData<CustomData>>) { self.delete_ui(&mut data); } fn on_resume(&mut self, mut data: StateData<CustomGameData<CustomData>>) { self.create_uis(&mut data); } fn on_pause(&mut self, mut data: StateData<CustomGameData<CustomData>>) { self.delete_ui(&mut data); } fn update( &mut self, data: StateData<CustomGameData<CustomData>>, ) -> Trans<CustomGameData<'a, 'b, CustomData>, StateEvent> { data.data.update(data.world, "menu").unwrap(); if let Some(trans) = self.handle_keys(data.world) { return trans; } if let Some(progress) = self.ui_loading_progress.as_ref() { if progress.is_complete() { self.populate_ui(data.world); self.ui_loading_progress = None; } } Trans::None } fn fixed_update( &mut self, mut data: StateData<CustomGameData<'a, 'b, CustomData>>, ) -> Trans<CustomGameData<'a, 'b, CustomData>, StateEvent> { if let Some(trans) = self.update_ui_events(&mut data) { trans } else { Trans::None } } fn shadow_update(&mut self, data: StateData<CustomGameData<CustomData>>) { // Stop audio if data.world.read_resource::<StopAudio>().0 { stop_audio(data.world); data.world.write_resource::<StopAudio>().0 = false; } } } impl DifficultySelect { fn create_uis(&mut self, data: &mut StateData<CustomGameData<CustomData>>) { let _progress = self.create_ui(data, resource(QUIT_UI_RON_PATH)); self.ui_loading_progress = Some(self.create_ui(data, resource(UI_RON_PATH))); self.create_selector(data.world); // Completion text self.maybe_create_completion_text_ui(data); } fn maybe_create_completion_text_ui( &mut self, data: &mut StateData<CustomGameData<CustomData>>, ) { if data .world .read_resource::<SavefileDataRes>() .0 .as_ref() .map(SavefileData::has_completed_all_levels_except_very_easy) .unwrap_or(false) { // Has completed all levels, and maybe VeryEasy let _progress = self.create_ui(data, resource(COMPLETION_TEXT_UI_RON_PATH)); } } fn populate_ui(&self, world: &mut World) { const VERSION_UI_TRANSFORM_ID: &str = "label_version"; const PREFIX_BUTTON_UI_TRANSFORM_ID: &str = "button_start_"; const PREFIX_BEST_TIME_UI_TRANSFORM_ID: &str = "label_best_time_"; const SUFFIX_BUTTON_TEXT_UI_TRANSFORM_ID: &str = "_btn_txt"; world.exec( |(settings, savefile_data_res, ui_transforms, mut ui_texts): ( ReadExpect<Settings>, Read<SavefileDataRes>, ReadStorage<UiTransform>, WriteStorage<UiText>, )| { let level_manager_settings = &settings.level_manager; for (transform, text) in (&ui_transforms, &mut ui_texts).join() { let transform_id = transform.id.as_str(); // Set version number if transform_id == VERSION_UI_TRANSFORM_ID && text.text.as_str() != crate::meta::VERSION { text.text = format!("v{}", crate::meta::VERSION); } // Set best time if let Some(savefile_data) = savefile_data_res.0.as_ref() { if transform_id .starts_with(PREFIX_BEST_TIME_UI_TRANSFORM_ID) { if let Some(best_time) = Level::try_from( transform_id .replace( PREFIX_BEST_TIME_UI_TRANSFORM_ID, "", ) .as_str(), ) .ok() .and_then(|level| savefile_data.level(&level)) .and_then(|level_data| { level_data.best_time.as_ref() }) { text.text = best_time.to_string(); } } } // Set locked text color if transform_id.starts_with(PREFIX_BUTTON_UI_TRANSFORM_ID) && transform_id .ends_with(SUFFIX_BUTTON_TEXT_UI_TRANSFORM_ID) { if let Some(locked_level) = Level::try_from( transform_id .replace(PREFIX_BUTTON_UI_TRANSFORM_ID, "") .replace(SUFFIX_BUTTON_TEXT_UI_TRANSFORM_ID, "") .as_str(), ) .ok() .filter(|level| { is_level_locked( level, level_manager_settings, &savefile_data_res.0, ) }) { let level_settings = level_manager_settings.level(&locked_level); text.color = level_settings.locked_text_color.unwrap_or( level_manager_settings .default_locked_text_color, ); } } } }, ); } fn handle_keys<'a, 'b>( &mut self, world: &World, ) -> Option<Trans<CustomGameData<'a, 'b, CustomData>, StateEvent>> { let input = world.read_resource::<InputManager<MenuBindings>>(); if input.is_down(MenuActionBinding::MenuPrev) { (&mut world.write_storage::<MenuSelector>()) .join() .next() .map(MenuSelector::prev); } else if input.is_down(MenuActionBinding::MenuNext) { (&mut world.write_storage::<MenuSelector>()) .join() .next() .map(MenuSelector::next); } else if input.is_down(MenuActionBinding::MenuSelect) { if let Some(selector) = (&mut world.write_storage::<MenuSelector>()).join().next() { return Some(start_level(world, selector.selection.level())); } } else if input.is_down(MenuActionBinding::MenuDeleteSave) { if let Some(selector) = (&mut world.write_storage::<MenuSelector>()).join().next() { return Some(start_level_with_delete_save( world, selector.selection.level(), )); } } if input.is_down(MenuActionBinding::Quit) { Some(Trans::Quit) } else { None } } fn create_selector(&mut self, world: &mut World) { let parent_transform = UiTransform::new( "container_menu_selector".to_string(), // id Anchor::Middle, // anchor Anchor::Middle, // pivot 0.05, // x 0.008, // y 0.0, // z 1.0, // width 1.0, // height ) .into_percent() .into_transparent(); let selector_transform = UiTransform::new( "menu_selector".to_string(), // id Anchor::MiddleLeft, // anchor Anchor::MiddleLeft, // pivot 0.0, // x 0.0, // y 1.1, // z 0.015, // width 0.015, // height ) .into_percent() .into_transparent(); let color = UiImage::SolidColor([1.0, 0.0, 0.0, 1.0]); let parent = world.create_entity().with(parent_transform).build(); let selector = world .create_entity() .with(Parent { entity: parent }) .with(selector_transform) .with(color) .with(MenuSelector::default()) .build(); self.push_ui_entity(parent); self.push_ui_entity(selector); } } impl<'a, 'b> Menu<CustomGameData<'a, 'b, CustomData>, StateEvent> for DifficultySelect { fn event_triggered( &mut self, data: &mut StateData<CustomGameData<CustomData>>, event_name: String, event: UiEvent, ) -> Option<Trans<CustomGameData<'a, 'b, CustomData>, StateEvent>> { match (event_name.as_ref(), event.event_type) { ("button_start_very_easy", UiEventType::ClickStop) => { Some(start_level(data.world, Level::VeryEasy)) } ("button_start_easy", UiEventType::ClickStop) => { Some(start_level(data.world, Level::Easy)) } ("button_start_normal", UiEventType::ClickStop) => { Some(start_level(data.world, Level::Normal)) } ("button_start_hard", UiEventType::ClickStop) => { Some(start_level(data.world, Level::Hard)) } ("button_start_absurd", UiEventType::ClickStop) => { Some(start_level(data.world, Level::Absurd)) } ("button_quit", UiEventType::ClickStop) => Some(Trans::Quit), (name, UiEventType::HoverStart) => { if let Ok(selection) = MenuSelection::try_from(name) { (&mut data.world.write_storage::<MenuSelector>()) .join() .next() .map(|selector| selector.set(selection)); } None } _ => None, } } fn ui_data(&self) -> &UiData { &self.ui_data } fn ui_data_mut(&mut self) -> &mut UiData { &mut self.ui_data } } fn start_level<'a, 'b>( world: &World, level: Level, ) -> Trans<CustomGameData<'a, 'b, CustomData>, StateEvent> { let settings = &world.read_resource::<Settings>().level_manager; let savefile_data = &world.read_resource::<SavefileDataRes>().0; if is_level_locked(&level, settings, savefile_data) { Trans::None } else { Trans::Push(Box::new(LevelLoad::new(level))) } } fn start_level_with_delete_save<'a, 'b>( world: &World, level: Level, ) -> Trans<CustomGameData<'a, 'b, CustomData>, StateEvent> { let settings = &world.read_resource::<Settings>().level_manager; let savefile_data = &world.read_resource::<SavefileDataRes>().0; if is_level_locked(&level, settings, savefile_data) { Trans::None } else { Trans::Push(Box::new(LevelLoad::with_delete_save(level))) } }
use std; use serialize; pub enum E { Other(String) } /// An Encoder which compiles but always returns an error pub struct T<'a, W : 'a + std::io::Writer> { writer : &'a mut W, } impl<'a, W : 'a + std::io::Writer> T<'a, W> { pub fn new<'b>(w: &'b mut W) -> T<'b, W> { T { writer: w } } } impl<'a, W: std::io::Writer> serialize::Encoder<E> for T<'a, W> { fn emit_nil(&mut self) -> Result<(), E> { unimplemented!(); } nope!(fn emit_uint(uint) -> E) nope!(fn emit_u64(u64) -> E) nope!(fn emit_u32(u32) -> E) nope!(fn emit_u16(u16) -> E) nope!(fn emit_u8(u8) -> E) nope!(fn emit_int(int) -> E) nope!(fn emit_i64(i64) -> E) nope!(fn emit_i32(i32) -> E) nope!(fn emit_i16(i16) -> E) nope!(fn emit_i8(i8) -> E) nope!(fn emit_bool(bool) -> E) nope!(fn emit_f64(f64) -> E) nope!(fn emit_f32(f32) -> E) fn emit_char(&mut self, _v: char) -> Result<(), E> { unimplemented!(); } fn emit_str(&mut self, _v: &str) -> Result<(), E> { unimplemented!(); } fn emit_enum(&mut self, _: &str, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!(); } fn emit_enum_variant(&mut self, _v_name: &str, _: uint, _len: uint, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!(); } fn emit_enum_variant_arg(&mut self, _: uint, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!(); } fn emit_enum_struct_variant(&mut self, _v_name: &str, _v_id: uint, _len: uint, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!(); } fn emit_enum_struct_variant_field(&mut self, _: &str, _: uint, _: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_struct(&mut self, _: &str, _len: uint, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_struct_field(&mut self, _: &str, _f_idx: uint, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_tuple(&mut self, _len: uint, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_tuple_arg(&mut self, _idx: uint, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_tuple_struct(&mut self, _: &str, _: uint, _: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_tuple_struct_arg(&mut self, _: uint, _: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_option(&mut self, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_option_none(&mut self) -> Result<(), E> { unimplemented!() } fn emit_option_some(&mut self, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_seq(&mut self, _len: uint, _f: |this: &mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_seq_elt(&mut self, _idx: uint, _f: |this: &mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_map(&mut self, _: uint, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_map_elt_key(&mut self, _: uint, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } fn emit_map_elt_val(&mut self, _: uint, _f: |&mut T<'a,W>| -> Result<(), E>) -> Result<(), E> { unimplemented!() } }
use crate::{Buffer, Float}; use core::mem::MaybeUninit; use core::slice; use core::str; impl Buffer { /// This is a cheap operation; you don't need to worry about reusing buffers /// for efficiency. #[inline] pub fn new() -> Self { let bytes = [MaybeUninit::<u8>::uninit(); 24]; Buffer { bytes } } /// Print a floating point number into this buffer and return a reference to /// its string representation within the buffer. /// /// # Special cases /// /// This function formats NaN as the string "NaN", positive infinity as /// "inf", and negative infinity as "-inf" to match std::fmt. /// /// If your input is known to be finite, you may get better performance by /// calling the `format_finite` method instead of `format` to avoid the /// checks for special cases. pub fn format<F: Float>(&mut self, f: F) -> &str { if f.is_nonfinite() { f.format_nonfinite() } else { self.format_finite(f) } } /// Print a floating point number into this buffer and return a reference to /// its string representation within the buffer. /// /// # Special cases /// /// This function **does not** check for NaN or infinity. If the input /// number is not a finite float, the printed representation will be some /// correctly formatted but unspecified numerical value. /// /// Please check [`is_finite`] yourself before calling this function, or /// check [`is_nan`] and [`is_infinite`] and handle those cases yourself. /// /// [`is_finite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_finite /// [`is_nan`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_nan /// [`is_infinite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_infinite #[inline] pub fn format_finite<F: Float>(&mut self, f: F) -> &str { unsafe { let n = f.write_to_dragonbox_buffer(self.bytes.as_mut_ptr() as *mut u8); debug_assert!(n <= self.bytes.len()); let slice = slice::from_raw_parts(self.bytes.as_ptr() as *const u8, n); str::from_utf8_unchecked(slice) } } } impl Copy for Buffer {} impl Clone for Buffer { #[inline] fn clone(&self) -> Self { Buffer::new() } } impl Default for Buffer { #[inline] fn default() -> Self { Buffer::new() } } impl Float for f64 {} const NAN: &str = "NaN"; const INFINITY: &str = "inf"; const NEG_INFINITY: &str = "-inf"; pub trait Sealed: Copy { fn is_nonfinite(self) -> bool; fn format_nonfinite(self) -> &'static str; unsafe fn write_to_dragonbox_buffer(self, result: *mut u8) -> usize; } impl Sealed for f64 { #[inline] fn is_nonfinite(self) -> bool { const EXP_MASK: u64 = 0x7ff0000000000000; let bits = self.to_bits(); bits & EXP_MASK == EXP_MASK } #[cold] fn format_nonfinite(self) -> &'static str { const MANTISSA_MASK: u64 = 0x000fffffffffffff; const SIGN_MASK: u64 = 0x8000000000000000; let bits = self.to_bits(); if bits & MANTISSA_MASK != 0 { NAN } else if bits & SIGN_MASK != 0 { NEG_INFINITY } else { INFINITY } } #[inline] unsafe fn write_to_dragonbox_buffer(self, buffer: *mut u8) -> usize { let end = crate::to_chars::to_chars(self, buffer); end.offset_from(buffer) as usize } }
use ndarray::prelude::*; use petgraph::visit::{IntoEdges, IntoNodeIdentifiers, NodeCount}; use petgraph_algorithm_shortest_path::warshall_floyd; use petgraph_drawing::{Drawing, DrawingIndex}; fn line_search(a: &Array2<f32>, dx: &Array1<f32>, d: &Array1<f32>) -> f32 { let n = dx.len(); let mut alpha = -d.dot(dx); let mut s = 0.; for i in 0..n { for j in 0..n { s += d[i] * d[j] * a[[i, j]]; } } alpha /= s; alpha } fn delta_f(a: &Array2<f32>, b: &Array1<f32>, x: &Array1<f32>, dx: &mut Array1<f32>) { let n = b.len(); for i in 0..n { dx[i] = 0.; for j in 0..n { dx[i] += a[[i, j]] * x[j]; } dx[i] -= b[i]; } } pub fn conjugate_gradient(a: &Array2<f32>, b: &Array1<f32>, x: &mut Array1<f32>, epsilon: f32) { let n = b.len(); let mut dx = Array1::zeros(n); let mut d = Array1::zeros(n); delta_f(a, b, &x, &mut dx); for i in 0..n { d[i] = -dx[i]; } let mut dx_norm0 = dx.dot(&dx); for _ in 0..n { let alpha = line_search(a, &dx, &d); for i in 0..n { x[i] += alpha * d[i]; } delta_f(a, b, &x, &mut dx); let dx_norm = dx.dot(&dx); if dx_norm < epsilon { break; } let beta = dx_norm / dx_norm0; dx_norm0 = dx_norm; for i in 0..n { d[i] = beta * d[i] - dx[i]; } } } fn stress(x: &Array1<f32>, y: &Array1<f32>, w: &Array2<f32>, d: &Array2<f32>) -> f32 { let n = x.len() + 1; let mut s = 0.; for j in 1..n - 1 { for i in 0..j { let dx = x[i] - x[j]; let dy = y[i] - y[j]; let norm = (dx * dx + dy * dy).sqrt(); let dij = d[[i, j]]; let wij = w[[i, j]]; let e = norm - dij; s += wij * e * e; } } for i in 0..n - 1 { let j = n - 1; let dx = x[i]; let dy = y[i]; let norm = (dx * dx + dy * dy).sqrt(); let dij = d[[i, j]]; let wij = w[[i, j]]; let e = norm - dij; s += wij * e * e; } s } pub struct StressMajorization { d: Array2<f32>, w: Array2<f32>, l_w: Array2<f32>, l_z: Array2<f32>, b: Array1<f32>, stress: f32, x_x: Array1<f32>, x_y: Array1<f32>, epsilon: f32, } impl StressMajorization { pub fn new<G, F>(graph: G, drawing: &Drawing<G::NodeId, f32>, length: F) -> StressMajorization where G: IntoEdges + IntoNodeIdentifiers + NodeCount, G::NodeId: DrawingIndex, F: FnMut(G::EdgeRef) -> f32, { let d = warshall_floyd(graph, length); StressMajorization::new_with_distance_matrix(drawing, &d) } pub fn new_with_distance_matrix<N>( drawing: &Drawing<N, f32>, d: &Array2<f32>, ) -> StressMajorization where N: DrawingIndex, { let n = drawing.len(); let w = Array2::zeros((n, n)); let l_w = Array2::zeros((n - 1, n - 1)); let mut x_x = Array1::zeros(n - 1); let mut x_y = Array1::zeros(n - 1); for i in 0..n - 1 { x_x[i] = drawing.coordinates[[i, 0]] - drawing.coordinates[[n - 1, 0]]; x_y[i] = drawing.coordinates[[i, 1]] - drawing.coordinates[[n - 1, 1]]; } let epsilon = 1e-4; let l_z = Array2::zeros((n - 1, n - 1)); let b = Array1::zeros(n - 1); let mut sm = StressMajorization { b, d: d.clone(), l_w, l_z, w, x_x, x_y, stress: std::f32::INFINITY, epsilon, }; sm.update_weight(|_, _, dij, _| 1. / (dij * dij)); sm } pub fn apply<N>(&mut self, drawing: &mut Drawing<N, f32>) -> f32 where N: DrawingIndex, { let n = drawing.len(); let StressMajorization { b, d, l_w, l_z, w, .. } = self; for i in 0..n { drawing.coordinates[[i, 0]] -= drawing.coordinates[[n - 1, 0]]; drawing.coordinates[[i, 1]] -= drawing.coordinates[[n - 1, 1]]; } for i in 1..n - 1 { for j in 0..i { let dx = drawing.coordinates[[i, 0]] - drawing.coordinates[[j, 0]]; let dy = drawing.coordinates[[i, 1]] - drawing.coordinates[[j, 1]]; let norm = (dx * dx + dy * dy).sqrt(); let lij = if norm < 1e-4 { 0. } else { -w[[i, j]] * d[[i, j]] / norm }; l_z[[i, j]] = lij; l_z[[j, i]] = lij; } } for i in 0..n - 1 { let mut s = 0.; for j in 0..n - 1 { if i != j { s -= l_z[[i, j]]; } } let j = n - 1; let dx = drawing.coordinates[[i, 0]]; let dy = drawing.coordinates[[i, 1]]; let norm = (dx * dx + dy * dy).sqrt(); s -= if norm < 1e-4 { 0. } else { -w[[i, j]] * d[[i, j]] / norm }; l_z[[i, i]] = s; } for i in 0..n - 1 { self.x_x[i] = drawing.coordinates[[i, 0]]; let mut s = 0.; for j in 0..n - 1 { s += l_z[[i, j]] * drawing.coordinates[[j, 0]]; } b[i] = s; } conjugate_gradient(&l_w, &b, &mut self.x_x, self.epsilon); for i in 0..n - 1 { self.x_y[i] = drawing.coordinates[[i, 1]]; let mut s = 0.; for j in 0..n - 1 { s += l_z[[i, j]] * drawing.coordinates[[j, 1]]; } b[i] = s; } conjugate_gradient(&l_w, &b, &mut self.x_y, self.epsilon); let stress = stress(&self.x_x, &self.x_y, &w, &d); let diff = (self.stress - stress) / self.stress; self.stress = stress; for i in 0..n - 1 { drawing.coordinates[[i, 0]] = self.x_x[i]; drawing.coordinates[[i, 1]] = self.x_y[i]; } diff } pub fn run<N>(&mut self, coordinates: &mut Drawing<N, f32>) where N: DrawingIndex, { loop { if self.apply(coordinates) < self.epsilon { break; } } } pub fn update_weight<F>(&mut self, mut weight: F) where F: FnMut(usize, usize, f32, f32) -> f32, { let n = self.x_x.len() + 1; for j in 1..n { for i in 0..j { let wij = weight(i, j, self.d[[i, j]], self.w[[i, j]]); self.w[[i, j]] = wij; self.w[[j, i]] = wij; } } for i in 0..n - 1 { self.l_w[[i, i]] = 0.; } for j in 1..n - 1 { for i in 0..j { let wij = self.w[[i, j]]; self.l_w[[i, j]] = -wij; self.l_w[[j, i]] = -wij; self.l_w[[i, i]] += wij; self.l_w[[j, j]] += wij; } } for i in 0..n - 1 { let j = n - 1; self.l_w[[i, i]] += self.w[[i, j]]; } self.stress = stress(&self.x_x, &self.x_y, &self.w, &self.d); } } #[test] fn test_conjugate_gradient() { let a = arr2(&[[3., 1.], [1., 2.]]); let b = arr1(&[6., 7.]); let mut x = arr1(&[2., 1.]); let epsilon = 1e-4; conjugate_gradient(&a, &b, &mut x, epsilon); let x_exact = vec![1., 3.]; let mut d = 0.; for i in 0..x.len() { let dx = x[i] - x_exact[i]; d += dx * dx; } assert!(d < epsilon); } #[test] fn test_stress_majorization() { use petgraph::Graph; let n = 10; let mut graph = Graph::new_undirected(); let nodes = (0..n).map(|_| graph.add_node(())).collect::<Vec<_>>(); for j in 1..n { for i in 0..j { graph.add_edge(nodes[i], nodes[j], ()); } } let mut coordinates = Drawing::initial_placement(&graph); for &u in &nodes { println!("{:?}", coordinates.position(u)); } let mut stress_majorization = StressMajorization::new(&graph, &coordinates, &mut |_| 1.); stress_majorization.run(&mut coordinates); for &u in &nodes { println!("{:?}", coordinates.position(u)); } }
use dotenv::dotenv; use mail::transports::{SmtpTransport, TestTransport, Transport}; use std::env; use tari_client::{HttpTariClient, TariClient, TariTestClient}; #[derive(Clone, PartialEq)] pub enum Environment { Development, Test, Production, } #[derive(Clone)] pub struct Config { pub allowed_origins: String, pub front_end_url: String, pub api_url: String, pub api_port: String, pub app_name: String, pub database_url: String, pub domain: String, pub environment: Environment, pub facebook_app_id: Option<String>, pub facebook_app_secret: Option<String>, pub google_recaptcha_secret_key: Option<String>, pub mail_from_email: String, pub mail_from_name: String, pub mail_transport: Box<Transport + Send + Sync>, pub primary_currency: String, pub stripe_secret_key: String, pub token_secret: String, pub token_issuer: String, pub tari_client: Box<TariClient + Send + Sync>, } const ALLOWED_ORIGINS: &str = "ALLOWED_ORIGINS"; const APP_NAME: &str = "APP_NAME"; const API_URL: &str = "API_URL"; const API_PORT: &str = "API_PORT"; const DATABASE_URL: &str = "DATABASE_URL"; const DOMAIN: &str = "DOMAIN"; const FACEBOOK_APP_ID: &str = "FACEBOOK_APP_ID"; const FACEBOOK_APP_SECRET: &str = "FACEBOOK_APP_SECRET"; const GOOGLE_RECAPTCHA_SECRET_KEY: &str = "GOOGLE_RECAPTCHA_SECRET_KEY"; const PRIMARY_CURRENCY: &str = "PRIMARY_CURRENCY"; const STRIPE_SECRET_KEY: &str = "STRIPE_SECRET_KEY"; const TARI_URL: &str = "TARI_URL"; const TEST_DATABASE_URL: &str = "TEST_DATABASE_URL"; const TOKEN_SECRET: &str = "TOKEN_SECRET"; const TOKEN_ISSUER: &str = "TOKEN_ISSUER"; // Mail settings const MAIL_FROM_EMAIL: &str = "MAIL_FROM_EMAIL"; const MAIL_FROM_NAME: &str = "MAIL_FROM_NAME"; // Optional for test environment, required for other environments const MAIL_SMTP_HOST: &str = "MAIL_SMTP_HOST"; const MAIL_SMTP_PORT: &str = "MAIL_SMTP_PORT"; const FRONT_END_URL: &str = "FRONT_END_URL"; impl Config { pub fn new(environment: Environment) -> Self { dotenv().ok(); let app_name = env::var(&APP_NAME).unwrap_or_else(|_| "Big Neon".to_string()); let database_url = match environment { Environment::Test => env::var(&TEST_DATABASE_URL) .unwrap_or_else(|_| panic!("{} must be defined.", DATABASE_URL)), _ => env::var(&DATABASE_URL) .unwrap_or_else(|_| panic!("{} must be defined.", DATABASE_URL)), }; let domain = env::var(&DOMAIN).unwrap_or_else(|_| "api.bigneon.com".to_string()); let mail_from_email = env::var(&MAIL_FROM_EMAIL) .unwrap_or_else(|_| panic!("{} must be defined.", MAIL_FROM_EMAIL)); let mail_from_name = env::var(&MAIL_FROM_NAME) .unwrap_or_else(|_| panic!("{} must be defined.", MAIL_FROM_NAME)); let mail_transport = match environment { Environment::Test => Box::new(TestTransport::new()) as Box<Transport + Send + Sync>, _ => { let host = env::var(&MAIL_SMTP_HOST) .unwrap_or_else(|_| panic!("{} must be defined.", MAIL_SMTP_HOST)); if host == "test" { Box::new(TestTransport::new()) as Box<Transport + Send + Sync> } else { let port = env::var(&MAIL_SMTP_PORT) .unwrap_or_else(|_| panic!("{} must be defined.", MAIL_SMTP_PORT)); info!("Mail configured {}:{}", host, port); Box::new(SmtpTransport::new( &domain, &host, port.parse::<u16>().unwrap(), )) as Box<Transport + Send + Sync> } } }; let allowed_origins = env::var(&ALLOWED_ORIGINS).unwrap_or_else(|_| "*".to_string()); let api_url = env::var(&API_URL).unwrap_or_else(|_| "127.0.0.1".to_string()); let api_port = env::var(&API_PORT).unwrap_or_else(|_| "8088".to_string()); let primary_currency = env::var(&PRIMARY_CURRENCY).unwrap_or_else(|_| "usd".to_string()); let stripe_secret_key = env::var(&STRIPE_SECRET_KEY).unwrap_or_else(|_| "<stripe not enabled>".to_string()); let token_secret = env::var(&TOKEN_SECRET).unwrap_or_else(|_| panic!("{} must be defined.", TOKEN_SECRET)); let token_issuer = env::var(&TOKEN_ISSUER).unwrap_or_else(|_| panic!("{} must be defined.", TOKEN_ISSUER)); let facebook_app_id = env::var(&FACEBOOK_APP_ID).ok(); let facebook_app_secret = env::var(&FACEBOOK_APP_SECRET).ok(); let front_end_url = env::var(&FRONT_END_URL).unwrap_or_else(|_| panic!("Front end url must be defined")); let tari_uri = env::var(&TARI_URL).unwrap_or_else(|_| panic!("{} must be defined.", TARI_URL)); let tari_client = match environment { Environment::Test => { Box::new(TariTestClient::new(tari_uri)) as Box<TariClient + Send + Sync> } _ => if tari_uri == "TEST" { Box::new(TariTestClient::new(tari_uri)) as Box<TariClient + Send + Sync> } else { Box::new(HttpTariClient::new(tari_uri)) as Box<TariClient + Send + Sync> }, }; let google_recaptcha_secret_key = env::var(&GOOGLE_RECAPTCHA_SECRET_KEY).ok(); Config { allowed_origins, app_name, api_url, api_port, database_url, domain, environment, facebook_app_id, facebook_app_secret, google_recaptcha_secret_key, mail_from_name, mail_from_email, mail_transport, primary_currency, stripe_secret_key, token_secret, token_issuer, front_end_url, tari_client, } } }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_describe_services( input: &crate::input::DescribeServicesInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_describe_services_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_attribute_values( input: &crate::input::GetAttributeValuesInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_attribute_values_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_products( input: &crate::input::GetProductsInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_products_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) }
use crate::traits::required::*; use crate::views::LocalTransformStoragesMut; use shipyard::*; impl<'a, V, Q, M, N> LocalTransformStoragesMut<'a, V, Q, M, N> where V: Vec3Ext<N> + Send + Sync + 'static, Q: QuatExt<N> + Send + Sync + 'static, M: Matrix4Ext<N> + Send + Sync + 'static, N: Copy + Send + Sync + 'static, { pub fn set_local_transform(&mut self, entity: EntityId, transform: M) { let Self { local_transforms, .. } = self; if let Some(local_transform) = (local_transforms).get(entity).iter_mut().next() { local_transform.copy_from(&transform); } } pub fn set_trs( &mut self, entity: EntityId, translation: Option<&V>, rotation: Option<&Q>, scale: Option<&V>, ) { let Self { translations, rotations, scales, .. } = self; if let Some((t, r, s)) = (translations, rotations, scales) .get(entity) .iter_mut() .next() { if let Some(translation) = translation { t.copy_from(translation); } if let Some(rotation) = rotation { r.copy_from(rotation); } if let Some(scale) = scale { s.copy_from(scale); } } } pub fn set_trs_origin( &mut self, entity: EntityId, translation: Option<&V>, rotation: Option<&Q>, scale: Option<&V>, origin: Option<&V>, ) { let Self { translations, rotations, scales, origins, .. } = self; if let Some((t, r, s, o)) = (translations, rotations, scales, origins) .get(entity) .iter_mut() .next() { if let Some(translation) = translation { t.copy_from(translation); } if let Some(rotation) = rotation { r.copy_from(rotation); } if let Some(scale) = scale { s.copy_from(scale); } if let Some(origin) = origin { o.copy_from(origin); } } } }
extern crate embed_resource; fn main() { embed_resource::compile("hdpi_plotting.rc"); }
use specs::{BitSet, world::Index}; type Point2 = nalgebra::Point2<f32>; pub struct Neighborhood{ areas: Vec<BitSet>, width: i32, height: i32, } impl Neighborhood { pub fn new(width: i32, height: i32) -> Self { let mut areas = Vec::with_capacity( (width * height) as usize ); for _ in 0..(width*height) { areas.push(BitSet::new()); } Self{areas,width,height} } pub fn get(&self, x: i32, y: i32) -> &BitSet { let x = (x + self.width) % self.width; let y = (y + self.height) % self.height; &self.areas[(self.width * y + x) as usize] } pub fn insert(&mut self, x: i32, y: i32, id: Index) -> bool { self.areas[(self.width * y + x) as usize].add(id) } pub fn remove(&mut self, x: i32, y: i32, id: Index) -> bool { self.areas[(self.width * y + x) as usize].remove(id) } } pub fn get_area(pos: Point2, area_width: f32, area_height: f32) -> (i32, i32) { let px = (pos.x / area_width) as i32; let py = (pos.y / area_height) as i32; (px, py) }
use grpc; mod greeter; pub fn server() -> grpc::Result<grpc::Server> { let mut builder = grpc::ServerBuilder::new_plain(); builder.http.set_port(3000); builder.add_service(greeter::GreeterService::new()); builder.build() }
// verify-helper: PROBLEM http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_B use spella::algebra::{AssociativeMagma, CommutativeMagma, InvertibleMagma, Magma, UnitalMagma}; use spella::io::Scanner; use spella::sequences::FenwickTree; use std::io::{self, prelude::*}; use std::iter::FromIterator; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Sum(pub i32); impl Magma for Sum { fn op(&self, rhs: &Self) -> Self { Sum(self.0 + rhs.0) } } impl AssociativeMagma for Sum {} impl CommutativeMagma for Sum {} impl UnitalMagma for Sum { fn identity() -> Self { Sum(0) } } impl InvertibleMagma for Sum { fn invert(&self) -> Self { Sum(-self.0) } } fn main() -> io::Result<()> { let stdin = io::stdin(); let reader = stdin.lock(); let stdout = io::stdout(); let mut writer = std::io::BufWriter::new(stdout); let mut scanner = Scanner::new(reader); macro_rules! scan { ($T:ty) => { scanner.next::<$T>()?.unwrap() }; } let n = scan!(usize); let q = scan!(usize); let mut seq = FenwickTree::new(n); for _ in 0..q { let com = scan!(usize); match com { 0 => { let i = scan!(usize); let x = scan!(i32); seq.point_append(i - 1, &Sum(x)); } 1 => { let s = scan!(usize); let t = scan!(usize); writeln!(writer, "{}", seq.fold(s - 1..t).0)?; } _ => unreachable!(), } } assert_eq!( FenwickTree::from_iter((0..seq.len()).map(|i| seq.get(i))), seq ); Ok(()) }
use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use std::rc::Rc; pub struct Environment { parent: Option<EnvRef>, entries: HashMap<String, Object>, } pub type EnvRef = Rc<RefCell<Environment>>; impl Environment { pub fn new() -> EnvRef { let mut env = Environment { parent: None, entries: HashMap::new(), }; let native_functions = &[ ("+", Function::Native(plus)), ("-", Function::Native(minus)), ("*", Function::Native(multiply)), ("list", Function::Native(list)), ("cons", Function::Native(cons)), ("car", Function::Native(car)), ]; for (name, func) in native_functions.into_iter() { env.define(name.to_string(), Object::Callable(func.clone())) .unwrap(); } Rc::new(RefCell::new(env)) } pub fn new_child(parent: EnvRef) -> EnvRef { let env = Environment { parent: Some(parent), entries: HashMap::new(), }; Rc::new(RefCell::new(env)) } pub fn define(&mut self, key: String, obj: Object) -> Result<Object, Object> { self.entries.insert(key, obj); Ok(Object::Nil) } pub fn get(&self, key: &String) -> Object { match self.entries.get(key) { Some(val) => val.clone(), None => match self.parent { Some(ref parent) => parent.borrow().get(key), None => Object::Nil, }, } } } pub type BuiltinFunction = fn(&[Object], EnvRef) -> Result<Object, Object>; pub enum Function { Native(BuiltinFunction), Lambda(Vec<Object>, Vec<Object>, EnvRef), } impl PartialEq for Function { fn eq(&self, other: &Function) -> bool { self == other } } impl fmt::Display for Function { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Function::Native(_) => write!(f, "<native>"), Function::Lambda(_, _, _) => write!(f, "<lambda>"), } } } impl Clone for Function { fn clone(&self) -> Function { match *self { Function::Native(ref func) => Function::Native(*func), Function::Lambda(ref parameters, ref body, ref env) => { Function::Lambda(parameters.clone(), body.clone(), env.clone()) } } } } #[derive(Clone, PartialEq)] pub enum Object { Nil, Integer(i64), Symbol(String), List(Vec<Object>), Callable(Function), Error(String), } impl Object { pub fn new_error(message: &str) -> Object { Object::Error(String::from(message)) } pub fn has_symbol_value(&self, s: &str) -> Option<bool> { match self { Object::Symbol(sym) => Some(sym == s), _ => None, } } } impl fmt::Display for Object { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Object::Nil => write!(f, "<nil>"), Object::Integer(num) => write!(f, "{}", num), Object::Symbol(sym) => write!(f, "{}", sym), Object::Error(sym) => write!(f, "Error({})", sym), Object::Callable(_) => write!(f, "<callable>"), Object::List(items) => { write!(f, "(")?; for (i, item) in items.iter().enumerate() { write!(f, "{}", item)?; if i != items.len() - 1 { write!(f, " ")?; } } write!(f, ")") } } } } impl fmt::Debug for Object { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Object::Nil => write!(f, "Object::Nil"), Object::Integer(num) => write!(f, "Object::Integer({})", num), Object::Symbol(sym) => write!(f, "Object::Symbol({})", sym), Object::Error(sym) => write!(f, "Object::Error({})", sym), Object::Callable(_) => write!(f, "Object::Callable(<callable>)"), Object::List(items) => { write!(f, "(")?; for (i, item) in items.iter().enumerate() { write!(f, "{}", item)?; if i != items.len() - 1 { write!(f, " ")?; } } write!(f, ")") } } } } pub fn plus(args: &[Object], _env: EnvRef) -> Result<Object, Object> { let mut sum = 0; for i in args.iter() { if let Object::Integer(val) = i { sum += val; } else { return Ok(Object::Nil); } } Ok(Object::Integer(sum)) } pub fn minus(args: &[Object], _env: EnvRef) -> Result<Object, Object> { if args.len() < 2 { return Err(Object::new_error("not enough arguments")); } let mut iter = args.iter(); let mut sum = match iter.next().unwrap() { Object::Integer(first) => *first, _ => return Err(Object::new_error("argument has wrong type")), }; for i in iter { if let Object::Integer(val) = i { sum -= val; } else { return Err(Object::Nil); } } Ok(Object::Integer(sum)) } pub fn multiply(args: &[Object], _env: EnvRef) -> Result<Object, Object> { let mut sum = 1; for o in args.iter() { if let Object::Integer(val) = o { sum *= val; } else { return Err(Object::Nil); } } Ok(Object::Integer(sum)) } pub fn list(args: &[Object], _env: EnvRef) -> Result<Object, Object> { let items = args.to_vec(); Ok(Object::List(items)) } pub fn cons(args: &[Object], _env: EnvRef) -> Result<Object, Object> { if args.len() != 2 { return Err(Object::new_error("wrong number of arguments")); } let items = args.to_vec(); Ok(Object::List(items)) } pub fn car(args: &[Object], _env: EnvRef) -> Result<Object, Object> { if args.len() != 1 { return Err(Object::new_error("wrong number of arguments")); } let items = match &args[0] { Object::List(items) => items, _ => return Err(Object::new_error("argument has wrong type")), }; if items.is_empty() { return Err(Object::new_error("empty list")); } Ok(items[0].clone()) } #[cfg(test)] mod tests { use super::*; macro_rules! integer_vec { ( $( $x:expr ),* ) => { { let mut temp_vec = Vec::new(); $(temp_vec.push(Object::Integer($x));)* temp_vec } }; } #[test] fn test_list_plus() { let args = integer_vec![1, 2, 3]; let sum = plus(&args, Environment::new()); assert_eq!(sum, Ok(Object::Integer(6))); } #[test] fn test_list_minus() { let args = integer_vec![8, 4, 2]; let result = minus(&args, Environment::new()); assert_eq!(result, Ok(Object::Integer(2))); } #[test] fn test_list_multiply() { let args = integer_vec![1, 2, 3]; let multiply_result = multiply(&args, Environment::new()); assert_eq!(multiply_result, Ok(Object::Integer(6))); } #[test] fn test_cons() { let args = integer_vec![1, 2]; let cons_result = cons(&args, Environment::new()); assert_eq!(cons_result, Ok(Object::List(integer_vec![1, 2]))); let args = integer_vec![1, 2, 3, 4]; let cons_result = cons(&args, Environment::new()); assert_eq!( cons_result, Err(Object::Error(String::from("wrong number of arguments"))) ); } #[test] fn test_car() { let args = vec![Object::List(integer_vec![1, 2])]; let car_result = car(&args, Environment::new()); assert_eq!(car_result, Ok(Object::Integer(1))); let args = vec![Object::List(Vec::new())]; let car_result = car(&args, Environment::new()); assert_eq!(car_result, Err(Object::Error(String::from("empty list")))); let args = vec![Object::Integer(1)]; let car_result = car(&args, Environment::new()); assert_eq!( car_result, Err(Object::Error(String::from("argument has wrong type"))) ); } #[test] fn test_environment_get() { let env = Environment::new(); let name = "six".to_string(); let result = env.borrow_mut().define(name.clone(), Object::Integer(6)); assert!(result.is_ok()); assert_eq!(env.borrow_mut().get(&name), Object::Integer(6)); let name = "doesnotexist".to_string(); assert_eq!(env.borrow_mut().get(&name), Object::Nil); } #[test] fn test_environment_get_with_parent() { let parent = Environment::new(); let only_in_parent = "inparent".to_string(); let result = parent .borrow_mut() .define(only_in_parent.clone(), Object::Integer(6)); assert!(result.is_ok()); assert_eq!(parent.borrow_mut().get(&only_in_parent), Object::Integer(6)); let child = Environment::new_child(parent.clone()); assert_eq!(child.borrow_mut().get(&only_in_parent), Object::Integer(6)); let only_in_child = "inchild".to_string(); let result = child .borrow_mut() .define(only_in_child.clone(), Object::Integer(99)); assert!(result.is_ok()); assert_eq!(child.borrow_mut().get(&only_in_child), Object::Integer(99)); assert_eq!(parent.borrow_mut().get(&only_in_child), Object::Nil); } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type HCS_CALLBACK = isize;
use std::fs::File; use std::io::Read; #[macro_use] extern crate glium; #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], tex: [f32; 2], } fn main() { use glium::{DisplayBuild, Surface}; let display = glium::glutin::WindowBuilder::new().build_glium().unwrap(); implement_vertex!(Vertex, position, tex); let tris = vec![Vertex {position: [-1.0,1.0], tex: [0.0,1.0]}, Vertex {position: [1.0,1.0], tex: [1.0,1.0]}, Vertex {position: [1.0,-1.0], tex: [1.0,0.0]}, Vertex {position: [-1.0,-1.0], tex: [0.0,0.0]}]; let ilist:Vec<u16> = vec![0, 1, 2, 0, 2, 3]; let vertex_buffer = glium::VertexBuffer::new(&display, &tris).unwrap(); let indices = glium::IndexBuffer::new(&display, glium::index::PrimitiveType::TrianglesList, &ilist).unwrap(); let mut v_file = File::open("assests/shaders/mandelbrot.vert").unwrap(); let mut vert_shader_src = String::new(); v_file.read_to_string(&mut vert_shader_src).unwrap(); let mut f_file = File::open("assests/shaders/mandelbrot.frag").unwrap(); let mut frag_shader_src = String::new(); f_file.read_to_string(&mut frag_shader_src).unwrap(); let program = glium::Program::from_source(&display, &vert_shader_src, &frag_shader_src, None).unwrap(); let mut x = 0.7f32; let mut y = 0.0f32; let mut iter = 100; let mut scale = 2.0f32; loop { let mut target = display.draw(); target.clear_color(0.0, 0.0, 1.0, 1.0); let uniforms = uniform!{scale: scale, center: [x, y], iter: iter}; target.draw(&vertex_buffer, &indices, &program, &uniforms, &Default::default()).unwrap(); target.finish().unwrap(); for ev in display.poll_events() { match ev { glium::glutin::Event::Closed => return, glium::glutin::Event::KeyboardInput(glium::glutin::ElementState::Pressed, _, Some(glium::glutin::VirtualKeyCode::Escape)) => return, glium::glutin::Event::KeyboardInput(glium::glutin::ElementState::Pressed, _, Some(glium::glutin::VirtualKeyCode::Up)) => y -= 0.1f32 * scale, glium::glutin::Event::KeyboardInput(glium::glutin::ElementState::Pressed, _, Some(glium::glutin::VirtualKeyCode::Down)) => y += 0.1f32 * scale, glium::glutin::Event::KeyboardInput(glium::glutin::ElementState::Pressed, _, Some(glium::glutin::VirtualKeyCode::Left)) => x += 0.1f32 * scale, glium::glutin::Event::KeyboardInput(glium::glutin::ElementState::Pressed, _, Some(glium::glutin::VirtualKeyCode::Right)) => x -=0.1f32 * scale, glium::glutin::Event::KeyboardInput(glium::glutin::ElementState::Pressed, _, Some(glium::glutin::VirtualKeyCode::PageUp)) => iter += 5, glium::glutin::Event::KeyboardInput(glium::glutin::ElementState::Pressed, _, Some(glium::glutin::VirtualKeyCode::PageDown)) => iter -= 5, glium::glutin::Event::KeyboardInput(glium::glutin::ElementState::Pressed, _, Some(glium::glutin::VirtualKeyCode::X)) => scale = scale * 0.9f32, glium::glutin::Event::KeyboardInput(glium::glutin::ElementState::Pressed, _, Some(glium::glutin::VirtualKeyCode::Z)) => scale = scale / 0.9f32, _ => () } } } }
use std::collections::VecDeque; pub fn gen_a1(prev: u64) -> u64 { (prev * 16807) % 2147483647 } pub fn gen_b1(prev: u64) -> u64 { (prev * 48271) % 2147483647 } pub fn part1() { let mut a: u64 = 783; let mut b: u64 = 325; let mut matches: i32 = 0; for _i in 0..40000000 { a = gen_a1(a); b = gen_b1(b); let a_lo = a & 0xffff; let b_lo = b & 0xffff; if a_lo == b_lo { matches = matches + 1; } } println!("Day 15 result 1: {}", matches); } pub fn gen_a2(prev: u64) -> (u64, bool) { let next = (prev * 16807) % 2147483647; (next, next % 4 == 0) } pub fn gen_b2(prev: u64) -> (u64, bool) { let next = (prev * 48271) % 2147483647; (next, next % 8 == 0) } pub fn part2() { let mut a: u64 = 783; let mut a_check: VecDeque<u64> = VecDeque::new(); let mut b: u64 = 325; let mut b_check: VecDeque<u64> = VecDeque::new(); const N: usize = 5000000; while a_check.len() < N || b_check.len() < N { let (a_next, a_ok) = gen_a2(a); let (b_next, b_ok) = gen_b2(b); a = a_next; b = b_next; if a_ok { a_check.push_back(a_next); } if b_ok { b_check.push_back(b_next); } } let mut matches: i32 = 0; let mut n = 0; while !a_check.is_empty() && !b_check.is_empty() { let a = a_check.pop_front().unwrap(); let a_lo = a & 0xffff; let b = b_check.pop_front().unwrap(); let b_lo = b & 0xffff; n = n + 1; if a_lo == b_lo { matches = matches + 1; } } println!("Day 15 result 2: {}", matches); } pub fn run() { part1(); part2(); }
// Copyright 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. // run-pass // check that we handle recursive arrays correctly in `type_of` struct Loopy { ptr: *mut [Loopy; 1] } fn main() { let _t = Loopy { ptr: 0 as *mut _ }; }
use std::io; fn main() { let mut reader = io::stdin(); let mut control: String = String::new(); loop { reader.read_line(&mut control); control.trim(); if control.eq("quit\r\n") { println!("adios!"); break; } else { println!("{}", control); } control.clear(); } }
#[doc = "Reader of register CR2"] pub type R = crate::R<u32, super::CR2>; #[doc = "Writer for register CR2"] pub type W = crate::W<u32, super::CR2>; #[doc = "Register CR2 `reset()`'s with value 0"] impl crate::ResetValue for super::CR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Output Idle state 1\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OIS1N_A { #[doc = "0: OC1N=0 after a dead-time when MOE=0"] LOW = 0, #[doc = "1: OC1N=1 after a dead-time when MOE=0"] HIGH = 1, } impl From<OIS1N_A> for bool { #[inline(always)] fn from(variant: OIS1N_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `OIS1N`"] pub type OIS1N_R = crate::R<bool, OIS1N_A>; impl OIS1N_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OIS1N_A { match self.bits { false => OIS1N_A::LOW, true => OIS1N_A::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline(always)] pub fn is_low(&self) -> bool { *self == OIS1N_A::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline(always)] pub fn is_high(&self) -> bool { *self == OIS1N_A::HIGH } } #[doc = "Write proxy for field `OIS1N`"] pub struct OIS1N_W<'a> { w: &'a mut W, } impl<'a> OIS1N_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OIS1N_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "OC1N=0 after a dead-time when MOE=0"] #[inline(always)] pub fn low(self) -> &'a mut W { self.variant(OIS1N_A::LOW) } #[doc = "OC1N=1 after a dead-time when MOE=0"] #[inline(always)] pub fn high(self) -> &'a mut W { self.variant(OIS1N_A::HIGH) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Output Idle state 1\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OIS1_A { #[doc = "0: OC1=0 (after a dead-time if OC1N is implemented) when MOE=0"] LOW = 0, #[doc = "1: OC1=1 (after a dead-time if OC1N is implemented) when MOE=0"] HIGH = 1, } impl From<OIS1_A> for bool { #[inline(always)] fn from(variant: OIS1_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `OIS1`"] pub type OIS1_R = crate::R<bool, OIS1_A>; impl OIS1_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OIS1_A { match self.bits { false => OIS1_A::LOW, true => OIS1_A::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline(always)] pub fn is_low(&self) -> bool { *self == OIS1_A::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline(always)] pub fn is_high(&self) -> bool { *self == OIS1_A::HIGH } } #[doc = "Write proxy for field `OIS1`"] pub struct OIS1_W<'a> { w: &'a mut W, } impl<'a> OIS1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OIS1_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "OC1=0 (after a dead-time if OC1N is implemented) when MOE=0"] #[inline(always)] pub fn low(self) -> &'a mut W { self.variant(OIS1_A::LOW) } #[doc = "OC1=1 (after a dead-time if OC1N is implemented) when MOE=0"] #[inline(always)] pub fn high(self) -> &'a mut W { self.variant(OIS1_A::HIGH) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Capture/compare DMA selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CCDS_A { #[doc = "0: CCx DMA request sent when CCx event occurs"] ONCOMPARE = 0, #[doc = "1: CCx DMA request sent when update event occurs"] ONUPDATE = 1, } impl From<CCDS_A> for bool { #[inline(always)] fn from(variant: CCDS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CCDS`"] pub type CCDS_R = crate::R<bool, CCDS_A>; impl CCDS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CCDS_A { match self.bits { false => CCDS_A::ONCOMPARE, true => CCDS_A::ONUPDATE, } } #[doc = "Checks if the value of the field is `ONCOMPARE`"] #[inline(always)] pub fn is_on_compare(&self) -> bool { *self == CCDS_A::ONCOMPARE } #[doc = "Checks if the value of the field is `ONUPDATE`"] #[inline(always)] pub fn is_on_update(&self) -> bool { *self == CCDS_A::ONUPDATE } } #[doc = "Write proxy for field `CCDS`"] pub struct CCDS_W<'a> { w: &'a mut W, } impl<'a> CCDS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CCDS_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "CCx DMA request sent when CCx event occurs"] #[inline(always)] pub fn on_compare(self) -> &'a mut W { self.variant(CCDS_A::ONCOMPARE) } #[doc = "CCx DMA request sent when update event occurs"] #[inline(always)] pub fn on_update(self) -> &'a mut W { self.variant(CCDS_A::ONUPDATE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Capture/compare control update selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CCUS_A { #[doc = "0: Capture/compare are updated only by setting the COMG bit"] DEFAULT = 0, #[doc = "1: Capture/compare are updated by setting the COMG bit or when an rising edge occurs on TRGI"] WITHRISINGEDGE = 1, } impl From<CCUS_A> for bool { #[inline(always)] fn from(variant: CCUS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CCUS`"] pub type CCUS_R = crate::R<bool, CCUS_A>; impl CCUS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CCUS_A { match self.bits { false => CCUS_A::DEFAULT, true => CCUS_A::WITHRISINGEDGE, } } #[doc = "Checks if the value of the field is `DEFAULT`"] #[inline(always)] pub fn is_default(&self) -> bool { *self == CCUS_A::DEFAULT } #[doc = "Checks if the value of the field is `WITHRISINGEDGE`"] #[inline(always)] pub fn is_with_rising_edge(&self) -> bool { *self == CCUS_A::WITHRISINGEDGE } } #[doc = "Write proxy for field `CCUS`"] pub struct CCUS_W<'a> { w: &'a mut W, } impl<'a> CCUS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CCUS_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Capture/compare are updated only by setting the COMG bit"] #[inline(always)] pub fn default(self) -> &'a mut W { self.variant(CCUS_A::DEFAULT) } #[doc = "Capture/compare are updated by setting the COMG bit or when an rising edge occurs on TRGI"] #[inline(always)] pub fn with_rising_edge(self) -> &'a mut W { self.variant(CCUS_A::WITHRISINGEDGE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Capture/compare preloaded control\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CCPC_A { #[doc = "0: CCxE, CCxNE and OCxM bits are not preloaded"] NOTPRELOADED = 0, #[doc = "1: CCxE, CCxNE and OCxM bits are preloaded"] PRELOADED = 1, } impl From<CCPC_A> for bool { #[inline(always)] fn from(variant: CCPC_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CCPC`"] pub type CCPC_R = crate::R<bool, CCPC_A>; impl CCPC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CCPC_A { match self.bits { false => CCPC_A::NOTPRELOADED, true => CCPC_A::PRELOADED, } } #[doc = "Checks if the value of the field is `NOTPRELOADED`"] #[inline(always)] pub fn is_not_preloaded(&self) -> bool { *self == CCPC_A::NOTPRELOADED } #[doc = "Checks if the value of the field is `PRELOADED`"] #[inline(always)] pub fn is_preloaded(&self) -> bool { *self == CCPC_A::PRELOADED } } #[doc = "Write proxy for field `CCPC`"] pub struct CCPC_W<'a> { w: &'a mut W, } impl<'a> CCPC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CCPC_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "CCxE, CCxNE and OCxM bits are not preloaded"] #[inline(always)] pub fn not_preloaded(self) -> &'a mut W { self.variant(CCPC_A::NOTPRELOADED) } #[doc = "CCxE, CCxNE and OCxM bits are preloaded"] #[inline(always)] pub fn preloaded(self) -> &'a mut W { self.variant(CCPC_A::PRELOADED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 9 - Output Idle state 1"] #[inline(always)] pub fn ois1n(&self) -> OIS1N_R { OIS1N_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - Output Idle state 1"] #[inline(always)] pub fn ois1(&self) -> OIS1_R { OIS1_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 3 - Capture/compare DMA selection"] #[inline(always)] pub fn ccds(&self) -> CCDS_R { CCDS_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - Capture/compare control update selection"] #[inline(always)] pub fn ccus(&self) -> CCUS_R { CCUS_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 0 - Capture/compare preloaded control"] #[inline(always)] pub fn ccpc(&self) -> CCPC_R { CCPC_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 9 - Output Idle state 1"] #[inline(always)] pub fn ois1n(&mut self) -> OIS1N_W { OIS1N_W { w: self } } #[doc = "Bit 8 - Output Idle state 1"] #[inline(always)] pub fn ois1(&mut self) -> OIS1_W { OIS1_W { w: self } } #[doc = "Bit 3 - Capture/compare DMA selection"] #[inline(always)] pub fn ccds(&mut self) -> CCDS_W { CCDS_W { w: self } } #[doc = "Bit 2 - Capture/compare control update selection"] #[inline(always)] pub fn ccus(&mut self) -> CCUS_W { CCUS_W { w: self } } #[doc = "Bit 0 - Capture/compare preloaded control"] #[inline(always)] pub fn ccpc(&mut self) -> CCPC_W { CCPC_W { w: self } } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HCS_CREATE_OPTIONS(pub i32); pub const HcsCreateOptions_1: HCS_CREATE_OPTIONS = HCS_CREATE_OPTIONS(65536i32); impl ::core::convert::From<i32> for HCS_CREATE_OPTIONS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HCS_CREATE_OPTIONS { type Abi = Self; } #[derive(:: core :: clone :: Clone)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub struct HCS_CREATE_OPTIONS_1 { pub Version: HCS_CREATE_OPTIONS, pub UserToken: super::super::Foundation::HANDLE, pub SecurityDescriptor: *mut super::super::Security::SECURITY_DESCRIPTOR, pub CallbackOptions: HCS_EVENT_OPTIONS, pub CallbackContext: *mut ::core::ffi::c_void, pub Callback: ::core::option::Option<HCS_EVENT_CALLBACK>, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl HCS_CREATE_OPTIONS_1 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::default::Default for HCS_CREATE_OPTIONS_1 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::fmt::Debug for HCS_CREATE_OPTIONS_1 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HCS_CREATE_OPTIONS_1").field("Version", &self.Version).field("UserToken", &self.UserToken).field("SecurityDescriptor", &self.SecurityDescriptor).field("CallbackOptions", &self.CallbackOptions).field("CallbackContext", &self.CallbackContext).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::cmp::PartialEq for HCS_CREATE_OPTIONS_1 { fn eq(&self, other: &Self) -> bool { self.Version == other.Version && self.UserToken == other.UserToken && self.SecurityDescriptor == other.SecurityDescriptor && self.CallbackOptions == other.CallbackOptions && self.CallbackContext == other.CallbackContext && self.Callback.map(|f| f as usize) == other.Callback.map(|f| f as usize) } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::cmp::Eq for HCS_CREATE_OPTIONS_1 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] unsafe impl ::windows::core::Abi for HCS_CREATE_OPTIONS_1 { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HCS_EVENT { pub Type: HCS_EVENT_TYPE, pub EventData: super::super::Foundation::PWSTR, pub Operation: HCS_OPERATION, } #[cfg(feature = "Win32_Foundation")] impl HCS_EVENT {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HCS_EVENT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HCS_EVENT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HCS_EVENT").field("Type", &self.Type).field("EventData", &self.EventData).field("Operation", &self.Operation).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HCS_EVENT { fn eq(&self, other: &Self) -> bool { self.Type == other.Type && self.EventData == other.EventData && self.Operation == other.Operation } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HCS_EVENT {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HCS_EVENT { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] pub type HCS_EVENT_CALLBACK = unsafe extern "system" fn(event: *const HCS_EVENT, context: *const ::core::ffi::c_void); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HCS_EVENT_OPTIONS(pub u32); pub const HcsEventOptionNone: HCS_EVENT_OPTIONS = HCS_EVENT_OPTIONS(0u32); pub const HcsEventOptionEnableOperationCallbacks: HCS_EVENT_OPTIONS = HCS_EVENT_OPTIONS(1u32); impl ::core::convert::From<u32> for HCS_EVENT_OPTIONS { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HCS_EVENT_OPTIONS { type Abi = Self; } impl ::core::ops::BitOr for HCS_EVENT_OPTIONS { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for HCS_EVENT_OPTIONS { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for HCS_EVENT_OPTIONS { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for HCS_EVENT_OPTIONS { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for HCS_EVENT_OPTIONS { 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 HCS_EVENT_TYPE(pub i32); pub const HcsEventInvalid: HCS_EVENT_TYPE = HCS_EVENT_TYPE(0i32); pub const HcsEventSystemExited: HCS_EVENT_TYPE = HCS_EVENT_TYPE(1i32); pub const HcsEventSystemCrashInitiated: HCS_EVENT_TYPE = HCS_EVENT_TYPE(2i32); pub const HcsEventSystemCrashReport: HCS_EVENT_TYPE = HCS_EVENT_TYPE(3i32); pub const HcsEventSystemRdpEnhancedModeStateChanged: HCS_EVENT_TYPE = HCS_EVENT_TYPE(4i32); pub const HcsEventSystemSiloJobCreated: HCS_EVENT_TYPE = HCS_EVENT_TYPE(5i32); pub const HcsEventSystemGuestConnectionClosed: HCS_EVENT_TYPE = HCS_EVENT_TYPE(6i32); pub const HcsEventProcessExited: HCS_EVENT_TYPE = HCS_EVENT_TYPE(65536i32); pub const HcsEventOperationCallback: HCS_EVENT_TYPE = HCS_EVENT_TYPE(16777216i32); pub const HcsEventServiceDisconnect: HCS_EVENT_TYPE = HCS_EVENT_TYPE(33554432i32); impl ::core::convert::From<i32> for HCS_EVENT_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HCS_EVENT_TYPE { 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 HCS_NOTIFICATIONS(pub i32); pub const HcsNotificationInvalid: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(0i32); pub const HcsNotificationSystemExited: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(1i32); pub const HcsNotificationSystemCreateCompleted: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(2i32); pub const HcsNotificationSystemStartCompleted: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(3i32); pub const HcsNotificationSystemPauseCompleted: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(4i32); pub const HcsNotificationSystemResumeCompleted: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(5i32); pub const HcsNotificationSystemCrashReport: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(6i32); pub const HcsNotificationSystemSiloJobCreated: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(7i32); pub const HcsNotificationSystemSaveCompleted: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(8i32); pub const HcsNotificationSystemRdpEnhancedModeStateChanged: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(9i32); pub const HcsNotificationSystemShutdownFailed: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(10i32); pub const HcsNotificationSystemShutdownCompleted: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(10i32); pub const HcsNotificationSystemGetPropertiesCompleted: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(11i32); pub const HcsNotificationSystemModifyCompleted: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(12i32); pub const HcsNotificationSystemCrashInitiated: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(13i32); pub const HcsNotificationSystemGuestConnectionClosed: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(14i32); pub const HcsNotificationSystemOperationCompletion: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(15i32); pub const HcsNotificationSystemPassThru: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(16i32); pub const HcsNotificationProcessExited: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(65536i32); pub const HcsNotificationServiceDisconnect: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(16777216i32); pub const HcsNotificationFlagsReserved: HCS_NOTIFICATIONS = HCS_NOTIFICATIONS(-268435456i32); impl ::core::convert::From<i32> for HCS_NOTIFICATIONS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HCS_NOTIFICATIONS { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] pub type HCS_NOTIFICATION_CALLBACK = unsafe extern "system" fn(notificationtype: u32, context: *const ::core::ffi::c_void, notificationstatus: ::windows::core::HRESULT, notificationdata: super::super::Foundation::PWSTR); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HCS_NOTIFICATION_FLAGS(pub i32); pub const HcsNotificationFlagSuccess: HCS_NOTIFICATION_FLAGS = HCS_NOTIFICATION_FLAGS(0i32); pub const HcsNotificationFlagFailure: HCS_NOTIFICATION_FLAGS = HCS_NOTIFICATION_FLAGS(-2147483648i32); impl ::core::convert::From<i32> for HCS_NOTIFICATION_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HCS_NOTIFICATION_FLAGS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq)] #[repr(transparent)] pub struct HCS_OPERATION(pub isize); impl ::core::default::Default for HCS_OPERATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } unsafe impl ::windows::core::Handle for HCS_OPERATION {} unsafe impl ::windows::core::Abi for HCS_OPERATION { type Abi = Self; } pub type HCS_OPERATION_COMPLETION = unsafe extern "system" fn(operation: HCS_OPERATION, context: *const ::core::ffi::c_void); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HCS_OPERATION_TYPE(pub i32); pub const HcsOperationTypeNone: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(-1i32); pub const HcsOperationTypeEnumerate: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(0i32); pub const HcsOperationTypeCreate: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(1i32); pub const HcsOperationTypeStart: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(2i32); pub const HcsOperationTypeShutdown: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(3i32); pub const HcsOperationTypePause: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(4i32); pub const HcsOperationTypeResume: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(5i32); pub const HcsOperationTypeSave: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(6i32); pub const HcsOperationTypeTerminate: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(7i32); pub const HcsOperationTypeModify: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(8i32); pub const HcsOperationTypeGetProperties: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(9i32); pub const HcsOperationTypeCreateProcess: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(10i32); pub const HcsOperationTypeSignalProcess: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(11i32); pub const HcsOperationTypeGetProcessInfo: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(12i32); pub const HcsOperationTypeGetProcessProperties: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(13i32); pub const HcsOperationTypeModifyProcess: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(14i32); pub const HcsOperationTypeCrash: HCS_OPERATION_TYPE = HCS_OPERATION_TYPE(15i32); impl ::core::convert::From<i32> for HCS_OPERATION_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HCS_OPERATION_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq)] #[repr(transparent)] pub struct HCS_PROCESS(pub isize); impl ::core::default::Default for HCS_PROCESS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } unsafe impl ::windows::core::Handle for HCS_PROCESS {} unsafe impl ::windows::core::Abi for HCS_PROCESS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HCS_PROCESS_INFORMATION { pub ProcessId: u32, pub Reserved: u32, pub StdInput: super::super::Foundation::HANDLE, pub StdOutput: super::super::Foundation::HANDLE, pub StdError: super::super::Foundation::HANDLE, } #[cfg(feature = "Win32_Foundation")] impl HCS_PROCESS_INFORMATION {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HCS_PROCESS_INFORMATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HCS_PROCESS_INFORMATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HCS_PROCESS_INFORMATION").field("ProcessId", &self.ProcessId).field("Reserved", &self.Reserved).field("StdInput", &self.StdInput).field("StdOutput", &self.StdOutput).field("StdError", &self.StdError).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HCS_PROCESS_INFORMATION { fn eq(&self, other: &Self) -> bool { self.ProcessId == other.ProcessId && self.Reserved == other.Reserved && self.StdInput == other.StdInput && self.StdOutput == other.StdOutput && self.StdError == other.StdError } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HCS_PROCESS_INFORMATION {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HCS_PROCESS_INFORMATION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq)] #[repr(transparent)] pub struct HCS_SYSTEM(pub isize); impl ::core::default::Default for HCS_SYSTEM { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } unsafe impl ::windows::core::Handle for HCS_SYSTEM {} unsafe impl ::windows::core::Abi for HCS_SYSTEM { type Abi = Self; } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsAttachLayerStorageFilter<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(layerpath: Param0, layerdata: Param1) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsAttachLayerStorageFilter(layerpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsAttachLayerStorageFilter(layerpath.into_param().abi(), layerdata.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsCancelOperation<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCancelOperation(operation: HCS_OPERATION) -> ::windows::core::HRESULT; } HcsCancelOperation(operation.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsCloseComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>>(computesystem: Param0) { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCloseComputeSystem(computesystem: HCS_SYSTEM); } ::core::mem::transmute(HcsCloseComputeSystem(computesystem.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsCloseOperation<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0) { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCloseOperation(operation: HCS_OPERATION); } ::core::mem::transmute(HcsCloseOperation(operation.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsCloseProcess<'a, Param0: ::windows::core::IntoParam<'a, HCS_PROCESS>>(process: Param0) { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCloseProcess(process: HCS_PROCESS); } ::core::mem::transmute(HcsCloseProcess(process.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsCrashComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(computesystem: Param0, operation: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCrashComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsCrashComputeSystem(computesystem.into_param().abi(), operation.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] #[inline] pub unsafe fn HcsCreateComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, HCS_OPERATION>>(id: Param0, configuration: Param1, operation: Param2, securitydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> ::windows::core::Result<HCS_SYSTEM> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCreateComputeSystem(id: super::super::Foundation::PWSTR, configuration: super::super::Foundation::PWSTR, operation: HCS_OPERATION, securitydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR, computesystem: *mut HCS_SYSTEM) -> ::windows::core::HRESULT; } let mut result__: <HCS_SYSTEM as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsCreateComputeSystem(id.into_param().abi(), configuration.into_param().abi(), operation.into_param().abi(), ::core::mem::transmute(securitydescriptor), &mut result__).from_abi::<HCS_SYSTEM>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsCreateComputeSystemInNamespace<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, HCS_OPERATION>>(idnamespace: Param0, id: Param1, configuration: Param2, operation: Param3, options: *const HCS_CREATE_OPTIONS) -> ::windows::core::Result<HCS_SYSTEM> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCreateComputeSystemInNamespace(idnamespace: super::super::Foundation::PWSTR, id: super::super::Foundation::PWSTR, configuration: super::super::Foundation::PWSTR, operation: HCS_OPERATION, options: *const HCS_CREATE_OPTIONS, computesystem: *mut HCS_SYSTEM) -> ::windows::core::HRESULT; } let mut result__: <HCS_SYSTEM as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsCreateComputeSystemInNamespace(idnamespace.into_param().abi(), id.into_param().abi(), configuration.into_param().abi(), operation.into_param().abi(), ::core::mem::transmute(options), &mut result__).from_abi::<HCS_SYSTEM>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsCreateEmptyGuestStateFile<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(gueststatefilepath: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCreateEmptyGuestStateFile(gueststatefilepath: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsCreateEmptyGuestStateFile(gueststatefilepath.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsCreateEmptyRuntimeStateFile<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(runtimestatefilepath: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCreateEmptyRuntimeStateFile(runtimestatefilepath: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsCreateEmptyRuntimeStateFile(runtimestatefilepath.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsCreateOperation(context: *const ::core::ffi::c_void, callback: ::core::option::Option<HCS_OPERATION_COMPLETION>) -> HCS_OPERATION { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCreateOperation(context: *const ::core::ffi::c_void, callback: ::windows::core::RawPtr) -> HCS_OPERATION; } ::core::mem::transmute(HcsCreateOperation(::core::mem::transmute(context), ::core::mem::transmute(callback))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] #[inline] pub unsafe fn HcsCreateProcess<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, HCS_OPERATION>>(computesystem: Param0, processparameters: Param1, operation: Param2, securitydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> ::windows::core::Result<HCS_PROCESS> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsCreateProcess(computesystem: HCS_SYSTEM, processparameters: super::super::Foundation::PWSTR, operation: HCS_OPERATION, securitydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR, process: *mut HCS_PROCESS) -> ::windows::core::HRESULT; } let mut result__: <HCS_PROCESS as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsCreateProcess(computesystem.into_param().abi(), processparameters.into_param().abi(), operation.into_param().abi(), ::core::mem::transmute(securitydescriptor), &mut result__).from_abi::<HCS_PROCESS>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsDestroyLayer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(layerpath: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsDestroyLayer(layerpath: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsDestroyLayer(layerpath.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsDetachLayerStorageFilter<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(layerpath: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsDetachLayerStorageFilter(layerpath: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsDetachLayerStorageFilter(layerpath.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsEnumerateComputeSystems<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>>(query: Param0, operation: Param1) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsEnumerateComputeSystems(query: super::super::Foundation::PWSTR, operation: HCS_OPERATION) -> ::windows::core::HRESULT; } HcsEnumerateComputeSystems(query.into_param().abi(), operation.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsEnumerateComputeSystemsInNamespace<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, HCS_OPERATION>>(idnamespace: Param0, query: Param1, operation: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsEnumerateComputeSystemsInNamespace(idnamespace: super::super::Foundation::PWSTR, query: super::super::Foundation::PWSTR, operation: HCS_OPERATION) -> ::windows::core::HRESULT; } HcsEnumerateComputeSystemsInNamespace(idnamespace.into_param().abi(), query.into_param().abi(), operation.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsExportLayer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(layerpath: Param0, exportfolderpath: Param1, layerdata: Param2, options: Param3) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsExportLayer(layerpath: super::super::Foundation::PWSTR, exportfolderpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsExportLayer(layerpath.into_param().abi(), exportfolderpath.into_param().abi(), layerdata.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsExportLegacyWritableLayer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(writablelayermountpath: Param0, writablelayerfolderpath: Param1, exportfolderpath: Param2, layerdata: Param3) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsExportLegacyWritableLayer(writablelayermountpath: super::super::Foundation::PWSTR, writablelayerfolderpath: super::super::Foundation::PWSTR, exportfolderpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsExportLegacyWritableLayer(writablelayermountpath.into_param().abi(), writablelayerfolderpath.into_param().abi(), exportfolderpath.into_param().abi(), layerdata.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsFormatWritableLayerVhd<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(vhdhandle: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsFormatWritableLayerVhd(vhdhandle: super::super::Foundation::HANDLE) -> ::windows::core::HRESULT; } HcsFormatWritableLayerVhd(vhdhandle.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsGetComputeSystemFromOperation<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0) -> HCS_SYSTEM { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetComputeSystemFromOperation(operation: HCS_OPERATION) -> HCS_SYSTEM; } ::core::mem::transmute(HcsGetComputeSystemFromOperation(operation.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsGetComputeSystemProperties<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(computesystem: Param0, operation: Param1, propertyquery: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetComputeSystemProperties(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, propertyquery: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsGetComputeSystemProperties(computesystem.into_param().abi(), operation.into_param().abi(), propertyquery.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsGetLayerVhdMountPath<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(vhdhandle: Param0) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetLayerVhdMountPath(vhdhandle: super::super::Foundation::HANDLE, mountpath: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsGetLayerVhdMountPath(vhdhandle.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsGetOperationContext<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0) -> *mut ::core::ffi::c_void { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetOperationContext(operation: HCS_OPERATION) -> *mut ::core::ffi::c_void; } ::core::mem::transmute(HcsGetOperationContext(operation.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsGetOperationId<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0) -> u64 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetOperationId(operation: HCS_OPERATION) -> u64; } ::core::mem::transmute(HcsGetOperationId(operation.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsGetOperationResult<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetOperationResult(operation: HCS_OPERATION, resultdocument: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsGetOperationResult(operation.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsGetOperationResultAndProcessInfo<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0, processinformation: *mut HCS_PROCESS_INFORMATION, resultdocument: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetOperationResultAndProcessInfo(operation: HCS_OPERATION, processinformation: *mut HCS_PROCESS_INFORMATION, resultdocument: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsGetOperationResultAndProcessInfo(operation.into_param().abi(), ::core::mem::transmute(processinformation), ::core::mem::transmute(resultdocument)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsGetOperationType<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0) -> HCS_OPERATION_TYPE { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetOperationType(operation: HCS_OPERATION) -> HCS_OPERATION_TYPE; } ::core::mem::transmute(HcsGetOperationType(operation.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsGetProcessFromOperation<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0) -> HCS_PROCESS { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetProcessFromOperation(operation: HCS_OPERATION) -> HCS_PROCESS; } ::core::mem::transmute(HcsGetProcessFromOperation(operation.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsGetProcessInfo<'a, Param0: ::windows::core::IntoParam<'a, HCS_PROCESS>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>>(process: Param0, operation: Param1) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetProcessInfo(process: HCS_PROCESS, operation: HCS_OPERATION) -> ::windows::core::HRESULT; } HcsGetProcessInfo(process.into_param().abi(), operation.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsGetProcessProperties<'a, Param0: ::windows::core::IntoParam<'a, HCS_PROCESS>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(process: Param0, operation: Param1, propertyquery: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetProcessProperties(process: HCS_PROCESS, operation: HCS_OPERATION, propertyquery: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsGetProcessProperties(process.into_param().abi(), operation.into_param().abi(), propertyquery.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsGetProcessorCompatibilityFromSavedState<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(runtimefilename: Param0) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetProcessorCompatibilityFromSavedState(runtimefilename: super::super::Foundation::PWSTR, processorfeaturesstring: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsGetProcessorCompatibilityFromSavedState(runtimefilename.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsGetServiceProperties<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(propertyquery: Param0) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGetServiceProperties(propertyquery: super::super::Foundation::PWSTR, result: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsGetServiceProperties(propertyquery.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsGrantVmAccess<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(vmid: Param0, filepath: Param1) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGrantVmAccess(vmid: super::super::Foundation::PWSTR, filepath: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsGrantVmAccess(vmid.into_param().abi(), filepath.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsGrantVmGroupAccess<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(filepath: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsGrantVmGroupAccess(filepath: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsGrantVmGroupAccess(filepath.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsImportLayer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(layerpath: Param0, sourcefolderpath: Param1, layerdata: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsImportLayer(layerpath: super::super::Foundation::PWSTR, sourcefolderpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsImportLayer(layerpath.into_param().abi(), sourcefolderpath.into_param().abi(), layerdata.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsInitializeLegacyWritableLayer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(writablelayermountpath: Param0, writablelayerfolderpath: Param1, layerdata: Param2, options: Param3) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsInitializeLegacyWritableLayer(writablelayermountpath: super::super::Foundation::PWSTR, writablelayerfolderpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsInitializeLegacyWritableLayer(writablelayermountpath.into_param().abi(), writablelayerfolderpath.into_param().abi(), layerdata.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsInitializeWritableLayer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(writablelayerpath: Param0, layerdata: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsInitializeWritableLayer(writablelayerpath: super::super::Foundation::PWSTR, layerdata: super::super::Foundation::PWSTR, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsInitializeWritableLayer(writablelayerpath.into_param().abi(), layerdata.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsModifyComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(computesystem: Param0, operation: Param1, configuration: Param2, identity: Param3) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsModifyComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, configuration: super::super::Foundation::PWSTR, identity: super::super::Foundation::HANDLE) -> ::windows::core::HRESULT; } HcsModifyComputeSystem(computesystem.into_param().abi(), operation.into_param().abi(), configuration.into_param().abi(), identity.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsModifyProcess<'a, Param0: ::windows::core::IntoParam<'a, HCS_PROCESS>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(process: Param0, operation: Param1, settings: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsModifyProcess(process: HCS_PROCESS, operation: HCS_OPERATION, settings: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsModifyProcess(process.into_param().abi(), operation.into_param().abi(), settings.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsModifyServiceSettings<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(settings: Param0) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsModifyServiceSettings(settings: super::super::Foundation::PWSTR, result: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsModifyServiceSettings(settings.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsOpenComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(id: Param0, requestedaccess: u32) -> ::windows::core::Result<HCS_SYSTEM> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsOpenComputeSystem(id: super::super::Foundation::PWSTR, requestedaccess: u32, computesystem: *mut HCS_SYSTEM) -> ::windows::core::HRESULT; } let mut result__: <HCS_SYSTEM as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsOpenComputeSystem(id.into_param().abi(), ::core::mem::transmute(requestedaccess), &mut result__).from_abi::<HCS_SYSTEM>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsOpenComputeSystemInNamespace<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(idnamespace: Param0, id: Param1, requestedaccess: u32) -> ::windows::core::Result<HCS_SYSTEM> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsOpenComputeSystemInNamespace(idnamespace: super::super::Foundation::PWSTR, id: super::super::Foundation::PWSTR, requestedaccess: u32, computesystem: *mut HCS_SYSTEM) -> ::windows::core::HRESULT; } let mut result__: <HCS_SYSTEM as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsOpenComputeSystemInNamespace(idnamespace.into_param().abi(), id.into_param().abi(), ::core::mem::transmute(requestedaccess), &mut result__).from_abi::<HCS_SYSTEM>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsOpenProcess<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>>(computesystem: Param0, processid: u32, requestedaccess: u32) -> ::windows::core::Result<HCS_PROCESS> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsOpenProcess(computesystem: HCS_SYSTEM, processid: u32, requestedaccess: u32, process: *mut HCS_PROCESS) -> ::windows::core::HRESULT; } let mut result__: <HCS_PROCESS as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsOpenProcess(computesystem.into_param().abi(), ::core::mem::transmute(processid), ::core::mem::transmute(requestedaccess), &mut result__).from_abi::<HCS_PROCESS>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsPauseComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(computesystem: Param0, operation: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsPauseComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsPauseComputeSystem(computesystem.into_param().abi(), operation.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsResumeComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(computesystem: Param0, operation: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsResumeComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsResumeComputeSystem(computesystem.into_param().abi(), operation.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsRevokeVmAccess<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(vmid: Param0, filepath: Param1) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsRevokeVmAccess(vmid: super::super::Foundation::PWSTR, filepath: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsRevokeVmAccess(vmid.into_param().abi(), filepath.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsRevokeVmGroupAccess<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(filepath: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsRevokeVmGroupAccess(filepath: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsRevokeVmGroupAccess(filepath.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsSaveComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(computesystem: Param0, operation: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsSaveComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsSaveComputeSystem(computesystem.into_param().abi(), operation.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsSetComputeSystemCallback<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>>(computesystem: Param0, callbackoptions: HCS_EVENT_OPTIONS, context: *const ::core::ffi::c_void, callback: ::core::option::Option<HCS_EVENT_CALLBACK>) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsSetComputeSystemCallback(computesystem: HCS_SYSTEM, callbackoptions: HCS_EVENT_OPTIONS, context: *const ::core::ffi::c_void, callback: ::windows::core::RawPtr) -> ::windows::core::HRESULT; } HcsSetComputeSystemCallback(computesystem.into_param().abi(), ::core::mem::transmute(callbackoptions), ::core::mem::transmute(context), ::core::mem::transmute(callback)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsSetOperationCallback<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0, context: *const ::core::ffi::c_void, callback: ::core::option::Option<HCS_OPERATION_COMPLETION>) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsSetOperationCallback(operation: HCS_OPERATION, context: *const ::core::ffi::c_void, callback: ::windows::core::RawPtr) -> ::windows::core::HRESULT; } HcsSetOperationCallback(operation.into_param().abi(), ::core::mem::transmute(context), ::core::mem::transmute(callback)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn HcsSetOperationContext<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsSetOperationContext(operation: HCS_OPERATION, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } HcsSetOperationContext(operation.into_param().abi(), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsSetProcessCallback<'a, Param0: ::windows::core::IntoParam<'a, HCS_PROCESS>>(process: Param0, callbackoptions: HCS_EVENT_OPTIONS, context: *const ::core::ffi::c_void, callback: ::core::option::Option<HCS_EVENT_CALLBACK>) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsSetProcessCallback(process: HCS_PROCESS, callbackoptions: HCS_EVENT_OPTIONS, context: *const ::core::ffi::c_void, callback: ::windows::core::RawPtr) -> ::windows::core::HRESULT; } HcsSetProcessCallback(process.into_param().abi(), ::core::mem::transmute(callbackoptions), ::core::mem::transmute(context), ::core::mem::transmute(callback)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsSetupBaseOSLayer<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(layerpath: Param0, vhdhandle: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsSetupBaseOSLayer(layerpath: super::super::Foundation::PWSTR, vhdhandle: super::super::Foundation::HANDLE, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsSetupBaseOSLayer(layerpath.into_param().abi(), vhdhandle.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsSetupBaseOSVolume<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(layerpath: Param0, volumepath: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsSetupBaseOSVolume(layerpath: super::super::Foundation::PWSTR, volumepath: super::super::Foundation::PWSTR, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsSetupBaseOSVolume(layerpath.into_param().abi(), volumepath.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsShutDownComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(computesystem: Param0, operation: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsShutDownComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsShutDownComputeSystem(computesystem.into_param().abi(), operation.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsSignalProcess<'a, Param0: ::windows::core::IntoParam<'a, HCS_PROCESS>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(process: Param0, operation: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsSignalProcess(process: HCS_PROCESS, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsSignalProcess(process.into_param().abi(), operation.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsStartComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(computesystem: Param0, operation: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsStartComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsStartComputeSystem(computesystem.into_param().abi(), operation.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsSubmitWerReport<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(settings: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsSubmitWerReport(settings: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsSubmitWerReport(settings.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsTerminateComputeSystem<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(computesystem: Param0, operation: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsTerminateComputeSystem(computesystem: HCS_SYSTEM, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsTerminateComputeSystem(computesystem.into_param().abi(), operation.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsTerminateProcess<'a, Param0: ::windows::core::IntoParam<'a, HCS_PROCESS>, Param1: ::windows::core::IntoParam<'a, HCS_OPERATION>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(process: Param0, operation: Param1, options: Param2) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsTerminateProcess(process: HCS_PROCESS, operation: HCS_OPERATION, options: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsTerminateProcess(process.into_param().abi(), operation.into_param().abi(), options.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsWaitForComputeSystemExit<'a, Param0: ::windows::core::IntoParam<'a, HCS_SYSTEM>>(computesystem: Param0, timeoutms: u32) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsWaitForComputeSystemExit(computesystem: HCS_SYSTEM, timeoutms: u32, result: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsWaitForComputeSystemExit(computesystem.into_param().abi(), ::core::mem::transmute(timeoutms), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsWaitForOperationResult<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0, timeoutms: u32) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsWaitForOperationResult(operation: HCS_OPERATION, timeoutms: u32, resultdocument: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsWaitForOperationResult(operation.into_param().abi(), ::core::mem::transmute(timeoutms), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsWaitForOperationResultAndProcessInfo<'a, Param0: ::windows::core::IntoParam<'a, HCS_OPERATION>>(operation: Param0, timeoutms: u32, processinformation: *mut HCS_PROCESS_INFORMATION, resultdocument: *mut super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsWaitForOperationResultAndProcessInfo(operation: HCS_OPERATION, timeoutms: u32, processinformation: *mut HCS_PROCESS_INFORMATION, resultdocument: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } HcsWaitForOperationResultAndProcessInfo(operation.into_param().abi(), ::core::mem::transmute(timeoutms), ::core::mem::transmute(processinformation), ::core::mem::transmute(resultdocument)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HcsWaitForProcessExit<'a, Param0: ::windows::core::IntoParam<'a, HCS_PROCESS>>(computesystem: Param0, timeoutms: u32) -> ::windows::core::Result<super::super::Foundation::PWSTR> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HcsWaitForProcessExit(computesystem: HCS_PROCESS, timeoutms: u32, result: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT; } let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HcsWaitForProcessExit(computesystem.into_param().abi(), ::core::mem::transmute(timeoutms), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); }
use super::*; use generational_arena::{Arena, Index}; use glutin::{ContextWrapper, PossiblyCurrent}; use image::GenericImageView; use lazy_static::lazy_static; use std::path::Path; use winit::window::Window; const DEFAULT_TEXTURE_SIZE: u32 = 2; lazy_static! { static ref DEFAULT_TEXTURE_DATA: Vec<u8> = vec![0, 0, 0, 128, 255, 0, 255, 128, 255, 0, 255, 128, 0, 0, 0, 128]; } pub struct MeshFlags { depth_write: bool, mode: u32, } impl MeshFlags { pub fn new() -> Self { Self { depth_write: true, mode: gl::TRIANGLES, } } pub fn no_depth(mut self) -> MeshFlags { self.depth_write = false; self } pub fn triangles_mode(mut self) -> MeshFlags { self.mode = gl::TRIANGLES; self } pub fn lines_mode(mut self) -> MeshFlags { self.mode = gl::LINES; self } pub fn opt(self) -> Option<Self> { Some(self) } } impl Default for MeshFlags { fn default() -> Self { Self { depth_write: true, mode: gl::TRIANGLES, } } } pub struct RendererDevice { pub ctx: OpenGLContext, pub texture_cache: Arena<Texture>, } impl RendererDevice { pub fn from_window(window_context: &ContextWrapper<PossiblyCurrent, Window>) -> Self { let mut value = Self { ctx: OpenGLContext::build_initialize(window_context), texture_cache: Arena::new(), }; value.resize(500, 500); value } pub fn register_texture(&mut self, texture_object: Texture) -> Index<Texture> { let mut texture_object = texture_object; let gl_texture = self.ctx.texture.create_texture(gl::TEXTURE_2D, None); self.ctx .texture .set_active_texture_unit(gl::TEXTURE0) .bind_texture(gl_texture) .set_wrappings(texture_object.wrapping as u32) .set_mig_mag_filter(texture_object.filtering as u32); texture_object.set_handle(gl_texture); self.texture_cache.insert(texture_object) } pub fn get_texture_mut(&mut self, index: Index<Texture>) -> Option<&mut Texture> { self.texture_cache.get_mut(index) } pub fn set_index_data<T>(&mut self, component: &mut RenderComponent, data: &[T]) { if let Some(ibo) = &component.ibo { self.ctx.buffer.bind_buffer(ibo).set_data(data); } if component.is_indexed { component.vertex_count = data.len(); } } pub fn set_vertex_data<T>(&mut self, component: &mut RenderComponent, data: &[T]) { self.ctx.buffer.bind_buffer(&component.vbo).set_data(data); if !component.is_indexed { component.vertex_count = data.len(); } } pub fn resize(&mut self, width: u32, height: u32) { self.ctx.viewport.resize(width, height); } pub fn new_mesh<T: VertexFormat>( &mut self, material_path: &Path, geometry: Vec<T>, index_buffer: Option<Vec<i32>>, textures: Vec<Index<Texture>>, flags: Option<MeshFlags>, ) -> RenderComponent { let flags = flags.unwrap_or_default(); let vao = self.ctx.vertex_array.create(); self.ctx.vertex_array.bind(&vao); let vb = self .ctx .buffer .create_buffer(gl::ARRAY_BUFFER, gl::STATIC_DRAW); self.ctx.buffer.bind_buffer(&vb).set_data(&geometry); let (ib, size) = if let Some(index_buffer) = index_buffer { let ib = self .ctx .buffer .create_buffer(gl::ELEMENT_ARRAY_BUFFER, gl::STATIC_DRAW); self.ctx.buffer.bind_buffer(&ib).set_data(&index_buffer); (Some(ib), index_buffer.len()) } else { (None, geometry.len()) }; let program = self.ctx.program.create_from_file::<T>(material_path); RenderComponent::new( program, textures, vao, vb, ib, flags.depth_write, flags.mode, size, ) } pub fn render_component(&mut self, component: &mut RenderComponent) { self.ctx.program.bind(&component.material); self.ctx.vertex_array.bind(&component.vao); self.ctx.depth_buffer.set_mask(component.depth_write as u8); let mut index = 0; for text_id in component.textures.iter() { let text = if let Some(text) = self.texture_cache.get_mut(*text_id) { text } else { continue; }; if let Some(txt) = text.handle { self.ctx .texture .set_active_texture_unit(gl::TEXTURE0 + index) .bind_texture(txt); } else { continue; }; if text.needs_update { match &mut text.storage { TextureStorage::Canvas2D(canvas) => { self.ctx.texture.set_raw_data( canvas.width as u32, canvas.height as u32, canvas.data(), ); } TextureStorage::Image(image) => { let data = image.raw_pixels(); let (width, height) = (image.width(), image.height()); self.ctx.texture.set_data(width, height, &data); } TextureStorage::Zeroed => { self.ctx.texture.set_data( DEFAULT_TEXTURE_SIZE, DEFAULT_TEXTURE_SIZE, &DEFAULT_TEXTURE_DATA, ); } } } text.needs_update = false; index += 1; } if component.is_indexed { gl::draw_elements( component.draw_mode, component.vertex_count, gl::UNSIGNED_INT, ); } else { gl::draw_arrays(component.draw_mode, 0, component.vertex_count); } } }
use std::io; use std::env; use std::time::Duration; use settimeout::set_timeout; use futures::executor::block_on; use std::process::{ Command, Stdio }; mod filesystem; pub use crate::filesystem::functions; struct IconParameters { pub width: u32, pub scale: u8, } impl IconParameters { fn get_icon_name(&self) -> String { let icon_name: String = if self.scale == 1 { format!("icon_{}x{}.png", &self.width, &self.width) } else { format!("icon_{}x{}@2x.png", &self.width / 2, &self.width / 2) }; icon_name } } fn png_collect() -> String { println!("Drag your png here"); let mut path = String::new(); io::stdin().read_line(&mut path).expect("Not a valid path of a png!"); path = path.replace("\\", ""); path } fn app_collect() -> String { println!("Drag your app here"); let mut app_path_string = String::new(); io::stdin().read_line(&mut app_path_string).expect("Not a valid path of a application!"); app_path_string = format!("{}", app_path_string.trim().replace("'", "").replace("\\", "")); app_path_string } async fn main_async() { let args: Vec<_> = env::args().collect(); let mut png_path: String = String::new(); let mut app_icon_path: String = String::new(); if args.len() == 3 { // println!("{:?}", args); png_path = args[1].clone(); app_icon_path = args[2].clone(); } else if args.len() == 2 { println!(r#"Usage: redock <png_path> <app_path> "#); return } else { png_path = png_collect(); app_icon_path = app_collect(); } println!("Icon Path: {}", png_path); println!("Path: {}", app_icon_path); let mut iterations: u8 = 0; let folder = functions::mkdir(); drop(folder); let python_script = r#"import Cocoa import sys Cocoa.NSWorkspace.sharedWorkspace().setIcon_forFile_options_( Cocoa.NSImage.alloc().initWithContentsOfFile_(sys.argv[1]), sys.argv[2], 0 ) or sys.exit("Unable to set file icon") "#; let list_of_icons: Vec<IconParameters> = vec![ IconParameters { width: 16, scale: 1 }, IconParameters { width: 16, scale: 2 }, IconParameters { width: 32, scale: 1 }, IconParameters { width: 32, scale: 2 }, IconParameters { width: 64, scale: 1 }, IconParameters { width: 64, scale: 2 }, IconParameters { width: 128, scale: 1 }, IconParameters { width: 128, scale: 2 }, IconParameters { width: 256, scale: 1 }, IconParameters { width: 256, scale: 2 }, IconParameters { width: 512, scale: 1 }, IconParameters { width: 512, scale: 2 }, IconParameters { width: 1024, scale: 1 }, IconParameters { width: 1024, scale: 2 } ]; for icon in list_of_icons { let icon_path: &str = &(format!("icons/{}", icon.get_icon_name()))[..]; let icon_width: &str = &(format!("{}", icon.width))[..]; let png_path_str: &str = &(format!("{}", png_path.trim().replace("'", "")))[..]; let echo_child = Command::new("sips") .args(["-z", icon_width, icon_width, png_path_str, "--out", icon_path]) .stdout(Stdio::piped()) .spawn() .expect("Failed to start echo process"); drop(echo_child); println!("Converted {}", icon_path); iterations += 1; if iterations == 14 { println!("Waiting..."); set_timeout(Duration::from_secs(3)).await; let renamed = functions::rename(); drop(renamed); let echo_child = Command::new("iconutil") .args(["-c", "icns", "./icons.iconset", "-o", "./icons.icns"]) .stdout(Stdio::piped()) .spawn() .expect("Failed to start echo process"); drop(echo_child); println!("Converting to icns..."); set_timeout(Duration::from_secs(3)).await; println!("Trying to move icon"); let echo_child_mv = Command::new("python") .args(["-c", python_script, "./icons.icns", &app_icon_path[..]]) .stdout(Stdio::piped()) .spawn() .expect("Failed to start echo process"); drop(echo_child_mv); println!("Clearing cache and cleaning up"); set_timeout(Duration::from_secs(3)).await; let echo_child_rm = Command::new("bash") .args(["-c", "rm /var/folders/*/*/*/com.apple.dock.iconcache; killall Dock"]) .stdout(Stdio::piped()) .spawn() .expect("Failed to start echo process"); drop(echo_child_rm); set_timeout(Duration::from_secs(3)).await; let removed_folder = functions::remove(); drop(removed_folder); let deleted_icon = functions::del(); drop(deleted_icon); println!("Process Complete"); } } } fn main() { block_on(main_async()); }
use super::helpers::c_long_remainder_assign; use crate::integer::Integer; use core::ops::RemAssign; // RemAssign The remainder assignment operator %=. // ['Integer', 'Integer', 'Integer::remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for Integer { fn rem_assign(&mut self, rhs: Integer) { Integer::remainder_assign(self, &rhs) } } // ['Integer', '&Integer', 'Integer::remainder_assign', 'no', [], []] impl RemAssign<&Integer> for Integer { fn rem_assign(&mut self, rhs: &Integer) { Integer::remainder_assign(self, rhs) } } // ['Integer', 'i8', 'Integer::remainder_c_long_assign', 'no', [], []] impl RemAssign<i8> for Integer { fn rem_assign(&mut self, rhs: i8) { Integer::remainder_c_long_assign(self, rhs) } } // ['Integer', '&i8', 'Integer::remainder_c_long_assign', 'no', [], ['deref']] impl RemAssign<&i8> for Integer { fn rem_assign(&mut self, rhs: &i8) { Integer::remainder_c_long_assign(self, *rhs) } } // ['i8', 'Integer', 'c_long_remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for i8 { fn rem_assign(&mut self, rhs: Integer) { c_long_remainder_assign(self, &rhs) } } // ['i8', '&Integer', 'c_long_remainder_assign', 'no', [], []] impl RemAssign<&Integer> for i8 { fn rem_assign(&mut self, rhs: &Integer) { c_long_remainder_assign(self, rhs) } } // ['Integer', 'u8', 'Integer::remainder_c_long_assign', 'no', [], []] impl RemAssign<u8> for Integer { fn rem_assign(&mut self, rhs: u8) { Integer::remainder_c_long_assign(self, rhs) } } // ['Integer', '&u8', 'Integer::remainder_c_long_assign', 'no', [], ['deref']] impl RemAssign<&u8> for Integer { fn rem_assign(&mut self, rhs: &u8) { Integer::remainder_c_long_assign(self, *rhs) } } // ['u8', 'Integer', 'c_long_remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for u8 { fn rem_assign(&mut self, rhs: Integer) { c_long_remainder_assign(self, &rhs) } } // ['u8', '&Integer', 'c_long_remainder_assign', 'no', [], []] impl RemAssign<&Integer> for u8 { fn rem_assign(&mut self, rhs: &Integer) { c_long_remainder_assign(self, rhs) } } // ['Integer', 'i16', 'Integer::remainder_c_long_assign', 'no', [], []] impl RemAssign<i16> for Integer { fn rem_assign(&mut self, rhs: i16) { Integer::remainder_c_long_assign(self, rhs) } } // ['Integer', '&i16', 'Integer::remainder_c_long_assign', 'no', [], ['deref']] impl RemAssign<&i16> for Integer { fn rem_assign(&mut self, rhs: &i16) { Integer::remainder_c_long_assign(self, *rhs) } } // ['i16', 'Integer', 'c_long_remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for i16 { fn rem_assign(&mut self, rhs: Integer) { c_long_remainder_assign(self, &rhs) } } // ['i16', '&Integer', 'c_long_remainder_assign', 'no', [], []] impl RemAssign<&Integer> for i16 { fn rem_assign(&mut self, rhs: &Integer) { c_long_remainder_assign(self, rhs) } } // ['Integer', 'u16', 'Integer::remainder_c_long_assign', 'no', [], []] impl RemAssign<u16> for Integer { fn rem_assign(&mut self, rhs: u16) { Integer::remainder_c_long_assign(self, rhs) } } // ['Integer', '&u16', 'Integer::remainder_c_long_assign', 'no', [], ['deref']] impl RemAssign<&u16> for Integer { fn rem_assign(&mut self, rhs: &u16) { Integer::remainder_c_long_assign(self, *rhs) } } // ['u16', 'Integer', 'c_long_remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for u16 { fn rem_assign(&mut self, rhs: Integer) { c_long_remainder_assign(self, &rhs) } } // ['u16', '&Integer', 'c_long_remainder_assign', 'no', [], []] impl RemAssign<&Integer> for u16 { fn rem_assign(&mut self, rhs: &Integer) { c_long_remainder_assign(self, rhs) } } // ['Integer', 'i32', 'Integer::remainder_c_long_assign', 'no', [], []] impl RemAssign<i32> for Integer { fn rem_assign(&mut self, rhs: i32) { Integer::remainder_c_long_assign(self, rhs) } } // ['Integer', '&i32', 'Integer::remainder_c_long_assign', 'no', [], ['deref']] impl RemAssign<&i32> for Integer { fn rem_assign(&mut self, rhs: &i32) { Integer::remainder_c_long_assign(self, *rhs) } } // ['i32', 'Integer', 'c_long_remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for i32 { fn rem_assign(&mut self, rhs: Integer) { c_long_remainder_assign(self, &rhs) } } // ['i32', '&Integer', 'c_long_remainder_assign', 'no', [], []] impl RemAssign<&Integer> for i32 { fn rem_assign(&mut self, rhs: &Integer) { c_long_remainder_assign(self, rhs) } } // ['Integer', 'u32', 'Integer::remainder_c_long_assign', 'no', [], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl RemAssign<u32> for Integer { fn rem_assign(&mut self, rhs: u32) { Integer::remainder_c_long_assign(self, rhs) } } // ['Integer', '&u32', 'Integer::remainder_c_long_assign', 'no', [], ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl RemAssign<&u32> for Integer { fn rem_assign(&mut self, rhs: &u32) { Integer::remainder_c_long_assign(self, *rhs) } } // ['Integer', 'i64', 'Integer::remainder_c_long_assign', 'no', [], []] #[cfg(all(target_pointer_width = "64", not(windows)))] impl RemAssign<i64> for Integer { fn rem_assign(&mut self, rhs: i64) { Integer::remainder_c_long_assign(self, rhs) } } // ['Integer', '&i64', 'Integer::remainder_c_long_assign', 'no', [], ['deref']] #[cfg(all(target_pointer_width = "64", not(windows)))] impl RemAssign<&i64> for Integer { fn rem_assign(&mut self, rhs: &i64) { Integer::remainder_c_long_assign(self, *rhs) } } // ['Integer', 'u32', 'Integer::remainder_assign', 'no', [], ['ref', {'convert': // 'Integer'}]] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl RemAssign<u32> for Integer { fn rem_assign(&mut self, rhs: u32) { Integer::remainder_assign(self, &Integer::from(rhs)) } } // ['Integer', '&u32', 'Integer::remainder_assign', 'no', [], ['ref', // {'convert': 'Integer'}, 'deref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl RemAssign<&u32> for Integer { fn rem_assign(&mut self, rhs: &u32) { Integer::remainder_assign(self, &Integer::from(*rhs)) } } // ['Integer', 'i64', 'Integer::remainder_assign', 'no', [], ['ref', {'convert': // 'Integer'}]] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl RemAssign<i64> for Integer { fn rem_assign(&mut self, rhs: i64) { Integer::remainder_assign(self, &Integer::from(rhs)) } } // ['Integer', '&i64', 'Integer::remainder_assign', 'no', [], ['ref', // {'convert': 'Integer'}, 'deref']] #[cfg(not(all(target_pointer_width = "64", not(windows))))] impl RemAssign<&i64> for Integer { fn rem_assign(&mut self, rhs: &i64) { Integer::remainder_assign(self, &Integer::from(*rhs)) } } // ['u32', 'Integer', 'c_long_remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for u32 { fn rem_assign(&mut self, rhs: Integer) { c_long_remainder_assign(self, &rhs) } } // ['u32', '&Integer', 'c_long_remainder_assign', 'no', [], []] impl RemAssign<&Integer> for u32 { fn rem_assign(&mut self, rhs: &Integer) { c_long_remainder_assign(self, rhs) } } // ['i64', 'Integer', 'c_long_remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for i64 { fn rem_assign(&mut self, rhs: Integer) { c_long_remainder_assign(self, &rhs) } } // ['i64', '&Integer', 'c_long_remainder_assign', 'no', [], []] impl RemAssign<&Integer> for i64 { fn rem_assign(&mut self, rhs: &Integer) { c_long_remainder_assign(self, rhs) } } // ['Integer', 'u64', 'Integer::remainder_assign', 'no', [], ['ref', {'convert': // 'Integer'}]] impl RemAssign<u64> for Integer { fn rem_assign(&mut self, rhs: u64) { Integer::remainder_assign(self, &Integer::from(rhs)) } } // ['Integer', '&u64', 'Integer::remainder_assign', 'no', [], ['ref', // {'convert': 'Integer'}, 'deref']] impl RemAssign<&u64> for Integer { fn rem_assign(&mut self, rhs: &u64) { Integer::remainder_assign(self, &Integer::from(*rhs)) } } // ['u64', 'Integer', 'c_long_remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for u64 { fn rem_assign(&mut self, rhs: Integer) { c_long_remainder_assign(self, &rhs) } } // ['u64', '&Integer', 'c_long_remainder_assign', 'no', [], []] impl RemAssign<&Integer> for u64 { fn rem_assign(&mut self, rhs: &Integer) { c_long_remainder_assign(self, rhs) } } // ['Integer', 'i128', 'Integer::remainder_assign', 'no', [], ['ref', // {'convert': 'Integer'}]] impl RemAssign<i128> for Integer { fn rem_assign(&mut self, rhs: i128) { Integer::remainder_assign(self, &Integer::from(rhs)) } } // ['Integer', '&i128', 'Integer::remainder_assign', 'no', [], ['ref', // {'convert': 'Integer'}, 'deref']] impl RemAssign<&i128> for Integer { fn rem_assign(&mut self, rhs: &i128) { Integer::remainder_assign(self, &Integer::from(*rhs)) } } // ['i128', 'Integer', 'c_long_remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for i128 { fn rem_assign(&mut self, rhs: Integer) { c_long_remainder_assign(self, &rhs) } } // ['i128', '&Integer', 'c_long_remainder_assign', 'no', [], []] impl RemAssign<&Integer> for i128 { fn rem_assign(&mut self, rhs: &Integer) { c_long_remainder_assign(self, rhs) } } // ['Integer', 'u128', 'Integer::remainder_assign', 'no', [], ['ref', // {'convert': 'Integer'}]] impl RemAssign<u128> for Integer { fn rem_assign(&mut self, rhs: u128) { Integer::remainder_assign(self, &Integer::from(rhs)) } } // ['Integer', '&u128', 'Integer::remainder_assign', 'no', [], ['ref', // {'convert': 'Integer'}, 'deref']] impl RemAssign<&u128> for Integer { fn rem_assign(&mut self, rhs: &u128) { Integer::remainder_assign(self, &Integer::from(*rhs)) } } // ['u128', 'Integer', 'c_long_remainder_assign', 'no', [], ['ref']] impl RemAssign<Integer> for u128 { fn rem_assign(&mut self, rhs: Integer) { c_long_remainder_assign(self, &rhs) } } // ['u128', '&Integer', 'c_long_remainder_assign', 'no', [], []] impl RemAssign<&Integer> for u128 { fn rem_assign(&mut self, rhs: &Integer) { c_long_remainder_assign(self, rhs) } }
use crate::models::Todo; use std::collections::HashMap; #[derive(Debug)] pub struct Store { tasks: HashMap<usize, Todo>, index: usize, } impl Store { pub fn new() -> Store { let mut store = Store { tasks: HashMap::new(), index: 1, }; // seed store store .tasks .insert(0, Todo::new(String::from("First thing to do"))); store } pub fn add(&mut self, task: Todo) { self.tasks.insert(self.index, task); self.index += 1; } pub fn get(&self, index: &usize) -> Option<&Todo> { self.tasks.get(index) } pub fn remove(&mut self, index: &usize) { self.tasks.remove(index); } pub fn display(self) { println!("{:?}", self.tasks) } }
#[doc = "Reader of register CSR"] pub type R = crate::R<u32, super::CSR>; #[doc = "Writer for register CSR"] pub type W = crate::W<u32, super::CSR>; #[doc = "Register CSR `reset()`'s with value 0x0c00_0600"] impl crate::ResetValue for super::CSR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0c00_0600 } } #[doc = "Reader of field `LPWRSTF`"] pub type LPWRSTF_R = crate::R<bool, bool>; #[doc = "Reader of field `WWDGRSTF`"] pub type WWDGRSTF_R = crate::R<bool, bool>; #[doc = "Reader of field `IWDGRSTF`"] pub type IWDGRSTF_R = crate::R<bool, bool>; #[doc = "Reader of field `SFTRSTF`"] pub type SFTRSTF_R = crate::R<bool, bool>; #[doc = "Reader of field `BORRSTF`"] pub type BORRSTF_R = crate::R<bool, bool>; #[doc = "Reader of field `PINRSTF`"] pub type PINRSTF_R = crate::R<bool, bool>; #[doc = "Reader of field `OBLRSTF`"] pub type OBLRSTF_R = crate::R<bool, bool>; #[doc = "Reader of field `FIREWALLRSTF`"] pub type FIREWALLRSTF_R = crate::R<bool, bool>; #[doc = "Reader of field `RMVF`"] pub type RMVF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RMVF`"] pub struct RMVF_W<'a> { w: &'a mut W, } impl<'a> RMVF_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 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `MSISRANGE`"] pub type MSISRANGE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `MSISRANGE`"] pub struct MSISRANGE_W<'a> { w: &'a mut W, } impl<'a> MSISRANGE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `LSIRDY`"] pub type LSIRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `LSION`"] pub type LSION_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LSION`"] pub struct LSION_W<'a> { w: &'a mut W, } impl<'a> LSION_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 31 - Low-power reset flag"] #[inline(always)] pub fn lpwrstf(&self) -> LPWRSTF_R { LPWRSTF_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 30 - Window watchdog reset flag"] #[inline(always)] pub fn wwdgrstf(&self) -> WWDGRSTF_R { WWDGRSTF_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 29 - Independent window watchdog reset flag"] #[inline(always)] pub fn iwdgrstf(&self) -> IWDGRSTF_R { IWDGRSTF_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 28 - Software reset flag"] #[inline(always)] pub fn sftrstf(&self) -> SFTRSTF_R { SFTRSTF_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 27 - BOR flag"] #[inline(always)] pub fn borrstf(&self) -> BORRSTF_R { BORRSTF_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 26 - Pin reset flag"] #[inline(always)] pub fn pinrstf(&self) -> PINRSTF_R { PINRSTF_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 25 - Option byte loader reset flag"] #[inline(always)] pub fn oblrstf(&self) -> OBLRSTF_R { OBLRSTF_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 24 - Firewall reset flag"] #[inline(always)] pub fn firewallrstf(&self) -> FIREWALLRSTF_R { FIREWALLRSTF_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 23 - Remove reset flag"] #[inline(always)] pub fn rmvf(&self) -> RMVF_R { RMVF_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bits 8:11 - SI range after Standby mode"] #[inline(always)] pub fn msisrange(&self) -> MSISRANGE_R { MSISRANGE_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bit 1 - LSI oscillator ready"] #[inline(always)] pub fn lsirdy(&self) -> LSIRDY_R { LSIRDY_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - LSI oscillator enable"] #[inline(always)] pub fn lsion(&self) -> LSION_R { LSION_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 23 - Remove reset flag"] #[inline(always)] pub fn rmvf(&mut self) -> RMVF_W { RMVF_W { w: self } } #[doc = "Bits 8:11 - SI range after Standby mode"] #[inline(always)] pub fn msisrange(&mut self) -> MSISRANGE_W { MSISRANGE_W { w: self } } #[doc = "Bit 0 - LSI oscillator enable"] #[inline(always)] pub fn lsion(&mut self) -> LSION_W { LSION_W { w: self } } }
/// ```rust,ignore /// 171. Excel表列序号 /// 给定一个Excel表格中的列名称,返回其相应的列序号。 /// /// 例如, /// /// A -> 1 /// B -> 2 /// C -> 3 /// ... /// Z -> 26 /// AA -> 27 /// AB -> 28 /// ... /// /// 示例 1: /// /// 输入: "A" /// 输出: 1 /// /// 示例 2: /// /// 输入: "AB" /// 输出: 28 /// /// 示例 3: /// /// 输入: "ZY" /// 输出: 701 /// /// 致谢: /// 特别感谢 @ts 添加此问题并创建所有测试用例。 /// /// 来源:力扣(LeetCode) /// 链接:https://leetcode-cn.com/problems/excel-sheet-column-number /// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 /// ``` pub fn title_to_number(s: String) -> i32 { let bytes = s.into_bytes(); let mut val = 0 as i32; for i in bytes { val = val * 26 - ('A' as i32) + (i as i32) + 1; } val as i32 } #[cfg(test)] mod test { use super::title_to_number; #[test] fn test_title_to_number() { assert_eq!(title_to_number("A".to_string()), 1); } }
// #![cfg_attr(feature = "dev", feature(plugin))] // #![cfg_attr(feature = "dev", plugin(clippy))] // #![cfg_attr( // feature = "dev", // warn( // cast_possible_truncation, cast_possible_wrap, cast_precision_loss, cast_sign_loss, mut_mut, // non_ascii_literal, result_unwrap_used, shadow_reuse, shadow_same, unicode_not_nfc, // wrong_self_convention, wrong_pub_self_convention // ) // )] // #![cfg_attr(feature = "dev", allow(string_extend_chars))] extern crate chrono; extern crate dirs; extern crate semver; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; #[macro_use] extern crate structopt; // extern crate structopt_derive; extern crate env_logger; #[macro_use] extern crate log; extern crate alfred; extern crate rusty_pin; use std::borrow::Cow; use std::collections::HashMap; use std::env; use std::io; use std::process; use alfred_rs::Updater; use rusty_pin::Pinboard; use structopt::StructOpt; use thiserror::Error; mod cli; mod commands; mod workflow_config; use crate::cli::{Opt, SubCommand}; use crate::workflow_config::Config; use crate::commands::Runner; // use commands::{config, delete, list, post, search, update}; use crate::commands::config; // TODO: Implement Debug for SubCommand in cli.rs so we don't show auth_token in Alfred's debug // window. <09-10-, Hamidme> // // TODO: Add a command to search pins that have 'toread' enabled. <01-09-21, Hamid> // // TODO: We need to come up with actual meaningful tests and deploy them to CIs. <23-08-21, Hamid> // // TODO: parse Alfred preferences and get number of visible items? // TODO: running ./alfred-pinboard-rs update from command line panics (starting from // fetch_latest_release) // TODO: Make sure that we don't show any json-like error in macOS's notification (check issue#27) // TODO: add an option to disable/enable update checks // TODO: Dont show full JSON errors after alfred's window has closed, just send a notification <01-04-20, hamid> // TODO: Can we do something about failure of parsing user's bookmarks or when the network times out // TODO: Try to reduce number of calls to get_browser_info in list.rs <04-04-20, hamid> // TODO: Separate finding the browser's info into a new separate sud-command so that delete.rs // does one thing which is deleting and not trying to find the browser's. <07-04-20, hamid> #[derive(Debug, Error)] pub enum AlfredError { #[error("Corrupted config file. Set API token again!")] ConfigFileErr, #[error("Missing config file (did you set API token?)")] MissingConfigFile, #[error("Cache: {0}")] CacheUpdateFailed(String), #[error("Post: {0}")] Post2PinboardFailed(String), #[error("Delete: {0}")] DeleteFailed(String), #[error("osascript error: {0}")] OsascriptError(String), #[error("What did you do?")] Other, } fn main() { /* - export alfred_workflow_version=0.11.1 - export alfred_workflow_data=$HOME/tmp/apr - export alfred_workflow_cache=$HOME/tmp/apr/ - export alfred_workflow_uid=hamid63 - export alfred_workflow_name="Rusty Pin" - export alfred_workflow_bundleid=cc.hamid.alfred-pinboard-rs - export alfred_version=3.6 */ // env::set_var("alfred_workflow_data", "/Volumes/Home/hamid/tmp/rust"); // env::set_var("alfred_workflow_cache", "/Volumes/Home/hamid/tmp/rust"); // env::set_var("alfred_workflow_uid", "hamid63"); // env::set_var("alfred_workflow_name", "alfred-pinboard-rs"); // env::set_var("alfred_version", "3.6"); // env::set_var("RUST_LOG", "rusty_pin=debug,alfred_pinboard_rs=debug"); // If user has Alfred's debug panel open, print all debug info // by setting RUST_LOG environment variable. use env::var_os; if alfred::env::is_debug() { env::set_var( "RUST_LOG", "rusty_pin=debug,alfred_rs=debug,alfred_pinboard_rs=debug", ); } env_logger::init(); debug!("Parsing input arguments."); let opt: Opt = Opt::from_args(); debug!("Looking for alfred_workflow_* env. vars"); let env_flags = ( var_os("alfred_workflow_version").is_some(), var_os("alfred_workflow_data").is_some(), var_os("alfred_workflow_cache").is_some(), var_os("alfred_workflow_uid").is_some(), var_os("alfred_workflow_name").is_some(), var_os("alfred_version").is_some(), ); if let (true, true, true, true, true, true) = env_flags { } else { show_error_alfred("Your workflow is not set up properly. Check alfred_workflow_* env var."); process::exit(1); } debug!( "alfred_workflow_version: {:?}", var_os("alfred_workflow_version") ); debug!("alfred_workflow_data: {:?}", var_os("alfred_workflow_data")); debug!( "alfred_workflow_cache: {:?}", var_os("alfred_workflow_cache") ); debug!("alfred_workflow_uid: {:?}", var_os("alfred_workflow_uid")); debug!("alfred_workflow_name: {:?}", var_os("alfred_workflow_name")); debug!("alfred_version: {:?}", var_os("alfred_version")); let pinboard; let config; debug!("Input cli command is {:?}", &opt.cmd); // Separate Config subcommand from rest of cli commands since during config we may run into // errors that cannot be fixed. if let SubCommand::Config { .. } = opt.cmd { config::run(opt.cmd); // Otherwise, if user is not configuring, we will abort upon any errors. } else { let setup = setup().unwrap_or_else(|err| { show_error_alfred(err.to_string()); process::exit(1); }); let mut updater = Updater::gh("spamwax/alfred-pinboard-rs").unwrap(); // If running ./alfred-pinboard-rs self -c, we have to make a network call // We do this by forcing the check interval to be zero if let SubCommand::SelfUpdate { check, .. } = opt.cmd { if check { updater.set_interval(0); } } updater.init().expect("cannot start updater!"); pinboard = setup.1; config = setup.0; debug!("Workflow Config: {:?}", &config); let mut runner = Runner { config: Some(config), pinboard: Some(pinboard), updater: Some(updater), }; match opt.cmd { SubCommand::Update => { runner.update_cache(false); } SubCommand::List { .. } => { runner.list(opt); } SubCommand::Search { .. } => { runner.search(opt.cmd); } SubCommand::Post { .. } => { runner.post(opt.cmd); } SubCommand::Delete { .. } => { runner.delete(opt.cmd); } SubCommand::SelfUpdate { .. } => { runner.upgrade(&opt.cmd); } SubCommand::Rename { .. } => { runner.rename(&opt.cmd); } // We have already checked for this variant SubCommand::Config { .. } => unimplemented!(), } } } fn setup<'a, 'p>() -> Result<(Config, Pinboard<'a, 'p>), Box<dyn std::error::Error>> { debug!("Starting in setup"); let config = Config::setup()?; let mut pinboard = Pinboard::new(config.auth_token.clone(), alfred::env::workflow_cache())?; pinboard.enable_fuzzy_search(config.fuzzy_search); pinboard.enable_tag_only_search(config.tag_only_search); pinboard.enable_private_new_pin(config.private_new_pin); pinboard.enable_toread_new_pin(config.toread_new_pin); Ok((config, pinboard)) } fn write_to_alfred<'a, 'b, I, J>(items: I, supports_json: bool, vars: Option<J>) where I: IntoIterator<Item = alfred::Item<'a>>, J: IntoIterator<Item = (&'b str, &'b str)>, { let exec_counter = env::var("apr_execution_counter").unwrap_or_else(|_| "1".to_string()); let output_items = items.into_iter().collect::<Vec<alfred::Item>>(); let mut variables: HashMap<&str, &str> = HashMap::new(); variables.insert("apr_execution_counter", exec_counter.as_str()); if let Some(items) = vars { items.into_iter().for_each(|(k, v)| { variables.insert(k, v); }); } debug!("variables: {:?}", variables); // Depending on alfred version use either json or xml output. if supports_json { alfred::json::Builder::with_items(output_items.as_slice()) .variables(variables) .write(io::stdout()) .expect("Couldn't write items to Alfred"); } else { alfred::xml::write_items(io::stdout(), &output_items) .expect("Couldn't write items to Alfred"); } } fn show_error_alfred<'a, T: Into<Cow<'a, str>>>(s: T) { debug!("Starting in show_error_alfred"); let item = alfred::ItemBuilder::new("Error") .subtitle(s) .icon_path("erroricon.icns") .into_item(); alfred::json::write_items(io::stdout(), &[item]).expect("Can't write to stdout"); std::process::exit(1); } fn alfred_error_item<'a, T: Into<Cow<'a, str>>>(s: T) -> alfred::Item<'a> { debug!("Starting in alfred_error"); alfred::ItemBuilder::new("Error") .subtitle(s) .icon_path("erroricon.icns") .into_item() }
use super::{Bucket, Entries, IndexMap, Slice}; use alloc::vec::{self, Vec}; use core::fmt; use core::iter::FusedIterator; use core::slice; impl<'a, K, V, S> IntoIterator for &'a IndexMap<K, V, S> { type Item = (&'a K, &'a V); type IntoIter = Iter<'a, K, V>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a, K, V, S> IntoIterator for &'a mut IndexMap<K, V, S> { type Item = (&'a K, &'a mut V); type IntoIter = IterMut<'a, K, V>; fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } impl<K, V, S> IntoIterator for IndexMap<K, V, S> { type Item = (K, V); type IntoIter = IntoIter<K, V>; fn into_iter(self) -> Self::IntoIter { IntoIter::new(self.into_entries()) } } /// An iterator over the entries of a `IndexMap`. /// /// This `struct` is created by the [`iter`] method on [`IndexMap`]. See its /// documentation for more. /// /// [`iter`]: struct.IndexMap.html#method.iter /// [`IndexMap`]: struct.IndexMap.html pub struct Iter<'a, K, V> { iter: slice::Iter<'a, Bucket<K, V>>, } impl<'a, K, V> Iter<'a, K, V> { pub(super) fn new(entries: &'a [Bucket<K, V>]) -> Self { Self { iter: entries.iter(), } } /// Returns a slice of the remaining entries in the iterator. pub fn as_slice(&self) -> &'a Slice<K, V> { Slice::from_slice(self.iter.as_slice()) } } impl<'a, K, V> Iterator for Iter<'a, K, V> { type Item = (&'a K, &'a V); iterator_methods!(Bucket::refs); } impl<K, V> DoubleEndedIterator for Iter<'_, K, V> { double_ended_iterator_methods!(Bucket::refs); } impl<K, V> ExactSizeIterator for Iter<'_, K, V> { fn len(&self) -> usize { self.iter.len() } } impl<K, V> FusedIterator for Iter<'_, K, V> {} // FIXME(#26925) Remove in favor of `#[derive(Clone)]` impl<K, V> Clone for Iter<'_, K, V> { fn clone(&self) -> Self { Iter { iter: self.iter.clone(), } } } impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.clone()).finish() } } impl<K, V> Default for Iter<'_, K, V> { fn default() -> Self { Self { iter: [].iter() } } } /// A mutable iterator over the entries of a `IndexMap`. /// /// This `struct` is created by the [`iter_mut`] method on [`IndexMap`]. See its /// documentation for more. /// /// [`iter_mut`]: struct.IndexMap.html#method.iter_mut /// [`IndexMap`]: struct.IndexMap.html pub struct IterMut<'a, K, V> { iter: slice::IterMut<'a, Bucket<K, V>>, } impl<'a, K, V> IterMut<'a, K, V> { pub(super) fn new(entries: &'a mut [Bucket<K, V>]) -> Self { Self { iter: entries.iter_mut(), } } /// Returns a slice of the remaining entries in the iterator. pub fn as_slice(&self) -> &Slice<K, V> { Slice::from_slice(self.iter.as_slice()) } /// Returns a mutable slice of the remaining entries in the iterator. /// /// To avoid creating `&mut` references that alias, this is forced to consume the iterator. pub fn into_slice(self) -> &'a mut Slice<K, V> { Slice::from_mut_slice(self.iter.into_slice()) } } impl<'a, K, V> Iterator for IterMut<'a, K, V> { type Item = (&'a K, &'a mut V); iterator_methods!(Bucket::ref_mut); } impl<K, V> DoubleEndedIterator for IterMut<'_, K, V> { double_ended_iterator_methods!(Bucket::ref_mut); } impl<K, V> ExactSizeIterator for IterMut<'_, K, V> { fn len(&self) -> usize { self.iter.len() } } impl<K, V> FusedIterator for IterMut<'_, K, V> {} impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let iter = self.iter.as_slice().iter().map(Bucket::refs); f.debug_list().entries(iter).finish() } } impl<K, V> Default for IterMut<'_, K, V> { fn default() -> Self { Self { iter: [].iter_mut(), } } } /// An owning iterator over the entries of a `IndexMap`. /// /// This `struct` is created by the [`into_iter`] method on [`IndexMap`] /// (provided by the `IntoIterator` trait). See its documentation for more. /// /// [`into_iter`]: struct.IndexMap.html#method.into_iter /// [`IndexMap`]: struct.IndexMap.html pub struct IntoIter<K, V> { iter: vec::IntoIter<Bucket<K, V>>, } impl<K, V> IntoIter<K, V> { pub(super) fn new(entries: Vec<Bucket<K, V>>) -> Self { Self { iter: entries.into_iter(), } } /// Returns a slice of the remaining entries in the iterator. pub fn as_slice(&self) -> &Slice<K, V> { Slice::from_slice(self.iter.as_slice()) } /// Returns a mutable slice of the remaining entries in the iterator. pub fn as_mut_slice(&mut self) -> &mut Slice<K, V> { Slice::from_mut_slice(self.iter.as_mut_slice()) } } impl<K, V> Iterator for IntoIter<K, V> { type Item = (K, V); iterator_methods!(Bucket::key_value); } impl<K, V> DoubleEndedIterator for IntoIter<K, V> { double_ended_iterator_methods!(Bucket::key_value); } impl<K, V> ExactSizeIterator for IntoIter<K, V> { fn len(&self) -> usize { self.iter.len() } } impl<K, V> FusedIterator for IntoIter<K, V> {} impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let iter = self.iter.as_slice().iter().map(Bucket::refs); f.debug_list().entries(iter).finish() } } impl<K, V> Default for IntoIter<K, V> { fn default() -> Self { Self { iter: Vec::new().into_iter(), } } } /// A draining iterator over the entries of a `IndexMap`. /// /// This `struct` is created by the [`drain`] method on [`IndexMap`]. See its /// documentation for more. /// /// [`drain`]: struct.IndexMap.html#method.drain /// [`IndexMap`]: struct.IndexMap.html pub struct Drain<'a, K, V> { iter: vec::Drain<'a, Bucket<K, V>>, } impl<'a, K, V> Drain<'a, K, V> { pub(super) fn new(iter: vec::Drain<'a, Bucket<K, V>>) -> Self { Self { iter } } /// Returns a slice of the remaining entries in the iterator. pub fn as_slice(&self) -> &Slice<K, V> { Slice::from_slice(self.iter.as_slice()) } } impl<K, V> Iterator for Drain<'_, K, V> { type Item = (K, V); iterator_methods!(Bucket::key_value); } impl<K, V> DoubleEndedIterator for Drain<'_, K, V> { double_ended_iterator_methods!(Bucket::key_value); } impl<K, V> ExactSizeIterator for Drain<'_, K, V> { fn len(&self) -> usize { self.iter.len() } } impl<K, V> FusedIterator for Drain<'_, K, V> {} impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Drain<'_, K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let iter = self.iter.as_slice().iter().map(Bucket::refs); f.debug_list().entries(iter).finish() } } /// An iterator over the keys of a `IndexMap`. /// /// This `struct` is created by the [`keys`] method on [`IndexMap`]. See its /// documentation for more. /// /// [`keys`]: struct.IndexMap.html#method.keys /// [`IndexMap`]: struct.IndexMap.html pub struct Keys<'a, K, V> { iter: slice::Iter<'a, Bucket<K, V>>, } impl<'a, K, V> Keys<'a, K, V> { pub(super) fn new(entries: &'a [Bucket<K, V>]) -> Self { Self { iter: entries.iter(), } } } impl<'a, K, V> Iterator for Keys<'a, K, V> { type Item = &'a K; iterator_methods!(Bucket::key_ref); } impl<K, V> DoubleEndedIterator for Keys<'_, K, V> { double_ended_iterator_methods!(Bucket::key_ref); } impl<K, V> ExactSizeIterator for Keys<'_, K, V> { fn len(&self) -> usize { self.iter.len() } } impl<K, V> FusedIterator for Keys<'_, K, V> {} // FIXME(#26925) Remove in favor of `#[derive(Clone)]` impl<K, V> Clone for Keys<'_, K, V> { fn clone(&self) -> Self { Keys { iter: self.iter.clone(), } } } impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.clone()).finish() } } impl<K, V> Default for Keys<'_, K, V> { fn default() -> Self { Self { iter: [].iter() } } } /// An owning iterator over the keys of a `IndexMap`. /// /// This `struct` is created by the [`into_keys`] method on [`IndexMap`]. /// See its documentation for more. /// /// [`IndexMap`]: struct.IndexMap.html /// [`into_keys`]: struct.IndexMap.html#method.into_keys pub struct IntoKeys<K, V> { iter: vec::IntoIter<Bucket<K, V>>, } impl<K, V> IntoKeys<K, V> { pub(super) fn new(entries: Vec<Bucket<K, V>>) -> Self { Self { iter: entries.into_iter(), } } } impl<K, V> Iterator for IntoKeys<K, V> { type Item = K; iterator_methods!(Bucket::key); } impl<K, V> DoubleEndedIterator for IntoKeys<K, V> { double_ended_iterator_methods!(Bucket::key); } impl<K, V> ExactSizeIterator for IntoKeys<K, V> { fn len(&self) -> usize { self.iter.len() } } impl<K, V> FusedIterator for IntoKeys<K, V> {} impl<K: fmt::Debug, V> fmt::Debug for IntoKeys<K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let iter = self.iter.as_slice().iter().map(Bucket::key_ref); f.debug_list().entries(iter).finish() } } impl<K, V> Default for IntoKeys<K, V> { fn default() -> Self { Self { iter: Vec::new().into_iter(), } } } /// An iterator over the values of a `IndexMap`. /// /// This `struct` is created by the [`values`] method on [`IndexMap`]. See its /// documentation for more. /// /// [`values`]: struct.IndexMap.html#method.values /// [`IndexMap`]: struct.IndexMap.html pub struct Values<'a, K, V> { iter: slice::Iter<'a, Bucket<K, V>>, } impl<'a, K, V> Values<'a, K, V> { pub(super) fn new(entries: &'a [Bucket<K, V>]) -> Self { Self { iter: entries.iter(), } } } impl<'a, K, V> Iterator for Values<'a, K, V> { type Item = &'a V; iterator_methods!(Bucket::value_ref); } impl<K, V> DoubleEndedIterator for Values<'_, K, V> { double_ended_iterator_methods!(Bucket::value_ref); } impl<K, V> ExactSizeIterator for Values<'_, K, V> { fn len(&self) -> usize { self.iter.len() } } impl<K, V> FusedIterator for Values<'_, K, V> {} // FIXME(#26925) Remove in favor of `#[derive(Clone)]` impl<K, V> Clone for Values<'_, K, V> { fn clone(&self) -> Self { Values { iter: self.iter.clone(), } } } impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.clone()).finish() } } impl<K, V> Default for Values<'_, K, V> { fn default() -> Self { Self { iter: [].iter() } } } /// A mutable iterator over the values of a `IndexMap`. /// /// This `struct` is created by the [`values_mut`] method on [`IndexMap`]. See its /// documentation for more. /// /// [`values_mut`]: struct.IndexMap.html#method.values_mut /// [`IndexMap`]: struct.IndexMap.html pub struct ValuesMut<'a, K, V> { iter: slice::IterMut<'a, Bucket<K, V>>, } impl<'a, K, V> ValuesMut<'a, K, V> { pub(super) fn new(entries: &'a mut [Bucket<K, V>]) -> Self { Self { iter: entries.iter_mut(), } } } impl<'a, K, V> Iterator for ValuesMut<'a, K, V> { type Item = &'a mut V; iterator_methods!(Bucket::value_mut); } impl<K, V> DoubleEndedIterator for ValuesMut<'_, K, V> { double_ended_iterator_methods!(Bucket::value_mut); } impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> { fn len(&self) -> usize { self.iter.len() } } impl<K, V> FusedIterator for ValuesMut<'_, K, V> {} impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let iter = self.iter.as_slice().iter().map(Bucket::value_ref); f.debug_list().entries(iter).finish() } } impl<K, V> Default for ValuesMut<'_, K, V> { fn default() -> Self { Self { iter: [].iter_mut(), } } } /// An owning iterator over the values of a `IndexMap`. /// /// This `struct` is created by the [`into_values`] method on [`IndexMap`]. /// See its documentation for more. /// /// [`IndexMap`]: struct.IndexMap.html /// [`into_values`]: struct.IndexMap.html#method.into_values pub struct IntoValues<K, V> { iter: vec::IntoIter<Bucket<K, V>>, } impl<K, V> IntoValues<K, V> { pub(super) fn new(entries: Vec<Bucket<K, V>>) -> Self { Self { iter: entries.into_iter(), } } } impl<K, V> Iterator for IntoValues<K, V> { type Item = V; iterator_methods!(Bucket::value); } impl<K, V> DoubleEndedIterator for IntoValues<K, V> { double_ended_iterator_methods!(Bucket::value); } impl<K, V> ExactSizeIterator for IntoValues<K, V> { fn len(&self) -> usize { self.iter.len() } } impl<K, V> FusedIterator for IntoValues<K, V> {} impl<K, V: fmt::Debug> fmt::Debug for IntoValues<K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let iter = self.iter.as_slice().iter().map(Bucket::value_ref); f.debug_list().entries(iter).finish() } } impl<K, V> Default for IntoValues<K, V> { fn default() -> Self { Self { iter: Vec::new().into_iter(), } } }
extern crate tictactoe; pub use tictactoe::board::Board; pub use tictactoe::error::{self, Result}; pub use tictactoe::{check_for_winner, prompt_for_position}; fn main() { let mut board = Board::new(); loop { println!("\n{}", board); prompt_for_position() .and_then(|position| board.play_x(position)) .and_then(|outcome| check_for_winner(outcome, &board)) .and_then(|_| board.play_o()) .and_then(|outcome| check_for_winner(outcome, &board)) .or_else(|error| -> Result<()> { println!("\n{}", error); Ok(()) }).unwrap(); } }
//! Templates parsed in from markup. mod attributes; mod component; mod parse; mod style; mod template; mod value; pub(crate) use self::component::{TemplateAttribute}; pub use self::attributes::{Attributes}; pub use self::component::{ComponentTemplate}; pub use self::style::{Style}; pub use self::template::{Template}; pub use self::value::{TemplateValue, Color, EventHook, Coordinates, Coordinate};
use proc_macro::TokenStream; use proc_macro_roids::{DeriveInputStructExt, FieldsNamedAppend}; use quote::quote; use syn::{AttributeArgs, DeriveInput, Fields, FieldsNamed, parse_macro_input, parse_quote, Type}; mod db_meta; mod cr; /// 生成数据库通用部分,包括如下: /// # 三个字段, id: String, create_time: i64,update_time: i64 /// # impl Shared /// # 选项,如果有“CRUDTable”参数,那么使用 rbatis的json方式实现 CRUDTable接口。 如果struct中带有sub struct只能使用这种方式实现 /// # 在目录 “generated_sql”下面生成创建数据表的sql语言,现只支持sqlite,详细说明如下: /// * 数据库表需要 "#[db_append_shared]" attribute /// * 每一个字段都需要 "#[serde(default)]" 在使用serde_json时,提供默认值,如果不给 model <==> db时会出错 /// * sub struct上需要使用 "#[serde(flatten)]" 在序列化时它会把sub struct中的字段直接放入parent struct中 /// * 在有sub struct时不能使用"#[derive(CRUDTable)]",只能使用[db_append_shared(CRUDTable)] /// * 如果没有sub struct 可以使用#[derive(CRUDTable)],它是在编译时生成的代码,没有运行开销。 /// * 所有字段不能重名,包含sub struct中的 /// ## 支持类型 /// i16,u16,i32,u32,i64,u64, /// String, /// bool, //#[serde(default, deserialize_with = "bool_from_u32", serialize_with = "bool_to_u32")] /// f32,f64 /// bigdecimal::BigDecimal /// #Sample include sub struct /// ```` /// use serde::{Deserialize, Serialize}; /// use wallets_macro::{db_append_shared,db_sub_struct}; /// /// #[db_append_shared(CRUDTable)] /// #[derive(Serialize, Deserialize, Debug, Default, DbBeforeSave, DbBeforeUpdate)] /// struct Big{ /// #[serde(default)] /// pub name: String, /// #[serde(flatten)] /// pub sub: Sub, /// } /// #[db_sub_struct] /// #[derive(Serialize, Deserialize, Debug, Default)] /// struct Sub { /// #[serde(default)] /// pub count: u64, /// } /// ```` /// # Sample no sub struct /// ```` /// use serde::{Deserialize, Serialize}; /// use rbatis_macro_driver::CRUDTable; /// /// use wallets_macro::db_append_shared; /// /// #[db_append_shared] /// #[derive(Serialize, Deserialize, Debug, Default,CRUDTable, DbBeforeSave, DbBeforeUpdate)] /// struct Big{ /// #[serde(default)] /// pub name: String, /// // other fields /// } /// ```` #[proc_macro_attribute] pub fn db_append_shared(args: TokenStream, input: TokenStream) -> TokenStream { let mut ast = parse_macro_input!(input as DeriveInput); let args = parse_macro_input!(args as AttributeArgs); // Append the fields. let fields_additional: FieldsNamed = parse_quote!({ #[serde(default)] pub id: String, #[serde(default)] pub create_time: i64, #[serde(default)] pub update_time: i64, }); ast.append_named(fields_additional); let name = &ast.ident; let imp_base = quote! { impl Shared for #name { fn get_id(&self) -> String { self.id.clone() } fn set_id(&mut self, id: String) { self.id = id; } fn get_create_time(&self) -> i64 { self.create_time } fn set_create_time(&mut self, create_time: i64) { self.create_time = create_time; } fn get_update_time(&self) -> i64 { self.update_time } fn set_update_time(&mut self, update_time: i64) { self.update_time = update_time; } } }; let impl_crud = if args.is_empty() { quote! {} } else { quote! { impl CRUDTable for #name { type IdType = String; fn get_id(&self) -> Option<&Self::IdType>{ if self.id.is_empty() { None }else{ Some(&self.id) } } } } }; let fields_stream = db_field_name(&ast.ident, &ast.fields()); let gen = TokenStream::from(quote! { #ast #fields_stream #imp_base #impl_crud }); if cfg!(feature = "print_macro") { println!("\n............gen impl db_append_shared {}:\n {}", name, gen); } // if name.to_string() == "MMnemonic"{ // println!("\n............gen impl db_append_shared {}:\n {}", name, gen); // } if cfg!(feature = "db_meta") { let mut meta = db_meta::DbMeta::get().lock().expect("db_meta::DbMeta::get().lock()"); (*meta).push(&ast); } gen } /// 标记为 sub struct。只有标记为sub struct的才能被用到表的struct中 #[proc_macro_attribute] pub fn db_sub_struct(_: TokenStream, input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let fields_stream = db_field_name(&ast.ident, &ast.fields()); let gen = TokenStream::from(quote! { #ast #fields_stream }); if cfg!(feature = "print_macro") { println!("\n////// gen impl db_sub_struct {}:\n {}", &ast.ident.to_string(), gen); } if cfg!(feature = "db_meta") { let mut meta = db_meta::DbMeta::get().lock().expect("db_meta::DbMeta::get().lock()"); (*meta).push_sub_struct(&ast); } gen } fn db_field_name(name: &syn::Ident, fields: &Fields) -> proc_macro2::TokenStream { let fields_stream = { let mut fields_vec = Vec::new(); for f in fields { let field_ident = &f.ident; if let Some(id) = &f.ident { let field_name = id.to_string(); fields_vec.push(quote! {pub const #field_ident : &'a str = #field_name; }); } } if fields_vec.is_empty() { quote! {} } else { quote! { #[allow(non_upper_case_globals)] impl<'a> #name { #(#fields_vec)* } } } }; fields_stream } /// impl BeforeSave #[proc_macro_derive(DbBeforeSave)] pub fn db_before_save(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let gen = quote! { impl dao::BeforeSave for #name { fn before_save(&mut self){ if Shared::get_id(self).is_empty() { self.set_id(kits::uuid()); self.set_update_time(kits::now_ts_seconds()); self.set_create_time(self.get_update_time()); } else { self.set_update_time(kits::now_ts_seconds()); } } } }; if cfg!(feature = "print_macro") { println!("\n............gen impl DbBeforeSave {}:\n {}", name, gen); } gen.into() } /// impl BeforeUpdate #[proc_macro_derive(DbBeforeUpdate)] pub fn db_before_update(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let gen = quote! { impl dao::BeforeUpdate for #name { fn before_update(&mut self){ self.set_update_time(kits::now_ts_seconds()); } } }; if cfg!(feature = "print_macro") { println!("\n............gen impl DbBeforeUpdate {}:\n {}", name, gen); } gen.into() } /// impl CStruct + Drop #[proc_macro_derive(DlStruct)] pub fn dl_struct(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let mut drops = Vec::new(); for field in ast.fields().iter() { if let (Type::Ptr(_), Some(ident)) = (&field.ty, field.ident.as_ref()) { let fname = ident; drops.push(quote! { self.#fname.free(); }); } } let gen = TokenStream::from(quote! { impl CStruct for #name { fn free(&mut self) { #(#drops)* } } impl Drop for #name { fn drop(&mut self) { self.free(); } } }); if cfg!(feature = "print_macro") { println!("\n............gen impl dl_struct {}:\n {}", name, gen); } gen } /// impl Default #[proc_macro_derive(DlDefault)] pub fn dl_default(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let mut drops = Vec::new(); for field in ast.fields().iter() { if let Some(ident) = field.ident.as_ref() { let fname = ident; if let Type::Ptr(_) = &field.ty { drops.push(quote! { #fname : std::ptr::null_mut() }); } else { drops.push(quote! { #fname : Default::default() }); } } } let gen = TokenStream::from(quote! { impl Default for #name { fn default() -> Self { #name { #(#drops,)* } } } }); if cfg!(feature = "print_macro") { println!("............gen impl dl_default {}:\n {}", name, gen); } gen } /// impl CR #[proc_macro_derive(DlCR)] pub fn dl_cr(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); cr::dl_cr(&ast.ident.to_string(), &ast.fields()) } /// impl Drop #[proc_macro_derive(DlDrop)] pub fn dl_drop(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let gen = TokenStream::from(quote! { impl Drop for #name { fn drop(&mut self) { self.free(); } } }); if cfg!(feature = "print_macro") { println!("............gen impl dl_drop {}:\n {}", name, gen); } gen } /// camel to snake /// Sample /// camelName to camel_name pub(crate) fn to_snake_name(name: &String) -> String { let chs = name.chars(); let mut new_name = String::new(); let mut index = 0; let chs_len = name.len(); for x in chs { if x.is_uppercase() { if index != 0 && (index + 1) != chs_len { new_name.push_str("_"); } new_name.push_str(x.to_lowercase().to_string().as_str()); } else { new_name.push(x); } index += 1; } return new_name; } #[cfg(test)] mod tests { use syn::{Fields, FieldsNamed, parse_quote, Type}; #[test] fn it_works() { let fields_named: FieldsNamed = parse_quote! {{ pub id: *mut c_char, pub count: u32, pub name: *mut c_char, pub next: *mut Dl, }}; let fields = Fields::from(fields_named); let mut count = 0; for field in fields.iter() { if let Type::Ptr(_) = field.ty { count += 1; println!("\nttt: {}, {}", field.ident.as_ref().unwrap().to_string(), "raw ptr"); } } assert_eq!(3, count); } }